diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/tests/org.eclipse.ecf.tests.provider.jms.activemq/src/org/eclipse/ecf/tests/provider/jms/activemq/remoteservice/ActiveMQClientServiceRegisterTest.java b/tests/org.eclipse.ecf.tests.provider.jms.activemq/src/org/eclipse/ecf/tests/provider/jms/activemq/remoteservice/ActiveMQClientServiceRegisterTest.java
index 51634eca..00ac9b73 100644
--- a/tests/org.eclipse.ecf.tests.provider.jms.activemq/src/org/eclipse/ecf/tests/provider/jms/activemq/remoteservice/ActiveMQClientServiceRegisterTest.java
+++ b/tests/org.eclipse.ecf.tests.provider.jms.activemq/src/org/eclipse/ecf/tests/provider/jms/activemq/remoteservice/ActiveMQClientServiceRegisterTest.java
@@ -1,315 +1,315 @@
/*******************************************************************************
* Copyright (c) 2009 EclipseSource and others. All rights reserved. This
* program and the accompanying materials are made available under the terms of
* the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* EclipseSource - initial API and implementation
******************************************************************************/
package org.eclipse.ecf.tests.provider.jms.activemq.remoteservice;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import org.eclipse.ecf.core.ContainerFactory;
import org.eclipse.ecf.core.IContainer;
import org.eclipse.ecf.core.identity.ID;
import org.eclipse.ecf.core.identity.IDFactory;
import org.eclipse.ecf.core.util.Trace;
import org.eclipse.ecf.remoteservice.Constants;
import org.eclipse.ecf.remoteservice.IRemoteCall;
import org.eclipse.ecf.remoteservice.IRemoteService;
import org.eclipse.ecf.tests.internal.osgi.services.distribution.Activator;
import org.eclipse.ecf.tests.osgi.services.distribution.AbstractServiceRegisterListenerTest;
import org.eclipse.ecf.tests.osgi.services.distribution.TestService1;
import org.eclipse.ecf.tests.osgi.services.distribution.TestServiceInterface1;
import org.eclipse.ecf.tests.provider.jms.activemq.ActiveMQ;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
public class ActiveMQClientServiceRegisterTest extends AbstractServiceRegisterListenerTest {
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
setClientCount(2);
createServerAndClients();
connectClients();
setupRemoteServiceAdapters();
}
protected String getClientContainerName() {
return ActiveMQ.CLIENT_CONTAINER_NAME;
}
/* (non-Javadoc)
* @see org.eclipse.ecf.tests.provider.jms.remoteservice.AbstractRemoteServiceTestCase#getServerContainerName()
*/
protected String getServerContainerName() {
return ActiveMQ.SERVER_CONTAINER_NAME;
}
protected ID getServerConnectID(int client) {
return IDFactory.getDefault().createID("ecf.namespace.jmsid", ActiveMQ.TARGET_NAME);
}
protected IContainer createServer() throws Exception {
return ContainerFactory.getDefault().createContainer(getServerContainerName(), new Object[] {ActiveMQ.TARGET_NAME});
}
protected void tearDown() throws Exception {
cleanUpServerAndClients();
super.tearDown();
}
public void testRegisterServer() throws Exception {
Properties props = new Properties();
// *For testing purposes only* -- Set the service container id property, so that the service is not
// distributed by both the client and server (which are both running in the same process
// for junit plugin tests)
IContainer clientContainer = getClient(0);
props.put(Constants.SERVICE_CONTAINER_ID, clientContainer.getID());
// Set OSGI property that identifies this service as a service to be remoted
props.put(SERVICE_EXPORTED_INTERFACES, new String[] {SERVICE_EXPORTED_INTERFACES_WILDCARD});
// Actually register with default service (IConcatService)
ServiceRegistration registration = registerDefaultService(props);
// Wait a while
Thread.sleep(REGISTER_WAIT);
// Then unregister
registration.unregister();
Thread.sleep(REGISTER_WAIT);
}
public void testGetProxy() throws Exception {
String classname = TestServiceInterface1.class.getName();
// Setup service tracker for client
ServiceTracker st = createProxyServiceTracker(classname);
// Server - register service with required OSGI property and some test properties
Properties props = new Properties();
// *For testing purposes only* -- Set the service container id property, so that the service is not
// distributed by both the client and server (which are both running in the same process
// for junit plugin tests)
IContainer clientContainer = getClient(1);
props.put(Constants.SERVICE_CONTAINER_ID, clientContainer.getID());
// Set required OSGI property that identifies this service as a service to be remoted
props.put(SERVICE_EXPORTED_INTERFACES, new String[] {SERVICE_EXPORTED_INTERFACES_WILDCARD});
// Put property foo with value bar into published properties
String testPropKey = "foo";
String testPropVal = "bar";
props.put(testPropKey, testPropVal);
// Actually register and wait a while
ServiceRegistration registration = registerService(classname, new TestService1(),props);
Thread.sleep(REGISTER_WAIT);
// Client - Get service references that are proxies
ServiceReference [] remoteReferences = st.getServiceReferences();
assertTrue(remoteReferences != null);
assertTrue(remoteReferences.length > 0);
for(int i=0; i < remoteReferences.length; i++) {
// Get OBJECTCLASS property from first remote reference
String[] classes = (String []) remoteReferences[i].getProperty(org.osgi.framework.Constants.OBJECTCLASS);
assertTrue(classes != null);
// Check object class
assertTrue(classname.equals(classes[0]));
// Check the prop
String prop = (String) remoteReferences[i].getProperty(testPropKey);
assertTrue(prop != null);
assertTrue(prop.equals(testPropVal));
}
// Now unregister original registration and wait
registration.unregister();
st.close();
Thread.sleep(REGISTER_WAIT);
}
public void testGetAndUseProxy() throws Exception {
String classname = TestServiceInterface1.class.getName();
// Setup service tracker for client
ServiceTracker st = createProxyServiceTracker(classname);
// Server - register service with required OSGI property and some test properties
Properties props = new Properties();
// *For testing purposes only* -- Set the service container id property, so that the service is not
// distributed by both the client and server (which are both running in the same process
// for junit plugin tests)
IContainer clientContainer = getClient(0);
props.put(Constants.SERVICE_CONTAINER_ID, clientContainer.getID());
// Set required OSGI property that identifies this service as a service to be remoted
props.put(SERVICE_EXPORTED_INTERFACES, new String[] {SERVICE_EXPORTED_INTERFACES_WILDCARD});
// Actually register and wait a while
ServiceRegistration registration = registerService(classname, new TestService1(),props);
Thread.sleep(REGISTER_WAIT);
// Client - Get service references from service tracker
ServiceReference [] remoteReferences = st.getServiceReferences();
assertTrue(remoteReferences != null);
assertTrue(remoteReferences.length > 0);
for(int i=0; i < remoteReferences.length; i++) {
// Get proxy/service
TestServiceInterface1 proxy = (TestServiceInterface1) getContext().getService(remoteReferences[0]);
assertNotNull(proxy);
// Now use proxy
String result = proxy.doStuff1();
Trace.trace(Activator.PLUGIN_ID, "proxy.doStuff1 result="+result);
assertTrue(TestServiceInterface1.TEST_SERVICE_STRING1.equals(result));
}
// Unregister on server and wait
registration.unregister();
st.close();
Thread.sleep(REGISTER_WAIT);
}
public void testGetAndUseIRemoteService() throws Exception {
String classname = TestServiceInterface1.class.getName();
// Setup service tracker for client
ServiceTracker st = createProxyServiceTracker(classname);
// Server - register service with required OSGI property and some test properties
Properties props = new Properties();
// *For testing purposes only* -- Set the server container id property, so that the service is not
// distributed by both the client and server (which are both running in the same process
// for junit plugin tests)
IContainer clientContainer = getClient(1);
props.put(Constants.SERVICE_CONTAINER_ID, clientContainer.getID());
// Set required OSGI property that identifies this service as a service to be remoted
props.put(SERVICE_EXPORTED_INTERFACES, new String[] {SERVICE_EXPORTED_INTERFACES_WILDCARD});
// Actually register and wait a while
ServiceRegistration registration = registerService(classname, new TestService1(),props);
Thread.sleep(REGISTER_WAIT);
// Client - Get service references from service tracker
ServiceReference [] remoteReferences = st.getServiceReferences();
assertTrue(remoteReferences != null);
assertTrue(remoteReferences.length > 0);
for(int i=0; i < remoteReferences.length; i++) {
Object o = remoteReferences[i].getProperty(SERVICE_IMPORTED);
assertNotNull(o);
assertTrue(o instanceof IRemoteService);
IRemoteService rs = (IRemoteService) o;
// Now call rs methods
- IRemoteCall call = createRemoteCall(TestServiceInterface1.class);
+ IRemoteCall call = createRemoteCall();
if (call != null) {
// Call synchronously
Object result = rs.callSync(call);
Trace.trace(Activator.PLUGIN_ID, "callSync.doStuff1 result="+result);
assertNotNull(result);
assertTrue(result instanceof String);
assertTrue(TestServiceInterface1.TEST_SERVICE_STRING1.equals(result));
}
}
// Unregister on server
registration.unregister();
st.close();
Thread.sleep(REGISTER_WAIT);
}
/*
public void testGetExposedServicesFromDistributionProvider() throws Exception {
String classname = TestServiceInterface1.class.getName();
// Setup service tracker for distribution provider
ServiceTracker st = new ServiceTracker(getContext(),DistributionProvider.class.getName(),null);
st.open();
DistributionProvider distributionProvider = (DistributionProvider) st.getService();
assertNotNull(distributionProvider);
// The returned collection should not be null
Collection exposedServices = distributionProvider.getExposedServices();
assertNotNull(exposedServices);
// Server - register service with required OSGI property and some test properties
Properties props = new Properties();
// *For testing purposes only* -- Set the server container id property, so that the service is not
// distributed by both the client and server (which are both running in the same process
// for junit plugin tests)
IContainer clientContainer = getClient(0);
props.put(Constants.SERVICE_CONTAINER_ID, clientContainer.getID());
// Set required OSGI property that identifies this service as a service to be remoted
props.put(REMOTE_INTERFACES, new String[] {REMOTE_INTERFACES_WILDCARD});
// Actually register and wait a while
ServiceRegistration registration = registerService(classname, new TestService1(),props);
Thread.sleep(REGISTER_WAIT);
// Client
exposedServices = distributionProvider.getExposedServices();
assertNotNull(exposedServices);
int exposedLength = exposedServices.size();
assertTrue(exposedLength > 0);
for(Iterator i=exposedServices.iterator(); i.hasNext(); ) {
Object o = ((ServiceReference) i.next()).getProperty(REMOTE_INTERFACES);
assertTrue(o != null);
}
// Unregister on server
registration.unregister();
st.close();
Thread.sleep(REGISTER_WAIT);
// Check to see that the exposed service went away
exposedServices= distributionProvider.getExposedServices();
assertNotNull(exposedServices);
assertTrue(exposedServices.size() == (exposedLength - 1));
}
public void testGetRemoteServicesFromDistributionProvider() throws Exception {
String classname = TestServiceInterface1.class.getName();
// Setup service tracker for distribution provider
ServiceTracker st = new ServiceTracker(getContext(),DistributionProvider.class.getName(),null);
st.open();
DistributionProvider distributionProvider = (DistributionProvider) st.getService();
assertNotNull(distributionProvider);
// The returned collection should not be null
Collection remoteServices = distributionProvider.getRemoteServices();
assertNotNull(remoteServices);
// Server - register service with required OSGI property and some test properties
Properties props = new Properties();
// *For testing purposes only* -- Set the server container id property, so that the service is not
// distributed by both the client and server (which are both running in the same process
// for junit plugin tests)
IContainer clientContainer = getClient(1);
props.put(Constants.SERVICE_CONTAINER_ID, clientContainer.getID());
// Set required OSGI property that identifies this service as a service to be remoted
props.put(REMOTE_INTERFACES, new String[] {REMOTE_INTERFACES_WILDCARD});
// Actually register and wait a while
ServiceRegistration registration = registerService(classname, new TestService1(),props);
Thread.sleep(REGISTER_WAIT);
// Check that distribution provider (client) has remote services now
remoteServices = distributionProvider.getRemoteServices();
assertNotNull(remoteServices);
int remotesLength = remoteServices.size();
assertTrue(remotesLength > 0);
for(Iterator i=remoteServices.iterator(); i.hasNext(); ) {
Object o = ((ServiceReference) i.next()).getProperty(REMOTE);
assertTrue(o != null);
}
// Unregister on server
registration.unregister();
st.close();
Thread.sleep(REGISTER_WAIT);
// Remote services should have gone down by one (because of unregister
remoteServices= distributionProvider.getRemoteServices();
assertNotNull(remoteServices);
assertTrue(remoteServices.size() < remotesLength);
}
*/
}
| true | true | public void testGetAndUseIRemoteService() throws Exception {
String classname = TestServiceInterface1.class.getName();
// Setup service tracker for client
ServiceTracker st = createProxyServiceTracker(classname);
// Server - register service with required OSGI property and some test properties
Properties props = new Properties();
// *For testing purposes only* -- Set the server container id property, so that the service is not
// distributed by both the client and server (which are both running in the same process
// for junit plugin tests)
IContainer clientContainer = getClient(1);
props.put(Constants.SERVICE_CONTAINER_ID, clientContainer.getID());
// Set required OSGI property that identifies this service as a service to be remoted
props.put(SERVICE_EXPORTED_INTERFACES, new String[] {SERVICE_EXPORTED_INTERFACES_WILDCARD});
// Actually register and wait a while
ServiceRegistration registration = registerService(classname, new TestService1(),props);
Thread.sleep(REGISTER_WAIT);
// Client - Get service references from service tracker
ServiceReference [] remoteReferences = st.getServiceReferences();
assertTrue(remoteReferences != null);
assertTrue(remoteReferences.length > 0);
for(int i=0; i < remoteReferences.length; i++) {
Object o = remoteReferences[i].getProperty(SERVICE_IMPORTED);
assertNotNull(o);
assertTrue(o instanceof IRemoteService);
IRemoteService rs = (IRemoteService) o;
// Now call rs methods
IRemoteCall call = createRemoteCall(TestServiceInterface1.class);
if (call != null) {
// Call synchronously
Object result = rs.callSync(call);
Trace.trace(Activator.PLUGIN_ID, "callSync.doStuff1 result="+result);
assertNotNull(result);
assertTrue(result instanceof String);
assertTrue(TestServiceInterface1.TEST_SERVICE_STRING1.equals(result));
}
}
// Unregister on server
registration.unregister();
st.close();
Thread.sleep(REGISTER_WAIT);
}
| public void testGetAndUseIRemoteService() throws Exception {
String classname = TestServiceInterface1.class.getName();
// Setup service tracker for client
ServiceTracker st = createProxyServiceTracker(classname);
// Server - register service with required OSGI property and some test properties
Properties props = new Properties();
// *For testing purposes only* -- Set the server container id property, so that the service is not
// distributed by both the client and server (which are both running in the same process
// for junit plugin tests)
IContainer clientContainer = getClient(1);
props.put(Constants.SERVICE_CONTAINER_ID, clientContainer.getID());
// Set required OSGI property that identifies this service as a service to be remoted
props.put(SERVICE_EXPORTED_INTERFACES, new String[] {SERVICE_EXPORTED_INTERFACES_WILDCARD});
// Actually register and wait a while
ServiceRegistration registration = registerService(classname, new TestService1(),props);
Thread.sleep(REGISTER_WAIT);
// Client - Get service references from service tracker
ServiceReference [] remoteReferences = st.getServiceReferences();
assertTrue(remoteReferences != null);
assertTrue(remoteReferences.length > 0);
for(int i=0; i < remoteReferences.length; i++) {
Object o = remoteReferences[i].getProperty(SERVICE_IMPORTED);
assertNotNull(o);
assertTrue(o instanceof IRemoteService);
IRemoteService rs = (IRemoteService) o;
// Now call rs methods
IRemoteCall call = createRemoteCall();
if (call != null) {
// Call synchronously
Object result = rs.callSync(call);
Trace.trace(Activator.PLUGIN_ID, "callSync.doStuff1 result="+result);
assertNotNull(result);
assertTrue(result instanceof String);
assertTrue(TestServiceInterface1.TEST_SERVICE_STRING1.equals(result));
}
}
// Unregister on server
registration.unregister();
st.close();
Thread.sleep(REGISTER_WAIT);
}
|
diff --git a/src/com/github/inside/PowerTimer.java b/src/com/github/inside/PowerTimer.java
index d46390a..0463451 100644
--- a/src/com/github/inside/PowerTimer.java
+++ b/src/com/github/inside/PowerTimer.java
@@ -1,43 +1,43 @@
package com.github.inside;
import java.util.Map;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import com.github.inside.PaddlePower;
public class PowerTimer
{
// The parameters were set on the advice of:
// http://ria101.wordpress.com/2011/12/12/concurrenthashmap-avoid-a-common-misuse/
public static ConcurrentHashMap<String, PaddlePower> leftPaddlePowers = new ConcurrentHashMap<String, PaddlePower>(8, 0.9f, 1);
public static ConcurrentHashMap<String, PaddlePower> rightPaddlePowers = new ConcurrentHashMap<String, PaddlePower>(8, 0.9f, 1);
public static void handlePowerTimer()
{
if (PowerTimer.leftPaddlePowers.size() > 0)
{
PowerTimer.iterateOverPowers(leftPaddlePowers);
}
if (PowerTimer.rightPaddlePowers.size() > 0)
{
PowerTimer.iterateOverPowers(rightPaddlePowers);
}
}
- public static void iterateOverPowers(ConcurrentHashMap map)
+ public static void iterateOverPowers(ConcurrentHashMap<String, PaddlePower> map)
{
Iterator<Map.Entry<String, PaddlePower>> entries = map.entrySet().iterator();
while (entries.hasNext())
{
Map.Entry<String, PaddlePower> entry = entries.next();
PaddlePower power = entry.getValue();
if (power.getInitTime() + power.getLifeTime() <= Board.currentTime)
{
power.action();
map.remove(entry.getKey());
}
}
}
}
| true | true | public static void iterateOverPowers(ConcurrentHashMap map)
{
Iterator<Map.Entry<String, PaddlePower>> entries = map.entrySet().iterator();
while (entries.hasNext())
{
Map.Entry<String, PaddlePower> entry = entries.next();
PaddlePower power = entry.getValue();
if (power.getInitTime() + power.getLifeTime() <= Board.currentTime)
{
power.action();
map.remove(entry.getKey());
}
}
}
| public static void iterateOverPowers(ConcurrentHashMap<String, PaddlePower> map)
{
Iterator<Map.Entry<String, PaddlePower>> entries = map.entrySet().iterator();
while (entries.hasNext())
{
Map.Entry<String, PaddlePower> entry = entries.next();
PaddlePower power = entry.getValue();
if (power.getInitTime() + power.getLifeTime() <= Board.currentTime)
{
power.action();
map.remove(entry.getKey());
}
}
}
|
diff --git a/src/com/axelby/podax/WidgetProvider.java b/src/com/axelby/podax/WidgetProvider.java
index aa976c8..ab3a861 100644
--- a/src/com/axelby/podax/WidgetProvider.java
+++ b/src/com/axelby/podax/WidgetProvider.java
@@ -1,61 +1,61 @@
package com.axelby.podax;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
public class WidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Log.d("Podax", "widget onUpdate");
updateWidget(context);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
public static void updateWidget(Context context) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] ids = appWidgetManager.getAppWidgetIds(new ComponentName(context, "com.axelby.podax.WidgetProvider"));
if (ids.length == 0)
return;
boolean isPlaying = PlayerService.isPlaying();
- RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
+ RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.smallwidget);
Podcast p = PlayerService.getActivePodcast(context);
if (p == null) {
views.setTextViewText(R.id.title, "Queue empty");
views.setTextViewText(R.id.podcast, "");
views.setTextViewText(R.id.positionstring, "");
views.setImageViewResource(R.id.play_btn, android.R.drawable.ic_media_play);
views.setOnClickPendingIntent(R.id.play_btn, null);
views.setOnClickPendingIntent(R.id.show_btn, null);
} else {
views.setTextViewText(R.id.title, p.getTitle());
views.setTextViewText(R.id.podcast, p.getSubscription().getDisplayTitle());
views.setTextViewText(R.id.positionstring, PlayerService.getPositionString(p.getDuration(), p.getLastPosition()));
int imageRes = isPlaying ? android.R.drawable.ic_media_pause : android.R.drawable.ic_media_play;
views.setImageViewResource(R.id.play_btn, imageRes);
// set up pending intents
Intent playIntent = new Intent(context, PlayerService.class);
playIntent.putExtra(Constants.EXTRA_PLAYER_COMMAND, Constants.PLAYER_COMMAND_PLAYPAUSE);
PendingIntent playPendingIntent = PendingIntent.getService(context, 0, playIntent, 0);
views.setOnClickPendingIntent(R.id.play_btn, playPendingIntent);
Intent showIntent = new Intent(context, PodcastDetailActivity.class);
PendingIntent showPendingIntent = PendingIntent.getActivity(context, 0, showIntent, 0);
views.setOnClickPendingIntent(R.id.show_btn, showPendingIntent);
}
appWidgetManager.updateAppWidget(new ComponentName(context, "com.axelby.podax.WidgetProvider"), views);
}
}
| true | true | public static void updateWidget(Context context) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] ids = appWidgetManager.getAppWidgetIds(new ComponentName(context, "com.axelby.podax.WidgetProvider"));
if (ids.length == 0)
return;
boolean isPlaying = PlayerService.isPlaying();
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
Podcast p = PlayerService.getActivePodcast(context);
if (p == null) {
views.setTextViewText(R.id.title, "Queue empty");
views.setTextViewText(R.id.podcast, "");
views.setTextViewText(R.id.positionstring, "");
views.setImageViewResource(R.id.play_btn, android.R.drawable.ic_media_play);
views.setOnClickPendingIntent(R.id.play_btn, null);
views.setOnClickPendingIntent(R.id.show_btn, null);
} else {
views.setTextViewText(R.id.title, p.getTitle());
views.setTextViewText(R.id.podcast, p.getSubscription().getDisplayTitle());
views.setTextViewText(R.id.positionstring, PlayerService.getPositionString(p.getDuration(), p.getLastPosition()));
int imageRes = isPlaying ? android.R.drawable.ic_media_pause : android.R.drawable.ic_media_play;
views.setImageViewResource(R.id.play_btn, imageRes);
// set up pending intents
Intent playIntent = new Intent(context, PlayerService.class);
playIntent.putExtra(Constants.EXTRA_PLAYER_COMMAND, Constants.PLAYER_COMMAND_PLAYPAUSE);
PendingIntent playPendingIntent = PendingIntent.getService(context, 0, playIntent, 0);
views.setOnClickPendingIntent(R.id.play_btn, playPendingIntent);
Intent showIntent = new Intent(context, PodcastDetailActivity.class);
PendingIntent showPendingIntent = PendingIntent.getActivity(context, 0, showIntent, 0);
views.setOnClickPendingIntent(R.id.show_btn, showPendingIntent);
}
appWidgetManager.updateAppWidget(new ComponentName(context, "com.axelby.podax.WidgetProvider"), views);
}
| public static void updateWidget(Context context) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] ids = appWidgetManager.getAppWidgetIds(new ComponentName(context, "com.axelby.podax.WidgetProvider"));
if (ids.length == 0)
return;
boolean isPlaying = PlayerService.isPlaying();
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.smallwidget);
Podcast p = PlayerService.getActivePodcast(context);
if (p == null) {
views.setTextViewText(R.id.title, "Queue empty");
views.setTextViewText(R.id.podcast, "");
views.setTextViewText(R.id.positionstring, "");
views.setImageViewResource(R.id.play_btn, android.R.drawable.ic_media_play);
views.setOnClickPendingIntent(R.id.play_btn, null);
views.setOnClickPendingIntent(R.id.show_btn, null);
} else {
views.setTextViewText(R.id.title, p.getTitle());
views.setTextViewText(R.id.podcast, p.getSubscription().getDisplayTitle());
views.setTextViewText(R.id.positionstring, PlayerService.getPositionString(p.getDuration(), p.getLastPosition()));
int imageRes = isPlaying ? android.R.drawable.ic_media_pause : android.R.drawable.ic_media_play;
views.setImageViewResource(R.id.play_btn, imageRes);
// set up pending intents
Intent playIntent = new Intent(context, PlayerService.class);
playIntent.putExtra(Constants.EXTRA_PLAYER_COMMAND, Constants.PLAYER_COMMAND_PLAYPAUSE);
PendingIntent playPendingIntent = PendingIntent.getService(context, 0, playIntent, 0);
views.setOnClickPendingIntent(R.id.play_btn, playPendingIntent);
Intent showIntent = new Intent(context, PodcastDetailActivity.class);
PendingIntent showPendingIntent = PendingIntent.getActivity(context, 0, showIntent, 0);
views.setOnClickPendingIntent(R.id.show_btn, showPendingIntent);
}
appWidgetManager.updateAppWidget(new ComponentName(context, "com.axelby.podax.WidgetProvider"), views);
}
|
diff --git a/src/java/org/lwjgl/openal/ALC11.java b/src/java/org/lwjgl/openal/ALC11.java
index 031a1b8f..e6df2b5b 100644
--- a/src/java/org/lwjgl/openal/ALC11.java
+++ b/src/java/org/lwjgl/openal/ALC11.java
@@ -1,193 +1,193 @@
/*
* Copyright (c) 2002-2004 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.openal;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
/**
* <p>
* The ALC11 class implements features in OpenAL 1.1, specifically
* ALC methods and properties.
* </p>
*
* @author Brian Matzon <[email protected]>
* @see ALC10
* @version $Revision: 2286 $
* $Id: ALC.java 2286 2006-03-23 19:32:21 +0000 (to, 23 mar 2006) matzon $
*/
public final class ALC11 {
public static int ALC_CAPTURE_DEVICE_SPECIFIER = 0x310;
public static int ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER = 0x311;
public static int ALC_CAPTURE_SAMPLES = 0x312;
/**
* The alcCaptureOpenDevice function allows the application to connect to a capture
* device. To obtain a list of all available capture devices, use getCaptureDevices a list of all
* capture devices will be returned. Retrieving ALC_CAPTURE_DEVICE_SPECIFIER with a valid capture device specified will result
* in the name of that device being returned as a single string.
*
* If the function returns null, then no sound driver/device has been found, or the
* requested format could not be fulfilled.
* The "deviceName" argument is a string that requests a certain device or
* device configuration. If null is specified, the implementation will provide an
* implementation specific default. The "frequency" and "format" arguments specify the format that
* audio data will be presented to the application, and match the values that can be passed to
* alBufferData. The implementation is expected to convert and resample to this format on
* behalf of the application. The "buffersize" argument specifies the number of sample frames
* to buffer in the AL, for example, requesting a format of AL_FORMAT_STEREO16 and
* a buffer size of 1024 would require the AL to store up to 1024 * 4 bytes of audio data.
* Note that the implementation may use a larger buffer than requested if it needs to, but the
* implementation will set up a buffer of at least the requested size.
* Specifying a compressed or extension-supplied format may result in failure, even if the
* extension is supplied for rendering.
*
* <i>LWJGL SPECIFIC: the actual created device is managed internally in lwjgl</i>
*
* @param devicename Name of device to open for capture
* @param frequency Frequency of samples to capture
* @param format Format of samples to capture
* @param buffersize Size of buffer to capture to
* @return ALCdevice if it was possible to open a device
*/
public static ALCdevice alcCaptureOpenDevice(String devicename, int frequency, int format, int buffersize) {
long device_address = nalcCaptureOpenDevice(devicename, frequency, format, buffersize);
if(device_address != 0) {
ALCdevice device = new ALCdevice(device_address);
synchronized (ALC10.devices) {
ALC10.devices.put(new Long(device_address), device);
}
return device;
}
return null;
}
static native long nalcCaptureOpenDevice( String devicename, int frequency, int format, int buffersize);
/**
* The alcCaptureCloseDevice function allows the application to disconnect from a capture
* device.
*
* The return code will be true or false, indicating success or failure. If
* the device is null or invalid, an ALC_INVALID_DEVICE error will be generated.
* Once closed, a capture device is invalid.
* @return true if device was successfully closed
*/
public static boolean alcCaptureCloseDevice(ALCdevice device) {
boolean result = nalcCaptureCloseDevice(ALC10.getDevice(device));
synchronized (ALC10.devices) {
device.setInvalid();
ALC10.devices.remove(new Long(device.device));
}
return result;
}
static native boolean nalcCaptureCloseDevice(long device);
/**
* Once a capture device has been opened via alcCaptureOpenDevice, it is made to start
* recording audio via the alcCaptureStart entry point:
*
* Once started, the device will record audio to an internal ring buffer, the size of which was
* specified when opening the device.
* The application may query the capture device to discover how much data is currently
* available via the alcGetInteger with the ALC_CAPTURE_SAMPLES token. This will
* report the number of sample frames currently available.
*/
public static void alcCaptureStart(ALCdevice device) {
nalcCaptureStart(ALC10.getDevice(device));
}
static native void nalcCaptureStart(long device);
/**
* If the application doesn't need to capture more audio for an amount of time, they can halt
* the device without closing it via the alcCaptureStop entry point.
* The implementation is encouraged to optimize for this case. The amount of audio
* samples available after restarting a stopped capture device is reset to zero. The
* application does not need to stop the capture device to read from it.
*/
public static void alcCaptureStop(ALCdevice device) {
nalcCaptureStop(ALC10.getDevice(device));
}
static native void nalcCaptureStop(long device);
/**
* When the application feels there are enough samples available to process, it can obtain
* them from the AL via the alcCaptureSamples entry point.
*
* The "buffer" argument specifies an application-allocated buffer that can contain at least
* "samples" sample frames. The implementation may defer conversion and resampling until
* this point. Requesting more sample frames than are currently available is an error.
*
* @param buffer Buffer to store samples in
* @param samples Number of samples to request
*/
public static void alcCaptureSamples(ALCdevice device, ByteBuffer buffer, int samples ) {
nalcCaptureSamples(ALC10.getDevice(device), buffer, buffer.position(), samples);
}
static native void nalcCaptureSamples(long device, ByteBuffer buffer, int position, int samples );
static native void initNativeStubs() throws LWJGLException;
/**
* Initializes ALC11, including any extensions
* @return true if initialization was successfull
*/
static boolean initialize() {
try {
IntBuffer ib = BufferUtils.createIntBuffer(2);
ALC10.alcGetInteger(AL.getDevice(), ALC10.ALC_MAJOR_VERSION, ib);
ib.position(1);
ALC10.alcGetInteger(AL.getDevice(), ALC10.ALC_MINOR_VERSION, ib);
int major = ib.get(0);
int minor = ib.get(1);
// checking for version 1.x+
if(major >= 1) {
// checking for version 1.1+
- if(minor >= 1) {
+ if(major > 1 || minor >= 1) {
initNativeStubs();
}
}
} catch (LWJGLException le) {
LWJGLUtil.log("failed to initialize ALC11: " + le);
return false;
}
return true;
}
}
| true | true | static boolean initialize() {
try {
IntBuffer ib = BufferUtils.createIntBuffer(2);
ALC10.alcGetInteger(AL.getDevice(), ALC10.ALC_MAJOR_VERSION, ib);
ib.position(1);
ALC10.alcGetInteger(AL.getDevice(), ALC10.ALC_MINOR_VERSION, ib);
int major = ib.get(0);
int minor = ib.get(1);
// checking for version 1.x+
if(major >= 1) {
// checking for version 1.1+
if(minor >= 1) {
initNativeStubs();
}
}
} catch (LWJGLException le) {
LWJGLUtil.log("failed to initialize ALC11: " + le);
return false;
}
return true;
}
| static boolean initialize() {
try {
IntBuffer ib = BufferUtils.createIntBuffer(2);
ALC10.alcGetInteger(AL.getDevice(), ALC10.ALC_MAJOR_VERSION, ib);
ib.position(1);
ALC10.alcGetInteger(AL.getDevice(), ALC10.ALC_MINOR_VERSION, ib);
int major = ib.get(0);
int minor = ib.get(1);
// checking for version 1.x+
if(major >= 1) {
// checking for version 1.1+
if(major > 1 || minor >= 1) {
initNativeStubs();
}
}
} catch (LWJGLException le) {
LWJGLUtil.log("failed to initialize ALC11: " + le);
return false;
}
return true;
}
|
diff --git a/SettleExpenses/src/com/app/settleexpenses/SplashScreen.java b/SettleExpenses/src/com/app/settleexpenses/SplashScreen.java
index 1ebabdd..2562002 100644
--- a/SettleExpenses/src/com/app/settleexpenses/SplashScreen.java
+++ b/SettleExpenses/src/com/app/settleexpenses/SplashScreen.java
@@ -1,35 +1,31 @@
package com.app.settleexpenses;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class SplashScreen extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread splashThread = new Thread() {
@Override
public void run() {
try {
- int waited = 0;
- while (waited < 5000) {
- sleep(100);
- waited += 100;
- }
+ sleep(3000);
} catch (InterruptedException e) {
// do nothing
} finally {
finish();
Intent i = new Intent();
i.setClassName("com.app.settleexpenses",
"com.app.settleexpenses.SettleExpenses");
startActivity(i);
}
}
};
splashThread.start();
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread splashThread = new Thread() {
@Override
public void run() {
try {
int waited = 0;
while (waited < 5000) {
sleep(100);
waited += 100;
}
} catch (InterruptedException e) {
// do nothing
} finally {
finish();
Intent i = new Intent();
i.setClassName("com.app.settleexpenses",
"com.app.settleexpenses.SettleExpenses");
startActivity(i);
}
}
};
splashThread.start();
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread splashThread = new Thread() {
@Override
public void run() {
try {
sleep(3000);
} catch (InterruptedException e) {
// do nothing
} finally {
finish();
Intent i = new Intent();
i.setClassName("com.app.settleexpenses",
"com.app.settleexpenses.SettleExpenses");
startActivity(i);
}
}
};
splashThread.start();
}
|
diff --git a/polly.core/src/commands/QuitCommand.java b/polly.core/src/commands/QuitCommand.java
index b474772d..20a38afc 100644
--- a/polly.core/src/commands/QuitCommand.java
+++ b/polly.core/src/commands/QuitCommand.java
@@ -1,75 +1,75 @@
package commands;
import polly.core.MyPlugin;
import de.skuzzle.polly.sdk.Command;
import de.skuzzle.polly.sdk.Conversation;
import de.skuzzle.polly.sdk.MyPolly;
import de.skuzzle.polly.sdk.Parameter;
import de.skuzzle.polly.sdk.Signature;
import de.skuzzle.polly.sdk.Types;
import de.skuzzle.polly.sdk.UserManager;
import de.skuzzle.polly.sdk.exceptions.CommandException;
import de.skuzzle.polly.sdk.exceptions.DuplicatedSignatureException;
import de.skuzzle.polly.sdk.model.User;
/**
*
* @author Simon
* @version 27.07.2011 3851c1b
*/
public class QuitCommand extends Command {
private final static String[] answers = {"ja", "yo", "jup", "yes", "jo", "ack"};
public QuitCommand(MyPolly polly) throws DuplicatedSignatureException {
super(polly, "flyaway");
this.createSignature("Beendet polly.", MyPlugin.QUIT_PERMISSION);
this.createSignature("Beendet polly mit der angegebenen Quit-Message",
MyPlugin.QUIT_PERMISSION,
new Parameter("Quit-Message", Types.STRING));
this.setRegisteredOnly();
this.setUserLevel(UserManager.ADMIN);
this.setHelpText("Befehl zum Beenden von Polly.");
}
@Override
protected boolean executeOnBoth(User executer, String channel,
Signature signature) throws CommandException {
String message = "*kr�chz* *kr�chz* *kr�chz*";
if (this.match(signature, 1)) {
message = signature.getStringValue(0);
}
Conversation c = null;
try {
c = this.createConversation(executer, channel);
- c.writeLine("Yo' seroius?");
+ c.writeLine("Yo' serious?");
String a = c.readLine().getMessage();
for (String ans : answers) {
if (a.equals(ans)) {
this.getMyPolly().irc().quit(message);
this.getMyPolly().shutdownManager().shutdown();
return false;
}
}
} catch (InterruptedException e) {
throw new CommandException("Answer timeout");
} catch (Exception e) {
throw new CommandException(e);
} finally {
if (c != null) {
c.close();
}
}
return false;
}
}
| true | true | protected boolean executeOnBoth(User executer, String channel,
Signature signature) throws CommandException {
String message = "*kr�chz* *kr�chz* *kr�chz*";
if (this.match(signature, 1)) {
message = signature.getStringValue(0);
}
Conversation c = null;
try {
c = this.createConversation(executer, channel);
c.writeLine("Yo' seroius?");
String a = c.readLine().getMessage();
for (String ans : answers) {
if (a.equals(ans)) {
this.getMyPolly().irc().quit(message);
this.getMyPolly().shutdownManager().shutdown();
return false;
}
}
} catch (InterruptedException e) {
throw new CommandException("Answer timeout");
} catch (Exception e) {
throw new CommandException(e);
} finally {
if (c != null) {
c.close();
}
}
return false;
}
| protected boolean executeOnBoth(User executer, String channel,
Signature signature) throws CommandException {
String message = "*kr�chz* *kr�chz* *kr�chz*";
if (this.match(signature, 1)) {
message = signature.getStringValue(0);
}
Conversation c = null;
try {
c = this.createConversation(executer, channel);
c.writeLine("Yo' serious?");
String a = c.readLine().getMessage();
for (String ans : answers) {
if (a.equals(ans)) {
this.getMyPolly().irc().quit(message);
this.getMyPolly().shutdownManager().shutdown();
return false;
}
}
} catch (InterruptedException e) {
throw new CommandException("Answer timeout");
} catch (Exception e) {
throw new CommandException(e);
} finally {
if (c != null) {
c.close();
}
}
return false;
}
|
diff --git a/git-tests/src/jetbrains/buildServer/buildTriggers/vcs/git/tests/CleanerTest.java b/git-tests/src/jetbrains/buildServer/buildTriggers/vcs/git/tests/CleanerTest.java
index ce3e2d7..7655c03 100644
--- a/git-tests/src/jetbrains/buildServer/buildTriggers/vcs/git/tests/CleanerTest.java
+++ b/git-tests/src/jetbrains/buildServer/buildTriggers/vcs/git/tests/CleanerTest.java
@@ -1,142 +1,142 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.buildTriggers.vcs.git.tests;
import jetbrains.buildServer.TempFiles;
import jetbrains.buildServer.TestLogger;
import jetbrains.buildServer.buildTriggers.vcs.git.*;
import jetbrains.buildServer.serverSide.BuildServerListener;
import jetbrains.buildServer.serverSide.SBuildServer;
import jetbrains.buildServer.serverSide.ServerPaths;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.vcs.SVcsRoot;
import jetbrains.buildServer.vcs.VcsException;
import jetbrains.buildServer.vcs.VcsManager;
import jetbrains.buildServer.vcs.VcsRoot;
import jetbrains.buildServer.vcs.impl.VcsRootImpl;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import jetbrains.buildServer.BaseTestCase;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static jetbrains.buildServer.buildTriggers.vcs.git.tests.GitTestUtil.dataFile;
import static org.testng.AssertJUnit.assertEquals;
/**
* @author dmitry.neverov
*/
public class CleanerTest extends BaseTestCase {
private static final TempFiles ourTempFiles = new TempFiles();
private ServerPaths myServerPaths;
private Cleaner myCleaner;
private ScheduledExecutorService myCleanExecutor;
private VcsManager myVcsManager;
private Mockery myContext;
@BeforeMethod
public void setUp() throws IOException {
File dotBuildServer = ourTempFiles.createTempDir();
myServerPaths = new ServerPaths(dotBuildServer.getAbsolutePath(), dotBuildServer.getAbsolutePath(), dotBuildServer.getAbsolutePath());
myCleanExecutor = Executors.newSingleThreadScheduledExecutor();
myContext = new Mockery();
final SBuildServer server = myContext.mock(SBuildServer.class);
myVcsManager = myContext.mock(VcsManager.class);
myContext.checking(new Expectations() {{
allowing(server).getExecutor(); will(returnValue(myCleanExecutor));
allowing(server).getVcsManager(); will(returnValue(myVcsManager));
}});
GitVcsSupport gitSupport = new GitVcsSupport(myServerPaths, null);
myCleaner = new Cleaner(server, EventDispatcher.create(BuildServerListener.class), myServerPaths, gitSupport);
}
@AfterMethod
public void tearDown() {
ourTempFiles.cleanup();
}
@Test
public void test_clean() throws VcsException, InterruptedException {
- System.setProperty("teamcity.server.git.gc.enabled ", String.valueOf(true));
+ System.setProperty("teamcity.server.git.gc.enabled", String.valueOf(true));
if (System.getenv(Constants.GIT_PATH_ENV) != null)
System.setProperty("teamcity.server.git.executable.path", System.getenv(Constants.GIT_PATH_ENV));
final VcsRoot root = getVcsRoot();
GitVcsSupport vcsSupport = new GitVcsSupport(myServerPaths, null);
vcsSupport.getCurrentVersion(root);//it will create dir in cache directory
File repositoryDir = getRepositoryDir(root);
File gitCacheDir = new File(myServerPaths.getCachesDir(), "git");
generateGarbage(gitCacheDir);
final SVcsRoot usedRoot = createSVcsRootFor(root);
myContext.checking(new Expectations() {{
allowing(myVcsManager).findRootsByVcsName(Constants.VCS_NAME); will(returnValue(Collections.singleton(usedRoot)));
}});
invokeClean();
File[] files = gitCacheDir.listFiles();
assertEquals(1, files.length);
assertEquals(repositoryDir, files[0]);
vcsSupport.getCurrentVersion(root);//check that repository is fine after git gc
}
private void invokeClean() throws InterruptedException {
myCleaner.cleanupStarted();
myCleanExecutor.shutdown();
myCleanExecutor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
}
private File getRepositoryDir(VcsRoot root) throws VcsException {
Settings settings = new Settings(root);
settings.setCachesDirectory(myServerPaths.getCachesDir());
return settings.getRepositoryPath();
}
private void generateGarbage(File dir) {
for (int i = 0; i < 10; i++) {
new File(dir, "git-AHAHAHA"+i+".git").mkdir();
}
}
private VcsRoot getVcsRoot() {
VcsRootImpl root = new VcsRootImpl(1, Constants.VCS_NAME);
root.addProperty(Constants.FETCH_URL, GitUtils.toURL(dataFile("repo.git")));
root.addProperty(Constants.BRANCH_NAME, "master");
return root;
}
private SVcsRoot createSVcsRootFor(final VcsRoot root) {
final SVcsRoot result = myContext.mock(SVcsRoot.class);
myContext.checking(new Expectations() {{
allowing(myVcsManager).findRootsByVcsName(Constants.VCS_NAME); will(returnValue(Collections.singleton(result)));
allowing(result).getProperty(Constants.PATH); will(returnValue(root.getProperty(Constants.PATH)));
allowing(result).getProperty(Constants.AUTH_METHOD); will(returnValue(root.getProperty(Constants.AUTH_METHOD)));
allowing(result).getProperty(Constants.FETCH_URL); will(returnValue(root.getProperty(Constants.FETCH_URL)));
}});
return result;
}
}
| true | true | public void test_clean() throws VcsException, InterruptedException {
System.setProperty("teamcity.server.git.gc.enabled ", String.valueOf(true));
if (System.getenv(Constants.GIT_PATH_ENV) != null)
System.setProperty("teamcity.server.git.executable.path", System.getenv(Constants.GIT_PATH_ENV));
final VcsRoot root = getVcsRoot();
GitVcsSupport vcsSupport = new GitVcsSupport(myServerPaths, null);
vcsSupport.getCurrentVersion(root);//it will create dir in cache directory
File repositoryDir = getRepositoryDir(root);
File gitCacheDir = new File(myServerPaths.getCachesDir(), "git");
generateGarbage(gitCacheDir);
final SVcsRoot usedRoot = createSVcsRootFor(root);
myContext.checking(new Expectations() {{
allowing(myVcsManager).findRootsByVcsName(Constants.VCS_NAME); will(returnValue(Collections.singleton(usedRoot)));
}});
invokeClean();
File[] files = gitCacheDir.listFiles();
assertEquals(1, files.length);
assertEquals(repositoryDir, files[0]);
vcsSupport.getCurrentVersion(root);//check that repository is fine after git gc
}
| public void test_clean() throws VcsException, InterruptedException {
System.setProperty("teamcity.server.git.gc.enabled", String.valueOf(true));
if (System.getenv(Constants.GIT_PATH_ENV) != null)
System.setProperty("teamcity.server.git.executable.path", System.getenv(Constants.GIT_PATH_ENV));
final VcsRoot root = getVcsRoot();
GitVcsSupport vcsSupport = new GitVcsSupport(myServerPaths, null);
vcsSupport.getCurrentVersion(root);//it will create dir in cache directory
File repositoryDir = getRepositoryDir(root);
File gitCacheDir = new File(myServerPaths.getCachesDir(), "git");
generateGarbage(gitCacheDir);
final SVcsRoot usedRoot = createSVcsRootFor(root);
myContext.checking(new Expectations() {{
allowing(myVcsManager).findRootsByVcsName(Constants.VCS_NAME); will(returnValue(Collections.singleton(usedRoot)));
}});
invokeClean();
File[] files = gitCacheDir.listFiles();
assertEquals(1, files.length);
assertEquals(repositoryDir, files[0]);
vcsSupport.getCurrentVersion(root);//check that repository is fine after git gc
}
|
diff --git a/src/org/mozilla/javascript/regexp/SubString.java b/src/org/mozilla/javascript/regexp/SubString.java
index b5383c9f..4fdecb40 100644
--- a/src/org/mozilla/javascript/regexp/SubString.java
+++ b/src/org/mozilla/javascript/regexp/SubString.java
@@ -1,76 +1,75 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript.regexp;
class SubString {
public SubString()
{
}
public SubString(String str)
{
index = 0;
charArray = str.toCharArray();
length = str.length();
}
public SubString(char[] source, int start, int len)
{
- // there must be a better way of doing this??
index = 0;
length = len;
charArray = new char[len];
- for (int j = 0; j < len; j++)
- charArray[j] = source[start + j];
+ // is this copy needed?
+ System.arraycopy(source, start, charArray, 0, len);
}
@Override
public String toString() {
return charArray == null
? ""
: new String(charArray, index, length);
}
static final SubString emptySubString = new SubString();
char[] charArray;
int index;
int length;
}
| false | true | public SubString(char[] source, int start, int len)
{
// there must be a better way of doing this??
index = 0;
length = len;
charArray = new char[len];
for (int j = 0; j < len; j++)
charArray[j] = source[start + j];
}
| public SubString(char[] source, int start, int len)
{
index = 0;
length = len;
charArray = new char[len];
// is this copy needed?
System.arraycopy(source, start, charArray, 0, len);
}
|
diff --git a/fog/src/de/tuilmenau/ics/fog/util/BlockingEventHandling.java b/fog/src/de/tuilmenau/ics/fog/util/BlockingEventHandling.java
index 3812aa21..f0555020 100644
--- a/fog/src/de/tuilmenau/ics/fog/util/BlockingEventHandling.java
+++ b/fog/src/de/tuilmenau/ics/fog/util/BlockingEventHandling.java
@@ -1,94 +1,94 @@
/*******************************************************************************
* Forwarding on Gates Simulator/Emulator
* Copyright (C) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* This program and the accompanying materials are dual-licensed under either
* the terms of the Eclipse Public License v1.0 as published by the Eclipse
* Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
******************************************************************************/
package de.tuilmenau.ics.fog.util;
import java.util.LinkedList;
import de.tuilmenau.ics.fog.facade.EventSource;
import de.tuilmenau.ics.fog.facade.NetworkException;
import de.tuilmenau.ics.fog.facade.EventSource.EventListener;
import de.tuilmenau.ics.fog.facade.events.Event;
import de.tuilmenau.ics.fog.ui.Logging;
public class BlockingEventHandling implements EventListener
{
public BlockingEventHandling(EventSource source, int numberEvents)
{
this.source = source;
this.numberEvents = numberEvents;
this.source.registerListener(this);
}
@Override
public synchronized void eventOccured(Event event) throws Exception
{
if((firstEvent == null) && (events != null)) {
firstEvent = event;
} else {
if(events == null) events = new LinkedList<Event>();
events.addLast(event);
}
numberEvents--;
if(numberEvents <= 0) {
source.unregisterListener(this);
}
notify();
}
public synchronized Event waitForEvent()
{
return waitForEvent(0);
}
public synchronized Event waitForEvent(double pTimeout)
{
Event res = null;
boolean tInterrupted = false;
int tAttempt = 0;
do {
if(firstEvent != null) {
res = firstEvent;
firstEvent = null;
} else {
if(events != null) {
if(!events.isEmpty()) {
res = events.removeFirst();
}
}
}
if(res == null) {
Logging.getInstance().log(this, "Waiting for event for " + pTimeout + " s - attempt " + tAttempt);
try {
wait((long)(pTimeout * 1000));
} catch (InterruptedException exc) {
tInterrupted = true;
}
}
tAttempt++;
}
- while((res == null) && (!tInterrupted));
+ while((res == null) && (!tInterrupted) && (tAttempt < 2));
return res;
}
private EventSource source;
private Event firstEvent;
private LinkedList<Event> events;
private int numberEvents;
}
| true | true | public synchronized Event waitForEvent(double pTimeout)
{
Event res = null;
boolean tInterrupted = false;
int tAttempt = 0;
do {
if(firstEvent != null) {
res = firstEvent;
firstEvent = null;
} else {
if(events != null) {
if(!events.isEmpty()) {
res = events.removeFirst();
}
}
}
if(res == null) {
Logging.getInstance().log(this, "Waiting for event for " + pTimeout + " s - attempt " + tAttempt);
try {
wait((long)(pTimeout * 1000));
} catch (InterruptedException exc) {
tInterrupted = true;
}
}
tAttempt++;
}
while((res == null) && (!tInterrupted));
return res;
}
| public synchronized Event waitForEvent(double pTimeout)
{
Event res = null;
boolean tInterrupted = false;
int tAttempt = 0;
do {
if(firstEvent != null) {
res = firstEvent;
firstEvent = null;
} else {
if(events != null) {
if(!events.isEmpty()) {
res = events.removeFirst();
}
}
}
if(res == null) {
Logging.getInstance().log(this, "Waiting for event for " + pTimeout + " s - attempt " + tAttempt);
try {
wait((long)(pTimeout * 1000));
} catch (InterruptedException exc) {
tInterrupted = true;
}
}
tAttempt++;
}
while((res == null) && (!tInterrupted) && (tAttempt < 2));
return res;
}
|
diff --git a/src/se/kth/maandree/utilsay/Program.java b/src/se/kth/maandree/utilsay/Program.java
index 8c8e024..6f39ade 100644
--- a/src/se/kth/maandree/utilsay/Program.java
+++ b/src/se/kth/maandree/utilsay/Program.java
@@ -1,134 +1,133 @@
/**
* util-say — Utilities for cowsay and cowsay-like programs
*
* Copyright © 2012, 2013 Mattias Andrée ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package se.kth.maandree.utilsay;
import java.io.*;
import java.util.*;
/**
* Program selector for util-say
*
* @author Mattias Andrée, <a href="mailto:[email protected]">[email protected]</a>
*/
public class Program
{
/**
* Non-constructor
*/
private Program()
{
assert false : "This class [Program] is not meant to be instansiated.";
}
/**
* This is the main entry point of the program
*
* @param args Startup arguments
*
* @throws IOException On I/O exception
*/
public static void main(final String... args) throws IOException
{
if ((args.length == 0) || ((args.length == 1) && args[0].equals("--help")))
{
System.out.println("Copyright (C) 2012, 2013 Mattias Andrée <[email protected]>");
System.out.println();
- System.out.println("You can use --list to get a list of all programs");
- System.out.println("USAGE: util-say [--help | PROGRAM ARGUMENTS...]");
+ System.out.println("USAGE: ponytool --import module [param*] {--export module [param*]}");
System.out.println();
System.out.println();
System.out.println("This program is free software: you can redistribute it and/or modify");
System.out.println("it under the terms of the GNU General Public License as published by");
System.out.println("the Free Software Foundation, either version 3 of the License, or");
System.out.println("(at your option) any later version.");
System.out.println();
System.out.println("This program is distributed in the hope that it will be useful,");
System.out.println("but WITHOUT ANY WARRANTY; without even the implied warranty of");
System.out.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the");
System.out.println("GNU General Public License for more details.");
System.out.println();
System.out.println("You should have received a copy of the GNU General Public License");
System.out.println("along with this program. If not, see <http://www.gnu.org/licenses/>.");
System.out.println();
System.out.println();
return;
}
HashMap<String, String> params = new HashMap<String, String>();
String pname = null;
HashMap<String, String> inparams = null;
String intype = null;
final ArrayList<HashMap<String, String>> outparams = new ArrayList<HashMap<String, String>>();
final ArrayList<String> outtypes = new ArrayList<String>();
for (final String arg : args)
if (arg.equals("--in") || arg.equals("--import") || arg.equals("--out") || arg.equals("--export"))
{ if (pname != null)
params.put(pname, "yes");
pname = arg.intern();
}
else if ((pname == "--in") || (pname == "--import"))
{ inparams = params = new HashMap<String, String>();
intype = arg.toLowerCase().intern();
pname = null;
}
else if ((pname == "--out") || (pname == "--export"))
{ outparams.add(params = new HashMap<String, String>());
outtypes.add(arg.toLowerCase().intern());
pname = null;
}
else if (arg.startsWith("--") || (pname == null))
{ if (pname != null)
params.put(pname, "yes");
int eq = arg.indexOf("=");
if (eq < 0)
pname = arg.replace("-", "");
else
{ pname = null;
params.put(arg.substring(0, eq).replace("-", ""), arg.substring(eq + 1));
} }
else
{ params.put(pname, arg);
pname = null;
}
Pony pony = null;
if (intype == "ponysay") pony = (new Ponysay(inparams)).importPony();
else if (intype == "unisay") pony = (new Unisay (inparams)).importPony();
else if (intype == "cowsay") pony = (new Cowsay (inparams)).importPony();
else if (intype == "image") pony = (new Image (inparams)).importPony();
else if (intype == "test") pony = (new Test (inparams)).importPony();
//TODO add warning
for (int i = 0, n = outtypes.size(); i < n; i++)
{ final String outtype = outtypes.get(i);
params = outparams.get(i);
if (outtype == "ponysay") (new Ponysay(params)).exportPony(pony);
else if (outtype == "unisay") (new Unisay (params)).exportPony(pony);
else if (outtype == "cowsay") (new Cowsay (params)).exportPony(pony);
else if (outtype == "image") (new Image (params)).exportPony(pony);
else if (outtype == "test") (new Test (params)).exportPony(pony);
//TODO add warning
}
}
}
| true | true | public static void main(final String... args) throws IOException
{
if ((args.length == 0) || ((args.length == 1) && args[0].equals("--help")))
{
System.out.println("Copyright (C) 2012, 2013 Mattias Andrée <[email protected]>");
System.out.println();
System.out.println("You can use --list to get a list of all programs");
System.out.println("USAGE: util-say [--help | PROGRAM ARGUMENTS...]");
System.out.println();
System.out.println();
System.out.println("This program is free software: you can redistribute it and/or modify");
System.out.println("it under the terms of the GNU General Public License as published by");
System.out.println("the Free Software Foundation, either version 3 of the License, or");
System.out.println("(at your option) any later version.");
System.out.println();
System.out.println("This program is distributed in the hope that it will be useful,");
System.out.println("but WITHOUT ANY WARRANTY; without even the implied warranty of");
System.out.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the");
System.out.println("GNU General Public License for more details.");
System.out.println();
System.out.println("You should have received a copy of the GNU General Public License");
System.out.println("along with this program. If not, see <http://www.gnu.org/licenses/>.");
System.out.println();
System.out.println();
return;
}
HashMap<String, String> params = new HashMap<String, String>();
String pname = null;
HashMap<String, String> inparams = null;
String intype = null;
final ArrayList<HashMap<String, String>> outparams = new ArrayList<HashMap<String, String>>();
final ArrayList<String> outtypes = new ArrayList<String>();
for (final String arg : args)
if (arg.equals("--in") || arg.equals("--import") || arg.equals("--out") || arg.equals("--export"))
{ if (pname != null)
params.put(pname, "yes");
pname = arg.intern();
}
else if ((pname == "--in") || (pname == "--import"))
{ inparams = params = new HashMap<String, String>();
intype = arg.toLowerCase().intern();
pname = null;
}
else if ((pname == "--out") || (pname == "--export"))
{ outparams.add(params = new HashMap<String, String>());
outtypes.add(arg.toLowerCase().intern());
pname = null;
}
else if (arg.startsWith("--") || (pname == null))
{ if (pname != null)
params.put(pname, "yes");
int eq = arg.indexOf("=");
if (eq < 0)
pname = arg.replace("-", "");
else
{ pname = null;
params.put(arg.substring(0, eq).replace("-", ""), arg.substring(eq + 1));
} }
else
{ params.put(pname, arg);
pname = null;
}
Pony pony = null;
if (intype == "ponysay") pony = (new Ponysay(inparams)).importPony();
else if (intype == "unisay") pony = (new Unisay (inparams)).importPony();
else if (intype == "cowsay") pony = (new Cowsay (inparams)).importPony();
else if (intype == "image") pony = (new Image (inparams)).importPony();
else if (intype == "test") pony = (new Test (inparams)).importPony();
//TODO add warning
for (int i = 0, n = outtypes.size(); i < n; i++)
{ final String outtype = outtypes.get(i);
params = outparams.get(i);
if (outtype == "ponysay") (new Ponysay(params)).exportPony(pony);
else if (outtype == "unisay") (new Unisay (params)).exportPony(pony);
else if (outtype == "cowsay") (new Cowsay (params)).exportPony(pony);
else if (outtype == "image") (new Image (params)).exportPony(pony);
else if (outtype == "test") (new Test (params)).exportPony(pony);
//TODO add warning
}
}
| public static void main(final String... args) throws IOException
{
if ((args.length == 0) || ((args.length == 1) && args[0].equals("--help")))
{
System.out.println("Copyright (C) 2012, 2013 Mattias Andrée <[email protected]>");
System.out.println();
System.out.println("USAGE: ponytool --import module [param*] {--export module [param*]}");
System.out.println();
System.out.println();
System.out.println("This program is free software: you can redistribute it and/or modify");
System.out.println("it under the terms of the GNU General Public License as published by");
System.out.println("the Free Software Foundation, either version 3 of the License, or");
System.out.println("(at your option) any later version.");
System.out.println();
System.out.println("This program is distributed in the hope that it will be useful,");
System.out.println("but WITHOUT ANY WARRANTY; without even the implied warranty of");
System.out.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the");
System.out.println("GNU General Public License for more details.");
System.out.println();
System.out.println("You should have received a copy of the GNU General Public License");
System.out.println("along with this program. If not, see <http://www.gnu.org/licenses/>.");
System.out.println();
System.out.println();
return;
}
HashMap<String, String> params = new HashMap<String, String>();
String pname = null;
HashMap<String, String> inparams = null;
String intype = null;
final ArrayList<HashMap<String, String>> outparams = new ArrayList<HashMap<String, String>>();
final ArrayList<String> outtypes = new ArrayList<String>();
for (final String arg : args)
if (arg.equals("--in") || arg.equals("--import") || arg.equals("--out") || arg.equals("--export"))
{ if (pname != null)
params.put(pname, "yes");
pname = arg.intern();
}
else if ((pname == "--in") || (pname == "--import"))
{ inparams = params = new HashMap<String, String>();
intype = arg.toLowerCase().intern();
pname = null;
}
else if ((pname == "--out") || (pname == "--export"))
{ outparams.add(params = new HashMap<String, String>());
outtypes.add(arg.toLowerCase().intern());
pname = null;
}
else if (arg.startsWith("--") || (pname == null))
{ if (pname != null)
params.put(pname, "yes");
int eq = arg.indexOf("=");
if (eq < 0)
pname = arg.replace("-", "");
else
{ pname = null;
params.put(arg.substring(0, eq).replace("-", ""), arg.substring(eq + 1));
} }
else
{ params.put(pname, arg);
pname = null;
}
Pony pony = null;
if (intype == "ponysay") pony = (new Ponysay(inparams)).importPony();
else if (intype == "unisay") pony = (new Unisay (inparams)).importPony();
else if (intype == "cowsay") pony = (new Cowsay (inparams)).importPony();
else if (intype == "image") pony = (new Image (inparams)).importPony();
else if (intype == "test") pony = (new Test (inparams)).importPony();
//TODO add warning
for (int i = 0, n = outtypes.size(); i < n; i++)
{ final String outtype = outtypes.get(i);
params = outparams.get(i);
if (outtype == "ponysay") (new Ponysay(params)).exportPony(pony);
else if (outtype == "unisay") (new Unisay (params)).exportPony(pony);
else if (outtype == "cowsay") (new Cowsay (params)).exportPony(pony);
else if (outtype == "image") (new Image (params)).exportPony(pony);
else if (outtype == "test") (new Test (params)).exportPony(pony);
//TODO add warning
}
}
|
diff --git a/mini2Dx-uats/src/main/java/org/mini2Dx/uats/common/TiledMapUAT.java b/mini2Dx-uats/src/main/java/org/mini2Dx/uats/common/TiledMapUAT.java
index e5c1a8601..054f926ac 100644
--- a/mini2Dx-uats/src/main/java/org/mini2Dx/uats/common/TiledMapUAT.java
+++ b/mini2Dx-uats/src/main/java/org/mini2Dx/uats/common/TiledMapUAT.java
@@ -1,76 +1,76 @@
/**
* Copyright (c) 2013, mini2Dx Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.mini2Dx.uats.common;
import java.io.IOException;
import org.mini2Dx.core.game.GameContainer;
import org.mini2Dx.core.game.Mini2DxGame;
import org.mini2Dx.core.graphics.Graphics;
import org.mini2Dx.tiled.TiledMap;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.graphics.Color;
/**
* A {@link GameContainer} that allows visual user acceptance testing of
* {@link TiledMap} rendering
*
* @author Thomas Cashman
*/
public class TiledMapUAT extends GameContainer {
private TiledMap tiledMap;
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void initialise() {
try {
tiledMap = new TiledMap(Gdx.files.classpath("simple.tmx"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void update(float delta) {
}
@Override
public void render(Graphics g) {
g.setBackgroundColor(Color.WHITE);
g.setColor(Color.RED);
tiledMap.draw(g, 0, 0);
tiledMap.getTilesets().get(0).drawTileset(g, tiledMap.getWidth() * tiledMap.getTileWidth() + 32, 0);
}
public static void main(String[] args) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
- cfg.title = "mini2Dx - Graphics Verification Test";
+ cfg.title = "mini2Dx - TiledMap Verification Test";
cfg.useGL20 = true;
cfg.width = 800;
cfg.height = 600;
cfg.useCPUSynch = false;
cfg.vSyncEnabled = true;
new LwjglApplication(new Mini2DxGame(new TiledMapUAT()), cfg);
}
}
| true | true | public static void main(String[] args) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "mini2Dx - Graphics Verification Test";
cfg.useGL20 = true;
cfg.width = 800;
cfg.height = 600;
cfg.useCPUSynch = false;
cfg.vSyncEnabled = true;
new LwjglApplication(new Mini2DxGame(new TiledMapUAT()), cfg);
}
| public static void main(String[] args) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "mini2Dx - TiledMap Verification Test";
cfg.useGL20 = true;
cfg.width = 800;
cfg.height = 600;
cfg.useCPUSynch = false;
cfg.vSyncEnabled = true;
new LwjglApplication(new Mini2DxGame(new TiledMapUAT()), cfg);
}
|
diff --git a/maven-scm-providers/maven-scm-provider-clearcase/src/main/java/org/apache/maven/scm/provider/clearcase/command/checkout/ClearCaseCheckOutCommand.java b/maven-scm-providers/maven-scm-provider-clearcase/src/main/java/org/apache/maven/scm/provider/clearcase/command/checkout/ClearCaseCheckOutCommand.java
index fbc8b52f..96c52985 100644
--- a/maven-scm-providers/maven-scm-provider-clearcase/src/main/java/org/apache/maven/scm/provider/clearcase/command/checkout/ClearCaseCheckOutCommand.java
+++ b/maven-scm-providers/maven-scm-provider-clearcase/src/main/java/org/apache/maven/scm/provider/clearcase/command/checkout/ClearCaseCheckOutCommand.java
@@ -1,391 +1,394 @@
package org.apache.maven.scm.provider.clearcase.command.checkout;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.ScmVersion;
import org.apache.maven.scm.command.checkout.AbstractCheckOutCommand;
import org.apache.maven.scm.command.checkout.CheckOutScmResult;
import org.apache.maven.scm.provider.ScmProviderRepository;
import org.apache.maven.scm.provider.clearcase.command.ClearCaseCommand;
import org.apache.maven.scm.provider.clearcase.repository.ClearCaseScmProviderRepository;
import org.apache.maven.scm.providers.clearcase.settings.Settings;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
/**
* @author <a href="mailto:[email protected]">Wim Deblauwe</a>
* @author <a href="mailto:[email protected]">Frederic Mura</a>
*/
public class ClearCaseCheckOutCommand
extends AbstractCheckOutCommand
implements ClearCaseCommand
{
private Settings settings = null;
// ----------------------------------------------------------------------
// AbstractCheckOutCommand Implementation
// ----------------------------------------------------------------------
protected CheckOutScmResult executeCheckOutCommand( ScmProviderRepository repository, ScmFileSet fileSet,
ScmVersion version )
throws ScmException
{
getLogger().debug( "executing checkout command..." );
ClearCaseScmProviderRepository repo = (ClearCaseScmProviderRepository) repository;
File workingDirectory = fileSet.getBasedir();
- getLogger().debug( version.getType() + ": " + version.getName() );
+ if ( version != null )
+ {
+ getLogger().debug( version.getType() + ": " + version.getName() );
+ }
getLogger().debug( "Running with CLEARCASE " + settings.getClearcaseType() );
ClearCaseCheckOutConsumer consumer = new ClearCaseCheckOutConsumer( getLogger() );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
int exitCode;
Commandline cl;
String projectDirectory = "";
try
{
// Since clearcase only wants to checkout to a non-existent directory, first delete the working dir if it already exists
FileUtils.deleteDirectory( workingDirectory );
// First create the view
String viewName = getUniqueViewName( repo, workingDirectory.getAbsolutePath() );
String streamIdentifier = getStreamIdentifier(repo.getStreamName(), repo.getVobName());
cl = createCreateViewCommandLine( workingDirectory, viewName, streamIdentifier );
getLogger().info( "Executing: " + cl.getWorkingDirectory().getAbsolutePath() + ">>" + cl.toString() );
exitCode = CommandLineUtils.executeCommandLine( cl, new CommandLineUtils.StringStreamConsumer(), stderr );
if ( exitCode == 0 )
{
File configSpecLocation;
if ( !repo.isAutoConfigSpec() )
{
configSpecLocation = repo.getConfigSpec();
if ( version != null && StringUtils.isNotEmpty( version.getName() ) )
{
// Another config spec is needed in this case.
//
// One option how to implement this would be to use a name convention for the config specs,
// e.g. the tag name could be appended to the original config spec name.
// If the config spec from the SCM URL would be \\myserver\configspecs\someproj.txt
// and the tag name would be mytag, the new config spec location could be
// \\myserver\configspecs\someproj-mytag.txt
//
throw new UnsupportedOperationException(
"Building on a label not supported with user-specified config specs" );
}
}
else
{
// write config spec to temp file
String configSpec = createConfigSpec( repo.getLoadDirectory(), version );
getLogger().info( "Created config spec for view '" + viewName + "':\n" + configSpec );
configSpecLocation = writeTemporaryConfigSpecFile( configSpec, viewName );
// When checking out from ClearCase, the directory structure of the
// SCM system is repeated within the checkout directory. E.g. if you check out the
// project "my/project" to "/some/dir", the project sources are actually checked out
// to "my/project/some/dir".
projectDirectory = repo.getLoadDirectory();
// strip off leading / to make the path relative
if ( projectDirectory.startsWith( "/" ) )
{
projectDirectory = projectDirectory.substring( 1 );
}
}
cl = createUpdateConfigSpecCommandLine( workingDirectory, configSpecLocation, viewName );
getLogger().info( "Executing: " + cl.getWorkingDirectory().getAbsolutePath() + ">>" + cl.toString() );
exitCode = CommandLineUtils.executeCommandLine( cl, consumer, stderr );
}
}
catch ( CommandLineException ex )
{
throw new ScmException( "Error while executing clearcase command.", ex );
}
catch ( IOException ex )
{
throw new ScmException( "Error while deleting working directory.", ex );
}
if ( exitCode != 0 )
{
return new CheckOutScmResult( cl.toString(), "The cleartool command failed.", stderr.getOutput(), false );
}
return new CheckOutScmResult( cl.toString(), consumer.getCheckedOutFiles(), projectDirectory );
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
/**
* Creates a temporary config spec file with the given contents that will be
* deleted on VM exit.
*
* @param configSpecContents The contents for the file
* @param viewName The name of the view; used to determine an appropriate file
* name
*/
protected File writeTemporaryConfigSpecFile( String configSpecContents, String viewName )
throws IOException
{
File configSpecLocation = File.createTempFile( "configspec-" + viewName, ".txt" );
FileWriter fw = new FileWriter( configSpecLocation );
try
{
fw.write( configSpecContents );
}
finally
{
try
{
fw.close();
}
catch ( IOException e )
{
// ignore
}
}
configSpecLocation.deleteOnExit();
return configSpecLocation;
}
/**
* Creates a config spec that loads the given loadDirectory and uses the
* given version tag
*
* @param loadDirectory the VOB directory to be loaded
* @param version ClearCase label type; notice that branch types are not
* supported
* @return Config Spec as String
*/
protected String createConfigSpec( String loadDirectory, ScmVersion version )
{
// create config spec
StringBuffer configSpec = new StringBuffer();
configSpec.append( "element * CHECKEDOUT\n" );
if ( version != null && StringUtils.isNotEmpty( version.getName() ) )
{
configSpec.append( "element * " + version.getName() + "\n" );
configSpec.append( "element -directory * /main/LATEST\n" );
}
else
{
configSpec.append( "element * /main/LATEST\n" );
}
configSpec.append( "load " + loadDirectory + "\n" );
return configSpec.toString();
}
// private static Commandline createDeleteViewCommandLine( ClearCaseScmProviderRepository repository,
// File workingDirectory )
// {
// Commandline command = new Commandline();
//
// command.setWorkingDirectory( workingDirectory.getAbsolutePath() );
//
// command.setExecutable( "cleartool" );
//
// command.createArgument().setValue( "rmview" );
// command.createArgument().setValue( "-force" );
// command.createArgument().setValue( "-tag" );
// if ( isClearCaseLT() )
// {
// command.createArgument().setValue( getViewStore() );
// }
// else
// {
// command.createArgument().setValue( getUniqueViewName( repository, workingDirectory.getAbsolutePath() ) );
// }
//
// return command;
// }
protected Commandline createCreateViewCommandLine( File workingDirectory, String viewName, String streamIdentifier)
throws IOException
{
Commandline command = new Commandline();
// We have to execute from 1 level up from the working dir, since we had to delete the working dir
command.setWorkingDirectory( workingDirectory.getParentFile().getAbsolutePath() );
command.setExecutable( "cleartool" );
command.createArgument().setValue( "mkview" );
command.createArgument().setValue( "-snapshot" );
command.createArgument().setValue( "-tag" );
command.createArgument().setValue( viewName );
if (isClearCaseUCM())
{
command.createArgument().setValue( "-stream" );
command.createArgument().setValue( streamIdentifier );
}
if ( !isClearCaseLT() )
{
if ( useVWS() )
{
command.createArgument().setValue( "-vws" );
command.createArgument().setValue( getViewStore() + viewName + ".vws" );
}
}
command.createArgument().setValue( workingDirectory.getCanonicalPath() );
return command;
}
/**
* Format the stream identifier for ClearCaseUCM
* @param streamName
* @param vobName
* @return the formatted stream identifier if the two parameter are not null
*/
protected String getStreamIdentifier(String streamName, String vobName)
{
if (streamName == null || vobName == null)
return null;
return "stream:" + streamName + "@" + vobName;
}
protected Commandline createUpdateConfigSpecCommandLine( File workingDirectory, File configSpecLocation,
String viewName )
{
Commandline command = new Commandline();
command.setWorkingDirectory( workingDirectory.getAbsolutePath() );
command.setExecutable( "cleartool" );
command.createArgument().setValue( "setcs" );
command.createArgument().setValue( "-tag" );
command.createArgument().setValue( viewName );
command.createArgument().setValue( configSpecLocation.getAbsolutePath() );
return command;
}
private String getUniqueViewName( ClearCaseScmProviderRepository repository, String absolutePath )
{
String uniqueId;
int lastIndexBack = absolutePath.lastIndexOf( '\\' );
int lastIndexForward = absolutePath.lastIndexOf( '/' );
if ( lastIndexBack != -1 )
{
uniqueId = absolutePath.substring( lastIndexBack + 1 );
}
else
{
uniqueId = absolutePath.substring( lastIndexForward + 1 );
}
return repository.getViewName( uniqueId );
}
protected String getViewStore()
{
String result = null;
if ( settings.getViewstore() != null )
{
result = settings.getViewstore();
}
if ( result == null )
{
result = "\\\\" + getHostName() + "\\viewstore\\";
}
else
{
// If ClearCase LT are use, the View store is identify by the
// username.
if ( isClearCaseLT() )
{
result = result + getUserName() + "\\";
}
}
return result;
}
protected boolean isClearCaseLT()
{
return ClearCaseScmProviderRepository.CLEARCASE_LT.equals(settings.getClearcaseType());
}
protected boolean isClearCaseUCM()
{
return ClearCaseScmProviderRepository.CLEARCASE_UCM.equals(settings.getClearcaseType());
}
/**
* @return the value of the setting property 'useVWS'
*/
protected boolean useVWS()
{
return settings.isUseVWSParameter();
}
private String getHostName()
{
String hostname;
try
{
hostname = InetAddress.getLocalHost().getHostName();
}
catch ( UnknownHostException e )
{
// Should never happen
throw new RuntimeException( e );
}
return hostname;
}
private String getUserName()
{
String username;
username = System.getProperty( "user.name" );
return username;
}
public void setSettings(Settings settings) {
this.settings = settings;
}
}
| true | true | protected CheckOutScmResult executeCheckOutCommand( ScmProviderRepository repository, ScmFileSet fileSet,
ScmVersion version )
throws ScmException
{
getLogger().debug( "executing checkout command..." );
ClearCaseScmProviderRepository repo = (ClearCaseScmProviderRepository) repository;
File workingDirectory = fileSet.getBasedir();
getLogger().debug( version.getType() + ": " + version.getName() );
getLogger().debug( "Running with CLEARCASE " + settings.getClearcaseType() );
ClearCaseCheckOutConsumer consumer = new ClearCaseCheckOutConsumer( getLogger() );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
int exitCode;
Commandline cl;
String projectDirectory = "";
try
{
// Since clearcase only wants to checkout to a non-existent directory, first delete the working dir if it already exists
FileUtils.deleteDirectory( workingDirectory );
// First create the view
String viewName = getUniqueViewName( repo, workingDirectory.getAbsolutePath() );
String streamIdentifier = getStreamIdentifier(repo.getStreamName(), repo.getVobName());
cl = createCreateViewCommandLine( workingDirectory, viewName, streamIdentifier );
getLogger().info( "Executing: " + cl.getWorkingDirectory().getAbsolutePath() + ">>" + cl.toString() );
exitCode = CommandLineUtils.executeCommandLine( cl, new CommandLineUtils.StringStreamConsumer(), stderr );
if ( exitCode == 0 )
{
File configSpecLocation;
if ( !repo.isAutoConfigSpec() )
{
configSpecLocation = repo.getConfigSpec();
if ( version != null && StringUtils.isNotEmpty( version.getName() ) )
{
// Another config spec is needed in this case.
//
// One option how to implement this would be to use a name convention for the config specs,
// e.g. the tag name could be appended to the original config spec name.
// If the config spec from the SCM URL would be \\myserver\configspecs\someproj.txt
// and the tag name would be mytag, the new config spec location could be
// \\myserver\configspecs\someproj-mytag.txt
//
throw new UnsupportedOperationException(
"Building on a label not supported with user-specified config specs" );
}
}
else
{
// write config spec to temp file
String configSpec = createConfigSpec( repo.getLoadDirectory(), version );
getLogger().info( "Created config spec for view '" + viewName + "':\n" + configSpec );
configSpecLocation = writeTemporaryConfigSpecFile( configSpec, viewName );
// When checking out from ClearCase, the directory structure of the
// SCM system is repeated within the checkout directory. E.g. if you check out the
// project "my/project" to "/some/dir", the project sources are actually checked out
// to "my/project/some/dir".
projectDirectory = repo.getLoadDirectory();
// strip off leading / to make the path relative
if ( projectDirectory.startsWith( "/" ) )
{
projectDirectory = projectDirectory.substring( 1 );
}
}
cl = createUpdateConfigSpecCommandLine( workingDirectory, configSpecLocation, viewName );
getLogger().info( "Executing: " + cl.getWorkingDirectory().getAbsolutePath() + ">>" + cl.toString() );
exitCode = CommandLineUtils.executeCommandLine( cl, consumer, stderr );
}
}
catch ( CommandLineException ex )
{
throw new ScmException( "Error while executing clearcase command.", ex );
}
catch ( IOException ex )
{
throw new ScmException( "Error while deleting working directory.", ex );
}
if ( exitCode != 0 )
{
return new CheckOutScmResult( cl.toString(), "The cleartool command failed.", stderr.getOutput(), false );
}
return new CheckOutScmResult( cl.toString(), consumer.getCheckedOutFiles(), projectDirectory );
}
| protected CheckOutScmResult executeCheckOutCommand( ScmProviderRepository repository, ScmFileSet fileSet,
ScmVersion version )
throws ScmException
{
getLogger().debug( "executing checkout command..." );
ClearCaseScmProviderRepository repo = (ClearCaseScmProviderRepository) repository;
File workingDirectory = fileSet.getBasedir();
if ( version != null )
{
getLogger().debug( version.getType() + ": " + version.getName() );
}
getLogger().debug( "Running with CLEARCASE " + settings.getClearcaseType() );
ClearCaseCheckOutConsumer consumer = new ClearCaseCheckOutConsumer( getLogger() );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
int exitCode;
Commandline cl;
String projectDirectory = "";
try
{
// Since clearcase only wants to checkout to a non-existent directory, first delete the working dir if it already exists
FileUtils.deleteDirectory( workingDirectory );
// First create the view
String viewName = getUniqueViewName( repo, workingDirectory.getAbsolutePath() );
String streamIdentifier = getStreamIdentifier(repo.getStreamName(), repo.getVobName());
cl = createCreateViewCommandLine( workingDirectory, viewName, streamIdentifier );
getLogger().info( "Executing: " + cl.getWorkingDirectory().getAbsolutePath() + ">>" + cl.toString() );
exitCode = CommandLineUtils.executeCommandLine( cl, new CommandLineUtils.StringStreamConsumer(), stderr );
if ( exitCode == 0 )
{
File configSpecLocation;
if ( !repo.isAutoConfigSpec() )
{
configSpecLocation = repo.getConfigSpec();
if ( version != null && StringUtils.isNotEmpty( version.getName() ) )
{
// Another config spec is needed in this case.
//
// One option how to implement this would be to use a name convention for the config specs,
// e.g. the tag name could be appended to the original config spec name.
// If the config spec from the SCM URL would be \\myserver\configspecs\someproj.txt
// and the tag name would be mytag, the new config spec location could be
// \\myserver\configspecs\someproj-mytag.txt
//
throw new UnsupportedOperationException(
"Building on a label not supported with user-specified config specs" );
}
}
else
{
// write config spec to temp file
String configSpec = createConfigSpec( repo.getLoadDirectory(), version );
getLogger().info( "Created config spec for view '" + viewName + "':\n" + configSpec );
configSpecLocation = writeTemporaryConfigSpecFile( configSpec, viewName );
// When checking out from ClearCase, the directory structure of the
// SCM system is repeated within the checkout directory. E.g. if you check out the
// project "my/project" to "/some/dir", the project sources are actually checked out
// to "my/project/some/dir".
projectDirectory = repo.getLoadDirectory();
// strip off leading / to make the path relative
if ( projectDirectory.startsWith( "/" ) )
{
projectDirectory = projectDirectory.substring( 1 );
}
}
cl = createUpdateConfigSpecCommandLine( workingDirectory, configSpecLocation, viewName );
getLogger().info( "Executing: " + cl.getWorkingDirectory().getAbsolutePath() + ">>" + cl.toString() );
exitCode = CommandLineUtils.executeCommandLine( cl, consumer, stderr );
}
}
catch ( CommandLineException ex )
{
throw new ScmException( "Error while executing clearcase command.", ex );
}
catch ( IOException ex )
{
throw new ScmException( "Error while deleting working directory.", ex );
}
if ( exitCode != 0 )
{
return new CheckOutScmResult( cl.toString(), "The cleartool command failed.", stderr.getOutput(), false );
}
return new CheckOutScmResult( cl.toString(), consumer.getCheckedOutFiles(), projectDirectory );
}
|
diff --git a/src/main/java/cc/redberry/core/utils/TensorUtils.java b/src/main/java/cc/redberry/core/utils/TensorUtils.java
index 9bac76e..7cd7e05 100644
--- a/src/main/java/cc/redberry/core/utils/TensorUtils.java
+++ b/src/main/java/cc/redberry/core/utils/TensorUtils.java
@@ -1,476 +1,476 @@
/*
* Redberry: symbolic tensor computations.
*
* Copyright (c) 2010-2012:
* Stanislav Poslavsky <[email protected]>
* Bolotin Dmitriy <[email protected]>
*
* This file is part of Redberry.
*
* Redberry is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Redberry is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Redberry. If not, see <http://www.gnu.org/licenses/>.
*/
package cc.redberry.core.utils;
import cc.redberry.core.combinatorics.Symmetry;
import cc.redberry.core.combinatorics.symmetries.Symmetries;
import cc.redberry.core.combinatorics.symmetries.SymmetriesFactory;
import cc.redberry.core.indexmapping.*;
import cc.redberry.core.indices.Indices;
import cc.redberry.core.indices.IndicesUtils;
import cc.redberry.core.number.Complex;
import cc.redberry.core.tensor.*;
import cc.redberry.core.tensor.functions.ScalarFunction;
import gnu.trove.set.hash.TIntHashSet;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @author Dmitry Bolotin
* @author Stanislav Poslavsky
*/
public class TensorUtils {
private TensorUtils() {
}
public static boolean isInteger(Tensor tensor) {
if (!(tensor instanceof Complex))
return false;
return ((Complex) tensor).isInteger();
}
public static boolean isNatural(Tensor tensor) {
if (!(tensor instanceof Complex))
return false;
return ((Complex) tensor).isNatural();
}
public static boolean isRealPositiveNumber(Tensor tensor) {
if (tensor instanceof Complex) {
Complex complex = (Complex) tensor;
return complex.isReal() && complex.getReal().signum() > 0;
}
return false;
}
public static boolean isRealNegativeNumber(Tensor tensor) {
if (tensor instanceof Complex) {
Complex complex = (Complex) tensor;
return complex.isReal() && complex.getReal().signum() < 0;
}
return false;
}
public static boolean isIndexless(Tensor... tensors) {
for (Tensor t : tensors)
if (!isIndexless1(t))
return false;
return true;
}
private static boolean isIndexless1(Tensor tensor) {
return tensor.getIndices().size() == 0;
}
public static boolean isScalar(Tensor... tensors) {
for (Tensor t : tensors)
if (!isScalar1(t))
return false;
return true;
}
private static boolean isScalar1(Tensor tensor) {
return tensor.getIndices().getFree().size() == 0;
}
public static boolean isOne(Tensor tensor) {
return tensor instanceof Complex && ((Complex) tensor).isOne();
}
public static boolean isZero(Tensor tensor) {
return tensor instanceof Complex && ((Complex) tensor).isZero();
}
public static boolean isImageOne(Tensor tensor) {
return tensor instanceof Complex && ((Complex) tensor).equals(Complex.IMAGEONE);
}
public static boolean isMinusOne(Tensor tensor) {
return tensor instanceof Complex && ((Complex) tensor).equals(Complex.MINUSE_ONE);
}
public static boolean isSymbol(Tensor t) {
return t.getClass() == SimpleTensor.class && t.getIndices().size() == 0;
}
public static boolean isSymbolOrNumber(Tensor t) {
return t instanceof Complex || isSymbol(t);
}
public static boolean isSymbolic(Tensor t) {
if (t.getClass() == SimpleTensor.class)
return t.getIndices().size() == 0;
if (t instanceof TensorField) {
boolean b = t.getIndices().size() == 0;
if (!b)
return false;
}
if (t instanceof Complex)
return true;
for (Tensor c : t)
if (!isSymbolic(c))
return false;
return true;
}
public static boolean isSymbolic(Tensor... tensors) {
for (Tensor t : tensors)
if (!isSymbolic(t))
return false;
return true;
}
public static boolean equalsExactly(Tensor[] u, Tensor[] v) {
if (u.length != v.length)
return false;
for (int i = 0; i < u.length; ++i)
if (!TensorUtils.equalsExactly(u[i], v[i]))
return false;
return true;
}
public static boolean equalsExactly(Tensor u, String v) {
return equalsExactly(u, Tensors.parse(v));
}
public static boolean equalsExactly(Tensor u, Tensor v) {
if (u == v)
return true;
if (u.getClass() != v.getClass())
return false;
if (u instanceof Complex)
return u.equals(v);
if (u.hashCode() != v.hashCode())
return false;
if (u.getClass() == SimpleTensor.class)
if (!u.getIndices().equals(v.getIndices()))
return false;
else
return true;
if (u.size() != v.size())
return false;
if (u instanceof MultiTensor) {
final int size = u.size();
int[] hashArray = new int[size];
int i;
for (i = 0; i < size; ++i)
if ((hashArray[i] = u.get(i).hashCode()) != v.get(i).hashCode())
return false;
int begin = 0, stretchLength, j, n;
for (i = 1; i <= size; ++i)
if (i == size || hashArray[i] != hashArray[i - 1]) {
if (i - 1 != begin) {
stretchLength = i - begin;
boolean[] usedPos = new boolean[stretchLength];
OUT:
for (n = begin; n < i; ++n) {
for (j = begin; j < i; ++j)
if (usedPos[j - begin] == false && equalsExactly(u.get(n), v.get(j))) {
usedPos[j - begin] = true;
continue OUT;
}
return false;
}
return true;
} else if (!equalsExactly(u.get(i - 1), v.get(i - 1)))
return false;
begin = i;
}
}
if (u.getClass() == TensorField.class) {
if (((SimpleTensor) u).getName() != ((SimpleTensor) v).getName()
- || !u.getIndices().equals(v.getIndices())) ;
- return false;
+ || !u.getIndices().equals(v.getIndices()))
+ return false;
}
final int size = u.size();
for (int i = 0; i < size; ++i)
if (!equalsExactly(u.get(i), v.get(i)))
return false;
return true;
}
@Deprecated
public static Set<Integer> getAllDummyIndicesNames(Tensor tensor) {
Set<Integer> dummy = getAllIndicesNames(tensor);
Indices ind = tensor.getIndices().getFree();
for (int i = ind.size() - 1; i >= 0; --i)
dummy.remove(IndicesUtils.getNameWithType(ind.get(i)));
return dummy;
}
public static Set<Integer> getAllIndicesNames(Tensor... tensors) {
Set<Integer> indices = new HashSet<>();
for (Tensor tensor : tensors)
appendAllIndicesNames(tensor, indices);
return indices;
}
private static void appendAllIndicesNames(Tensor tensor, Set<Integer> indices) {
if (tensor instanceof SimpleTensor) {
Indices ind = tensor.getIndices();
final int size = ind.size();
for (int i = 0; i < size; ++i)
indices.add(IndicesUtils.getNameWithType(ind.get(i)));
} else {
final int size = tensor.size();
Tensor t;
for (int i = 0; i < size; ++i) {
t = tensor.get(i);
if (t instanceof ScalarFunction)
continue;
appendAllIndicesNames(tensor.get(i), indices);
}
}
}
public static TIntHashSet getAllDummyIndicesT(Tensor tensor) {
TIntHashSet indices = getAllIndicesNamesT(tensor);
indices.removeAll(IndicesUtils.getIndicesNames(tensor.getIndices().getFree()));
return indices;
}
public static TIntHashSet getAllIndicesNamesT(Tensor... tensors) {
TIntHashSet set = new TIntHashSet();
for (Tensor tensor : tensors)
appendAllIndicesNamesT(tensor, set);
return set;
}
private static void appendAllIndicesNamesT(Tensor tensor, TIntHashSet set) {
if (tensor instanceof SimpleTensor) {
Indices ind = tensor.getIndices();
final int size = ind.size();
for (int i = 0; i < size; ++i)
set.add(IndicesUtils.getNameWithType(ind.get(i)));
} else {
final int size = tensor.size();
Tensor t;
for (int i = 0; i < size; ++i) {
t = tensor.get(i);
if (t instanceof ScalarFunction)
continue;
appendAllIndicesNamesT(tensor.get(i), set);
}
}
}
public static boolean equals(Tensor u, Tensor v) {
if (u == v)
return true;
Indices freeIndices = u.getIndices().getFree();
if (!freeIndices.equalsRegardlessOrder(v.getIndices().getFree()))
return false;
int[] free = freeIndices.getAllIndices().copy();
IndexMappingBuffer tester = new IndexMappingBufferTester(free, false);
MappingsPort mp = IndexMappings.createPort(tester, u, v);
IndexMappingBuffer buffer;
while ((buffer = mp.take()) != null)
if (buffer.getSignum() == false)
return true;
return false;
}
public static Boolean compare1(Tensor u, Tensor v) {
Indices freeIndices = u.getIndices().getFree();
if (!freeIndices.equalsRegardlessOrder(v.getIndices().getFree()))
return false;
int[] free = freeIndices.getAllIndices().copy();
IndexMappingBuffer tester = new IndexMappingBufferTester(free, false);
IndexMappingBuffer buffer = IndexMappings.createPort(tester, u, v).take();
if (buffer == null)
return null;
return buffer.getSignum();
}
/**
* @param t s AssertionError
*/
public static void assertIndicesConsistency(Tensor t) {
assertIndicesConsistency(t, new HashSet<Integer>());
}
private static void assertIndicesConsistency(Tensor t, Set<Integer> indices) {
if (t instanceof SimpleTensor) {
Indices ind = t.getIndices();
for (int i = ind.size() - 1; i >= 0; --i)
if (indices.contains(ind.get(i)))
throw new AssertionError();
else
indices.add(ind.get(i));
}
if (t instanceof Product)
for (int i = t.size() - 1; i >= 0; --i)
assertIndicesConsistency(t.get(i), indices);
if (t instanceof Sum) {
Set<Integer> sumIndices = new HashSet<>(), temp;
for (int i = t.size() - 1; i >= 0; --i) {
temp = new HashSet<>(indices);
assertIndicesConsistency(t.get(i), temp);
appendAllIndices(t.get(i), sumIndices);
}
indices.addAll(sumIndices);
}
if (t instanceof Expression)//FUTURE incorporate expression correctly
for (Tensor c : t)
assertIndicesConsistency(c, new HashSet<>(indices));
}
private static void appendAllIndices(Tensor t, Set<Integer> set) {
if (t instanceof SimpleTensor) {
Indices ind = t.getIndices();
for (int i = ind.size() - 1; i >= 0; --i)
set.add(ind.get(i));
} else
for (Tensor c : t)
if (c instanceof ScalarFunction)
continue;
else
appendAllIndices(c, set);
}
public static boolean isZeroDueToSymmetry(Tensor t) {
int[] indices = IndicesUtils.getIndicesNames(t.getIndices().getFree());
IndexMappingBufferTester bufferTester = new IndexMappingBufferTester(indices, false);
MappingsPort mp = IndexMappings.createPort(bufferTester, t, t);
IndexMappingBuffer buffer;
while ((buffer = mp.take()) != null)
if (buffer.getSignum())
return true;
return false;
}
private static Symmetry getSymmetryFromMapping1(final int[] indicesNames, IndexMappingBuffer indexMappingBuffer) {
final int dimension = indicesNames.length;
int[] permutation = new int[dimension];
Arrays.fill(permutation, -1);
int i;
for (i = 0; i < dimension; ++i) {
int fromIndex = indicesNames[i];
IndexMappingBufferRecord record = indexMappingBuffer.getMap().get(fromIndex);
if (record == null)
throw new IllegalArgumentException("Index " + IndicesUtils.toString(fromIndex) + " does not contains in specified IndexMappingBuffer.");
int newPosition = -1;
//TODO refactor with sort and binary search
for (int j = 0; j < dimension; ++j)
if (indicesNames[j] == record.getIndexName()) {
newPosition = j;
break;
}
if (newPosition < 0)
throw new IllegalArgumentException("Index " + IndicesUtils.toString(record.getIndexName()) + " does not contains in specified indices array.");
permutation[i] = newPosition;
}
for (i = 0; i < dimension; ++i)
if (permutation[i] == -1)
permutation[i] = i;
return new Symmetry(permutation, indexMappingBuffer.getSignum());
}
public static Symmetry getSymmetryFromMapping(final int[] indices, IndexMappingBuffer indexMappingBuffer) {
return getSymmetryFromMapping1(IndicesUtils.getIndicesNames(indices), indexMappingBuffer);
}
public static Symmetries getSymmetriesFromMappings(final int[] indices, MappingsPort mappingsPort) {
Symmetries symmetries = SymmetriesFactory.createSymmetries(indices.length);
int[] indicesNames = IndicesUtils.getIndicesNames(indices);
IndexMappingBuffer buffer;
while ((buffer = mappingsPort.take()) != null)
symmetries.add(getSymmetryFromMapping1(indicesNames, buffer));
return symmetries;
}
public static Symmetries getIndicesSymmetries(int[] indices, Tensor tensor) {
return getSymmetriesFromMappings(indices, IndexMappings.createPort(tensor, tensor));
}
public static Symmetries getIndicesSymmetriesForIndicesWithSameStates(final int[] indices, Tensor tensor) {
Symmetries total = getIndicesSymmetries(indices, tensor);
Symmetries symmetries = SymmetriesFactory.createSymmetries(indices.length);
int i;
OUT:
for (Symmetry s : total) {
for (i = 0; i < indices.length; ++i)
if (IndicesUtils.getRawStateInt(indices[i]) != IndicesUtils.getRawStateInt(indices[s.newIndexOf(i)]))
continue OUT;
symmetries.add(s);
}
return symmetries;
}
public static Set<SimpleTensor> getAllSymbols(Tensor... tensors) {
Set<SimpleTensor> set = new HashSet<>();
for (Tensor tensor : tensors)
addSymbols(tensor, set);
return set;
}
private static void addSymbols(Tensor tensor, Set<SimpleTensor> set) {
if (isSymbol(tensor)) {
set.add((SimpleTensor) tensor);
} else
for (Tensor t : tensor)
addSymbols(t, set);
}
// public static Tensor[] getDistinct(final Tensor[] array) {
// final int length = array.length;
// final Indices indices = array[0].getIndices().getFree();
// final int[] hashes = new int[length];
// int i;
// for (i = 0; i < length; ++i)
// hashes[i] = TensorHashCalculator.hashWithIndices(array[i], indices);
// ArraysUtils.quickSort(hashes, array);
//
// //Searching for stretches in from hashes
// final List<Tensor> tensors = new ArrayList<>();
// int begin = 0;
// for (i = 1; i <= length; ++i)
// if (i == length || hashes[i] != hashes[i - 1]) {
// if (i - 1 != begin)
// _addDistinctToList(array, begin, i, tensors);
// else
// tensors.add(array[begin]);
// begin = i;
// }
// return tensors.toArray(new Tensor[tensors.size()]);
// }
//
// private static void _addDistinctToList(final Tensor[] array, final int from, final int to, final List<Tensor> tensors) {
// int j;
// OUTER:
// for (int i = from; i < to; ++i) {
// for (j = i + 1; j < to; ++j)
// if (TTest.equals(array[i], array[j]))
// continue OUTER;
// tensors.add(array[i]);
// }
// }
}
| true | true | public static boolean equalsExactly(Tensor u, Tensor v) {
if (u == v)
return true;
if (u.getClass() != v.getClass())
return false;
if (u instanceof Complex)
return u.equals(v);
if (u.hashCode() != v.hashCode())
return false;
if (u.getClass() == SimpleTensor.class)
if (!u.getIndices().equals(v.getIndices()))
return false;
else
return true;
if (u.size() != v.size())
return false;
if (u instanceof MultiTensor) {
final int size = u.size();
int[] hashArray = new int[size];
int i;
for (i = 0; i < size; ++i)
if ((hashArray[i] = u.get(i).hashCode()) != v.get(i).hashCode())
return false;
int begin = 0, stretchLength, j, n;
for (i = 1; i <= size; ++i)
if (i == size || hashArray[i] != hashArray[i - 1]) {
if (i - 1 != begin) {
stretchLength = i - begin;
boolean[] usedPos = new boolean[stretchLength];
OUT:
for (n = begin; n < i; ++n) {
for (j = begin; j < i; ++j)
if (usedPos[j - begin] == false && equalsExactly(u.get(n), v.get(j))) {
usedPos[j - begin] = true;
continue OUT;
}
return false;
}
return true;
} else if (!equalsExactly(u.get(i - 1), v.get(i - 1)))
return false;
begin = i;
}
}
if (u.getClass() == TensorField.class) {
if (((SimpleTensor) u).getName() != ((SimpleTensor) v).getName()
|| !u.getIndices().equals(v.getIndices())) ;
return false;
}
final int size = u.size();
for (int i = 0; i < size; ++i)
if (!equalsExactly(u.get(i), v.get(i)))
return false;
return true;
}
| public static boolean equalsExactly(Tensor u, Tensor v) {
if (u == v)
return true;
if (u.getClass() != v.getClass())
return false;
if (u instanceof Complex)
return u.equals(v);
if (u.hashCode() != v.hashCode())
return false;
if (u.getClass() == SimpleTensor.class)
if (!u.getIndices().equals(v.getIndices()))
return false;
else
return true;
if (u.size() != v.size())
return false;
if (u instanceof MultiTensor) {
final int size = u.size();
int[] hashArray = new int[size];
int i;
for (i = 0; i < size; ++i)
if ((hashArray[i] = u.get(i).hashCode()) != v.get(i).hashCode())
return false;
int begin = 0, stretchLength, j, n;
for (i = 1; i <= size; ++i)
if (i == size || hashArray[i] != hashArray[i - 1]) {
if (i - 1 != begin) {
stretchLength = i - begin;
boolean[] usedPos = new boolean[stretchLength];
OUT:
for (n = begin; n < i; ++n) {
for (j = begin; j < i; ++j)
if (usedPos[j - begin] == false && equalsExactly(u.get(n), v.get(j))) {
usedPos[j - begin] = true;
continue OUT;
}
return false;
}
return true;
} else if (!equalsExactly(u.get(i - 1), v.get(i - 1)))
return false;
begin = i;
}
}
if (u.getClass() == TensorField.class) {
if (((SimpleTensor) u).getName() != ((SimpleTensor) v).getName()
|| !u.getIndices().equals(v.getIndices()))
return false;
}
final int size = u.size();
for (int i = 0; i < size; ++i)
if (!equalsExactly(u.get(i), v.get(i)))
return false;
return true;
}
|
diff --git a/src/plugin/PluginManager.java b/src/plugin/PluginManager.java
index d5fe5a2..16fb218 100644
--- a/src/plugin/PluginManager.java
+++ b/src/plugin/PluginManager.java
@@ -1,31 +1,31 @@
package plugin;
import java.io.File;
import java.util.ArrayList;
public class PluginManager {
public static ArrayList<PluginFile> loadInstalledPlugins() {
- File path = new File("src/plugin");
+ File path = new File("plugins");
File files[] = path.listFiles();
ArrayList<PluginFile> filePaths = new ArrayList<PluginFile>();
try {
ClassLoader loader = ClassLoader.getSystemClassLoader();
for (File file : files) {
if (file.getName().contains(".jar")) {
String name = file.getName().replace(".jar", "");
- Plugin plugin = (Plugin) loader.loadClass("plugin." + name).newInstance();
+ Plugin plugin = (Plugin) loader.loadClass("plugins." + name).newInstance();
PluginFile pFile = new PluginFile(name, file.getPath(), plugin);
filePaths.add(pFile);
}
}
}
catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
return filePaths;
}
}
| false | true | public static ArrayList<PluginFile> loadInstalledPlugins() {
File path = new File("src/plugin");
File files[] = path.listFiles();
ArrayList<PluginFile> filePaths = new ArrayList<PluginFile>();
try {
ClassLoader loader = ClassLoader.getSystemClassLoader();
for (File file : files) {
if (file.getName().contains(".jar")) {
String name = file.getName().replace(".jar", "");
Plugin plugin = (Plugin) loader.loadClass("plugin." + name).newInstance();
PluginFile pFile = new PluginFile(name, file.getPath(), plugin);
filePaths.add(pFile);
}
}
}
catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
return filePaths;
}
| public static ArrayList<PluginFile> loadInstalledPlugins() {
File path = new File("plugins");
File files[] = path.listFiles();
ArrayList<PluginFile> filePaths = new ArrayList<PluginFile>();
try {
ClassLoader loader = ClassLoader.getSystemClassLoader();
for (File file : files) {
if (file.getName().contains(".jar")) {
String name = file.getName().replace(".jar", "");
Plugin plugin = (Plugin) loader.loadClass("plugins." + name).newInstance();
PluginFile pFile = new PluginFile(name, file.getPath(), plugin);
filePaths.add(pFile);
}
}
}
catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
return filePaths;
}
|
diff --git a/com.ibm.wala.core/src/com/ibm/wala/analysis/reflection/ForNameContextInterpreter.java b/com.ibm.wala.core/src/com/ibm/wala/analysis/reflection/ForNameContextInterpreter.java
index a1b0b642b..100ceedff 100644
--- a/com.ibm.wala.core/src/com/ibm/wala/analysis/reflection/ForNameContextInterpreter.java
+++ b/com.ibm.wala.core/src/com/ibm/wala/analysis/reflection/ForNameContextInterpreter.java
@@ -1,152 +1,149 @@
/*******************************************************************************
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.wala.analysis.reflection;
import java.util.ArrayList;
import java.util.Iterator;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.summaries.SyntheticIR;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSALoadClassInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.strings.Atom;
/**
* An {@link SSAContextInterpreter} specialized to interpret Class.forName in a {@link JavaTypeContext} which
* represents the point-type of the class object created by the call.
*
* @author pistoia
*/
public class ForNameContextInterpreter implements SSAContextInterpreter {
public final static Atom forNameAtom = Atom.findOrCreateUnicodeAtom("forName");
private final static Descriptor forNameDescriptor = Descriptor.findOrCreateUTF8("(Ljava/lang/String;)Ljava/lang/Class;");
public final static MethodReference FOR_NAME_REF = MethodReference.findOrCreate(TypeReference.JavaLangClass, forNameAtom,
forNameDescriptor);
public IR getIR(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
if (Assertions.verifyAssertions) {
Assertions._assert(understands(node));
}
IR result = makeIR(node.getMethod(), (JavaTypeContext) node.getContext());
return result;
}
public int getNumberOfStatements(CGNode node) {
if (Assertions.verifyAssertions) {
Assertions._assert(understands(node));
}
return getIR(node).getInstructions().length;
}
public boolean understands(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
if (!(node.getContext() instanceof JavaTypeContext))
return false;
return node.getMethod().getReference().equals(FOR_NAME_REF);
}
public Iterator<NewSiteReference> iterateNewSites(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
if (Assertions.verifyAssertions) {
Assertions._assert(understands(node));
}
JavaTypeContext context = (JavaTypeContext) node.getContext();
TypeReference tr = context.getType().getTypeReference();
if (tr != null) {
return new NonNullSingletonIterator<NewSiteReference>(NewSiteReference.make(0, tr));
}
return EmptyIterator.instance();
}
public Iterator<CallSiteReference> iterateCallSites(CGNode node) {
if (Assertions.verifyAssertions) {
Assertions._assert(understands(node));
}
return EmptyIterator.instance();
}
private SSAInstruction[] makeStatements(JavaTypeContext context) {
ArrayList<SSAInstruction> statements = new ArrayList<SSAInstruction>();
- int nextLocal = 1;
- int retValue = nextLocal++;
+ // vn1 is the string parameter
+ int retValue = 2;
TypeReference tr = context.getType().getTypeReference();
if (tr != null) {
SSALoadClassInstruction l = new SSALoadClassInstruction(retValue, tr);
statements.add(l);
SSAReturnInstruction R = new SSAReturnInstruction(retValue, false);
statements.add(R);
} else {
SSAThrowInstruction t = new SSAThrowInstruction(retValue);
statements.add(t);
}
SSAInstruction[] result = new SSAInstruction[statements.size()];
- Iterator<SSAInstruction> it = statements.iterator();
- for (int i = 0; i < result.length; i++) {
- result[i] = it.next();
- }
+ statements.toArray(result);
return result;
}
private IR makeIR(IMethod method, JavaTypeContext context) {
SSAInstruction instrs[] = makeStatements(context);
return new SyntheticIR(method, context, new InducedCFG(instrs, method, context), instrs, SSAOptions.defaultOptions(), null);
}
public boolean recordFactoryType(CGNode node, IClass klass) {
return false;
}
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
return EmptyIterator.instance();
}
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
return EmptyIterator.instance();
}
public ControlFlowGraph<ISSABasicBlock> getCFG(CGNode N) {
return getIR(N).getControlFlowGraph();
}
public DefUse getDU(CGNode node) {
return new DefUse(getIR(node));
}
}
| false | true | private SSAInstruction[] makeStatements(JavaTypeContext context) {
ArrayList<SSAInstruction> statements = new ArrayList<SSAInstruction>();
int nextLocal = 1;
int retValue = nextLocal++;
TypeReference tr = context.getType().getTypeReference();
if (tr != null) {
SSALoadClassInstruction l = new SSALoadClassInstruction(retValue, tr);
statements.add(l);
SSAReturnInstruction R = new SSAReturnInstruction(retValue, false);
statements.add(R);
} else {
SSAThrowInstruction t = new SSAThrowInstruction(retValue);
statements.add(t);
}
SSAInstruction[] result = new SSAInstruction[statements.size()];
Iterator<SSAInstruction> it = statements.iterator();
for (int i = 0; i < result.length; i++) {
result[i] = it.next();
}
return result;
}
| private SSAInstruction[] makeStatements(JavaTypeContext context) {
ArrayList<SSAInstruction> statements = new ArrayList<SSAInstruction>();
// vn1 is the string parameter
int retValue = 2;
TypeReference tr = context.getType().getTypeReference();
if (tr != null) {
SSALoadClassInstruction l = new SSALoadClassInstruction(retValue, tr);
statements.add(l);
SSAReturnInstruction R = new SSAReturnInstruction(retValue, false);
statements.add(R);
} else {
SSAThrowInstruction t = new SSAThrowInstruction(retValue);
statements.add(t);
}
SSAInstruction[] result = new SSAInstruction[statements.size()];
statements.toArray(result);
return result;
}
|
diff --git a/src/com/gitblit/GitBlit.java b/src/com/gitblit/GitBlit.java
index a62d4e4..a468060 100644
--- a/src/com/gitblit/GitBlit.java
+++ b/src/com/gitblit/GitBlit.java
@@ -1,1718 +1,1723 @@
/*
* Copyright 2011 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.Cookie;
import org.apache.wicket.protocol.http.WebResponse;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryCache.FileKey;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.transport.resolver.FileResolver;
import org.eclipse.jgit.transport.resolver.RepositoryResolver;
import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException;
import org.eclipse.jgit.transport.resolver.ServiceNotEnabledException;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gitblit.Constants.AccessRestrictionType;
import com.gitblit.Constants.FederationRequest;
import com.gitblit.Constants.FederationStrategy;
import com.gitblit.Constants.FederationToken;
import com.gitblit.models.FederationModel;
import com.gitblit.models.FederationProposal;
import com.gitblit.models.FederationSet;
import com.gitblit.models.Metric;
import com.gitblit.models.RepositoryModel;
import com.gitblit.models.ServerSettings;
import com.gitblit.models.ServerStatus;
import com.gitblit.models.SettingModel;
import com.gitblit.models.TeamModel;
import com.gitblit.models.UserModel;
import com.gitblit.utils.ByteFormat;
import com.gitblit.utils.FederationUtils;
import com.gitblit.utils.JGitUtils;
import com.gitblit.utils.JsonUtils;
import com.gitblit.utils.MetricUtils;
import com.gitblit.utils.ObjectCache;
import com.gitblit.utils.StringUtils;
/**
* GitBlit is the servlet context listener singleton that acts as the core for
* the web ui and the servlets. This class is either directly instantiated by
* the GitBlitServer class (Gitblit GO) or is reflectively instantiated from the
* definition in the web.xml file (Gitblit WAR).
*
* This class is the central logic processor for Gitblit. All settings, user
* object, and repository object operations pass through this class.
*
* Repository Resolution. There are two pathways for finding repositories. One
* pathway, for web ui display and repository authentication & authorization, is
* within this class. The other pathway is through the standard GitServlet.
*
* @author James Moger
*
*/
public class GitBlit implements ServletContextListener {
private static GitBlit gitblit;
private final Logger logger = LoggerFactory.getLogger(GitBlit.class);
private final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(5);
private final List<FederationModel> federationRegistrations = Collections
.synchronizedList(new ArrayList<FederationModel>());
private final Map<String, FederationModel> federationPullResults = new ConcurrentHashMap<String, FederationModel>();
private final ObjectCache<Long> repositorySizeCache = new ObjectCache<Long>();
private final ObjectCache<List<Metric>> repositoryMetricsCache = new ObjectCache<List<Metric>>();
private RepositoryResolver<Void> repositoryResolver;
private ServletContext servletContext;
private File repositoriesFolder;
private boolean exportAll = true;
private IUserService userService;
private IStoredSettings settings;
private ServerSettings settingsModel;
private ServerStatus serverStatus;
private MailExecutor mailExecutor;
public GitBlit() {
if (gitblit == null) {
// set the static singleton reference
gitblit = this;
}
}
/**
* Returns the Gitblit singleton.
*
* @return gitblit singleton
*/
public static GitBlit self() {
if (gitblit == null) {
new GitBlit();
}
return gitblit;
}
/**
* Determine if this is the GO variant of Gitblit.
*
* @return true if this is the GO variant of Gitblit.
*/
public static boolean isGO() {
return self().settings instanceof FileSettings;
}
/**
* Returns the boolean value for the specified key. If the key does not
* exist or the value for the key can not be interpreted as a boolean, the
* defaultValue is returned.
*
* @see IStoredSettings.getBoolean(String, boolean)
* @param key
* @param defaultValue
* @return key value or defaultValue
*/
public static boolean getBoolean(String key, boolean defaultValue) {
return self().settings.getBoolean(key, defaultValue);
}
/**
* Returns the integer value for the specified key. If the key does not
* exist or the value for the key can not be interpreted as an integer, the
* defaultValue is returned.
*
* @see IStoredSettings.getInteger(String key, int defaultValue)
* @param key
* @param defaultValue
* @return key value or defaultValue
*/
public static int getInteger(String key, int defaultValue) {
return self().settings.getInteger(key, defaultValue);
}
/**
* Returns the char value for the specified key. If the key does not exist
* or the value for the key can not be interpreted as a character, the
* defaultValue is returned.
*
* @see IStoredSettings.getChar(String key, char defaultValue)
* @param key
* @param defaultValue
* @return key value or defaultValue
*/
public static char getChar(String key, char defaultValue) {
return self().settings.getChar(key, defaultValue);
}
/**
* Returns the string value for the specified key. If the key does not exist
* or the value for the key can not be interpreted as a string, the
* defaultValue is returned.
*
* @see IStoredSettings.getString(String key, String defaultValue)
* @param key
* @param defaultValue
* @return key value or defaultValue
*/
public static String getString(String key, String defaultValue) {
return self().settings.getString(key, defaultValue);
}
/**
* Returns a list of space-separated strings from the specified key.
*
* @see IStoredSettings.getStrings(String key)
* @param name
* @return list of strings
*/
public static List<String> getStrings(String key) {
return self().settings.getStrings(key);
}
/**
* Returns the list of keys whose name starts with the specified prefix. If
* the prefix is null or empty, all key names are returned.
*
* @see IStoredSettings.getAllKeys(String key)
* @param startingWith
* @return list of keys
*/
public static List<String> getAllKeys(String startingWith) {
return self().settings.getAllKeys(startingWith);
}
/**
* Is Gitblit running in debug mode?
*
* @return true if Gitblit is running in debug mode
*/
public static boolean isDebugMode() {
return self().settings.getBoolean(Keys.web.debugMode, false);
}
/**
* Returns the file object for the specified configuration key.
*
* @return the file
*/
public static File getFileOrFolder(String key, String defaultFileOrFolder) {
String fileOrFolder = GitBlit.getString(key, defaultFileOrFolder);
return getFileOrFolder(fileOrFolder);
}
/**
* Returns the file object which may have it's base-path determined by
* environment variables for running on a cloud hosting service. All Gitblit
* file or folder retrievals are (at least initially) funneled through this
* method so it is the correct point to globally override/alter filesystem
* access based on environment or some other indicator.
*
* @return the file
*/
public static File getFileOrFolder(String fileOrFolder) {
String openShift = System.getenv("OPENSHIFT_DATA_DIR");
if (!StringUtils.isEmpty(openShift)) {
// running on RedHat OpenShift
return new File(openShift, fileOrFolder);
}
return new File(fileOrFolder);
}
/**
* Returns the path of the repositories folder. This method checks to see if
* Gitblit is running on a cloud service and may return an adjusted path.
*
* @return the repositories folder path
*/
public static File getRepositoriesFolder() {
return getFileOrFolder(Keys.git.repositoriesFolder, "git");
}
/**
* Returns the path of the proposals folder. This method checks to see if
* Gitblit is running on a cloud service and may return an adjusted path.
*
* @return the proposals folder path
*/
public static File getProposalsFolder() {
return getFileOrFolder(Keys.federation.proposalsFolder, "proposals");
}
/**
* Returns the path of the Groovy folder. This method checks to see if
* Gitblit is running on a cloud service and may return an adjusted path.
*
* @return the Groovy scripts folder path
*/
public static File getGroovyScriptsFolder() {
return getFileOrFolder(Keys.groovy.scriptsFolder, "groovy");
}
/**
* Updates the list of server settings.
*
* @param settings
* @return true if the update succeeded
*/
public boolean updateSettings(Map<String, String> updatedSettings) {
return settings.saveSettings(updatedSettings);
}
public ServerStatus getStatus() {
// update heap memory status
serverStatus.heapAllocated = Runtime.getRuntime().totalMemory();
serverStatus.heapFree = Runtime.getRuntime().freeMemory();
return serverStatus;
}
/**
* Returns the list of non-Gitblit clone urls. This allows Gitblit to
* advertise alternative urls for Git client repository access.
*
* @param repositoryName
* @return list of non-gitblit clone urls
*/
public List<String> getOtherCloneUrls(String repositoryName) {
List<String> cloneUrls = new ArrayList<String>();
for (String url : settings.getStrings(Keys.web.otherUrls)) {
cloneUrls.add(MessageFormat.format(url, repositoryName));
}
return cloneUrls;
}
/**
* Set the user service. The user service authenticates all users and is
* responsible for managing user permissions.
*
* @param userService
*/
public void setUserService(IUserService userService) {
logger.info("Setting up user service " + userService.toString());
this.userService = userService;
this.userService.setup(settings);
}
/**
* Authenticate a user based on a username and password.
*
* @see IUserService.authenticate(String, char[])
* @param username
* @param password
* @return a user object or null
*/
public UserModel authenticate(String username, char[] password) {
if (StringUtils.isEmpty(username)) {
// can not authenticate empty username
return null;
}
String pw = new String(password);
if (StringUtils.isEmpty(pw)) {
// can not authenticate empty password
return null;
}
// check to see if this is the federation user
if (canFederate()) {
if (username.equalsIgnoreCase(Constants.FEDERATION_USER)) {
List<String> tokens = getFederationTokens();
if (tokens.contains(pw)) {
// the federation user is an administrator
UserModel federationUser = new UserModel(Constants.FEDERATION_USER);
federationUser.canAdmin = true;
return federationUser;
}
}
}
// delegate authentication to the user service
if (userService == null) {
return null;
}
return userService.authenticate(username, password);
}
/**
* Authenticate a user based on their cookie.
*
* @param cookies
* @return a user object or null
*/
public UserModel authenticate(Cookie[] cookies) {
if (userService == null) {
return null;
}
if (userService.supportsCookies()) {
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(Constants.NAME)) {
String value = cookie.getValue();
return userService.authenticate(value.toCharArray());
}
}
}
}
return null;
}
/**
* Sets a cookie for the specified user.
*
* @param response
* @param user
*/
public void setCookie(WebResponse response, UserModel user) {
if (userService == null) {
return;
}
if (userService.supportsCookies()) {
Cookie userCookie;
if (user == null) {
// clear cookie for logout
userCookie = new Cookie(Constants.NAME, "");
} else {
// set cookie for login
char[] cookie = userService.getCookie(user);
userCookie = new Cookie(Constants.NAME, new String(cookie));
userCookie.setMaxAge(Integer.MAX_VALUE);
}
userCookie.setPath("/");
response.addCookie(userCookie);
}
}
/**
* Returns the list of all users available to the login service.
*
* @see IUserService.getAllUsernames()
* @return list of all usernames
*/
public List<String> getAllUsernames() {
List<String> names = new ArrayList<String>(userService.getAllUsernames());
Collections.sort(names);
return names;
}
/**
* Delete the user object with the specified username
*
* @see IUserService.deleteUser(String)
* @param username
* @return true if successful
*/
public boolean deleteUser(String username) {
return userService.deleteUser(username);
}
/**
* Retrieve the user object for the specified username.
*
* @see IUserService.getUserModel(String)
* @param username
* @return a user object or null
*/
public UserModel getUserModel(String username) {
UserModel user = userService.getUserModel(username);
return user;
}
/**
* Returns the list of all users who are allowed to bypass the access
* restriction placed on the specified repository.
*
* @see IUserService.getUsernamesForRepositoryRole(String)
* @param repository
* @return list of all usernames that can bypass the access restriction
*/
public List<String> getRepositoryUsers(RepositoryModel repository) {
return userService.getUsernamesForRepositoryRole(repository.name);
}
/**
* Sets the list of all uses who are allowed to bypass the access
* restriction placed on the specified repository.
*
* @see IUserService.setUsernamesForRepositoryRole(String, List<String>)
* @param repository
* @param usernames
* @return true if successful
*/
public boolean setRepositoryUsers(RepositoryModel repository, List<String> repositoryUsers) {
return userService.setUsernamesForRepositoryRole(repository.name, repositoryUsers);
}
/**
* Adds/updates a complete user object keyed by username. This method allows
* for renaming a user.
*
* @see IUserService.updateUserModel(String, UserModel)
* @param username
* @param user
* @param isCreate
* @throws GitBlitException
*/
public void updateUserModel(String username, UserModel user, boolean isCreate)
throws GitBlitException {
if (!username.equalsIgnoreCase(user.username)) {
if (userService.getUserModel(user.username) != null) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.", username,
user.username));
}
}
if (!userService.updateUserModel(username, user)) {
throw new GitBlitException(isCreate ? "Failed to add user!" : "Failed to update user!");
}
}
/**
* Returns the list of available teams that a user or repository may be
* assigned to.
*
* @return the list of teams
*/
public List<String> getAllTeamnames() {
List<String> teams = new ArrayList<String>(userService.getAllTeamNames());
Collections.sort(teams);
return teams;
}
/**
* Returns the TeamModel object for the specified name.
*
* @param teamname
* @return a TeamModel object or null
*/
public TeamModel getTeamModel(String teamname) {
return userService.getTeamModel(teamname);
}
/**
* Returns the list of all teams who are allowed to bypass the access
* restriction placed on the specified repository.
*
* @see IUserService.getTeamnamesForRepositoryRole(String)
* @param repository
* @return list of all teamnames that can bypass the access restriction
*/
public List<String> getRepositoryTeams(RepositoryModel repository) {
return userService.getTeamnamesForRepositoryRole(repository.name);
}
/**
* Sets the list of all uses who are allowed to bypass the access
* restriction placed on the specified repository.
*
* @see IUserService.setTeamnamesForRepositoryRole(String, List<String>)
* @param repository
* @param teamnames
* @return true if successful
*/
public boolean setRepositoryTeams(RepositoryModel repository, List<String> repositoryTeams) {
return userService.setTeamnamesForRepositoryRole(repository.name, repositoryTeams);
}
/**
* Updates the TeamModel object for the specified name.
*
* @param teamname
* @param team
* @param isCreate
*/
public void updateTeamModel(String teamname, TeamModel team, boolean isCreate)
throws GitBlitException {
if (!teamname.equalsIgnoreCase(team.name)) {
if (userService.getTeamModel(team.name) != null) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.", teamname,
team.name));
}
}
if (!userService.updateTeamModel(teamname, team)) {
throw new GitBlitException(isCreate ? "Failed to add team!" : "Failed to update team!");
}
}
/**
* Delete the team object with the specified teamname
*
* @see IUserService.deleteTeam(String)
* @param teamname
* @return true if successful
*/
public boolean deleteTeam(String teamname) {
return userService.deleteTeam(teamname);
}
/**
* Clears all the cached data for the specified repository.
*
* @param repositoryName
*/
public void clearRepositoryCache(String repositoryName) {
repositorySizeCache.remove(repositoryName);
repositoryMetricsCache.remove(repositoryName);
}
/**
* Returns the list of all repositories available to Gitblit. This method
* does not consider user access permissions.
*
* @return list of all repositories
*/
public List<String> getRepositoryList() {
return JGitUtils.getRepositoryList(repositoriesFolder, exportAll,
settings.getBoolean(Keys.git.searchRepositoriesSubfolders, true));
}
/**
* Returns the JGit repository for the specified name.
*
* @param repositoryName
* @return repository or null
*/
public Repository getRepository(String repositoryName) {
Repository r = null;
try {
r = repositoryResolver.open(null, repositoryName);
} catch (RepositoryNotFoundException e) {
r = null;
logger.error("GitBlit.getRepository(String) failed to find "
+ new File(repositoriesFolder, repositoryName).getAbsolutePath());
} catch (ServiceNotAuthorizedException e) {
r = null;
logger.error("GitBlit.getRepository(String) failed to find "
+ new File(repositoriesFolder, repositoryName).getAbsolutePath(), e);
} catch (ServiceNotEnabledException e) {
r = null;
logger.error("GitBlit.getRepository(String) failed to find "
+ new File(repositoriesFolder, repositoryName).getAbsolutePath(), e);
}
return r;
}
/**
* Returns the list of repository models that are accessible to the user.
*
* @param user
* @return list of repository models accessible to user
*/
public List<RepositoryModel> getRepositoryModels(UserModel user) {
List<String> list = getRepositoryList();
List<RepositoryModel> repositories = new ArrayList<RepositoryModel>();
for (String repo : list) {
RepositoryModel model = getRepositoryModel(user, repo);
if (model != null) {
repositories.add(model);
}
}
if (getBoolean(Keys.web.showRepositorySizes, true)) {
int repoCount = 0;
long startTime = System.currentTimeMillis();
ByteFormat byteFormat = new ByteFormat();
for (RepositoryModel model : repositories) {
if (!model.skipSizeCalculation) {
repoCount++;
model.size = byteFormat.format(calculateSize(model));
}
}
long duration = System.currentTimeMillis() - startTime;
logger.info(MessageFormat.format("{0} repository sizes calculated in {1} msecs",
repoCount, duration));
}
return repositories;
}
/**
* Returns a repository model if the repository exists and the user may
* access the repository.
*
* @param user
* @param repositoryName
* @return repository model or null
*/
public RepositoryModel getRepositoryModel(UserModel user, String repositoryName) {
RepositoryModel model = getRepositoryModel(repositoryName);
if (model == null) {
return null;
}
if (model.accessRestriction.atLeast(AccessRestrictionType.VIEW)) {
if (user != null && user.canAccessRepository(model)) {
return model;
}
return null;
} else {
return model;
}
}
/**
* Returns the repository model for the specified repository. This method
* does not consider user access permissions.
*
* @param repositoryName
* @return repository model or null
*/
public RepositoryModel getRepositoryModel(String repositoryName) {
Repository r = getRepository(repositoryName);
if (r == null) {
return null;
}
RepositoryModel model = new RepositoryModel();
model.name = repositoryName;
model.hasCommits = JGitUtils.hasCommits(r);
model.lastChange = JGitUtils.getLastChange(r, null);
StoredConfig config = JGitUtils.readConfig(r);
if (config != null) {
model.description = getConfig(config, "description", "");
model.owner = getConfig(config, "owner", "");
model.useTickets = getConfig(config, "useTickets", false);
model.useDocs = getConfig(config, "useDocs", false);
model.accessRestriction = AccessRestrictionType.fromName(getConfig(config,
"accessRestriction", null));
model.showRemoteBranches = getConfig(config, "showRemoteBranches", false);
model.isFrozen = getConfig(config, "isFrozen", false);
model.showReadme = getConfig(config, "showReadme", false);
model.skipSizeCalculation = getConfig(config, "skipSizeCalculation", false);
model.skipSummaryMetrics = getConfig(config, "skipSummaryMetrics", false);
model.federationStrategy = FederationStrategy.fromName(getConfig(config,
"federationStrategy", null));
model.federationSets = new ArrayList<String>(Arrays.asList(config.getStringList(
"gitblit", null, "federationSets")));
model.isFederated = getConfig(config, "isFederated", false);
model.origin = config.getString("remote", "origin", "url");
model.preReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
"gitblit", null, "preReceiveScript")));
model.postReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
"gitblit", null, "postReceiveScript")));
model.mailingLists = new ArrayList<String>(Arrays.asList(config.getStringList(
"gitblit", null, "mailingList")));
}
r.close();
return model;
}
/**
* Returns the size in bytes of the repository. Gitblit caches the
* repository sizes to reduce the performance penalty of recursive
* calculation. The cache is updated if the repository has been changed
* since the last calculation.
*
* @param model
* @return size in bytes
*/
public long calculateSize(RepositoryModel model) {
if (repositorySizeCache.hasCurrent(model.name, model.lastChange)) {
return repositorySizeCache.getObject(model.name);
}
File gitDir = FileKey.resolve(new File(repositoriesFolder, model.name), FS.DETECTED);
long size = com.gitblit.utils.FileUtils.folderSize(gitDir);
repositorySizeCache.updateObject(model.name, model.lastChange, size);
return size;
}
/**
* Ensure that a cached repository is completely closed and its resources
* are properly released.
*
* @param repositoryName
*/
private void closeRepository(String repositoryName) {
Repository repository = getRepository(repositoryName);
// assume 2 uses in case reflection fails
int uses = 2;
try {
// The FileResolver caches repositories which is very useful
// for performance until you want to delete a repository.
// I have to use reflection to call close() the correct
// number of times to ensure that the object and ref databases
// are properly closed before I can delete the repository from
// the filesystem.
Field useCnt = Repository.class.getDeclaredField("useCnt");
useCnt.setAccessible(true);
uses = ((AtomicInteger) useCnt.get(repository)).get();
} catch (Exception e) {
logger.warn(MessageFormat
.format("Failed to reflectively determine use count for repository {0}",
repositoryName), e);
}
if (uses > 0) {
logger.info(MessageFormat
.format("{0}.useCnt={1}, calling close() {2} time(s) to close object and ref databases",
repositoryName, uses, uses));
for (int i = 0; i < uses; i++) {
repository.close();
}
}
}
/**
* Returns the metrics for the default branch of the specified repository.
* This method builds a metrics cache. The cache is updated if the
* repository is updated. A new copy of the metrics list is returned on each
* call so that modifications to the list are non-destructive.
*
* @param model
* @param repository
* @return a new array list of metrics
*/
public List<Metric> getRepositoryDefaultMetrics(RepositoryModel model, Repository repository) {
if (repositoryMetricsCache.hasCurrent(model.name, model.lastChange)) {
return new ArrayList<Metric>(repositoryMetricsCache.getObject(model.name));
}
List<Metric> metrics = MetricUtils.getDateMetrics(repository, null, true, null);
repositoryMetricsCache.updateObject(model.name, model.lastChange, metrics);
return new ArrayList<Metric>(metrics);
}
/**
* Returns the gitblit string value for the specified key. If key is not
* set, returns defaultValue.
*
* @param config
* @param field
* @param defaultValue
* @return field value or defaultValue
*/
private String getConfig(StoredConfig config, String field, String defaultValue) {
String value = config.getString("gitblit", null, field);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return value;
}
/**
* Returns the gitblit boolean vlaue for the specified key. If key is not
* set, returns defaultValue.
*
* @param config
* @param field
* @param defaultValue
* @return field value or defaultValue
*/
private boolean getConfig(StoredConfig config, String field, boolean defaultValue) {
return config.getBoolean("gitblit", field, defaultValue);
}
/**
* Creates/updates the repository model keyed by reopsitoryName. Saves all
* repository settings in .git/config. This method allows for renaming
* repositories and will update user access permissions accordingly.
*
* All repositories created by this method are bare and automatically have
* .git appended to their names, which is the standard convention for bare
* repositories.
*
* @param repositoryName
* @param repository
* @param isCreate
* @throws GitBlitException
*/
public void updateRepositoryModel(String repositoryName, RepositoryModel repository,
boolean isCreate) throws GitBlitException {
Repository r = null;
if (isCreate) {
// ensure created repository name ends with .git
if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
if (new File(repositoriesFolder, repository.name).exists()) {
throw new GitBlitException(MessageFormat.format(
"Can not create repository ''{0}'' because it already exists.",
repository.name));
}
// create repository
logger.info("create repository " + repository.name);
r = JGitUtils.createRepository(repositoriesFolder, repository.name);
} else {
// rename repository
if (!repositoryName.equalsIgnoreCase(repository.name)) {
if (!repository.name.toLowerCase().endsWith(
org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
if (new File(repositoriesFolder, repository.name).exists()) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
closeRepository(repositoryName);
File folder = new File(repositoriesFolder, repositoryName);
File destFolder = new File(repositoriesFolder, repository.name);
if (destFolder.exists()) {
throw new GitBlitException(
MessageFormat
.format("Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
+ File parentFile = destFolder.getParentFile();
+ if (!parentFile.exists() && !parentFile.mkdirs()) {
+ throw new GitBlitException(MessageFormat.format(
+ "Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
+ }
if (!folder.renameTo(destFolder)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository ''{0}'' to ''{1}''.", repositoryName,
repository.name));
}
// rename the roles
if (!userService.renameRepositoryRole(repositoryName, repository.name)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository permissions ''{0}'' to ''{1}''.",
repositoryName, repository.name));
}
// clear the cache
clearRepositoryCache(repositoryName);
}
// load repository
logger.info("edit repository " + repository.name);
try {
r = repositoryResolver.open(null, repository.name);
} catch (RepositoryNotFoundException e) {
logger.error("Repository not found", e);
} catch (ServiceNotAuthorizedException e) {
logger.error("Service not authorized", e);
} catch (ServiceNotEnabledException e) {
logger.error("Service not enabled", e);
}
}
// update settings
if (r != null) {
updateConfiguration(r, repository);
r.close();
}
}
/**
* Updates the Gitblit configuration for the specified repository.
*
* @param r
* the Git repository
* @param repository
* the Gitblit repository model
*/
public void updateConfiguration(Repository r, RepositoryModel repository) {
StoredConfig config = JGitUtils.readConfig(r);
config.setString("gitblit", null, "description", repository.description);
config.setString("gitblit", null, "owner", repository.owner);
config.setBoolean("gitblit", null, "useTickets", repository.useTickets);
config.setBoolean("gitblit", null, "useDocs", repository.useDocs);
config.setString("gitblit", null, "accessRestriction", repository.accessRestriction.name());
config.setBoolean("gitblit", null, "showRemoteBranches", repository.showRemoteBranches);
config.setBoolean("gitblit", null, "isFrozen", repository.isFrozen);
config.setBoolean("gitblit", null, "showReadme", repository.showReadme);
config.setBoolean("gitblit", null, "skipSizeCalculation", repository.skipSizeCalculation);
config.setBoolean("gitblit", null, "skipSummaryMetrics", repository.skipSummaryMetrics);
config.setStringList("gitblit", null, "federationSets", repository.federationSets);
config.setString("gitblit", null, "federationStrategy",
repository.federationStrategy.name());
config.setBoolean("gitblit", null, "isFederated", repository.isFederated);
if (repository.preReceiveScripts != null) {
config.setStringList("gitblit", null, "preReceiveScript", repository.preReceiveScripts);
}
if (repository.postReceiveScripts != null) {
config.setStringList("gitblit", null, "postReceiveScript",
repository.postReceiveScripts);
}
if (repository.mailingLists != null) {
config.setStringList("gitblit", null, "mailingList", repository.mailingLists);
}
try {
config.save();
} catch (IOException e) {
logger.error("Failed to save repository config!", e);
}
}
/**
* Deletes the repository from the file system and removes the repository
* permission from all repository users.
*
* @param model
* @return true if successful
*/
public boolean deleteRepositoryModel(RepositoryModel model) {
return deleteRepository(model.name);
}
/**
* Deletes the repository from the file system and removes the repository
* permission from all repository users.
*
* @param repositoryName
* @return true if successful
*/
public boolean deleteRepository(String repositoryName) {
try {
closeRepository(repositoryName);
File folder = new File(repositoriesFolder, repositoryName);
if (folder.exists() && folder.isDirectory()) {
FileUtils.delete(folder, FileUtils.RECURSIVE | FileUtils.RETRY);
if (userService.deleteRepositoryRole(repositoryName)) {
return true;
}
}
// clear the repository cache
clearRepositoryCache(repositoryName);
} catch (Throwable t) {
logger.error(MessageFormat.format("Failed to delete repository {0}", repositoryName), t);
}
return false;
}
/**
* Returns an html version of the commit message with any global or
* repository-specific regular expression substitution applied.
*
* @param repositoryName
* @param text
* @return html version of the commit message
*/
public String processCommitMessage(String repositoryName, String text) {
String html = StringUtils.breakLinesForHtml(text);
Map<String, String> map = new HashMap<String, String>();
// global regex keys
if (settings.getBoolean(Keys.regex.global, false)) {
for (String key : settings.getAllKeys(Keys.regex.global)) {
if (!key.equals(Keys.regex.global)) {
String subKey = key.substring(key.lastIndexOf('.') + 1);
map.put(subKey, settings.getString(key, ""));
}
}
}
// repository-specific regex keys
List<String> keys = settings.getAllKeys(Keys.regex._ROOT + "."
+ repositoryName.toLowerCase());
for (String key : keys) {
String subKey = key.substring(key.lastIndexOf('.') + 1);
map.put(subKey, settings.getString(key, ""));
}
for (Entry<String, String> entry : map.entrySet()) {
String definition = entry.getValue().trim();
String[] chunks = definition.split("!!!");
if (chunks.length == 2) {
html = html.replaceAll(chunks[0], chunks[1]);
} else {
logger.warn(entry.getKey()
+ " improperly formatted. Use !!! to separate match from replacement: "
+ definition);
}
}
return html;
}
/**
* Returns Gitblit's scheduled executor service for scheduling tasks.
*
* @return scheduledExecutor
*/
public ScheduledExecutorService executor() {
return scheduledExecutor;
}
public static boolean canFederate() {
String passphrase = getString(Keys.federation.passphrase, "");
return !StringUtils.isEmpty(passphrase);
}
/**
* Configures this Gitblit instance to pull any registered federated gitblit
* instances.
*/
private void configureFederation() {
boolean validPassphrase = true;
String passphrase = settings.getString(Keys.federation.passphrase, "");
if (StringUtils.isEmpty(passphrase)) {
logger.warn("Federation passphrase is blank! This server can not be PULLED from.");
validPassphrase = false;
}
if (validPassphrase) {
// standard tokens
for (FederationToken tokenType : FederationToken.values()) {
logger.info(MessageFormat.format("Federation {0} token = {1}", tokenType.name(),
getFederationToken(tokenType)));
}
// federation set tokens
for (String set : settings.getStrings(Keys.federation.sets)) {
logger.info(MessageFormat.format("Federation Set {0} token = {1}", set,
getFederationToken(set)));
}
}
// Schedule the federation executor
List<FederationModel> registrations = getFederationRegistrations();
if (registrations.size() > 0) {
FederationPullExecutor executor = new FederationPullExecutor(registrations, true);
scheduledExecutor.schedule(executor, 1, TimeUnit.MINUTES);
}
}
/**
* Returns the list of federated gitblit instances that this instance will
* try to pull.
*
* @return list of registered gitblit instances
*/
public List<FederationModel> getFederationRegistrations() {
if (federationRegistrations.isEmpty()) {
federationRegistrations.addAll(FederationUtils.getFederationRegistrations(settings));
}
return federationRegistrations;
}
/**
* Retrieve the specified federation registration.
*
* @param name
* the name of the registration
* @return a federation registration
*/
public FederationModel getFederationRegistration(String url, String name) {
// check registrations
for (FederationModel r : getFederationRegistrations()) {
if (r.name.equals(name) && r.url.equals(url)) {
return r;
}
}
// check the results
for (FederationModel r : getFederationResultRegistrations()) {
if (r.name.equals(name) && r.url.equals(url)) {
return r;
}
}
return null;
}
/**
* Returns the list of federation sets.
*
* @return list of federation sets
*/
public List<FederationSet> getFederationSets(String gitblitUrl) {
List<FederationSet> list = new ArrayList<FederationSet>();
// generate standard tokens
for (FederationToken type : FederationToken.values()) {
FederationSet fset = new FederationSet(type.toString(), type, getFederationToken(type));
fset.repositories = getRepositories(gitblitUrl, fset.token);
list.add(fset);
}
// generate tokens for federation sets
for (String set : settings.getStrings(Keys.federation.sets)) {
FederationSet fset = new FederationSet(set, FederationToken.REPOSITORIES,
getFederationToken(set));
fset.repositories = getRepositories(gitblitUrl, fset.token);
list.add(fset);
}
return list;
}
/**
* Returns the list of possible federation tokens for this Gitblit instance.
*
* @return list of federation tokens
*/
public List<String> getFederationTokens() {
List<String> tokens = new ArrayList<String>();
// generate standard tokens
for (FederationToken type : FederationToken.values()) {
tokens.add(getFederationToken(type));
}
// generate tokens for federation sets
for (String set : settings.getStrings(Keys.federation.sets)) {
tokens.add(getFederationToken(set));
}
return tokens;
}
/**
* Returns the specified federation token for this Gitblit instance.
*
* @param type
* @return a federation token
*/
public String getFederationToken(FederationToken type) {
return getFederationToken(type.name());
}
/**
* Returns the specified federation token for this Gitblit instance.
*
* @param value
* @return a federation token
*/
public String getFederationToken(String value) {
String passphrase = settings.getString(Keys.federation.passphrase, "");
return StringUtils.getSHA1(passphrase + "-" + value);
}
/**
* Compares the provided token with this Gitblit instance's tokens and
* determines if the requested permission may be granted to the token.
*
* @param req
* @param token
* @return true if the request can be executed
*/
public boolean validateFederationRequest(FederationRequest req, String token) {
String all = getFederationToken(FederationToken.ALL);
String unr = getFederationToken(FederationToken.USERS_AND_REPOSITORIES);
String jur = getFederationToken(FederationToken.REPOSITORIES);
switch (req) {
case PULL_REPOSITORIES:
return token.equals(all) || token.equals(unr) || token.equals(jur);
case PULL_USERS:
case PULL_TEAMS:
return token.equals(all) || token.equals(unr);
case PULL_SETTINGS:
return token.equals(all);
}
return false;
}
/**
* Acknowledge and cache the status of a remote Gitblit instance.
*
* @param identification
* the identification of the pulling Gitblit instance
* @param registration
* the registration from the pulling Gitblit instance
* @return true if acknowledged
*/
public boolean acknowledgeFederationStatus(String identification, FederationModel registration) {
// reset the url to the identification of the pulling Gitblit instance
registration.url = identification;
String id = identification;
if (!StringUtils.isEmpty(registration.folder)) {
id += "-" + registration.folder;
}
federationPullResults.put(id, registration);
return true;
}
/**
* Returns the list of registration results.
*
* @return the list of registration results
*/
public List<FederationModel> getFederationResultRegistrations() {
return new ArrayList<FederationModel>(federationPullResults.values());
}
/**
* Submit a federation proposal. The proposal is cached locally and the
* Gitblit administrator(s) are notified via email.
*
* @param proposal
* the proposal
* @param gitblitUrl
* the url of your gitblit instance to send an email to
* administrators
* @return true if the proposal was submitted
*/
public boolean submitFederationProposal(FederationProposal proposal, String gitblitUrl) {
// convert proposal to json
String json = JsonUtils.toJsonString(proposal);
try {
// make the proposals folder
File proposalsFolder = getProposalsFolder();
proposalsFolder.mkdirs();
// cache json to a file
File file = new File(proposalsFolder, proposal.token + Constants.PROPOSAL_EXT);
com.gitblit.utils.FileUtils.writeContent(file, json);
} catch (Exception e) {
logger.error(MessageFormat.format("Failed to cache proposal from {0}", proposal.url), e);
}
// send an email, if possible
try {
Message message = mailExecutor.createMessageForAdministrators();
if (message != null) {
message.setSubject("Federation proposal from " + proposal.url);
message.setText("Please review the proposal @ " + gitblitUrl + "/proposal/"
+ proposal.token);
mailExecutor.queue(message);
}
} catch (Throwable t) {
logger.error("Failed to notify administrators of proposal", t);
}
return true;
}
/**
* Returns the list of pending federation proposals
*
* @return list of federation proposals
*/
public List<FederationProposal> getPendingFederationProposals() {
List<FederationProposal> list = new ArrayList<FederationProposal>();
File folder = getProposalsFolder();
if (folder.exists()) {
File[] files = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isFile()
&& file.getName().toLowerCase().endsWith(Constants.PROPOSAL_EXT);
}
});
for (File file : files) {
String json = com.gitblit.utils.FileUtils.readContent(file, null);
FederationProposal proposal = JsonUtils.fromJsonString(json,
FederationProposal.class);
list.add(proposal);
}
}
return list;
}
/**
* Get repositories for the specified token.
*
* @param gitblitUrl
* the base url of this gitblit instance
* @param token
* the federation token
* @return a map of <cloneurl, RepositoryModel>
*/
public Map<String, RepositoryModel> getRepositories(String gitblitUrl, String token) {
Map<String, String> federationSets = new HashMap<String, String>();
for (String set : getStrings(Keys.federation.sets)) {
federationSets.put(getFederationToken(set), set);
}
// Determine the Gitblit clone url
StringBuilder sb = new StringBuilder();
sb.append(gitblitUrl);
sb.append(Constants.GIT_PATH);
sb.append("{0}");
String cloneUrl = sb.toString();
// Retrieve all available repositories
UserModel user = new UserModel(Constants.FEDERATION_USER);
user.canAdmin = true;
List<RepositoryModel> list = getRepositoryModels(user);
// create the [cloneurl, repositoryModel] map
Map<String, RepositoryModel> repositories = new HashMap<String, RepositoryModel>();
for (RepositoryModel model : list) {
// by default, setup the url for THIS repository
String url = MessageFormat.format(cloneUrl, model.name);
switch (model.federationStrategy) {
case EXCLUDE:
// skip this repository
continue;
case FEDERATE_ORIGIN:
// federate the origin, if it is defined
if (!StringUtils.isEmpty(model.origin)) {
url = model.origin;
}
break;
}
if (federationSets.containsKey(token)) {
// include repositories only for federation set
String set = federationSets.get(token);
if (model.federationSets.contains(set)) {
repositories.put(url, model);
}
} else {
// standard federation token for ALL
repositories.put(url, model);
}
}
return repositories;
}
/**
* Creates a proposal from the token.
*
* @param gitblitUrl
* the url of this Gitblit instance
* @param token
* @return a potential proposal
*/
public FederationProposal createFederationProposal(String gitblitUrl, String token) {
FederationToken tokenType = FederationToken.REPOSITORIES;
for (FederationToken type : FederationToken.values()) {
if (token.equals(getFederationToken(type))) {
tokenType = type;
break;
}
}
Map<String, RepositoryModel> repositories = getRepositories(gitblitUrl, token);
FederationProposal proposal = new FederationProposal(gitblitUrl, tokenType, token,
repositories);
return proposal;
}
/**
* Returns the proposal identified by the supplied token.
*
* @param token
* @return the specified proposal or null
*/
public FederationProposal getPendingFederationProposal(String token) {
List<FederationProposal> list = getPendingFederationProposals();
for (FederationProposal proposal : list) {
if (proposal.token.equals(token)) {
return proposal;
}
}
return null;
}
/**
* Deletes a pending federation proposal.
*
* @param a
* proposal
* @return true if the proposal was deleted
*/
public boolean deletePendingFederationProposal(FederationProposal proposal) {
File folder = getProposalsFolder();
File file = new File(folder, proposal.token + Constants.PROPOSAL_EXT);
return file.delete();
}
/**
* Returns the list of all available Groovy push hook scripts that are not
* already specified globally for all repositories. Script files must have
* .groovy extension
*
* @return list of available hook scripts
*/
public List<String> getAvailableScripts() {
File groovyFolder = getGroovyScriptsFolder();
File[] files = groovyFolder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".groovy");
}
});
Set<String> globals = new HashSet<String>();
String[] keys = { Keys.groovy.preReceiveScripts, Keys.groovy.postReceiveScripts };
for (String key : keys) {
for (String script : getStrings(key)) {
if (script.endsWith(".groovy")) {
globals.add(script.substring(0, script.lastIndexOf('.')));
} else {
globals.add(script);
}
}
}
// create list of available scripts by excluding scripts that are
// globally specified
List<String> scripts = new ArrayList<String>();
if (files != null) {
for (File file : files) {
String script = file.getName().substring(0, file.getName().lastIndexOf('.'));
if (!globals.contains(script)) {
scripts.add(script);
}
}
}
return scripts;
}
public List<String> getInheritedPreReceiveScripts(RepositoryModel repository) {
Set<String> globals = new HashSet<String>();
for (String script : getStrings(Keys.groovy.preReceiveScripts)) {
if (script.endsWith(".groovy")) {
globals.add(script.substring(0, script.lastIndexOf('.')));
} else {
globals.add(script);
}
}
return new ArrayList<String>(globals);
}
public List<String> getInheritedPostReceiveScripts(RepositoryModel repository) {
Set<String> globals = new HashSet<String>();
for (String script : getStrings(Keys.groovy.postReceiveScripts)) {
if (script.endsWith(".groovy")) {
globals.add(script.substring(0, script.lastIndexOf('.')));
} else {
globals.add(script);
}
}
return new ArrayList<String>(globals);
}
/**
* Notify the administrators by email.
*
* @param subject
* @param message
*/
public void sendMailToAdministrators(String subject, String message) {
try {
Message mail = mailExecutor.createMessageForAdministrators();
if (mail != null) {
mail.setSubject(subject);
mail.setText(message);
mailExecutor.queue(mail);
}
} catch (MessagingException e) {
logger.error("Messaging error", e);
}
}
/**
* Notify users by email of something.
*
* @param subject
* @param message
* @param toAddresses
*/
public void sendMail(String subject, String message, Collection<String> toAddresses) {
this.sendMail(subject, message, toAddresses.toArray(new String[0]));
}
/**
* Notify users by email of something.
*
* @param subject
* @param message
* @param toAddresses
*/
public void sendMail(String subject, String message, String... toAddresses) {
try {
Message mail = mailExecutor.createMessage(toAddresses);
if (mail != null) {
mail.setSubject(subject);
mail.setText(message);
mailExecutor.queue(mail);
}
} catch (MessagingException e) {
logger.error("Messaging error", e);
}
}
/**
* Returns the descriptions/comments of the Gitblit config settings.
*
* @return SettingsModel
*/
public ServerSettings getSettingsModel() {
// ensure that the current values are updated in the setting models
for (String key : settings.getAllKeys(null)) {
SettingModel setting = settingsModel.get(key);
if (setting != null) {
setting.currentValue = settings.getString(key, "");
}
}
settingsModel.pushScripts = getAvailableScripts();
return settingsModel;
}
/**
* Parse the properties file and aggregate all the comments by the setting
* key. A setting model tracks the current value, the default value, the
* description of the setting and and directives about the setting.
*
* @return Map<String, SettingModel>
*/
private ServerSettings loadSettingModels() {
ServerSettings settingsModel = new ServerSettings();
try {
// Read bundled Gitblit properties to extract setting descriptions.
// This copy is pristine and only used for populating the setting
// models map.
InputStream is = servletContext.getResourceAsStream("/WEB-INF/reference.properties");
BufferedReader propertiesReader = new BufferedReader(new InputStreamReader(is));
StringBuilder description = new StringBuilder();
SettingModel setting = new SettingModel();
String line = null;
while ((line = propertiesReader.readLine()) != null) {
if (line.length() == 0) {
description.setLength(0);
setting = new SettingModel();
} else {
if (line.charAt(0) == '#') {
if (line.length() > 1) {
String text = line.substring(1).trim();
if (SettingModel.CASE_SENSITIVE.equals(text)) {
setting.caseSensitive = true;
} else if (SettingModel.RESTART_REQUIRED.equals(text)) {
setting.restartRequired = true;
} else if (SettingModel.SPACE_DELIMITED.equals(text)) {
setting.spaceDelimited = true;
} else if (text.startsWith(SettingModel.SINCE)) {
try {
setting.since = text.split(" ")[1];
} catch (Exception e) {
setting.since = text;
}
} else {
description.append(text);
description.append('\n');
}
}
} else {
String[] kvp = line.split("=", 2);
String key = kvp[0].trim();
setting.name = key;
setting.defaultValue = kvp[1].trim();
setting.currentValue = setting.defaultValue;
setting.description = description.toString().trim();
settingsModel.add(setting);
description.setLength(0);
setting = new SettingModel();
}
}
}
propertiesReader.close();
} catch (NullPointerException e) {
logger.error("Failed to find resource copy of gitblit.properties");
} catch (IOException e) {
logger.error("Failed to load resource copy of gitblit.properties");
}
return settingsModel;
}
/**
* Configure the Gitblit singleton with the specified settings source. This
* source may be file settings (Gitblit GO) or may be web.xml settings
* (Gitblit WAR).
*
* @param settings
*/
public void configureContext(IStoredSettings settings, boolean startFederation) {
logger.info("Reading configuration from " + settings.toString());
this.settings = settings;
repositoriesFolder = getRepositoriesFolder();
logger.info("Git repositories folder " + repositoriesFolder.getAbsolutePath());
repositoryResolver = new FileResolver<Void>(repositoriesFolder, exportAll);
serverStatus = new ServerStatus(isGO());
String realm = settings.getString(Keys.realm.userService, "users.properties");
IUserService loginService = null;
try {
// check to see if this "file" is a login service class
Class<?> realmClass = Class.forName(realm);
if (IUserService.class.isAssignableFrom(realmClass)) {
loginService = (IUserService) realmClass.newInstance();
}
} catch (Throwable t) {
loginService = new GitblitUserService();
}
setUserService(loginService);
mailExecutor = new MailExecutor(settings);
if (mailExecutor.isReady()) {
scheduledExecutor.scheduleAtFixedRate(mailExecutor, 1, 2, TimeUnit.MINUTES);
} else {
logger.warn("Mail server is not properly configured. Mail services disabled.");
}
if (startFederation) {
configureFederation();
}
}
/**
* Configure Gitblit from the web.xml, if no configuration has already been
* specified.
*
* @see ServletContextListener.contextInitialize(ServletContextEvent)
*/
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
servletContext = contextEvent.getServletContext();
settingsModel = loadSettingModels();
if (settings == null) {
// Gitblit WAR is running in a servlet container
ServletContext context = contextEvent.getServletContext();
WebXmlSettings webxmlSettings = new WebXmlSettings(context);
// 0.7.0 web.properties in the deployed war folder
File overrideFile = new File(context.getRealPath("/WEB-INF/web.properties"));
if (overrideFile.exists()) {
webxmlSettings.applyOverrides(overrideFile);
}
// 0.8.0 gitblit.properties file located outside the deployed war
// folder lie, for example, on RedHat OpenShift.
overrideFile = getFileOrFolder("gitblit.properties");
if (!overrideFile.getPath().equals("gitblit.properties")) {
webxmlSettings.applyOverrides(overrideFile);
}
configureContext(webxmlSettings, true);
}
serverStatus.servletContainer = servletContext.getServerInfo();
}
/**
* Gitblit is being shutdown either because the servlet container is
* shutting down or because the servlet container is re-deploying Gitblit.
*/
@Override
public void contextDestroyed(ServletContextEvent contextEvent) {
logger.info("Gitblit context destroyed by servlet container.");
scheduledExecutor.shutdownNow();
}
}
| true | true | public void updateRepositoryModel(String repositoryName, RepositoryModel repository,
boolean isCreate) throws GitBlitException {
Repository r = null;
if (isCreate) {
// ensure created repository name ends with .git
if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
if (new File(repositoriesFolder, repository.name).exists()) {
throw new GitBlitException(MessageFormat.format(
"Can not create repository ''{0}'' because it already exists.",
repository.name));
}
// create repository
logger.info("create repository " + repository.name);
r = JGitUtils.createRepository(repositoriesFolder, repository.name);
} else {
// rename repository
if (!repositoryName.equalsIgnoreCase(repository.name)) {
if (!repository.name.toLowerCase().endsWith(
org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
if (new File(repositoriesFolder, repository.name).exists()) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
closeRepository(repositoryName);
File folder = new File(repositoriesFolder, repositoryName);
File destFolder = new File(repositoriesFolder, repository.name);
if (destFolder.exists()) {
throw new GitBlitException(
MessageFormat
.format("Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
if (!folder.renameTo(destFolder)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository ''{0}'' to ''{1}''.", repositoryName,
repository.name));
}
// rename the roles
if (!userService.renameRepositoryRole(repositoryName, repository.name)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository permissions ''{0}'' to ''{1}''.",
repositoryName, repository.name));
}
// clear the cache
clearRepositoryCache(repositoryName);
}
// load repository
logger.info("edit repository " + repository.name);
try {
r = repositoryResolver.open(null, repository.name);
} catch (RepositoryNotFoundException e) {
logger.error("Repository not found", e);
} catch (ServiceNotAuthorizedException e) {
logger.error("Service not authorized", e);
} catch (ServiceNotEnabledException e) {
logger.error("Service not enabled", e);
}
}
// update settings
if (r != null) {
updateConfiguration(r, repository);
r.close();
}
}
| public void updateRepositoryModel(String repositoryName, RepositoryModel repository,
boolean isCreate) throws GitBlitException {
Repository r = null;
if (isCreate) {
// ensure created repository name ends with .git
if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
if (new File(repositoriesFolder, repository.name).exists()) {
throw new GitBlitException(MessageFormat.format(
"Can not create repository ''{0}'' because it already exists.",
repository.name));
}
// create repository
logger.info("create repository " + repository.name);
r = JGitUtils.createRepository(repositoriesFolder, repository.name);
} else {
// rename repository
if (!repositoryName.equalsIgnoreCase(repository.name)) {
if (!repository.name.toLowerCase().endsWith(
org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
if (new File(repositoriesFolder, repository.name).exists()) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
closeRepository(repositoryName);
File folder = new File(repositoriesFolder, repositoryName);
File destFolder = new File(repositoriesFolder, repository.name);
if (destFolder.exists()) {
throw new GitBlitException(
MessageFormat
.format("Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
File parentFile = destFolder.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
throw new GitBlitException(MessageFormat.format(
"Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
}
if (!folder.renameTo(destFolder)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository ''{0}'' to ''{1}''.", repositoryName,
repository.name));
}
// rename the roles
if (!userService.renameRepositoryRole(repositoryName, repository.name)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository permissions ''{0}'' to ''{1}''.",
repositoryName, repository.name));
}
// clear the cache
clearRepositoryCache(repositoryName);
}
// load repository
logger.info("edit repository " + repository.name);
try {
r = repositoryResolver.open(null, repository.name);
} catch (RepositoryNotFoundException e) {
logger.error("Repository not found", e);
} catch (ServiceNotAuthorizedException e) {
logger.error("Service not authorized", e);
} catch (ServiceNotEnabledException e) {
logger.error("Service not enabled", e);
}
}
// update settings
if (r != null) {
updateConfiguration(r, repository);
r.close();
}
}
|
diff --git a/src/org/apache/xerces/validators/common/XMLValidator.java b/src/org/apache/xerces/validators/common/XMLValidator.java
index 0546456c4..1eaca6211 100644
--- a/src/org/apache/xerces/validators/common/XMLValidator.java
+++ b/src/org/apache/xerces/validators/common/XMLValidator.java
@@ -1,3548 +1,3551 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999,2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.validators.common;
import org.apache.xerces.framework.XMLAttrList;
import org.apache.xerces.framework.XMLContentSpec;
import org.apache.xerces.framework.XMLDocumentHandler;
import org.apache.xerces.framework.XMLDocumentScanner;
import org.apache.xerces.framework.XMLErrorReporter;
import org.apache.xerces.readers.DefaultEntityHandler;
import org.apache.xerces.readers.XMLEntityHandler;
import org.apache.xerces.utils.ChunkyCharArray;
import org.apache.xerces.utils.Hash2intTable;
import org.apache.xerces.utils.NamespacesScope;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.StringPool;
import org.apache.xerces.utils.XMLCharacterProperties;
import org.apache.xerces.utils.XMLMessages;
import org.apache.xerces.utils.ImplementationMessages;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.EntityResolver;
import org.xml.sax.Locator;
import org.xml.sax.helpers.LocatorImpl;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.xerces.validators.dtd.DTDGrammar;
import org.apache.xerces.validators.schema.SchemaGrammar;
import org.apache.xerces.validators.schema.SchemaMessageProvider;
import org.apache.xerces.validators.schema.SchemaSymbols;
import org.apache.xerces.validators.schema.TraverseSchema;
import org.apache.xerces.validators.datatype.DatatypeValidator;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
/**
* This class is the super all-in-one validator used by the parser.
*
* @version $Id$
*/
public final class XMLValidator
implements DefaultEntityHandler.EventHandler,
XMLEntityHandler.CharDataHandler,
XMLDocumentScanner.EventHandler,
NamespacesScope.NamespacesHandler {
//
// Constants
//
// debugging
private static final boolean PRINT_EXCEPTION_STACK_TRACE = false;
private static final boolean DEBUG_PRINT_ATTRIBUTES = false;
private static final boolean DEBUG_PRINT_CONTENT = false;
private static final boolean DEBUG_SCHEMA_VALIDATION = false;
private static final boolean DEBUG_ELEMENT_CHILDREN = false;
// Chunk size constants
private static final int CHUNK_SHIFT = 8; // 2^8 = 256
private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT);
private static final int CHUNK_MASK = CHUNK_SIZE - 1;
private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k
//
// Data
//
// REVISIT: The data should be regrouped and re-organized so that
// it's easier to find a meaningful field.
// debugging
// private static boolean DEBUG = false;
// other
private Hashtable fIdDefs = null;
private Hashtable fIdRefs = null;
private Object fNullValue = null;
// attribute validators
// REVISIT: Validation. A validator per element declaration and
// attribute declaration is required to accomodate
// Schema facets on simple types.
private AttributeValidator fAttValidatorCDATA = null;
private AttributeValidator fAttValidatorID = new AttValidatorID();
private AttributeValidator fAttValidatorIDREF = new AttValidatorIDREF();
private AttributeValidator fAttValidatorIDREFS = new AttValidatorIDREFS();
private AttributeValidator fAttValidatorENTITY = new AttValidatorENTITY();
private AttributeValidator fAttValidatorENTITIES = new AttValidatorENTITIES();
private AttributeValidator fAttValidatorNMTOKEN = new AttValidatorNMTOKEN();
private AttributeValidator fAttValidatorNMTOKENS = new AttValidatorNMTOKENS();
private AttributeValidator fAttValidatorNOTATION = new AttValidatorNOTATION();
private AttributeValidator fAttValidatorENUMERATION = new AttValidatorENUMERATION();
private AttributeValidator fAttValidatorDATATYPE = null;
// Package access for use by AttributeValidator classes.
StringPool fStringPool = null;
boolean fValidating = false;
boolean fInElementContent = false;
int fStandaloneReader = -1;
// settings
private boolean fValidationEnabled = false;
private boolean fDynamicValidation = false;
private boolean fSchemaValidation = true;
private boolean fValidationEnabledByDynamic = false;
private boolean fDynamicDisabledByValidation = false;
private boolean fWarningOnDuplicateAttDef = false;
private boolean fWarningOnUndeclaredElements = false;
// declarations
private int fDeclaration[];
private XMLErrorReporter fErrorReporter = null;
private DefaultEntityHandler fEntityHandler = null;
private QName fCurrentElement = new QName();
//REVISIT: validation
private int[] fScopeStack = new int[8];
private int[] fGrammarNameSpaceIndexStack = new int[8];
private int[] fElementTypeStack = new int[8];
private int[] fElementEntityStack = new int[8];
private int[] fElementIndexStack = new int[8];
private int[] fContentSpecTypeStack = new int[8];
private QName[] fElementChildren = new QName[32];
private int fElementChildrenLength = 0;
private int[] fElementChildrenOffsetStack = new int[32];
private int fElementDepth = -1;
private boolean fNamespacesEnabled = false;
private NamespacesScope fNamespacesScope = null;
private int fNamespacesPrefix = -1;
private QName fRootElement = new QName();
private int fAttrListHandle = -1;
private int fCurrentElementEntity = -1;
private int fCurrentElementIndex = -1;
private int fCurrentContentSpecType = -1;
private boolean fSeenDoctypeDecl = false;
private final int TOP_LEVEL_SCOPE = -1;
private int fCurrentScope = TOP_LEVEL_SCOPE;
private int fCurrentSchemaURI = -1;
private int fEmptyURI = - 1;
private int fXsiPrefix = - 1;
private int fXsiURI = -2;
private Grammar fGrammar = null;
private int fGrammarNameSpaceIndex = -1;
private GrammarResolver fGrammarResolver = null;
// state and stuff
private boolean fScanningDTD = false;
private XMLDocumentScanner fDocumentScanner = null;
private boolean fCalledStartDocument = false;
private XMLDocumentHandler fDocumentHandler = null;
private XMLDocumentHandler.DTDHandler fDTDHandler = null;
private boolean fSeenRootElement = false;
private XMLAttrList fAttrList = null;
private int fXMLLang = -1;
private LocatorImpl fAttrNameLocator = null;
private boolean fCheckedForSchema = false;
private boolean fDeclsAreExternal = false;
private StringPool.CharArrayRange fCurrentElementCharArrayRange = null;
private char[] fCharRefData = null;
private boolean fSendCharDataAsCharArray = false;
private boolean fBufferDatatype = false;
private StringBuffer fDatatypeBuffer = new StringBuffer();
private QName fTempQName = new QName();
private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl();
private XMLElementDecl fTempElementDecl = new XMLElementDecl();
//REVISIT: ericye, use this temp QName whenever we can!!
private boolean fGrammarIsDTDGrammar = false;
private boolean fGrammarIsSchemaGrammar = false;
// symbols
private int fEMPTYSymbol = -1;
private int fANYSymbol = -1;
private int fMIXEDSymbol = -1;
private int fCHILDRENSymbol = -1;
private int fCDATASymbol = -1;
private int fIDSymbol = -1;
private int fIDREFSymbol = -1;
private int fIDREFSSymbol = -1;
private int fENTITYSymbol = -1;
private int fENTITIESSymbol = -1;
private int fNMTOKENSymbol = -1;
private int fNMTOKENSSymbol = -1;
private int fNOTATIONSymbol = -1;
private int fENUMERATIONSymbol = -1;
private int fREQUIREDSymbol = -1;
private int fFIXEDSymbol = -1;
private int fDATATYPESymbol = -1;
private int fEpsilonIndex = -1;
//
// Constructors
//
/** Constructs an XML validator. */
public XMLValidator(StringPool stringPool,
XMLErrorReporter errorReporter,
DefaultEntityHandler entityHandler,
XMLDocumentScanner documentScanner) {
// keep references
fStringPool = stringPool;
fErrorReporter = errorReporter;
fEntityHandler = entityHandler;
fDocumentScanner = documentScanner;
fEmptyURI = fStringPool.addSymbol("");
fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI);
// initialize
fAttrList = new XMLAttrList(fStringPool);
entityHandler.setEventHandler(this);
entityHandler.setCharDataHandler(this);
fDocumentScanner.setEventHandler(this);
init();
} // <init>(StringPool,XMLErrorReporter,DefaultEntityHandler,XMLDocumentScanner)
public void setGrammarResolver(GrammarResolver grammarResolver){
fGrammarResolver = grammarResolver;
}
//
// Public methods
//
// initialization
/** Set char data processing preference and handlers. */
public void initHandlers(boolean sendCharDataAsCharArray,
XMLDocumentHandler docHandler,
XMLDocumentHandler.DTDHandler dtdHandler) {
fSendCharDataAsCharArray = sendCharDataAsCharArray;
fEntityHandler.setSendCharDataAsCharArray(fSendCharDataAsCharArray);
fDocumentHandler = docHandler;
fDTDHandler = dtdHandler;
} // initHandlers(boolean,XMLDocumentHandler,XMLDocumentHandler.DTDHandler)
/** Reset or copy. */
public void resetOrCopy(StringPool stringPool) throws Exception {
fAttrList = new XMLAttrList(stringPool);
resetCommon(stringPool);
}
/** Reset. */
public void reset(StringPool stringPool) throws Exception {
fAttrList.reset(stringPool);
resetCommon(stringPool);
}
// settings
/**
* Turning on validation/dynamic turns on validation if it is off, and
* this is remembered. Turning off validation DISABLES validation/dynamic
* if it is on. Turning off validation/dynamic DOES NOT turn off
* validation if it was explicitly turned on, only if it was turned on
* BECAUSE OF the call to turn validation/dynamic on. Turning on
* validation will REENABLE and turn validation/dynamic back on if it
* was disabled by a call that turned off validation while
* validation/dynamic was enabled.
*/
public void setValidationEnabled(boolean flag) throws Exception {
fValidationEnabled = flag;
fValidationEnabledByDynamic = false;
if (fValidationEnabled) {
if (fDynamicDisabledByValidation) {
fDynamicValidation = true;
fDynamicDisabledByValidation = false;
}
} else if (fDynamicValidation) {
fDynamicValidation = false;
fDynamicDisabledByValidation = true;
}
fValidating = fValidationEnabled;
}
/** Returns true if validation is enabled. */
public boolean getValidationEnabled() {
return fValidationEnabled;
}
/** Sets whether Schema support is on/off. */
public void setSchemaValidationEnabled(boolean flag) {
fSchemaValidation = flag;
}
/** Returns true if Schema support is on. */
public boolean getSchemaValidationEnabled() {
return fSchemaValidation;
}
/** Sets whether validation is dynamic. */
public void setDynamicValidationEnabled(boolean flag) throws Exception {
fDynamicValidation = flag;
fDynamicDisabledByValidation = false;
if (!fDynamicValidation) {
if (fValidationEnabledByDynamic) {
fValidationEnabled = false;
fValidationEnabledByDynamic = false;
}
} else if (!fValidationEnabled) {
fValidationEnabled = true;
fValidationEnabledByDynamic = true;
}
fValidating = fValidationEnabled;
}
/** Returns true if validation is dynamic. */
public boolean getDynamicValidationEnabled() {
return fDynamicValidation;
}
/** Sets whether namespaces are enabled. */
public void setNamespacesEnabled(boolean flag) {
fNamespacesEnabled = flag;
}
/** Returns true if namespaces are enabled. */
public boolean getNamespacesEnabled() {
return fNamespacesEnabled;
}
/** Sets whether duplicate attribute definitions signal a warning. */
public void setWarningOnDuplicateAttDef(boolean flag) {
fWarningOnDuplicateAttDef = flag;
}
/** Returns true if duplicate attribute definitions signal a warning. */
public boolean getWarningOnDuplicateAttDef() {
return fWarningOnDuplicateAttDef;
}
/** Sets whether undeclared elements signal a warning. */
public void setWarningOnUndeclaredElements(boolean flag) {
fWarningOnUndeclaredElements = flag;
}
/** Returns true if undeclared elements signal a warning. */
public boolean getWarningOnUndeclaredElements() {
return fWarningOnUndeclaredElements;
}
//
// DefaultEntityHandler.EventHandler methods
//
/** Start entity reference. */
public void startEntityReference(int entityName, int entityType, int entityContext) throws Exception {
fDocumentHandler.startEntityReference(entityName, entityType, entityContext);
}
/** End entity reference. */
public void endEntityReference(int entityName, int entityType, int entityContext) throws Exception {
fDocumentHandler.endEntityReference(entityName, entityType, entityContext);
}
/** Send end of input notification. */
public void sendEndOfInputNotifications(int entityName, boolean moreToFollow) throws Exception {
fDocumentScanner.endOfInput(entityName, moreToFollow);
/***
if (fScanningDTD) {
fDTDImporter.sendEndOfInputNotifications(entityName, moreToFollow);
}
/***/
}
/** Send reader change notifications. */
public void sendReaderChangeNotifications(XMLEntityHandler.EntityReader reader, int readerId) throws Exception {
fDocumentScanner.readerChange(reader, readerId);
/***
if (fScanningDTD) {
fDTDImporter.sendReaderChangeNotifications(reader, readerId);
}
/***/
}
/** External entity standalone check. */
public boolean externalEntityStandaloneCheck() {
return (fStandaloneReader != -1 && fValidating);
}
/** Return true if validating. */
public boolean getValidating() {
return fValidating;
}
//
// XMLEntityHandler.CharDataHandler methods
//
/** Process characters. */
public void processCharacters(char[] chars, int offset, int length) throws Exception {
if (fValidating) {
if (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
if (fBufferDatatype) {
fDatatypeBuffer.append(chars, offset, length);
}
}
fDocumentHandler.characters(chars, offset, length);
}
/** Process characters. */
public void processCharacters(int data) throws Exception {
if (fValidating) {
if (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
if (fBufferDatatype) {
fDatatypeBuffer.append(fStringPool.toString(data));
}
}
fDocumentHandler.characters(data);
}
/** Process whitespace. */
public void processWhitespace(char[] chars, int offset, int length)
throws Exception {
if (fInElementContent) {
if (fStandaloneReader != -1 && fValidating && getElementDeclIsExternal(fCurrentElementIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION);
}
fDocumentHandler.ignorableWhitespace(chars, offset, length);
}
else {
if (fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
fDocumentHandler.characters(chars, offset, length);
}
} // processWhitespace(char[],int,int)
/** Process whitespace. */
public void processWhitespace(int data) throws Exception {
if (fInElementContent) {
if (fStandaloneReader != -1 && fValidating && getElementDeclIsExternal(fCurrentElementIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION);
}
fDocumentHandler.ignorableWhitespace(data);
} else {
if (fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
fDocumentHandler.characters(data);
}
} // processWhitespace(int)
//
// XMLDocumentScanner.EventHandler methods
//
/** Scans element type. */
public void scanElementType(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName element) throws Exception {
if (!fNamespacesEnabled) {
element.clear();
element.localpart = entityReader.scanName(fastchar);
element.rawname = element.localpart;
}
else {
entityReader.scanQName(fastchar, element);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
}
} // scanElementType(XMLEntityHandler.EntityReader,char,QName)
/** Scans expected element type. */
public boolean scanExpectedElementType(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName element)
throws Exception {
if (fCurrentElementCharArrayRange == null) {
fCurrentElementCharArrayRange = fStringPool.createCharArrayRange();
}
fStringPool.getCharArrayRange(fCurrentElement.rawname, fCurrentElementCharArrayRange);
return entityReader.scanExpectedName(fastchar, fCurrentElementCharArrayRange);
} // scanExpectedElementType(XMLEntityHandler.EntityReader,char,QName)
/** Scans attribute name. */
public void scanAttributeName(XMLEntityHandler.EntityReader entityReader,
QName element, QName attribute)
throws Exception {
if (!fSeenRootElement) {
fSeenRootElement = true;
rootElementSpecified(element);
fStringPool.resetShuffleCount();
}
if (!fNamespacesEnabled) {
attribute.clear();
attribute.localpart = entityReader.scanName('=');
attribute.rawname = attribute.localpart;
}
else {
entityReader.scanQName('=', attribute);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
}
} // scanAttributeName(XMLEntityHandler.EntityReader,QName,QName)
/** Call start document. */
public void callStartDocument() throws Exception {
if (!fCalledStartDocument) {
fDocumentHandler.startDocument();
fCalledStartDocument = true;
}
}
/** Call end document. */
public void callEndDocument() throws Exception {
if (fCalledStartDocument) {
fDocumentHandler.endDocument();
}
}
/** Call XML declaration. */
public void callXMLDecl(int version, int encoding, int standalone) throws Exception {
fDocumentHandler.xmlDecl(version, encoding, standalone);
}
public void callStandaloneIsYes() throws Exception {
// standalone = "yes". said XMLDocumentScanner.
fStandaloneReader = fEntityHandler.getReaderId() ;
}
/** Call text declaration. */
public void callTextDecl(int version, int encoding) throws Exception {
fDocumentHandler.textDecl(version, encoding);
}
/**
* Signal the scanning of an element name in a start element tag.
*
* @param element Element name scanned.
*/
public void element(QName element) throws Exception {
fAttrListHandle = -1;
}
/**
* Signal the scanning of an attribute associated to the previous
* start element tag.
*
* @param element Element name scanned.
* @param attrName Attribute name scanned.
* @param attrValue The string pool index of the attribute value.
*/
public boolean attribute(QName element, QName attrName, int attrValue) throws Exception {
if (fAttrListHandle == -1) {
fAttrListHandle = fAttrList.startAttrList();
}
// if fAttrList.addAttr returns -1, indicates duplicate att in start tag of an element.
// specified: true, search : true
return fAttrList.addAttr(attrName, attrValue, fCDATASymbol, true, true) == -1;
}
/** Call start element. */
public void callStartElement(QName element) throws Exception {
if ( DEBUG_SCHEMA_VALIDATION )
System.out.println("\n=======StartElement : " + fStringPool.toString(element.localpart));
//
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// (2) add default attrs (FIXED and NOT_FIXED)
//
if (!fSeenRootElement) {
fSeenRootElement = true;
rootElementSpecified(element);
fStringPool.resetShuffleCount();
}
fCheckedForSchema = true;
if (fNamespacesEnabled) {
bindNamespacesToElementAndAttributes(element, fAttrList);
}
validateElementAndAttributes(element, fAttrList);
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
fDocumentHandler.startElement(element, fAttrList, fAttrListHandle);
fAttrListHandle = -1;
//before we increment the element depth, add this element's QName to its enclosing element 's children list
fElementDepth++;
//if (fElementDepth >= 0) {
if (fValidating) {
// push current length onto stack
if (fElementChildrenOffsetStack.length < fElementDepth) {
int newarray[] = new int[fElementChildrenOffsetStack.length * 2];
System.arraycopy(fElementChildrenOffsetStack, 0, newarray, 0, fElementChildrenOffsetStack.length);
fElementChildrenOffsetStack = newarray;
}
fElementChildrenOffsetStack[fElementDepth] = fElementChildrenLength;
// add this element to children
if (fElementChildren.length <= fElementChildrenLength) {
QName[] newarray = new QName[fElementChildrenLength * 2];
System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length);
fElementChildren = newarray;
}
QName qname = fElementChildren[fElementChildrenLength];
if (qname == null) {
for (int i = fElementChildrenLength; i < fElementChildren.length; i++) {
fElementChildren[i] = new QName();
}
qname = fElementChildren[fElementChildrenLength];
}
qname.setValues(element);
fElementChildrenLength++;
if (DEBUG_ELEMENT_CHILDREN) {
printChildren();
printStack();
}
}
// One more level of depth
//fElementDepth++;
ensureStackCapacity(fElementDepth);
fCurrentElement.setValues(element);
fCurrentElementEntity = fEntityHandler.getReaderId();
fElementTypeStack[fElementDepth] = fCurrentElement.rawname;
fElementEntityStack[fElementDepth] = fCurrentElementEntity;
fElementIndexStack[fElementDepth] = fCurrentElementIndex;
fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType;
//REVISIT: Validation
if ( fCurrentElementIndex > -1 && fGrammarIsSchemaGrammar && fValidating) {
fCurrentScope = ((SchemaGrammar) fGrammar).getElementDefinedScope(fCurrentElementIndex);
}
fScopeStack[fElementDepth] = fCurrentScope;
fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex;
} // callStartElement(QName)
private void ensureStackCapacity ( int newElementDepth) {
if (newElementDepth == fElementTypeStack.length) {
int[] newStack = new int[newElementDepth * 2];
System.arraycopy(fScopeStack, 0, newStack, 0, newElementDepth);
fScopeStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fGrammarNameSpaceIndexStack, 0, newStack, 0, newElementDepth);
fGrammarNameSpaceIndexStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fElementTypeStack, 0, newStack, 0, newElementDepth);
fElementTypeStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fElementEntityStack, 0, newStack, 0, newElementDepth);
fElementEntityStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fElementIndexStack, 0, newStack, 0, newElementDepth);
fElementIndexStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, newElementDepth);
fContentSpecTypeStack = newStack;
}
}
/** Call end element. */
public void callEndElement(int readerId) throws Exception {
if ( DEBUG_SCHEMA_VALIDATION )
System.out.println("=======EndElement : " + fStringPool.toString(fCurrentElement.localpart)+"\n");
int prefixIndex = fCurrentElement.prefix;
// REVISIT: Validation
int elementType = fCurrentElement.rawname;
if (fCurrentElementEntity != readerId) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ELEMENT_ENTITY_MISMATCH,
XMLMessages.P78_NOT_WELLFORMED,
new Object[] { fStringPool.toString(elementType) },
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
fElementDepth--;
if (fValidating) {
int elementIndex = fCurrentElementIndex;
if (elementIndex != -1 && fCurrentContentSpecType != -1) {
QName children[] = fElementChildren;
int childrenOffset = fElementChildrenOffsetStack[fElementDepth + 1] + 1;
int childrenLength = fElementChildrenLength - childrenOffset;
if (DEBUG_ELEMENT_CHILDREN) {
System.out.println("endElement("+fStringPool.toString(fCurrentElement.rawname)+')');
System.out.print("offset: ");
System.out.print(childrenOffset);
System.out.print(", length: ");
System.out.print(childrenLength);
System.out.println();
printChildren();
printStack();
}
int result = checkContent(elementIndex,
children, childrenOffset, childrenLength);
if ( DEBUG_SCHEMA_VALIDATION )
System.out.println("!!!!!!!!In XMLValidator, the return value from checkContent : " + result);
if (result != -1) {
int majorCode = result != childrenLength ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE;
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
reportRecoverableXMLError(majorCode,
0,
fStringPool.toString(elementType),
XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex));// REVISIT: getContentSpecAsString(elementIndex));
}
}
fElementChildrenLength = fElementChildrenOffsetStack[fElementDepth + 1] + 1;
}
fDocumentHandler.endElement(fCurrentElement);
if (fNamespacesEnabled) {
fNamespacesScope.decreaseDepth();
}
// now pop this element off the top of the element stack
//if (fElementDepth-- < 0) {
if (fElementDepth < -1) {
throw new RuntimeException("FWK008 Element stack underflow");
}
if (fElementDepth < 0) {
fCurrentElement.clear();
fCurrentElementEntity = -1;
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
//
// Check after document is fully parsed
// (1) check that there was an element with a matching id for every
// IDREF and IDREFS attr (V_IDREF0)
//
if (fValidating && fIdRefs != null) {
checkIdRefs();
}
return;
}
//restore enclosing element to all the "current" variables
// REVISIT: Validation. This information needs to be stored.
fCurrentElement.prefix = -1;
fCurrentElement.localpart = fElementTypeStack[fElementDepth];
fCurrentElement.rawname = fElementTypeStack[fElementDepth];
fCurrentElementEntity = fElementEntityStack[fElementDepth];
fCurrentElementIndex = fElementIndexStack[fElementDepth];
fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth];
//REVISIT: Validation
fCurrentScope = fScopeStack[fElementDepth];
//if ( DEBUG_SCHEMA_VALIDATION ) {
/****
System.out.println("+++++ currentElement : " + fStringPool.toString(elementType)+
"\n fCurrentElementIndex : " + fCurrentElementIndex +
"\n fCurrentScope : " + fCurrentScope +
"\n fCurrentContentSpecType : " + fCurrentContentSpecType +
"\n++++++++++++++++++++++++++++++++++++++++++++++++" );
/****/
//}
// if enclosing element's Schema is different, need to switch "context"
if ( fGrammarNameSpaceIndex != fGrammarNameSpaceIndexStack[fElementDepth] ) {
fGrammarNameSpaceIndex = fGrammarNameSpaceIndexStack[fElementDepth];
switchGrammar(fGrammarNameSpaceIndex);
}
if (fValidating) {
fBufferDatatype = false;
}
fInElementContent = (fCurrentContentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // callEndElement(int)
/** Call start CDATA section. */
public void callStartCDATA() throws Exception {
fDocumentHandler.startCDATA();
}
/** Call end CDATA section. */
public void callEndCDATA() throws Exception {
fDocumentHandler.endCDATA();
}
/** Call characters. */
public void callCharacters(int ch) throws Exception {
if (fCharRefData == null) {
fCharRefData = new char[2];
}
int count = (ch < 0x10000) ? 1 : 2;
if (count == 1) {
fCharRefData[0] = (char)ch;
}
else {
fCharRefData[0] = (char)(((ch-0x00010000)>>10)+0xd800);
fCharRefData[1] = (char)(((ch-0x00010000)&0x3ff)+0xdc00);
}
if (fValidating && (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY)) {
charDataInContent();
}
if (fSendCharDataAsCharArray) {
fDocumentHandler.characters(fCharRefData, 0, count);
}
else {
int index = fStringPool.addString(new String(fCharRefData, 0, count));
fDocumentHandler.characters(index);
}
} // callCharacters(int)
/** Call processing instruction. */
public void callProcessingInstruction(int target, int data) throws Exception {
fDocumentHandler.processingInstruction(target, data);
}
/** Call comment. */
public void callComment(int comment) throws Exception {
fDocumentHandler.comment(comment);
}
//
// NamespacesScope.NamespacesHandler methods
//
/** Start a new namespace declaration scope. */
public void startNamespaceDeclScope(int prefix, int uri) throws Exception {
fDocumentHandler.startNamespaceDeclScope(prefix, uri);
}
/** End a namespace declaration scope. */
public void endNamespaceDeclScope(int prefix) throws Exception {
fDocumentHandler.endNamespaceDeclScope(prefix);
}
// attributes
/** Normalize attribute value. */
public int normalizeAttValue(QName element, QName attribute,
int attValue, int attType, boolean list,
int enumHandle) throws Exception {
AttributeValidator av = getValidatorForAttType(attType, list);
if (av != null) {
return av.normalize(element, attribute, attValue, attType, enumHandle);
}
return -1;
} // normalizeAttValue(QName,QName,int,int,boolean,int):int
// other
/** Sets the root element. */
public void setRootElementType(QName rootElement) {
fRootElement.setValues(rootElement);
}
/**
* Returns true if the element declaration is external.
* <p>
* <strong>Note:</strong> This method is primarilly useful for
* DTDs with internal and external subsets.
*/
private boolean getElementDeclIsExternal(int elementIndex) {
/*if (elementIndex < 0 || elementIndex >= fElementCount) {
return false;
}
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
return (fElementDeclIsExternal[chunk][index] != 0);
*/
if (fGrammarIsDTDGrammar ) {
return ((DTDGrammar) fGrammar).getElementDeclIsExternal(elementIndex);
}
return false;
}
/** Returns the content spec type for an element index. */
public int getContentSpecType(int elementIndex) {
int contentSpecType = -1;
if ( elementIndex > -1) {
if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) {
contentSpecType = fTempElementDecl.type;
}
}
return contentSpecType;
}
/** Returns the content spec handle for an element index. */
public int getContentSpecHandle(int elementIndex) {
int contentSpecHandle = -1;
if ( elementIndex > -1) {
if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) {
contentSpecHandle = fTempElementDecl.contentSpecIndex;
}
}
return contentSpecHandle;
}
//
// Protected methods
//
// error reporting
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode)
throws Exception {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
null,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
int stringIndex1)
throws Exception {
Object[] args = { fStringPool.toString(stringIndex1) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,int)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1) throws Exception {
Object[] args = { string1 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
int stringIndex1, int stringIndex2)
throws Exception {
Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,int,int)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1, String string2)
throws Exception {
Object[] args = { string1, string2 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String,String)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1, String string2,
String string3) throws Exception {
Object[] args = { string1, string2, string3 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String,String,String)
// content spec
/**
* Returns information about which elements can be placed at a particular point
* in the passed element's content model.
* <p>
* Note that the incoming content model to test must be valid at least up to
* the insertion point. If not, then -1 will be returned and the info object
* will not have been filled in.
* <p>
* If, on return, the info.isValidEOC flag is set, then the 'insert after'
* elemement is a valid end of content, i.e. nothing needs to be inserted
* after it to make the parent element's content model valid.
*
* @param elementIndex The index within the <code>ElementDeclPool</code> of the
* element which is being querying.
* @param fullyValid Only return elements that can be inserted and still
* maintain the validity of subsequent elements past the
* insertion point (if any). If the insertion point is at
* the end, and this is true, then only elements that can
* be legal final states will be returned.
* @param info An object that contains the required input data for the method,
* and which will contain the output information if successful.
*
* @return The value -1 if fully valid, else the 0 based index of the child
* that first failed before the insertion point. If the value
* returned is equal to the number of children, then the specified
* children are valid but additional content is required to reach a
* valid ending state.
*
* @exception Exception Thrown on error.
*
* @see InsertableElementsInfo
*/
protected int whatCanGoHere(int elementIndex, boolean fullyValid,
InsertableElementsInfo info) throws Exception {
//
// Do some basic sanity checking on the info packet. First, make sure
// that insertAt is not greater than the child count. It can be equal,
// which means to get appendable elements, but not greater. Or, if
// the current children array is null, that's bad too.
//
// Since the current children array must have a blank spot for where
// the insert is going to be, the child count must always be at least
// one.
//
// Make sure that the child count is not larger than the current children
// array. It can be equal, which means get appendable elements, but not
// greater.
//
if (info.insertAt > info.childCount || info.curChildren == null ||
info.childCount < 1 || info.childCount > info.curChildren.length) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
ImplementationMessages.VAL_WCGHI,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
int retVal = 0;
try {
// Get the content model for this element
final XMLContentModel cmElem = getContentModel(elementIndex);
// And delegate this call to it
retVal = cmElem.whatCanGoHere(fullyValid, info);
}
catch (CMException excToCatch) {
// REVISIT - Translate caught error to the protected error handler interface
int majorCode = excToCatch.getErrorCode();
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
majorCode,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
throw excToCatch;
}
return retVal;
} // whatCanGoHere(int,boolean,InsertableElementsInfo):int
// attribute information
/** Protected for use by AttributeValidator classes. */
protected boolean getAttDefIsExternal(QName element, QName attribute) {
int attDefIndex = getAttDef(element, attribute);
if (fGrammarIsDTDGrammar ) {
return ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attDefIndex);
}
return false;
}
/** addId. */
protected boolean addId(int idIndex) {
Integer key = new Integer(idIndex);
if (fIdDefs == null) {
fIdDefs = new Hashtable();
}
else if (fIdDefs.containsKey(key)) {
return false;
}
if (fNullValue == null) {
fNullValue = new Object();
}
fIdDefs.put(key, fNullValue/*new Integer(elementType)*/);
return true;
} // addId(int):boolean
/** addIdRef. */
protected void addIdRef(int idIndex) {
Integer key = new Integer(idIndex);
if (fIdDefs != null && fIdDefs.containsKey(key)) {
return;
}
if (fIdRefs == null) {
fIdRefs = new Hashtable();
}
else if (fIdRefs.containsKey(key)) {
return;
}
if (fNullValue == null) {
fNullValue = new Object();
}
fIdRefs.put(key, fNullValue/*new Integer(elementType)*/);
} // addIdRef(int)
//
// Private methods
//
// other
/** Returns true if using a standalone reader. */
private boolean usingStandaloneReader() {
return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader;
}
/** Returns a locator implementation. */
private LocatorImpl getLocatorImpl(LocatorImpl fillin) {
Locator here = fErrorReporter.getLocator();
if (fillin == null)
return new LocatorImpl(here);
fillin.setPublicId(here.getPublicId());
fillin.setSystemId(here.getSystemId());
fillin.setLineNumber(here.getLineNumber());
fillin.setColumnNumber(here.getColumnNumber());
return fillin;
} // getLocatorImpl(LocatorImpl):LocatorImpl
// content models
/**
* This method will handle the querying of the content model for a
* particular element. If the element does not have a content model, then
* it will be created.
*/
private XMLContentModel getContentModel(int elementIndex)
throws CMException {
// See if a content model already exists first
XMLContentModel cmRet = getElementContentModel(elementIndex);
// If we have one, just return that. Otherwise, gotta create one
if (cmRet != null) {
return cmRet;
}
// Get the type of content this element has
final int contentSpec = getContentSpecType(elementIndex);
// And create the content model according to the spec type
if (contentSpec == XMLElementDecl.TYPE_MIXED) {
//
// Just create a mixel content model object. This type of
// content model is optimized for mixed content validation.
//
//REVISIT, could not compile
// XMLContentSpec specNode = new XMLContentSpec();
// int contentSpecIndex = getContentSpecHandle(elementIndex);
// makeContentList(contentSpecIndex, specNode);
// cmRet = new MixedContentModel(fCount, fContentList);
}
else if (contentSpec == XMLElementDecl.TYPE_CHILDREN) {
//
// This method will create an optimal model for the complexity
// of the element's defined model. If its simple, it will create
// a SimpleContentModel object. If its a simple list, it will
// create a SimpleListContentModel object. If its complex, it
// will create a DFAContentModel object.
//
//REVISIT: couldnot compile
//cmRet = createChildModel(elementIndex);
}
else if (contentSpec == fDATATYPESymbol) {
// cmRet = fSchemaImporter.createDatatypeContentModel(elementIndex);
}
else {
throw new CMException(ImplementationMessages.VAL_CST);
}
// Add the new model to the content model for this element
//REVISIT
setContentModel(elementIndex, cmRet);
return cmRet;
} // getContentModel(int):XMLContentModel
// initialization
/** Reset pool. */
private void poolReset() {
if (fIdDefs != null) {
fIdDefs.clear();
}
if (fIdRefs != null) {
fIdRefs.clear();
}
} // poolReset()
/** Reset common. */
private void resetCommon(StringPool stringPool) throws Exception {
fStringPool = stringPool;
fValidating = fValidationEnabled;
fValidationEnabledByDynamic = false;
fDynamicDisabledByValidation = false;
poolReset();
fCalledStartDocument = false;
fStandaloneReader = -1;
fElementChildrenLength = 0;
fElementDepth = -1;
fSeenRootElement = false;
fSeenDoctypeDecl = false;
fNamespacesScope = null;
fNamespacesPrefix = -1;
fRootElement.clear();
fAttrListHandle = -1;
fCheckedForSchema = false;
fCurrentScope = TOP_LEVEL_SCOPE;
fCurrentSchemaURI = -1;
fEmptyURI = - 1;
fXsiPrefix = - 1;
fGrammar = null;
fGrammarNameSpaceIndex = -1;
fGrammarResolver = null;
fGrammarIsDTDGrammar = false;
fGrammarIsSchemaGrammar = false;
init();
} // resetCommon(StringPool)
/** Initialize. */
private void init() {
fEmptyURI = fStringPool.addSymbol("");
fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI);
fEMPTYSymbol = fStringPool.addSymbol("EMPTY");
fANYSymbol = fStringPool.addSymbol("ANY");
fMIXEDSymbol = fStringPool.addSymbol("MIXED");
fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN");
fCDATASymbol = fStringPool.addSymbol("CDATA");
fIDSymbol = fStringPool.addSymbol("ID");
fIDREFSymbol = fStringPool.addSymbol("IDREF");
fIDREFSSymbol = fStringPool.addSymbol("IDREFS");
fENTITYSymbol = fStringPool.addSymbol("ENTITY");
fENTITIESSymbol = fStringPool.addSymbol("ENTITIES");
fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN");
fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS");
fNOTATIONSymbol = fStringPool.addSymbol("NOTATION");
fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION");
fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED");
fFIXEDSymbol = fStringPool.addSymbol("#FIXED");
fDATATYPESymbol = fStringPool.addSymbol("<<datatype>>");
fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>");
fXMLLang = fStringPool.addSymbol("xml:lang");
/**
fEMPTYSymbol = XMLElementDecl.TYPE_EMPTY;
fANYSymbol = XMLElementDecl.TYPE_ANY;
fMIXEDSymbol = XMLElementDecl.TYPE_MIXED;
fCHILDRENSymbol = XMLElementDecl.TYPE_CHILDREN;
fCDATASymbol = XMLAttributeDecl.TYPE_CDATA;
fIDSymbol = XMLAttributeDecl.TYPE_ID;
fIDREFSymbol = XMLAttributeDecl.TYPE_IDREF;
fIDREFSSymbol = XMLAttributeDecl.TYPE_IDREF;
fENTITYSymbol = XMLAttributeDecl.TYPE_ENTITY;
fENTITIESSymbol = XMLAttributeDecl.TYPE_ENTITY;
fNMTOKENSymbol = XMLAttributeDecl.TYPE_NMTOKEN;
fNMTOKENSSymbol = XMLAttributeDecl.TYPE_NMTOKEN;
fNOTATIONSymbol = XMLAttributeDecl.TYPE_NOTATION;
fENUMERATIONSymbol = XMLAttributeDecl.TYPE_ENUMERATION;
fREQUIREDSymbol = XMLAttributeDecl.DEFAULT_TYPE_REQUIRED;
fFIXEDSymbol = XMLAttributeDecl.DEFAULT_TYPE_FIXED;
fDATATYPESymbol = XMLElementDecl.TYPE_SIMPLE;
**/
} // init()
// other
// default attribute
/** addDefaultAttributes. */
private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception {
//System.out.println("XMLValidator#addDefaultAttributes");
//System.out.print(" ");
//fGrammar.printAttributes(elementIndex);
//
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// (2) check that FIXED attrs have matching value (V_TAGd)
// (3) add default attrs (FIXED and NOT_FIXED)
//
fGrammar.getElementDecl(elementIndex,fTempElementDecl);
//System.out.println("addDefaultAttributes: " + fStringPool.toString(fTempElementDecl.name.localpart)+
// "," + attrIndex + "," + validationEnabled);
int elementNameIndex = fTempElementDecl.name.localpart;
int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex);
int firstCheck = attrIndex;
int lastCheck = -1;
while (attlistIndex != -1) {
//int adChunk = attlistIndex >> CHUNK_SHIFT;
//int adIndex = attlistIndex & CHUNK_MASK;
fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl);
// TO DO: For ericye Debug only
/***
if (fTempAttDecl != null) {
XMLElementDecl element = new XMLElementDecl();
fGrammar.getElementDecl(elementIndex, element);
System.out.println("element: "+fStringPool.toString(element.name.localpart));
System.out.println("attlistIndex " + attlistIndex + "\n"+
"attName : '"+fStringPool.toString(fTempAttDecl.name.localpart) + "'\n"
+ "attType : "+fTempAttDecl.type + "\n"
+ "attDefaultType : "+fTempAttDecl.defaultType + "\n"
+ "attDefaultValue : '"+fTempAttDecl.defaultValue + "'\n"
+ attrList.getLength() +"\n"
);
}
/***/
int attPrefix = fTempAttDecl.name.prefix;
int attName = fTempAttDecl.name.localpart;
int attType = attributeTypeName(fTempAttDecl);
int attDefType =fTempAttDecl.defaultType;
int attValue = -1 ;
if (fTempAttDecl.defaultValue != null ) {
attValue = fStringPool.addSymbol(fTempAttDecl.defaultValue);
}
boolean specified = false;
boolean required = attDefType == XMLAttributeDecl.DEFAULT_TYPE_REQUIRED;
/****
if (fValidating && fGrammar != null && fGrammarIsDTDGrammar && attValue != -1) {
normalizeAttValue(null, fTempAttDecl.name,
attValue,attType,fTempAttDecl.list,
fTempAttDecl.enumeration);
}
/****/
if (firstCheck != -1) {
boolean cdata = attType == fCDATASymbol;
if (!cdata || required || attValue != -1) {
int i = attrList.getFirstAttr(firstCheck);
while (i != -1 && (lastCheck == -1 || i <= lastCheck)) {
//if (fStringPool.equalNames(attrList.getAttrName(i), attName)) {
if ( fStringPool.equalNames(attrList.getAttrLocalpart(i), attName)
&& fStringPool.equalNames(attrList.getAttrURI(i), fTempAttDecl.name.uri) ) {
if (validationEnabled && attDefType == XMLAttributeDecl.DEFAULT_TYPE_FIXED) {
int alistValue = attrList.getAttValue(i);
if (alistValue != attValue &&
!fStringPool.toString(alistValue).equals(fStringPool.toString(attValue))) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName),
fStringPool.toString(alistValue),
fStringPool.toString(attValue) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_FIXED_ATTVALUE_INVALID,
XMLMessages.VC_FIXED_ATTRIBUTE_DEFAULT,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
specified = true;
break;
}
i = attrList.getNextAttr(i);
}
}
}
if (!specified) {
if (required) {
if (validationEnabled) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_REQUIRED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_REQUIRED_ATTRIBUTE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
else if (attValue != -1) {
if (validationEnabled && standalone )
if ( fGrammarIsDTDGrammar
&& ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attlistIndex) ) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_DEFAULTED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
if (attType == fIDREFSymbol) {
addIdRef(attValue);
}
else if (attType == fIDREFSSymbol) {
StringTokenizer tokenizer = new StringTokenizer(fStringPool.toString(attValue));
while (tokenizer.hasMoreTokens()) {
String idName = tokenizer.nextToken();
addIdRef(fStringPool.addSymbol(idName));
}
}
if (attrIndex == -1) {
attrIndex = attrList.startAttrList();
}
// REVISIT: Validation. What should the prefix be?
fTempQName.setValues(attPrefix, attName, attName, fTempAttDecl.name.uri);
int newAttr = attrList.addAttr(fTempQName,
attValue, attType,
false, false);
if (lastCheck == -1) {
lastCheck = newAttr;
}
}
}
attlistIndex = fGrammar.getNextAttributeDeclIndex(attlistIndex);
}
return attrIndex;
} // addDefaultAttributes(int,XMLAttrList,int,boolean,boolean):int
// content models
/** Queries the content model for the specified element index. */
private XMLContentModel getElementContentModel(int elementIndex) throws CMException {
XMLContentModel contentModel = null;
if ( elementIndex > -1) {
if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) {
contentModel = fGrammar.getElementContentModel(elementIndex);
}
}
//return fGrammar.getElementContentModel(elementIndex);
return contentModel;
}
/** Sets the content model for the specified element index. */
private void setContentModel(int elementIndex, XMLContentModel cm) {
// REVISIT: What's this method do?
/*if (elementIndex < 0 || elementIndex >= fElementCount) {
return;
}
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
fContentModel[chunk][index] = cm;
*/
}
// query attribute information
/** Returns the validatator for an attribute type. */
private AttributeValidator getValidatorForAttType(int attType, boolean list) {
if (attType == XMLAttributeDecl.TYPE_CDATA) {
if (fAttValidatorCDATA == null) {
fAttValidatorCDATA = new AttValidatorCDATA();
}
return fAttValidatorCDATA;
}
if (attType == XMLAttributeDecl.TYPE_ID) {
if (fAttValidatorID == null) {
fAttValidatorID = new AttValidatorID();
}
return fAttValidatorID;
}
if (attType == XMLAttributeDecl.TYPE_IDREF) {
if (!list) {
if (fAttValidatorIDREF == null) {
fAttValidatorIDREF = new AttValidatorIDREF();
}
return fAttValidatorIDREF;
}
else {
if (fAttValidatorIDREFS == null) {
fAttValidatorIDREFS = new AttValidatorIDREFS();
}
return fAttValidatorIDREFS;
}
}
if (attType == XMLAttributeDecl.TYPE_ENTITY) {
if (!list) {
if (fAttValidatorENTITY == null) {
fAttValidatorENTITY = new AttValidatorENTITY();
}
return fAttValidatorENTITY;
}
else{
if (fAttValidatorENTITIES == null) {
fAttValidatorENTITIES = new AttValidatorENTITIES();
}
return fAttValidatorENTITIES;
}
}
if (attType == XMLAttributeDecl.TYPE_NMTOKEN) {
if (!list) {
if (fAttValidatorNMTOKEN == null) {
fAttValidatorNMTOKEN = new AttValidatorNMTOKEN();
}
return fAttValidatorNMTOKEN;
}
else{
if (fAttValidatorNMTOKENS == null) {
fAttValidatorNMTOKENS = new AttValidatorNMTOKENS();
}
return fAttValidatorNMTOKENS;
}
}
if (attType == XMLAttributeDecl.TYPE_NOTATION) {
if (fAttValidatorNOTATION == null) {
fAttValidatorNOTATION = new AttValidatorNOTATION();
}
return fAttValidatorNOTATION;
}
if (attType == XMLAttributeDecl.TYPE_ENUMERATION) {
if (fAttValidatorENUMERATION == null) {
fAttValidatorENUMERATION = new AttValidatorENUMERATION();
}
return fAttValidatorENUMERATION;
}
if (attType == XMLAttributeDecl.TYPE_SIMPLE) {
if (fAttValidatorDATATYPE == null) {
fAttValidatorDATATYPE = null; //REVISIT : !!! used to be fSchemaImporter.createDatatypeAttributeValidator();
}
//return fAttValidatorDATATYPE;
}
return null;
//throw new RuntimeException("getValidatorForAttType(" + fStringPool.toString(attType) + ")");
}
/** Returns an attribute definition for an element type. */
private int getAttDef(QName element, QName attribute) {
if (fGrammar != null) {
int scope = fCurrentScope;
if (element.uri > -1) {
scope = TOP_LEVEL_SCOPE;
}
int elementIndex = fGrammar.getElementDeclIndex(element.localpart,scope);
if (elementIndex == -1) {
return -1;
}
int attDefIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex);
while (attDefIndex != -1) {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
if (fTempAttDecl.name.localpart == attribute.localpart &&
fTempAttDecl.name.uri == attribute.uri ) {
return attDefIndex;
}
attDefIndex = fGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
return -1;
} // getAttDef(QName,QName)
/** Returns an attribute definition for an element type. */
private int getAttDefByElementIndex(int elementIndex, QName attribute) {
if (fGrammar != null && elementIndex > -1) {
if (elementIndex == -1) {
return -1;
}
int attDefIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex);
while (attDefIndex != -1) {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
if (fTempAttDecl.name.localpart == attribute.localpart &&
fTempAttDecl.name.uri == attribute.uri ) {
return attDefIndex;
}
attDefIndex = fGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
return -1;
} // getAttDef(QName,QName)
// validation
/** Root element specified. */
private void rootElementSpecified(QName rootElement) throws Exception {
// this is what it used to be
//if (fDynamicValidation && !fSeenDoctypeDecl) {
//fValidating = false;
//}
if (fValidating) {
// initialize the grammar to be the default one.
if (fGrammar == null) {
fGrammar = fGrammarResolver.getGrammar("");
//TO DO, for ericye debug only
if (fGrammar == null && DEBUG_SCHEMA_VALIDATION) {
System.out.println("Oops! no grammar is found for validation");
}
if (fDynamicValidation && fGrammar==null) {
fValidating = false;
}
if (fGrammar != null) {
if (fGrammar instanceof DTDGrammar) {
fGrammarIsDTDGrammar = true;
fGrammarIsSchemaGrammar = false;
}
else if ( fGrammar instanceof SchemaGrammar ) {
fGrammarIsSchemaGrammar = true;
fGrammarIsDTDGrammar = false;
}
fGrammarNameSpaceIndex = fEmptyURI;
}
}
if ( fGrammarIsDTDGrammar &&
((DTDGrammar) fGrammar).getRootElementQName(fRootElement) ) {
String root1 = fStringPool.toString(fRootElement.rawname);
String root2 = fStringPool.toString(rootElement.rawname);
if (!root1.equals(root2)) {
reportRecoverableXMLError(XMLMessages.MSG_ROOT_ELEMENT_TYPE,
XMLMessages.VC_ROOT_ELEMENT_TYPE,
fRootElement.rawname,
rootElement.rawname);
}
}
}
if (fNamespacesEnabled) {
if (fNamespacesScope == null) {
fNamespacesScope = new NamespacesScope(this);
fNamespacesPrefix = fStringPool.addSymbol("xmlns");
fNamespacesScope.setNamespaceForPrefix(fNamespacesPrefix, -1);
int xmlSymbol = fStringPool.addSymbol("xml");
int xmlNamespace = fStringPool.addSymbol("http://www.w3.org/XML/1998/namespace");
fNamespacesScope.setNamespaceForPrefix(xmlSymbol, xmlNamespace);
}
}
} // rootElementSpecified(QName)
/** Switchs to correct validating symbol tables when Schema changes.*/
private void switchGrammar(int newGrammarNameSpaceIndex) {
Grammar tempGrammar = fGrammarResolver.getGrammar(fStringPool.toString(newGrammarNameSpaceIndex));
if (tempGrammar == null) {
System.out.println(fStringPool.toString(newGrammarNameSpaceIndex) + " grammar not found");
//TO DO report error here
}
else {
fGrammar = tempGrammar;
if (fGrammar instanceof DTDGrammar) {
fGrammarIsDTDGrammar = true;
fGrammarIsSchemaGrammar = false;
}
else if ( fGrammar instanceof SchemaGrammar ) {
fGrammarIsSchemaGrammar = true;
fGrammarIsDTDGrammar = false;
}
}
}
/** Binds namespaces to the element and attributes. */
private void bindNamespacesToElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
fNamespacesScope.increaseDepth();
//Vector schemaCandidateURIs = null;
Hashtable locationUriPairs = null;
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
int attPrefix = attrList.getAttrPrefix(index);
if (fStringPool.equalNames(attName, fXMLLang)) {
/***
// NOTE: This check is done in the validateElementsAndAttributes
// method.
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
/***/
}
else if (fStringPool.equalNames(attName, fNamespacesPrefix)) {
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(StringPool.EMPTY_STRING, uri);
}
else {
if (attPrefix == fNamespacesPrefix) {
int nsPrefix = attrList.getAttrLocalpart(index);
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(nsPrefix, uri);
if (fValidating && fSchemaValidation) {
boolean seeXsi = false;
String attrValue = fStringPool.toString(attrList.getAttValue(index));
if (attrValue.equals(SchemaSymbols.URI_XSI)) {
fXsiPrefix = nsPrefix;
seeXsi = true;
}
if (!seeXsi) {
/***
if (schemaCandidateURIs == null) {
schemaCandidateURIs = new Vector();
}
schemaCandidateURIs.addElement( fStringPool.toString(uri) );
/***/
}
}
}
}
index = attrList.getNextAttr(index);
}
// if validating, walk through the list again to deal with "xsi:...."
if (fValidating && fSchemaValidation) {
index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
int attPrefix = attrList.getAttrPrefix(index);
if (fStringPool.equalNames(attName, fNamespacesPrefix)) {
// REVISIT
}
else {
if ( DEBUG_SCHEMA_VALIDATION ) {
System.out.println("deal with XSI");
System.out.println("before find XSI: "+fStringPool.toString(attPrefix)
+","+fStringPool.toString(fXsiPrefix) );
}
if (attPrefix == fXsiPrefix && fXsiPrefix != -1 ) {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("find XSI: "+fStringPool.toString(attPrefix)
+","+fStringPool.toString(attName) );
}
int localpart = attrList.getAttrLocalpart(index);
if (localpart == fStringPool.addSymbol(SchemaSymbols.XSI_SCHEMALOCACTION)) {
if (locationUriPairs == null) {
locationUriPairs = new Hashtable();
}
parseSchemaLocation(fStringPool.toString(attrList.getAttValue(index)), locationUriPairs);
}
else if (localpart == fStringPool.addSymbol(SchemaSymbols.XSI_NONAMESPACESCHEMALOCACTION)) {
if (locationUriPairs == null) {
locationUriPairs = new Hashtable();
}
locationUriPairs.put(fStringPool.toString(attrList.getAttValue(index)), "");
if (fNamespacesScope != null) {
//bind prefix "" to URI "" in this case
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol(""));
}
}
// REVISIT: should we break here?
//break;
}
}
index = attrList.getNextAttr(index);
}
// try to resolve all the grammars here
if (locationUriPairs != null) {
Enumeration locations = locationUriPairs.keys();
while (locations.hasMoreElements()) {
String loc = (String) locations.nextElement();
String uri = (String) locationUriPairs.get(loc);
resolveSchemaGrammar( loc, uri);
//schemaCandidateURIs.removeElement(uri);
}
}
//TO DO: This should be a feature that can be turned on or off
/*****
for (int i=0; i< schemaCandidateURIs.size(); i++) {
String uri = (String) schemaCandidateURIs.elementAt(i);
resolveSchemaGrammar(uri);
}
/*****/
}
}
// bind element to URI
int prefix = element.prefix != -1 ? element.prefix : 0;
int uri = fNamespacesScope.getNamespaceForPrefix(prefix);
if (element.prefix != -1 || uri != -1) {
element.uri = uri;
if (element.uri == -1) {
Object[] args = { fStringPool.toString(element.prefix) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
//REVISIT: is this the right place to check on if the Schema has changed?
if ( fValidating && element.uri != fGrammarNameSpaceIndex && element.uri != -1 ) {
fGrammarNameSpaceIndex = element.uri;
switchGrammar(fGrammarNameSpaceIndex);
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
prefix = attPrefix != -1 ? attPrefix : 0;
int attrUri = fNamespacesScope.getNamespaceForPrefix(prefix);
if (attPrefix != -1 || attrUri != -1) {
//int attrUri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (attrUri == -1) {
Object[] args = { fStringPool.toString(attPrefix) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, attrUri);
}
}
}
index = attrList.getNextAttr(index);
}
}
} // bindNamespacesToElementAndAttributes(QName,XMLAttrList)
void parseSchemaLocation(String schemaLocationStr, Hashtable locationUriPairs){
if (locationUriPairs != null) {
StringTokenizer tokenizer = new StringTokenizer(schemaLocationStr, " \n\t\r", false);
int tokenTotal = tokenizer.countTokens();
if (tokenTotal % 2 != 0 ) {
// TO DO: report warning - malformed schemaLocation string
}
else {
while (tokenizer.hasMoreTokens()) {
String uri = tokenizer.nextToken();
String location = tokenizer.nextToken();
locationUriPairs.put(location, uri);
}
}
}
else {
// TO DO: should report internal error here
}
}// parseSchemaLocaltion(String, Hashtable)
private void resolveSchemaGrammar( String loc, String uri) throws Exception {
SchemaGrammar grammar = (SchemaGrammar) fGrammarResolver.getGrammar(uri);
if (grammar == null) {
DOMParser parser = new DOMParser();
parser.setEntityResolver( new Resolver(fEntityHandler) );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
// expand it before passing it to the parser
loc = fEntityHandler.expandSystemId(loc);
try {
parser.parse( loc );
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
//e.printStackTrace();
reportRecoverableXMLError(167, 144, e.getMessage() );
}
Document document = parser.getDocument(); //Our Grammar
TraverseSchema tst = null;
try {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("I am geting the Schema Document");
}
Element root = document.getDocumentElement();// This is what we pass to TraverserSchema
if (root == null) {
reportRecoverableXMLError(167, 144, "Can't get back Schema document's root element :" + loc);
}
else {
if (uri == null || !uri.equals(root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE)) ) {
reportRecoverableXMLError(167,144, "Schema in " + loc + " has a different target namespace " +
"from the one specified in the instance document :" + uri);
}
grammar = new SchemaGrammar();
grammar.setGrammarDocument(document);
tst = new TraverseSchema( root, fStringPool, (SchemaGrammar)grammar, fGrammarResolver, fErrorReporter, loc);
fGrammarResolver.putGrammar(document.getDocumentElement().getAttribute("targetNamespace"), grammar);
}
}
catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
private void resolveSchemaGrammar(String uri) throws Exception{
resolveSchemaGrammar(uri, uri);
}
static class Resolver implements EntityResolver {
//
// Constants
//
private static final String SYSTEM[] = {
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/structures.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/datatypes.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/versionInfo.ent",
};
private static final String PATH[] = {
"structures.dtd",
"datatypes.dtd",
"versionInfo.ent",
};
//
// Data
//
private DefaultEntityHandler fEntityHandler;
//
// Constructors
//
public Resolver(DefaultEntityHandler handler) {
fEntityHandler = handler;
}
//
// EntityResolver methods
//
public InputSource resolveEntity(String publicId, String systemId)
throws IOException, SAXException {
// looking for the schema DTDs?
for (int i = 0; i < SYSTEM.length; i++) {
if (systemId.equals(SYSTEM[i])) {
InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i]));
source.setPublicId(publicId);
source.setSystemId(systemId);
return source;
}
}
// first try to resolve using user's entity resolver
EntityResolver resolver = fEntityHandler.getEntityResolver();
if (resolver != null) {
InputSource source = resolver.resolveEntity(publicId, systemId);
if (source != null) {
return source;
}
}
// use default resolution
return new InputSource(fEntityHandler.expandSystemId(systemId));
} // resolveEntity(String,String):InputSource
} // class Resolver
static class ErrorHandler implements org.xml.sax.ErrorHandler {
/** Warning. */
public void warning(SAXParseException ex) {
System.err.println("[Warning] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Error. */
public void error(SAXParseException ex) {
System.err.println("[Error] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Fatal error. */
public void fatalError(SAXParseException ex) {
System.err.println("[Fatal Error] "+
getLocationString(ex)+": "+
ex.getMessage());
//throw ex;
}
//
// Private methods
//
/** Returns a string of the location. */
private String getLocationString(SAXParseException ex) {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':');
str.append(ex.getLineNumber());
str.append(':');
str.append(ex.getColumnNumber());
return str.toString();
} // getLocationString(SAXParseException):String
}
private int attributeTypeName(XMLAttributeDecl attrDecl) {
switch (attrDecl.type) {
//case XMLAttributeDecl.TYPE_CDATA:
case XMLAttributeDecl.TYPE_ENTITY: {
return attrDecl.list ? fENTITIESSymbol : fENTITYSymbol;
}
case XMLAttributeDecl.TYPE_ENUMERATION: {
String enumeration = fStringPool.stringListAsString(attrDecl.enumeration);
return fStringPool.addString(enumeration);
}
case XMLAttributeDecl.TYPE_ID: {
return fIDSymbol;
}
case XMLAttributeDecl.TYPE_IDREF: {
return attrDecl.list ? fIDREFSSymbol : fIDREFSymbol;
}
case XMLAttributeDecl.TYPE_NMTOKEN: {
return attrDecl.list ? fNMTOKENSSymbol : fNMTOKENSSymbol;
}
case XMLAttributeDecl.TYPE_NOTATION: {
return fNOTATIONSymbol;
}
}
return fCDATASymbol;
}
/** Validates element and attributes. */
private void validateElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
if (fGrammar == null &&
!fValidating && !fNamespacesEnabled) {
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index));
break;
}
index = fAttrList.getNextAttr(index);
}
}
return;
}
int elementIndex = -1;
//REVISIT, is it possible, fValidating is false and fGrammar is no null.???
if ( fGrammar != null ){
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("localpart: '" + fStringPool.toString(element.localpart)
+"' and scope : " + fCurrentScope);
}
if (element.uri == -1) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart,fCurrentScope);
}
else {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
}
if (elementIndex == -1) {
// if validating based on a Schema, try to resolve the element again by look it up in its ancestor types
if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) {
TraverseSchema.ComplexTypeInfo baseTypeInfo = null;
baseTypeInfo = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(fCurrentElementIndex);
while (baseTypeInfo != null) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, baseTypeInfo.scopeDefined);
if (elementIndex > -1 ) {
break;
}
baseTypeInfo = baseTypeInfo.baseComplexTypeInfo;
}
}
//if still can't resolve it, try TOP_LEVEL_SCOPE AGAIN
+ /****
if ( element.uri == -1 && elementIndex == -1
+ && fNamespacesScope != null
&& fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING) != -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
// REVISIT:
// this is a hack to handle the situation where namespace prefix "" is bound to nothing, and there
// is a "noNamespaceSchemaLocation" specified, and element
element.uri = StringPool.EMPTY_STRING;
}
+ /****/
/****/
if (elementIndex == -1)
if (DEBUG_SCHEMA_VALIDATION)
System.out.println("!!! can not find elementDecl in the grammar, " +
" the element localpart: " + element.localpart+"["+fStringPool.toString(element.localpart) +"]" +
" the element uri: " + element.uri+"["+fStringPool.toString(element.uri) +"]" +
" and the current enclosing scope: " + fCurrentScope );
/****/
}
if (DEBUG_SCHEMA_VALIDATION) {
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
System.out.println("elementIndex: " + elementIndex+" \n and itsName : '"
+ fStringPool.toString(fTempElementDecl.name.localpart)
+"' \n its ContentType:" + fTempElementDecl.type
+"\n its ContentSpecIndex : " + fTempElementDecl.contentSpecIndex +"\n");
}
}
// here need to check if we need to switch Grammar by asking SchemaGrammar whether
// this element actually is of a type in another Schema.
if (fGrammarIsSchemaGrammar && elementIndex != -1) {
String anotherSchemaURI = ((SchemaGrammar)fGrammar).getElementFromAnotherSchemaURI(elementIndex);
if (anotherSchemaURI != null) {
fGrammarNameSpaceIndex = fCurrentSchemaURI = fStringPool.addSymbol(anotherSchemaURI);
switchGrammar(fCurrentSchemaURI);
}
}
int contentSpecType = getContentSpecType(elementIndex);
if (contentSpecType == -1 && fValidating) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
element.rawname);
}
if (fGrammar != null && elementIndex != -1) {
//REVISIT: broken
fAttrListHandle = addDefaultAttributes(elementIndex, attrList, fAttrListHandle, fValidating, fStandaloneReader != -1);
}
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
if (DEBUG_PRINT_ATTRIBUTES) {
String elementStr = fStringPool.toString(element.rawname);
System.out.print("startElement: <" + elementStr);
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
// REVISIT: Validation. Do we need to recheck for the xml:lang
// attribute? It was already checked above -- perhaps
// this is to check values that are defaulted in? If
// so, this check could move to the attribute decl
// callback so we can check the default value before
// it is used.
if (fAttrListHandle != -1) {
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attrNameIndex = attrList.getAttrName(index);
if (fStringPool.equalNames(attrNameIndex, fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
// break;
}
// here, we validate every "user-defined" attributes
int _xmlns = fStringPool.addSymbol("xmlns");
if (attrNameIndex != _xmlns && attrList.getAttrPrefix(index) != _xmlns)
if (fValidating) {
fAttrNameLocator = getLocatorImpl(fAttrNameLocator);
fTempQName.setValues(attrList.getAttrPrefix(index),
attrList.getAttrLocalpart(index),
attrList.getAttrName(index),
attrList.getAttrURI(index) );
int attDefIndex = getAttDefByElementIndex(elementIndex, fTempQName);
if (fTempQName.uri != fXsiURI)
if (attDefIndex == -1) {
// REVISIT - cache the elem/attr tuple so that we only give
// this error once for each unique occurrence
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index)) };
System.out.println("[Error] attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
/*****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/******/
}
else {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
int attributeType = attributeTypeName(fTempAttDecl);
attrList.setAttType(index, attributeType);
if (fGrammarIsDTDGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ENTITY ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ENUMERATION ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NMTOKEN ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NOTATION)
) {
validateDTDattribute(element, attrList.getAttValue(index), fTempAttDecl);
}
if (fTempAttDecl.datatypeValidator == null) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index)) };
System.out.println("[Error] Datatypevalidator for attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
//REVISIT : is this the right message?
/****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/****/
}
else{
try {
fTempAttDecl.datatypeValidator.validate(fStringPool.toString(attrList.getAttValue(index)), null );
}
catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage() },
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
}
}
index = fAttrList.getNextAttr(index);
}
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix != -1) {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
if (fValidating && contentSpecType == XMLElementDecl.TYPE_SIMPLE) {
fBufferDatatype = true;
fDatatypeBuffer.setLength(0);
}
fInElementContent = (contentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // validateElementAndAttributes(QName,XMLAttrList)
//validate attributes in DTD fashion
private void validateDTDattribute(QName element, int attValue,
XMLAttributeDecl attributeDecl) throws Exception{
AttributeValidator av = null;
switch (attributeDecl.type) {
case XMLAttributeDecl.TYPE_ENTITY:
if (attributeDecl.list) {
av = fAttValidatorENTITIES;
}
else {
av = fAttValidatorENTITY;
}
break;
case XMLAttributeDecl.TYPE_ENUMERATION:
av = fAttValidatorENUMERATION;
break;
case XMLAttributeDecl.TYPE_ID:
av = fAttValidatorID;
break;
case XMLAttributeDecl.TYPE_IDREF:
if (attributeDecl.list) {
av = fAttValidatorIDREFS;
}
else {
av = fAttValidatorIDREF;
}
break;
case XMLAttributeDecl.TYPE_NOTATION:
av = fAttValidatorNOTATION;
break;
case XMLAttributeDecl.TYPE_NMTOKEN:
if (attributeDecl.list) {
av = fAttValidatorNMTOKENS;
}
else {
av = fAttValidatorNMTOKEN;
}
break;
}
av.normalize(element, attributeDecl.name, attValue,
attributeDecl.type, attributeDecl.enumeration);
}
/** Character data in content. */
private void charDataInContent() {
if (DEBUG_ELEMENT_CHILDREN) {
System.out.println("charDataInContent()");
}
if (fElementChildren.length <= fElementChildrenLength) {
QName[] newarray = new QName[fElementChildren.length * 2];
System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length);
fElementChildren = newarray;
}
QName qname = fElementChildren[fElementChildrenLength];
if (qname == null) {
for (int i = fElementChildrenLength; i < fElementChildren.length; i++) {
fElementChildren[i] = new QName();
}
qname = fElementChildren[fElementChildrenLength];
}
qname.clear();
fElementChildrenLength++;
} // charDataInCount()
/**
* Check that the content of an element is valid.
* <p>
* This is the method of primary concern to the validator. This method is called
* upon the scanner reaching the end tag of an element. At that time, the
* element's children must be structurally validated, so it calls this method.
* The index of the element being checked (in the decl pool), is provided as
* well as an array of element name indexes of the children. The validator must
* confirm that this element can have these children in this order.
* <p>
* This can also be called to do 'what if' testing of content models just to see
* if they would be valid.
* <p>
* Note that the element index is an index into the element decl pool, whereas
* the children indexes are name indexes, i.e. into the string pool.
* <p>
* A value of -1 in the children array indicates a PCDATA node. All other
* indexes will be positive and represent child elements. The count can be
* zero, since some elements have the EMPTY content model and that must be
* confirmed.
*
* @param elementIndex The index within the <code>ElementDeclPool</code> of this
* element.
* @param childCount The number of entries in the <code>children</code> array.
* @param children The children of this element. Each integer is an index within
* the <code>StringPool</code> of the child element name. An index
* of -1 is used to indicate an occurrence of non-whitespace character
* data.
*
* @return The value -1 if fully valid, else the 0 based index of the child
* that first failed. If the value returned is equal to the number
* of children, then additional content is required to reach a valid
* ending state.
*
* @exception Exception Thrown on error.
*/
private int checkContent(int elementIndex,
QName[] children,
int childOffset,
int childCount) throws Exception {
// Get the element name index from the element
// REVISIT: Validation
final int elementType = fCurrentElement.rawname;
if (DEBUG_PRINT_CONTENT) {
String strTmp = fStringPool.toString(elementType);
System.out.println("Name: "+strTmp+", "+
"Count: "+childCount+", "+
"ContentSpecType: " +fCurrentContentSpecType); //+getContentSpecAsString(elementIndex));
for (int index = childOffset; index < (childOffset+childCount) && index < 10; index++) {
if (index == 0) {
System.out.print(" (");
}
String childName = (children[index].localpart == -1) ? "#PCDATA" : fStringPool.toString(children[index].localpart);
if (index + 1 == childCount) {
System.out.println(childName + ")");
}
else if (index + 1 == 10) {
System.out.println(childName + ",...)");
}
else {
System.out.print(childName + ",");
}
}
}
// Get out the content spec for this element
final int contentType = fCurrentContentSpecType;
// debugging
//System.out.println("~~~~~~in checkContent, fCurrentContentSpecType : " + fCurrentContentSpecType);
//
// Deal with the possible types of content. We try to optimized here
// by dealing specially with content models that don't require the
// full DFA treatment.
//
if (contentType == XMLElementDecl.TYPE_EMPTY) {
//
// If the child count is greater than zero, then this is
// an error right off the bat at index 0.
//
if (childCount != 0) {
return 0;
}
}
else if (contentType == XMLElementDecl.TYPE_ANY) {
//
// This one is open game so we don't pass any judgement on it
// at all. Its assumed to fine since it can hold anything.
//
}
else if (contentType == XMLElementDecl.TYPE_MIXED ||
contentType == XMLElementDecl.TYPE_CHILDREN) {
// Get the content model for this element, faulting it in if needed
XMLContentModel cmElem = null;
try {
cmElem = getContentModel(elementIndex);
return cmElem.validateContent(children, childOffset, childCount);
}
catch(CMException excToCatch) {
// REVISIT - Translate the caught exception to the protected error API
int majorCode = excToCatch.getErrorCode();
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
majorCode,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
}
else if (contentType == -1) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
elementType);
}
else if (contentType == XMLElementDecl.TYPE_SIMPLE ) {
XMLContentModel cmElem = null;
try {
// REVISIT: this might not be right
//cmElem = getContentModel(elementIndex);
//fTempQName.rawname = fTempQName.localpart = fStringPool.addString(fDatatypeBuffer.toString());
//return cmElem.validateContent(1, new QName[] { fTempQName });
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
DatatypeValidator dv = fTempElementDecl.datatypeValidator;
if (dv == null) {
System.out.println("Internal Error: this element have a simpletype "+
"but no datatypevalidator was found, element "+fTempElementDecl.name
+",locapart: "+fStringPool.toString(fTempElementDecl.name.localpart));
}
else {
dv.validate(fDatatypeBuffer.toString(), null);
}
}
//catch (CMException cme) {
// System.out.println("Internal Error in datatype validation");
//}
catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage() },
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
/*
boolean DEBUG_DATATYPES = false;
if (DEBUG_DATATYPES) {
System.out.println("Checking content of datatype");
String strTmp = fStringPool.toString(elementTypeIndex);
int contentSpecIndex = fElementDeclPool.getContentSpec(elementIndex);
XMLContentSpec csn = new XMLContentSpec();
fElementDeclPool.getContentSpecNode(contentSpecIndex, csn);
String contentSpecString = fStringPool.toString(csn.value);
System.out.println
(
"Name: "
+ strTmp
+ ", Count: "
+ childCount
+ ", ContentSpec: "
+ contentSpecString
);
for (int index = 0; index < childCount && index < 10; index++) {
if (index == 0) System.out.print(" (");
String childName = (children[index] == -1) ? "#PCDATA" : fStringPool.toString(children[index]);
if (index + 1 == childCount)
System.out.println(childName + ")");
else if (index + 1 == 10)
System.out.println(childName + ",...)");
else
System.out.print(childName + ",");
}
}
try { // REVISIT - integrate w/ error handling
int contentSpecIndex = fElementDeclPool.getContentSpec(elementIndex);
XMLContentSpec csn = new XMLContentSpec();
fElementDeclPool.getContentSpecNode(contentSpecIndex, csn);
String type = fStringPool.toString(csn.value);
DatatypeValidator v = fDatatypeRegistry.getValidatorFor(type);
if (v != null)
v.validate(fDatatypeBuffer.toString());
else
System.out.println("No validator for datatype "+type);
} catch (InvalidDatatypeValueException idve) {
System.out.println("Incorrect datatype: "+idve.getMessage());
} catch (Exception e) {
e.printStackTrace();
System.out.println("Internal error in datatype validation");
}
*/
}
else {
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
ImplementationMessages.VAL_CST,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
// We succeeded
return -1;
} // checkContent(int,int,int[]):int
/**
* Check that all ID references were to ID attributes present in the document.
* <p>
* This method is a convenience call that allows the validator to do any id ref
* checks above and beyond those done by the scanner. The scanner does the checks
* specificied in the XML spec, i.e. that ID refs refer to ids which were
* eventually defined somewhere in the document.
* <p>
* If the validator is for a Schema perhaps, which defines id semantics beyond
* those of the XML specificiation, this is where that extra checking would be
* done. For most validators, this is a no-op.
*
* @exception Exception Thrown on error.
*/
private void checkIdRefs() throws Exception {
if (fIdRefs == null)
return;
Enumeration en = fIdRefs.keys();
while (en.hasMoreElements()) {
Integer key = (Integer)en.nextElement();
if (fIdDefs == null || !fIdDefs.containsKey(key)) {
Object[] args = { fStringPool.toString(key.intValue()) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ELEMENT_WITH_ID_REQUIRED,
XMLMessages.VC_IDREF,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} // checkIdRefs()
/**
* Checks that all declared elements refer to declared elements
* in their content models. This method calls out to the error
* handler to indicate warnings.
*/
/*private void checkDeclaredElements() throws Exception {
//****DEBUG****
if (DEBUG) print("(???) XMLValidator.checkDeclaredElements\n");
//****DEBUG****
for (int i = 0; i < fElementCount; i++) {
int type = fGrammar.getContentSpecType(i);
if (type == XMLElementDecl.TYPE_MIXED || type == XMLElementDecl.TYPE_CHILDREN) {
int chunk = i >> CHUNK_SHIFT;
int index = i & CHUNK_MASK;
int contentSpecIndex = fContentSpec[chunk][index];
checkDeclaredElements(i, contentSpecIndex);
}
}
}
*/
private void printChildren() {
if (DEBUG_ELEMENT_CHILDREN) {
System.out.print('[');
for (int i = 0; i < fElementChildrenLength; i++) {
System.out.print(' ');
QName qname = fElementChildren[i];
if (qname != null) {
System.out.print(fStringPool.toString(qname.rawname));
}
else {
System.out.print("null");
}
if (i < fElementChildrenLength - 1) {
System.out.print(", ");
}
System.out.flush();
}
System.out.print(" ]");
System.out.println();
}
}
private void printStack() {
if (DEBUG_ELEMENT_CHILDREN) {
System.out.print('{');
for (int i = 0; i <= fElementDepth; i++) {
System.out.print(' ');
System.out.print(fElementChildrenOffsetStack[i]);
if (i < fElementDepth) {
System.out.print(", ");
}
System.out.flush();
}
System.out.print(" }");
System.out.println();
}
}
//
// Interfaces
//
/**
* AttributeValidator.
*/
public interface AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValue, int attType, int enumHandle)
throws Exception;
} // interface AttributeValidator
//
// Classes
//
/**
* AttValidatorCDATA.
*/
final class AttValidatorCDATA
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
// Normalize attribute based upon attribute type...
return attValueHandle;
}
} // class AttValidatorCDATA
/**
* AttValidatorID.
*/
final class AttValidatorID
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
}
else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
if (!XMLCharacterProperties.validName(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_ID_INVALID,
XMLMessages.VC_ID,
fStringPool.toString(attribute.rawname), newAttValue);
}
//
// ID - check that the id value is unique within the document (V_TAG8)
//
if (element.rawname != -1 && !addId(attValueHandle)) {
reportRecoverableXMLError(XMLMessages.MSG_ID_NOT_UNIQUE,
XMLMessages.VC_ID,
fStringPool.toString(attribute.rawname), newAttValue);
}
}
else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalong attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorID
/**
* AttValidatorIDREF.
*/
final class AttValidatorIDREF
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
}
else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
if (!XMLCharacterProperties.validName(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_IDREF_INVALID,
XMLMessages.VC_IDREF,
fStringPool.toString(attribute.rawname), newAttValue);
}
//
// IDREF - remember the id value
//
if (element.rawname != -1)
addIdRef(attValueHandle);
}
else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorIDREF
/**
* AttValidatorIDREFS.
*/
final class AttValidatorIDREFS
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
StringTokenizer tokenizer = new StringTokenizer(attValue);
StringBuffer sb = new StringBuffer(attValue.length());
boolean ok = true;
if (tokenizer.hasMoreTokens()) {
while (true) {
String idName = tokenizer.nextToken();
if (fValidating) {
if (!XMLCharacterProperties.validName(idName)) {
ok = false;
}
//
// IDREFS - remember the id values
//
if (element.rawname != -1) {
addIdRef(fStringPool.addSymbol(idName));
}
}
sb.append(idName);
if (!tokenizer.hasMoreTokens())
break;
sb.append(' ');
}
}
String newAttValue = sb.toString();
if (fValidating && (!ok || newAttValue.length() == 0)) {
reportRecoverableXMLError(XMLMessages.MSG_IDREFS_INVALID,
XMLMessages.VC_IDREF,
fStringPool.toString(attribute.rawname), newAttValue);
}
if (!newAttValue.equals(attValue)) {
attValueHandle = fStringPool.addString(newAttValue);
if (fValidating && invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorIDREFS
/**
* AttValidatorENTITY.
*/
final class AttValidatorENTITY
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
}
else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
//
// ENTITY - check that the value is an unparsed entity name (V_TAGa)
//
if (!fEntityHandler.isUnparsedEntity(attValueHandle)) {
reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID,
XMLMessages.VC_ENTITY_NAME,
fStringPool.toString(attribute.rawname), newAttValue);
}
}
else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorENTITY
/**
* AttValidatorENTITIES.
*/
final class AttValidatorENTITIES
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
StringTokenizer tokenizer = new StringTokenizer(attValue);
StringBuffer sb = new StringBuffer(attValue.length());
boolean ok = true;
if (tokenizer.hasMoreTokens()) {
while (true) {
String entityName = tokenizer.nextToken();
//
// ENTITIES - check that each value is an unparsed entity name (V_TAGa)
//
if (fValidating && !fEntityHandler.isUnparsedEntity(fStringPool.addSymbol(entityName))) {
ok = false;
}
sb.append(entityName);
if (!tokenizer.hasMoreTokens()) {
break;
}
sb.append(' ');
}
}
String newAttValue = sb.toString();
if (fValidating && (!ok || newAttValue.length() == 0)) {
reportRecoverableXMLError(XMLMessages.MSG_ENTITIES_INVALID,
XMLMessages.VC_ENTITY_NAME,
fStringPool.toString(attribute.rawname), newAttValue);
}
if (!newAttValue.equals(attValue)) {
attValueHandle = fStringPool.addString(newAttValue);
if (fValidating && invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorENTITIES
/**
* AttValidatorNMTOKEN.
*/
final class AttValidatorNMTOKEN
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
}
else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
if (!XMLCharacterProperties.validNmtoken(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID,
XMLMessages.VC_NAME_TOKEN,
fStringPool.toString(attribute.rawname), newAttValue);
}
}
else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorNMTOKEN
/**
* AttValidatorNMTOKENS.
*/
final class AttValidatorNMTOKENS
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
StringTokenizer tokenizer = new StringTokenizer(attValue);
StringBuffer sb = new StringBuffer(attValue.length());
boolean ok = true;
if (tokenizer.hasMoreTokens()) {
while (true) {
String nmtoken = tokenizer.nextToken();
if (fValidating && !XMLCharacterProperties.validNmtoken(nmtoken)) {
ok = false;
}
sb.append(nmtoken);
if (!tokenizer.hasMoreTokens()) {
break;
}
sb.append(' ');
}
}
String newAttValue = sb.toString();
if (fValidating && (!ok || newAttValue.length() == 0)) {
reportRecoverableXMLError(XMLMessages.MSG_NMTOKENS_INVALID,
XMLMessages.VC_NAME_TOKEN,
fStringPool.toString(attribute.rawname), newAttValue);
}
if (!newAttValue.equals(attValue)) {
attValueHandle = fStringPool.addString(newAttValue);
if (fValidating && invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorNMTOKENS
/**
* AttValidatorNOTATION.
*/
final class AttValidatorNOTATION
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
}
else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
//
// NOTATION - check that the value is in the AttDef enumeration (V_TAGo)
//
if (!fStringPool.stringInList(enumHandle, attValueHandle)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST,
XMLMessages.VC_NOTATION_ATTRIBUTES,
fStringPool.toString(attribute.rawname),
newAttValue, fStringPool.stringListAsString(enumHandle));
}
}
else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorNOTATION
/**
* AttValidatorENUMERATION.
*/
final class AttValidatorENUMERATION
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
}
else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
//
// ENUMERATION - check that value is in the AttDef enumeration (V_TAG9)
//
if (!fStringPool.stringInList(enumHandle, attValueHandle)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST,
XMLMessages.VC_ENUMERATION,
fStringPool.toString(attribute.rawname),
newAttValue, fStringPool.stringListAsString(enumHandle));
}
}
else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorENUMERATION
} // class XMLValidator
| false | true | private void validateElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
if (fGrammar == null &&
!fValidating && !fNamespacesEnabled) {
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index));
break;
}
index = fAttrList.getNextAttr(index);
}
}
return;
}
int elementIndex = -1;
//REVISIT, is it possible, fValidating is false and fGrammar is no null.???
if ( fGrammar != null ){
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("localpart: '" + fStringPool.toString(element.localpart)
+"' and scope : " + fCurrentScope);
}
if (element.uri == -1) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart,fCurrentScope);
}
else {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
}
if (elementIndex == -1) {
// if validating based on a Schema, try to resolve the element again by look it up in its ancestor types
if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) {
TraverseSchema.ComplexTypeInfo baseTypeInfo = null;
baseTypeInfo = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(fCurrentElementIndex);
while (baseTypeInfo != null) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, baseTypeInfo.scopeDefined);
if (elementIndex > -1 ) {
break;
}
baseTypeInfo = baseTypeInfo.baseComplexTypeInfo;
}
}
//if still can't resolve it, try TOP_LEVEL_SCOPE AGAIN
if ( element.uri == -1 && elementIndex == -1
&& fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING) != -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
// REVISIT:
// this is a hack to handle the situation where namespace prefix "" is bound to nothing, and there
// is a "noNamespaceSchemaLocation" specified, and element
element.uri = StringPool.EMPTY_STRING;
}
/****/
if (elementIndex == -1)
if (DEBUG_SCHEMA_VALIDATION)
System.out.println("!!! can not find elementDecl in the grammar, " +
" the element localpart: " + element.localpart+"["+fStringPool.toString(element.localpart) +"]" +
" the element uri: " + element.uri+"["+fStringPool.toString(element.uri) +"]" +
" and the current enclosing scope: " + fCurrentScope );
/****/
}
if (DEBUG_SCHEMA_VALIDATION) {
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
System.out.println("elementIndex: " + elementIndex+" \n and itsName : '"
+ fStringPool.toString(fTempElementDecl.name.localpart)
+"' \n its ContentType:" + fTempElementDecl.type
+"\n its ContentSpecIndex : " + fTempElementDecl.contentSpecIndex +"\n");
}
}
// here need to check if we need to switch Grammar by asking SchemaGrammar whether
// this element actually is of a type in another Schema.
if (fGrammarIsSchemaGrammar && elementIndex != -1) {
String anotherSchemaURI = ((SchemaGrammar)fGrammar).getElementFromAnotherSchemaURI(elementIndex);
if (anotherSchemaURI != null) {
fGrammarNameSpaceIndex = fCurrentSchemaURI = fStringPool.addSymbol(anotherSchemaURI);
switchGrammar(fCurrentSchemaURI);
}
}
int contentSpecType = getContentSpecType(elementIndex);
if (contentSpecType == -1 && fValidating) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
element.rawname);
}
if (fGrammar != null && elementIndex != -1) {
//REVISIT: broken
fAttrListHandle = addDefaultAttributes(elementIndex, attrList, fAttrListHandle, fValidating, fStandaloneReader != -1);
}
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
if (DEBUG_PRINT_ATTRIBUTES) {
String elementStr = fStringPool.toString(element.rawname);
System.out.print("startElement: <" + elementStr);
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
// REVISIT: Validation. Do we need to recheck for the xml:lang
// attribute? It was already checked above -- perhaps
// this is to check values that are defaulted in? If
// so, this check could move to the attribute decl
// callback so we can check the default value before
// it is used.
if (fAttrListHandle != -1) {
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attrNameIndex = attrList.getAttrName(index);
if (fStringPool.equalNames(attrNameIndex, fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
// break;
}
// here, we validate every "user-defined" attributes
int _xmlns = fStringPool.addSymbol("xmlns");
if (attrNameIndex != _xmlns && attrList.getAttrPrefix(index) != _xmlns)
if (fValidating) {
fAttrNameLocator = getLocatorImpl(fAttrNameLocator);
fTempQName.setValues(attrList.getAttrPrefix(index),
attrList.getAttrLocalpart(index),
attrList.getAttrName(index),
attrList.getAttrURI(index) );
int attDefIndex = getAttDefByElementIndex(elementIndex, fTempQName);
if (fTempQName.uri != fXsiURI)
if (attDefIndex == -1) {
// REVISIT - cache the elem/attr tuple so that we only give
// this error once for each unique occurrence
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index)) };
System.out.println("[Error] attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
/*****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/******/
}
else {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
int attributeType = attributeTypeName(fTempAttDecl);
attrList.setAttType(index, attributeType);
if (fGrammarIsDTDGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ENTITY ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ENUMERATION ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NMTOKEN ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NOTATION)
) {
validateDTDattribute(element, attrList.getAttValue(index), fTempAttDecl);
}
if (fTempAttDecl.datatypeValidator == null) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index)) };
System.out.println("[Error] Datatypevalidator for attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
//REVISIT : is this the right message?
/****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/****/
}
else{
try {
fTempAttDecl.datatypeValidator.validate(fStringPool.toString(attrList.getAttValue(index)), null );
}
catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage() },
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
}
}
index = fAttrList.getNextAttr(index);
}
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix != -1) {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
if (fValidating && contentSpecType == XMLElementDecl.TYPE_SIMPLE) {
fBufferDatatype = true;
fDatatypeBuffer.setLength(0);
}
fInElementContent = (contentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // validateElementAndAttributes(QName,XMLAttrList)
| private void validateElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
if (fGrammar == null &&
!fValidating && !fNamespacesEnabled) {
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index));
break;
}
index = fAttrList.getNextAttr(index);
}
}
return;
}
int elementIndex = -1;
//REVISIT, is it possible, fValidating is false and fGrammar is no null.???
if ( fGrammar != null ){
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("localpart: '" + fStringPool.toString(element.localpart)
+"' and scope : " + fCurrentScope);
}
if (element.uri == -1) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart,fCurrentScope);
}
else {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
}
if (elementIndex == -1) {
// if validating based on a Schema, try to resolve the element again by look it up in its ancestor types
if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) {
TraverseSchema.ComplexTypeInfo baseTypeInfo = null;
baseTypeInfo = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(fCurrentElementIndex);
while (baseTypeInfo != null) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, baseTypeInfo.scopeDefined);
if (elementIndex > -1 ) {
break;
}
baseTypeInfo = baseTypeInfo.baseComplexTypeInfo;
}
}
//if still can't resolve it, try TOP_LEVEL_SCOPE AGAIN
/****
if ( element.uri == -1 && elementIndex == -1
&& fNamespacesScope != null
&& fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING) != -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
// REVISIT:
// this is a hack to handle the situation where namespace prefix "" is bound to nothing, and there
// is a "noNamespaceSchemaLocation" specified, and element
element.uri = StringPool.EMPTY_STRING;
}
/****/
/****/
if (elementIndex == -1)
if (DEBUG_SCHEMA_VALIDATION)
System.out.println("!!! can not find elementDecl in the grammar, " +
" the element localpart: " + element.localpart+"["+fStringPool.toString(element.localpart) +"]" +
" the element uri: " + element.uri+"["+fStringPool.toString(element.uri) +"]" +
" and the current enclosing scope: " + fCurrentScope );
/****/
}
if (DEBUG_SCHEMA_VALIDATION) {
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
System.out.println("elementIndex: " + elementIndex+" \n and itsName : '"
+ fStringPool.toString(fTempElementDecl.name.localpart)
+"' \n its ContentType:" + fTempElementDecl.type
+"\n its ContentSpecIndex : " + fTempElementDecl.contentSpecIndex +"\n");
}
}
// here need to check if we need to switch Grammar by asking SchemaGrammar whether
// this element actually is of a type in another Schema.
if (fGrammarIsSchemaGrammar && elementIndex != -1) {
String anotherSchemaURI = ((SchemaGrammar)fGrammar).getElementFromAnotherSchemaURI(elementIndex);
if (anotherSchemaURI != null) {
fGrammarNameSpaceIndex = fCurrentSchemaURI = fStringPool.addSymbol(anotherSchemaURI);
switchGrammar(fCurrentSchemaURI);
}
}
int contentSpecType = getContentSpecType(elementIndex);
if (contentSpecType == -1 && fValidating) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
element.rawname);
}
if (fGrammar != null && elementIndex != -1) {
//REVISIT: broken
fAttrListHandle = addDefaultAttributes(elementIndex, attrList, fAttrListHandle, fValidating, fStandaloneReader != -1);
}
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
if (DEBUG_PRINT_ATTRIBUTES) {
String elementStr = fStringPool.toString(element.rawname);
System.out.print("startElement: <" + elementStr);
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
// REVISIT: Validation. Do we need to recheck for the xml:lang
// attribute? It was already checked above -- perhaps
// this is to check values that are defaulted in? If
// so, this check could move to the attribute decl
// callback so we can check the default value before
// it is used.
if (fAttrListHandle != -1) {
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attrNameIndex = attrList.getAttrName(index);
if (fStringPool.equalNames(attrNameIndex, fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
// break;
}
// here, we validate every "user-defined" attributes
int _xmlns = fStringPool.addSymbol("xmlns");
if (attrNameIndex != _xmlns && attrList.getAttrPrefix(index) != _xmlns)
if (fValidating) {
fAttrNameLocator = getLocatorImpl(fAttrNameLocator);
fTempQName.setValues(attrList.getAttrPrefix(index),
attrList.getAttrLocalpart(index),
attrList.getAttrName(index),
attrList.getAttrURI(index) );
int attDefIndex = getAttDefByElementIndex(elementIndex, fTempQName);
if (fTempQName.uri != fXsiURI)
if (attDefIndex == -1) {
// REVISIT - cache the elem/attr tuple so that we only give
// this error once for each unique occurrence
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index)) };
System.out.println("[Error] attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
/*****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/******/
}
else {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
int attributeType = attributeTypeName(fTempAttDecl);
attrList.setAttType(index, attributeType);
if (fGrammarIsDTDGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ENTITY ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ENUMERATION ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NMTOKEN ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NOTATION)
) {
validateDTDattribute(element, attrList.getAttValue(index), fTempAttDecl);
}
if (fTempAttDecl.datatypeValidator == null) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index)) };
System.out.println("[Error] Datatypevalidator for attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
//REVISIT : is this the right message?
/****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/****/
}
else{
try {
fTempAttDecl.datatypeValidator.validate(fStringPool.toString(attrList.getAttValue(index)), null );
}
catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage() },
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
}
}
index = fAttrList.getNextAttr(index);
}
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix != -1) {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
if (fValidating && contentSpecType == XMLElementDecl.TYPE_SIMPLE) {
fBufferDatatype = true;
fDatatypeBuffer.setLength(0);
}
fInElementContent = (contentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // validateElementAndAttributes(QName,XMLAttrList)
|
diff --git a/core/src/main/java/com/dtolabs/rundeck/core/tasks/net/ExtSSHExec.java b/core/src/main/java/com/dtolabs/rundeck/core/tasks/net/ExtSSHExec.java
index 77a9d8752..c02becd75 100644
--- a/core/src/main/java/com/dtolabs/rundeck/core/tasks/net/ExtSSHExec.java
+++ b/core/src/main/java/com/dtolabs/rundeck/core/tasks/net/ExtSSHExec.java
@@ -1,574 +1,574 @@
/*
* Copyright 2010 DTO Labs, Inc. (http://dtolabs.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This class is a copy of SSHExec from Ant 1.8.1 sources to support RUNDECK specific
* requirements (e.g., log verbosity).
*
*
* @author Alex Honor <a href="mailto:[email protected]">[email protected]</a>
* @version $Revision$
*/
package com.dtolabs.rundeck.core.tasks.net;
import com.jcraft.jsch.*;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.optional.ssh.SSHBase;
import org.apache.tools.ant.types.Environment;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.resources.FileResource;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.KeepAliveOutputStream;
import org.apache.tools.ant.util.TeeOutputStream;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Executes a command on a remote machine via ssh.
* @since Ant 1.6 (created February 2, 2003)
*/
public class ExtSSHExec extends SSHBase {
private static final int BUFFER_SIZE = 8192;
private static final int RETRY_INTERVAL = 500;
/** the command to execute via ssh */
private String command = null;
/** units are milliseconds, default is 0=infinite */
private long maxwait = 0;
/** for waiting for the command to finish */
private Thread thread = null;
private String outputProperty = null; // like <exec>
private File outputFile = null; // like <exec>
private String inputProperty = null; // like <exec>
private File inputFile = null; // like <exec>
private boolean append = false; // like <exec>
private InputStream inputStream=null;
private OutputStream secondaryStream=null;
private DisconnectHolder disconnectHolder=null;
private Resource commandResource = null;
private List<Environment.Variable> envVars=null;
private static final String TIMEOUT_MESSAGE =
"Timeout period exceeded, connection dropped.";
/**
* Constructor for SSHExecTask.
*/
public ExtSSHExec() {
super();
}
/**
* Sets the command to execute on the remote host.
*
* @param command The new command value
*/
public void setCommand(String command) {
this.command = command;
}
/**
* Sets a commandResource from a file
* @param f the value to use.
* @since Ant 1.7.1
*/
public void setCommandResource(String f) {
this.commandResource = new FileResource(new File(f));
}
/**
* The connection can be dropped after a specified number of
* milliseconds. This is sometimes useful when a connection may be
* flaky. Default is 0, which means "wait forever".
*
* @param timeout The new timeout value in seconds
*/
public void setTimeout(long timeout) {
maxwait = timeout;
}
/**
* If used, stores the output of the command to the given file.
*
* @param output The file to write to.
*/
public void setOutput(File output) {
outputFile = output;
}
/**
* If used, the content of the file is piped to the remote command
*
* @param input The file which provides the input data for the remote command
*/
public void setInput(File input) {
inputFile = input;
}
/**
* If used, the content of the property is piped to the remote command
*
* @param inputProperty The property which contains the input data for the remote command.
*/
public void setInputProperty(String inputProperty) {
this.inputProperty = inputProperty;
}
/**
* Determines if the output is appended to the file given in
* <code>setOutput</code>. Default is false, that is, overwrite
* the file.
*
* @param append True to append to an existing file, false to overwrite.
*/
public void setAppend(boolean append) {
this.append = append;
}
/**
* If set, the output of the command will be stored in the given property.
*
* @param property The name of the property in which the command output
* will be stored.
*/
public void setOutputproperty(String property) {
outputProperty = property;
}
private boolean allocatePty = false;
/**
* Allocate a Pseudo-Terminal.
* If set true, the SSH connection will be setup to run over an allocated pty.
* @param b if true, allocate the pty. (default false
*/
public void setAllocatePty(boolean b) {
allocatePty = b;
}
private int exitStatus =-1;
/**
* Return exitStatus of the remote execution, after it has finished or failed.
* The return value prior to retrieving the result will be -1. If that value is returned
* after the task has executed, it indicates that an exception was thrown prior to retrieval
* of the value.
*/
public int getExitStatus(){
return exitStatus;
}
/**
* Add an Env element
* @param env element
*/
public void addEnv(final Environment.Variable env){
if(null==envVars) {
envVars = new ArrayList<Environment.Variable>();
}
envVars.add(env);
}
/**
* Return the disconnectHolder
*/
public DisconnectHolder getDisconnectHolder() {
return disconnectHolder;
}
/**
* Set a disconnectHolder
*/
public void setDisconnectHolder(final DisconnectHolder disconnectHolder) {
this.disconnectHolder = disconnectHolder;
}
/**
* Allows disconnecting the ssh connection
*/
public static interface Disconnectable{
/**
* Disconnect
*/
public void disconnect();
}
/**
* Interface for receiving access to Disconnectable
*/
public static interface DisconnectHolder{
/**
* Set disconnectable
*/
public void setDisconnectable(Disconnectable disconnectable);
}
/**
* Execute the command on the remote host.
*
* @exception BuildException Most likely a network error or bad parameter.
*/
public void execute() throws BuildException {
if (getHost() == null) {
throw new BuildException("Host is required.");
}
if (getUserInfo().getName() == null) {
throw new BuildException("Username is required.");
}
if (getUserInfo().getKeyfile() == null
&& getUserInfo().getPassword() == null) {
throw new BuildException("Password or Keyfile is required.");
}
if (command == null && commandResource == null) {
throw new BuildException("Command or commandResource is required.");
}
if (inputFile != null && inputProperty != null) {
throw new BuildException("You can't specify both inputFile and"
+ " inputProperty.");
}
if (inputFile != null && !inputFile.exists()) {
throw new BuildException("The input file "
+ inputFile.getAbsolutePath()
+ " does not exist.");
}
Session session = null;
StringBuffer output = new StringBuffer();
try {
session = openSession();
if(null!=getDisconnectHolder()){
final Session sub=session;
getDisconnectHolder().setDisconnectable(new Disconnectable() {
public void disconnect() {
sub.disconnect();
}
});
}
/* called once */
if (command != null) {
if (getVerbose()) {
log("cmd : " + command);
}
executeCommand(session, command, output);
} else { // read command resource and execute for each command
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(commandResource.getInputStream()));
String cmd;
while ((cmd = br.readLine()) != null) {
if (getVerbose()) {
log("cmd : " + cmd);
}
output.append(cmd).append(" : ");
executeCommand(session, cmd, output);
output.append("\n");
}
FileUtils.close(br);
} catch (IOException e) {
if (getFailonerror()) {
throw new BuildException(e);
} else {
log("Caught exception: " + e.getMessage(),
Project.MSG_ERR);
}
}
}
} catch (JSchException e) {
if (getFailonerror()) {
throw new BuildException(e);
} else {
log("Caught exception: " + e.getMessage(), Project.MSG_ERR);
}
} finally {
if (outputProperty != null) {
getProject().setNewProperty(outputProperty, output.toString());
}
if (session != null && session.isConnected()) {
session.disconnect();
}
}
}
private void executeCommand(Session session, String cmd, StringBuffer sb)
throws BuildException {
final ByteArrayOutputStream out ;
final OutputStream tee;
final OutputStream teeout;
if(null!=outputFile || null!=outputProperty){
out = new ByteArrayOutputStream();
}else{
out=null;
}
if(null!=getSecondaryStream() && null!=out) {
teeout= new TeeOutputStream(out, getSecondaryStream());
} else if(null!= getSecondaryStream()){
teeout= getSecondaryStream();
- }else if(null==out){
+ }else if(null!=out){
teeout=out;
}else{
teeout=null;
}
if(null!=teeout){
tee = new TeeOutputStream(teeout, new KeepAliveOutputStream(System.out));
}else{
tee= new KeepAliveOutputStream(System.out);
}
InputStream istream = null ;
if (inputFile != null) {
try {
istream = new FileInputStream(inputFile) ;
} catch (IOException e) {
// because we checked the existence before, this one
// shouldn't happen What if the file exists, but there
// are no read permissions?
log("Failed to read " + inputFile + " because of: "
+ e.getMessage(), Project.MSG_WARN);
}
}
if (inputProperty != null) {
String inputData = getProject().getProperty(inputProperty) ;
if (inputData != null) {
istream = new ByteArrayInputStream(inputData.getBytes()) ;
}
}
if(getInputStream()!=null){
istream=getInputStream();
}
try {
final ChannelExec channel;
session.setTimeout((int) maxwait);
/* execute the command */
channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(cmd);
channel.setOutputStream(tee);
channel.setExtOutputStream(new KeepAliveOutputStream(System.err), true);
if (istream != null) {
channel.setInputStream(istream);
}
channel.setPty(allocatePty);
/* set env vars if any are embedded */
if(null!=envVars && envVars.size()>0){
for(final Environment.Variable env:envVars) {
channel.setEnv(env.getKey(), env.getValue());
}
}
channel.connect();
// wait for it to finish
thread =
new Thread() {
public void run() {
while (!channel.isClosed()) {
if (thread == null) {
return;
}
try {
sleep(RETRY_INTERVAL);
} catch (Exception e) {
// ignored
}
}
}
};
thread.start();
thread.join(maxwait);
if (thread.isAlive()) {
// ran out of time
thread = null;
if (getFailonerror()) {
throw new BuildException(TIMEOUT_MESSAGE);
} else {
log(TIMEOUT_MESSAGE, Project.MSG_ERR);
}
} else {
//success
if (outputFile != null && null != out) {
writeToFile(out.toString(), append, outputFile);
}
// this is the wrong test if the remote OS is OpenVMS,
// but there doesn't seem to be a way to detect it.
exitStatus = channel.getExitStatus();
int ec = channel.getExitStatus();
if (ec != 0) {
String msg = "Remote command failed with exit status " + ec;
if (getFailonerror()) {
throw new BuildException(msg);
} else {
log(msg, Project.MSG_ERR);
}
}
}
} catch (BuildException e) {
throw e;
} catch (JSchException e) {
if (e.getMessage().indexOf("session is down") >= 0) {
if (getFailonerror()) {
throw new BuildException(TIMEOUT_MESSAGE, e);
} else {
log(TIMEOUT_MESSAGE, Project.MSG_ERR);
}
} else {
if (getFailonerror()) {
throw new BuildException(e);
} else {
log("Caught exception: " + e.getMessage(),
Project.MSG_ERR);
}
}
} catch (Exception e) {
if (getFailonerror()) {
throw new BuildException(e);
} else {
log("Caught exception: " + e.getMessage(), Project.MSG_ERR);
}
} finally {
if(null!=out){
sb.append(out.toString());
}
FileUtils.close(istream);
}
}
/**
* Writes a string to a file. If destination file exists, it may be
* overwritten depending on the "append" value.
*
* @param from string to write
* @param to file to write to
* @param append if true, append to existing file, else overwrite
* @exception Exception most likely an IOException
*/
private void writeToFile(String from, boolean append, File to)
throws IOException {
FileWriter out = null;
try {
out = new FileWriter(to.getAbsolutePath(), append);
StringReader in = new StringReader(from);
char[] buffer = new char[BUFFER_SIZE];
int bytesRead;
while (true) {
bytesRead = in.read(buffer);
if (bytesRead == -1) {
break;
}
out.write(buffer, 0, bytesRead);
}
out.flush();
} finally {
if (out != null) {
out.close();
}
}
}
private String knownHosts;
/**
* Sets the path to the file that has the identities of
* all known hosts. This is used by SSH protocol to validate
* the identity of the host. The default is
* <i>${user.home}/.ssh/known_hosts</i>.
*
* @param knownHosts a path to the known hosts file.
*/
public void setKnownhosts(String knownHosts) {
this.knownHosts = knownHosts;
super.setKnownhosts(knownHosts);
}
/**
* Open an ssh seession.
*
* Copied from SSHBase 1.8.1
* @return the opened session
* @throws JSchException on error
*/
protected Session openSession() throws JSchException {
JSch jsch = new JSch();
final SSHBase base = this;
if(getVerbose()) {
JSch.setLogger(new com.jcraft.jsch.Logger(){
public boolean isEnabled(int level){
return true;
}
public void log(int level, String message){
base.log(message, Project.MSG_INFO);
}
});
}
if (null != getUserInfo().getKeyfile()) {
jsch.addIdentity(getUserInfo().getKeyfile());
}
if (!getUserInfo().getTrust() && knownHosts != null) {
log("Using known hosts: " + knownHosts, Project.MSG_DEBUG);
jsch.setKnownHosts(knownHosts);
}
Session session = jsch.getSession(getUserInfo().getName(), getHost(), getPort());
session.setTimeout( (int) maxwait);
if (getVerbose()) {
log("Set timeout to " + maxwait);
}
session.setUserInfo(getUserInfo());
if (getVerbose()) {
log("Connecting to " + getHost() + ":" + getPort());
}
session.connect();
return session;
}
public InputStream getInputStream() {
return inputStream;
}
/**
* Set an inputstream for pty input to the session
*/
public void setInputStream(final InputStream inputStream) {
this.inputStream = inputStream;
}
public OutputStream getSecondaryStream() {
return secondaryStream;
}
/**
* Set a secondary outputstream to read from the connection
*/
public void setSecondaryStream(final OutputStream secondaryStream) {
this.secondaryStream = secondaryStream;
}
}
| true | true | private void executeCommand(Session session, String cmd, StringBuffer sb)
throws BuildException {
final ByteArrayOutputStream out ;
final OutputStream tee;
final OutputStream teeout;
if(null!=outputFile || null!=outputProperty){
out = new ByteArrayOutputStream();
}else{
out=null;
}
if(null!=getSecondaryStream() && null!=out) {
teeout= new TeeOutputStream(out, getSecondaryStream());
} else if(null!= getSecondaryStream()){
teeout= getSecondaryStream();
}else if(null==out){
teeout=out;
}else{
teeout=null;
}
if(null!=teeout){
tee = new TeeOutputStream(teeout, new KeepAliveOutputStream(System.out));
}else{
tee= new KeepAliveOutputStream(System.out);
}
InputStream istream = null ;
if (inputFile != null) {
try {
istream = new FileInputStream(inputFile) ;
} catch (IOException e) {
// because we checked the existence before, this one
// shouldn't happen What if the file exists, but there
// are no read permissions?
log("Failed to read " + inputFile + " because of: "
+ e.getMessage(), Project.MSG_WARN);
}
}
if (inputProperty != null) {
String inputData = getProject().getProperty(inputProperty) ;
if (inputData != null) {
istream = new ByteArrayInputStream(inputData.getBytes()) ;
}
}
if(getInputStream()!=null){
istream=getInputStream();
}
try {
final ChannelExec channel;
session.setTimeout((int) maxwait);
/* execute the command */
channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(cmd);
channel.setOutputStream(tee);
channel.setExtOutputStream(new KeepAliveOutputStream(System.err), true);
if (istream != null) {
channel.setInputStream(istream);
}
channel.setPty(allocatePty);
/* set env vars if any are embedded */
if(null!=envVars && envVars.size()>0){
for(final Environment.Variable env:envVars) {
channel.setEnv(env.getKey(), env.getValue());
}
}
channel.connect();
// wait for it to finish
thread =
new Thread() {
public void run() {
while (!channel.isClosed()) {
if (thread == null) {
return;
}
try {
sleep(RETRY_INTERVAL);
} catch (Exception e) {
// ignored
}
}
}
};
thread.start();
thread.join(maxwait);
if (thread.isAlive()) {
// ran out of time
thread = null;
if (getFailonerror()) {
throw new BuildException(TIMEOUT_MESSAGE);
} else {
log(TIMEOUT_MESSAGE, Project.MSG_ERR);
}
} else {
//success
if (outputFile != null && null != out) {
writeToFile(out.toString(), append, outputFile);
}
// this is the wrong test if the remote OS is OpenVMS,
// but there doesn't seem to be a way to detect it.
exitStatus = channel.getExitStatus();
int ec = channel.getExitStatus();
if (ec != 0) {
String msg = "Remote command failed with exit status " + ec;
if (getFailonerror()) {
throw new BuildException(msg);
} else {
log(msg, Project.MSG_ERR);
}
}
}
} catch (BuildException e) {
throw e;
} catch (JSchException e) {
if (e.getMessage().indexOf("session is down") >= 0) {
if (getFailonerror()) {
throw new BuildException(TIMEOUT_MESSAGE, e);
} else {
log(TIMEOUT_MESSAGE, Project.MSG_ERR);
}
} else {
if (getFailonerror()) {
throw new BuildException(e);
} else {
log("Caught exception: " + e.getMessage(),
Project.MSG_ERR);
}
}
} catch (Exception e) {
if (getFailonerror()) {
throw new BuildException(e);
} else {
log("Caught exception: " + e.getMessage(), Project.MSG_ERR);
}
} finally {
if(null!=out){
sb.append(out.toString());
}
FileUtils.close(istream);
}
}
| private void executeCommand(Session session, String cmd, StringBuffer sb)
throws BuildException {
final ByteArrayOutputStream out ;
final OutputStream tee;
final OutputStream teeout;
if(null!=outputFile || null!=outputProperty){
out = new ByteArrayOutputStream();
}else{
out=null;
}
if(null!=getSecondaryStream() && null!=out) {
teeout= new TeeOutputStream(out, getSecondaryStream());
} else if(null!= getSecondaryStream()){
teeout= getSecondaryStream();
}else if(null!=out){
teeout=out;
}else{
teeout=null;
}
if(null!=teeout){
tee = new TeeOutputStream(teeout, new KeepAliveOutputStream(System.out));
}else{
tee= new KeepAliveOutputStream(System.out);
}
InputStream istream = null ;
if (inputFile != null) {
try {
istream = new FileInputStream(inputFile) ;
} catch (IOException e) {
// because we checked the existence before, this one
// shouldn't happen What if the file exists, but there
// are no read permissions?
log("Failed to read " + inputFile + " because of: "
+ e.getMessage(), Project.MSG_WARN);
}
}
if (inputProperty != null) {
String inputData = getProject().getProperty(inputProperty) ;
if (inputData != null) {
istream = new ByteArrayInputStream(inputData.getBytes()) ;
}
}
if(getInputStream()!=null){
istream=getInputStream();
}
try {
final ChannelExec channel;
session.setTimeout((int) maxwait);
/* execute the command */
channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(cmd);
channel.setOutputStream(tee);
channel.setExtOutputStream(new KeepAliveOutputStream(System.err), true);
if (istream != null) {
channel.setInputStream(istream);
}
channel.setPty(allocatePty);
/* set env vars if any are embedded */
if(null!=envVars && envVars.size()>0){
for(final Environment.Variable env:envVars) {
channel.setEnv(env.getKey(), env.getValue());
}
}
channel.connect();
// wait for it to finish
thread =
new Thread() {
public void run() {
while (!channel.isClosed()) {
if (thread == null) {
return;
}
try {
sleep(RETRY_INTERVAL);
} catch (Exception e) {
// ignored
}
}
}
};
thread.start();
thread.join(maxwait);
if (thread.isAlive()) {
// ran out of time
thread = null;
if (getFailonerror()) {
throw new BuildException(TIMEOUT_MESSAGE);
} else {
log(TIMEOUT_MESSAGE, Project.MSG_ERR);
}
} else {
//success
if (outputFile != null && null != out) {
writeToFile(out.toString(), append, outputFile);
}
// this is the wrong test if the remote OS is OpenVMS,
// but there doesn't seem to be a way to detect it.
exitStatus = channel.getExitStatus();
int ec = channel.getExitStatus();
if (ec != 0) {
String msg = "Remote command failed with exit status " + ec;
if (getFailonerror()) {
throw new BuildException(msg);
} else {
log(msg, Project.MSG_ERR);
}
}
}
} catch (BuildException e) {
throw e;
} catch (JSchException e) {
if (e.getMessage().indexOf("session is down") >= 0) {
if (getFailonerror()) {
throw new BuildException(TIMEOUT_MESSAGE, e);
} else {
log(TIMEOUT_MESSAGE, Project.MSG_ERR);
}
} else {
if (getFailonerror()) {
throw new BuildException(e);
} else {
log("Caught exception: " + e.getMessage(),
Project.MSG_ERR);
}
}
} catch (Exception e) {
if (getFailonerror()) {
throw new BuildException(e);
} else {
log("Caught exception: " + e.getMessage(), Project.MSG_ERR);
}
} finally {
if(null!=out){
sb.append(out.toString());
}
FileUtils.close(istream);
}
}
|
diff --git a/jmx-extractor/src/main/java/org/jmxdatamart/Extractor/Bean2DB.java b/jmx-extractor/src/main/java/org/jmxdatamart/Extractor/Bean2DB.java
index 48e52d2..c729bd6 100644
--- a/jmx-extractor/src/main/java/org/jmxdatamart/Extractor/Bean2DB.java
+++ b/jmx-extractor/src/main/java/org/jmxdatamart/Extractor/Bean2DB.java
@@ -1,314 +1,314 @@
package org.jmxdatamart.Extractor;
import org.jmxdatamart.JMXTestServer.TestBean;
import org.jmxdatamart.common.*;
import org.slf4j.LoggerFactory;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: Xiao Han
* To change this template use File | Settings | File Templates.
*/
public class Bean2DB {
private final static org.slf4j.Logger logger = LoggerFactory.getLogger(Extractor.class);
public static void main(String[] args) {
// TODO code application logic here
int expected = 42;
//Create new test MBean
TestBean tb = new TestBean();
tb.setA(new Integer(expected));
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
String mbName = "org.jmxdatamart.JMXTestServer:type=TestBean";
ObjectName mbeanName = null;
try {
mbeanName = new ObjectName(mbName);
} catch (MalformedObjectNameException e) {
logger.error("Error creating MBean object name", e);
System.exit(0); //this is a fatal error and cannot be resolved later
} catch (NullPointerException e) {
logger.error("Error: no MBean object name provided", e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
try {
mbs.registerMBean(tb, mbeanName);
} catch (InstanceAlreadyExistsException e) {
logger.error("Error: " + mbeanName + " already registered with MBeanServer", e);
} catch (MBeanRegistrationException e) {
logger.error("Error registering " + mbeanName + " with MBeanServer", e);
System.exit(0); //this is a fatal error and cannot be resolved later
} catch (NotCompliantMBeanException e) {
logger.error("Error: " + mbeanName + " is not compliant with MBeanServer", e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
//Create test MBean's MBeanData
Attribute a = new Attribute("A", "Alpha", DataType.INT);
MBeanData mbd = new MBeanData(mbName, "testMBean", Collections.singletonList(a), true);
//Init MBeanExtract
MBeanExtract instance = null;
- try {
- instance = new MBeanExtract(mbd, mbs);
- } catch (MalformedObjectNameException e) {
- logger.error(e.getMessage(), e);
- System.exit(0); //this is a fatal error and cannot be resolved later
- }
+ try {
+ instance = new MBeanExtract(mbd, mbs);
+ } catch (MalformedObjectNameException e) {
+ logger.error(e.getMessage(), e);
+ System.exit(0); //this is a fatal error and cannot be resolved later
+ }
Map result = instance.extract();
Settings s = new Settings();
s.setBeans(Collections.singletonList((BeanData)mbd));
s.setFolderLocation("HyperSQL/");
s.setPollingRate(2);
s.setUrl("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
Properties props = new Properties();
props.put("username", "sa");
props.put("password", "whatever");
Bean2DB bd = new Bean2DB();
String dbname = bd.generateMBeanDB(s);
HypersqlHandler hsql = new HypersqlHandler();
Connection conn = null;
try {
conn = hsql.connectDatabase(dbname, props);
} catch (SQLException e) {
logger.error("Error connecting to SQL database", e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
bd.export2DB(conn,mbd,result);
ResultSet rs = null;
String query = "select * from " + bd.convertIllegalTableName(mbd.getName());
try {
rs = conn.createStatement().executeQuery(query);
} catch (SQLException e) {
logger.error("Error executing SQL query: " + query, e);
}
try {
while(rs.next()){
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2));
}
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
try {
hsql.shutdownDatabase(conn);
} catch (SQLException e) {
logger.error("Error shutting down SQL database", e);
}
DBHandler.disconnectDatabase(rs, null, null, conn);
}
//get rid of the . : =, which are illegal for a table name
public String convertIllegalTableName(String tablename){
return tablename.replaceAll("\\.","_").replaceAll(":","__").replaceAll("=","___");
}
public String recoverOriginalTableName(String tablename){
return tablename.replaceAll("___","=").replaceAll("__",":").replaceAll("_","\\.");
}
private void dealWithDynamicBean(Connection conn, String tableName , Map<Attribute, Object> result) {
try {
if (!DBHandler.tableExists(tableName,conn))
logger.error("Error: " + tableName + " does not exist");
} catch (SQLException e) {
logger.error("Error accessing database handler", e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
String sql;
boolean bl = false;
try {
bl = conn.getAutoCommit();
} catch (SQLException e) {
logger.error("Error getting auto commit from SQL database connection", e);
}
try {
conn.setAutoCommit(false);
} catch (SQLException e) {
logger.error("Error setting auto commit in SQL database connection", e);
}
for (Map.Entry<Attribute, Object> m : result.entrySet()) {
try {
if (!DBHandler.columnExists(m.getKey().getName(),tableName,conn)){
sql = "Alter table " + tableName +" add " +m.getKey().getName()+ " "+m.getKey().getDataType();
conn.createStatement().executeUpdate(sql);
}
} catch (SQLException e) {
logger.error("Error accessing SQL database handler", e);
}
}
try {
conn.commit();
} catch (SQLException e) {
logger.error("Error with commit to SQL database", e);
}
try {
conn.setAutoCommit(bl);
} catch (SQLException e) {
logger.error("Error setting auto commit in SQL database connection", e);
}
}
public void export2DB(Connection conn, BeanData mbd, Map<Attribute, Object> result) {
String tablename = convertIllegalTableName(mbd.getName());
//deal with dynamic bean
dealWithDynamicBean(conn,tablename,result);
PreparedStatement ps = null;
StringBuilder insertstring = new StringBuilder() ;
insertstring.append("insert into ").append(tablename).append(" (");
StringBuilder insertvalue = new StringBuilder();
insertvalue.append(" values(");
for (Map.Entry<Attribute, Object> m : result.entrySet()) {
insertstring.append(((Attribute)m.getKey()).getName()).append(",");
insertvalue.append("?,");
}
String sql = insertstring.append("time)").toString();
sql += insertvalue.append("?)").toString();
try {
ps = conn.prepareStatement(sql);
} catch (SQLException e1) {
logger.error("Error preparing statement for SQL database connection", e1);
System.exit(0); //this is a fatal error and cannot be resolved later
}
//need to think about how to avoid retrieving the map twice
int i=0;
for (Map.Entry<Attribute, Object> m : result.entrySet()) {
switch (((Attribute)m.getKey()).getDataType())
{
case INT:
try {
ps.setInt(++i,(Integer)m.getValue());
} catch (SQLException e) {
logger.error("Error setting statement for SQL prepared statement", e);
}
break;
case STRING:
try {
ps.setString(++i,m.getValue().toString());
} catch (SQLException e) {
logger.error("Error setting statement for SQL prepared statement", e);
}
break;
case FLOAT:
try {
ps.setFloat(++i,(Float)m.getValue());
} catch (SQLException e) {
logger.error("Error setting statement for SQL prepared statement", e);
}
break;
}
}
try {
ps.setTimestamp(++i, new Timestamp((new java.util.Date()).getTime()));
} catch (SQLException e1) {
logger.error("Error setting timestamp for SQL prepared statement", e1);
}
boolean bl=false;
try {
bl = conn.getAutoCommit();
conn.setAutoCommit(false);
ps.executeUpdate();
conn.commit();
} catch (SQLException e){
try {
conn.rollback();
} catch (SQLException e1) {
logger.error("Error rolling back SQL database connection", e);
}
} finally {
try {
ps.close();
} catch (SQLException e) {
logger.error("Error closing SQL prepared statement", e);
}
try {
conn.setAutoCommit(bl);
} catch (SQLException e) {
logger.error("Error setting auto commit for SQL database connection", e);
}
}
}
public String generateMBeanDB(Settings s) {
Connection conn = null;
Statement st = null;
HypersqlHandler hypersql = new HypersqlHandler();
hypersql.loadDriver(hypersql.getDriver());
String dbName = s.getFolderLocation()+"Extrator" + new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date());
StringBuilder sb;
String tablename = null;
try{
Properties props = new Properties();
props.put("username", "sa");
props.put("password", "whatever");
conn = hypersql.connectDatabase(dbName, props);
System.out.println("Database " + dbName + " is created.");
st = conn.createStatement();
conn.setAutoCommit(false);
for (BeanData bean:s.getBeans()){
sb = new StringBuilder();
tablename = convertIllegalTableName(bean.getName());
//1.the bean names are unique, but alias not
//2.the field name of "time"(or whatever) should be reserved, can't be used as an attribute name
//3.the datatyype should be valid in embedded SQL (ie. HyperSQL)
//All above requirements must be set to a DTD for the setting xml file!!!
sb.append("create table " + tablename + "(");
for (Attribute ab: bean.getAttributes()){
sb.append(ab.getName() + " " + ab.getDataType() + ",");
}
sb.append("time TIMESTAMP)");
st.executeUpdate(sb.toString());
System.out.println("Table " + recoverOriginalTableName(tablename) + " is created.");
}
conn.commit();
} catch (Exception e){
System.err.println(e.getMessage());
try {
conn.rollback();
} catch (SQLException e1) {
logger.error("Error rolling back SQL database connection", e);
}
return null;
}
finally {
try {
hypersql.shutdownDatabase(conn);
} catch (SQLException e) {
logger.error("Error shutting down SQL database", e);
} //we should shut down a Hsql DB
DBHandler.disconnectDatabase(null, st, null, conn);
}
return dbName;
}
}
| true | true | public static void main(String[] args) {
// TODO code application logic here
int expected = 42;
//Create new test MBean
TestBean tb = new TestBean();
tb.setA(new Integer(expected));
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
String mbName = "org.jmxdatamart.JMXTestServer:type=TestBean";
ObjectName mbeanName = null;
try {
mbeanName = new ObjectName(mbName);
} catch (MalformedObjectNameException e) {
logger.error("Error creating MBean object name", e);
System.exit(0); //this is a fatal error and cannot be resolved later
} catch (NullPointerException e) {
logger.error("Error: no MBean object name provided", e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
try {
mbs.registerMBean(tb, mbeanName);
} catch (InstanceAlreadyExistsException e) {
logger.error("Error: " + mbeanName + " already registered with MBeanServer", e);
} catch (MBeanRegistrationException e) {
logger.error("Error registering " + mbeanName + " with MBeanServer", e);
System.exit(0); //this is a fatal error and cannot be resolved later
} catch (NotCompliantMBeanException e) {
logger.error("Error: " + mbeanName + " is not compliant with MBeanServer", e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
//Create test MBean's MBeanData
Attribute a = new Attribute("A", "Alpha", DataType.INT);
MBeanData mbd = new MBeanData(mbName, "testMBean", Collections.singletonList(a), true);
//Init MBeanExtract
MBeanExtract instance = null;
try {
instance = new MBeanExtract(mbd, mbs);
} catch (MalformedObjectNameException e) {
logger.error(e.getMessage(), e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
Map result = instance.extract();
Settings s = new Settings();
s.setBeans(Collections.singletonList((BeanData)mbd));
s.setFolderLocation("HyperSQL/");
s.setPollingRate(2);
s.setUrl("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
Properties props = new Properties();
props.put("username", "sa");
props.put("password", "whatever");
Bean2DB bd = new Bean2DB();
String dbname = bd.generateMBeanDB(s);
HypersqlHandler hsql = new HypersqlHandler();
Connection conn = null;
try {
conn = hsql.connectDatabase(dbname, props);
} catch (SQLException e) {
logger.error("Error connecting to SQL database", e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
bd.export2DB(conn,mbd,result);
ResultSet rs = null;
String query = "select * from " + bd.convertIllegalTableName(mbd.getName());
try {
rs = conn.createStatement().executeQuery(query);
} catch (SQLException e) {
logger.error("Error executing SQL query: " + query, e);
}
try {
while(rs.next()){
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2));
}
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
try {
hsql.shutdownDatabase(conn);
} catch (SQLException e) {
logger.error("Error shutting down SQL database", e);
}
DBHandler.disconnectDatabase(rs, null, null, conn);
}
| public static void main(String[] args) {
// TODO code application logic here
int expected = 42;
//Create new test MBean
TestBean tb = new TestBean();
tb.setA(new Integer(expected));
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
String mbName = "org.jmxdatamart.JMXTestServer:type=TestBean";
ObjectName mbeanName = null;
try {
mbeanName = new ObjectName(mbName);
} catch (MalformedObjectNameException e) {
logger.error("Error creating MBean object name", e);
System.exit(0); //this is a fatal error and cannot be resolved later
} catch (NullPointerException e) {
logger.error("Error: no MBean object name provided", e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
try {
mbs.registerMBean(tb, mbeanName);
} catch (InstanceAlreadyExistsException e) {
logger.error("Error: " + mbeanName + " already registered with MBeanServer", e);
} catch (MBeanRegistrationException e) {
logger.error("Error registering " + mbeanName + " with MBeanServer", e);
System.exit(0); //this is a fatal error and cannot be resolved later
} catch (NotCompliantMBeanException e) {
logger.error("Error: " + mbeanName + " is not compliant with MBeanServer", e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
//Create test MBean's MBeanData
Attribute a = new Attribute("A", "Alpha", DataType.INT);
MBeanData mbd = new MBeanData(mbName, "testMBean", Collections.singletonList(a), true);
//Init MBeanExtract
MBeanExtract instance = null;
try {
instance = new MBeanExtract(mbd, mbs);
} catch (MalformedObjectNameException e) {
logger.error(e.getMessage(), e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
Map result = instance.extract();
Settings s = new Settings();
s.setBeans(Collections.singletonList((BeanData)mbd));
s.setFolderLocation("HyperSQL/");
s.setPollingRate(2);
s.setUrl("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
Properties props = new Properties();
props.put("username", "sa");
props.put("password", "whatever");
Bean2DB bd = new Bean2DB();
String dbname = bd.generateMBeanDB(s);
HypersqlHandler hsql = new HypersqlHandler();
Connection conn = null;
try {
conn = hsql.connectDatabase(dbname, props);
} catch (SQLException e) {
logger.error("Error connecting to SQL database", e);
System.exit(0); //this is a fatal error and cannot be resolved later
}
bd.export2DB(conn,mbd,result);
ResultSet rs = null;
String query = "select * from " + bd.convertIllegalTableName(mbd.getName());
try {
rs = conn.createStatement().executeQuery(query);
} catch (SQLException e) {
logger.error("Error executing SQL query: " + query, e);
}
try {
while(rs.next()){
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2));
}
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
try {
hsql.shutdownDatabase(conn);
} catch (SQLException e) {
logger.error("Error shutting down SQL database", e);
}
DBHandler.disconnectDatabase(rs, null, null, conn);
}
|
diff --git a/src/java/org/apache/xmlrpc/XmlRpcClientLite.java b/src/java/org/apache/xmlrpc/XmlRpcClientLite.java
index eb5de41..2c868d0 100644
--- a/src/java/org/apache/xmlrpc/XmlRpcClientLite.java
+++ b/src/java/org/apache/xmlrpc/XmlRpcClientLite.java
@@ -1,423 +1,427 @@
package org.apache.xmlrpc;
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "XML-RPC" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.net.*;
import java.io.*;
import java.util.*;
import org.xml.sax.*;
/**
* A multithreaded, reusable XML-RPC client object. This version uses a homegrown
* HTTP client which can be quite a bit faster than java.net.URLConnection, especially
* when used with XmlRpc.setKeepAlive(true).
*
* @author <a href="mailto:[email protected]">Hannes Wallnoefer</a>
*/
public class XmlRpcClientLite
extends XmlRpcClient
{
static String auth;
/**
* Construct a XML-RPC client with this URL.
*/
public XmlRpcClientLite (URL url)
{
super (url);
}
/**
* Construct a XML-RPC client for the URL represented by this String.
*/
public XmlRpcClientLite (String url) throws MalformedURLException
{
super (url);
}
/**
* Construct a XML-RPC client for the specified hostname and port.
*/
public XmlRpcClientLite (String hostname,
int port) throws MalformedURLException
{
super (hostname, port);
}
synchronized Worker getWorker (boolean async)
throws IOException
{
try
{
Worker w = (Worker) pool.pop ();
if (async)
asyncWorkers += 1;
else
workers += 1;
return w;
}
catch (EmptyStackException x)
{
if (workers < XmlRpc.getMaxThreads())
{
if (async)
asyncWorkers += 1;
else
workers += 1;
return new LiteWorker ();
}
throw new IOException ("XML-RPC System overload");
}
}
class LiteWorker extends Worker implements Runnable
{
HttpClient client = null;
public LiteWorker ()
{
super ();
}
Object execute (String method, Vector params)
throws XmlRpcException, IOException
{
long now = System.currentTimeMillis ();
fault = false;
try
{
if (buffer == null)
{
buffer = new ByteArrayOutputStream();
}
else
{
buffer.reset();
}
XmlWriter writer = new XmlWriter (buffer);
writeRequest (writer, method, params);
writer.flush();
byte[] request = buffer.toByteArray();
// and send it to the server
if (client == null)
client = new HttpClient (url);
InputStream in = null;
// send request to the server and get an input stream
// from which to read the response
try {
in = client.sendRequest (request);
} catch (IOException iox) {
// if we get an exception while sending the request,
// and the connection is a keepalive connection, it may
// have been timed out by the server. Try again.
if (client.keepalive) {
client.closeConnection ();
client.initConnection ();
in = client.sendRequest (request);
+ } else {
+ throw iox;
}
}
// parse the response
parse (in);
// client keepalive is always false if XmlRpc.keepalive is false
- if (!client.keepalive)
+ if (!client.keepalive) {
client.closeConnection ();
+ client = null;
+ }
if (debug)
System.err.println ("result = "+result);
// check for errors from the XML parser
if (errorLevel == FATAL)
throw new Exception (errorMsg);
}
catch (IOException iox)
{
// this is a lower level problem, client could not talk to server for some reason.
throw iox;
}
catch (Exception x)
{
// same as above, but exception has to be converted to IOException.
if (XmlRpc.debug)
x.printStackTrace ();
String msg = x.getMessage ();
if (msg == null || msg.length () == 0)
msg = x.toString ();
throw new IOException (msg);
}
if (fault)
{
// this is an XML-RPC-level problem, i.e. the server reported an error.
// throw an XmlRpcException.
XmlRpcException exception = null;
try
{
Hashtable f = (Hashtable) result;
String faultString = (String) f.get ("faultString");
int faultCode = Integer.parseInt (
f.get ("faultCode").toString ());
exception = new XmlRpcException (faultCode,
faultString.trim ());
}
catch (Exception x)
{
throw new XmlRpcException (0, "Server returned an invalid fault response.");
}
throw exception;
}
if (debug)
System.err.println ("Spent "+
(System.currentTimeMillis () - now) + " millis in request");
return result;
}
} // end of class Worker
// A replacement for java.net.URLConnection, which seems very slow on MS Java.
class HttpClient
{
String hostname;
String host;
int port;
String uri;
Socket socket = null;
BufferedOutputStream output;
BufferedInputStream input;
boolean keepalive;
public HttpClient (URL url) throws IOException
{
hostname = url.getHost ();
port = url.getPort ();
if (port < 1)
port = 80;
uri = url.getFile ();
if (uri == null || "".equals (uri))
uri = "/";
host = port == 80 ? hostname : hostname + ":"+port;
initConnection ();
}
protected void initConnection () throws IOException
{
socket = new Socket (hostname, port);
output = new BufferedOutputStream (socket.getOutputStream());
input = new BufferedInputStream (socket.getInputStream ());
}
protected void closeConnection ()
{
try
{
socket.close ();
}
catch (Exception ignore)
{}
}
public InputStream sendRequest (byte[] request) throws IOException
{
output.write (("POST "+uri + " HTTP/1.0\r\n").getBytes());
output.write ( ("User-Agent: "+XmlRpc.version +
"\r\n").getBytes());
output.write (("Host: "+host + "\r\n").getBytes());
if (XmlRpc.getKeepAlive())
output.write ("Connection: Keep-Alive\r\n".getBytes());
output.write ("Content-Type: text/xml\r\n".getBytes());
if (auth != null)
output.write ( ("Authorization: Basic "+auth +
"\r\n").getBytes());
output.write (
("Content-Length: "+request.length).getBytes());
output.write ("\r\n\r\n".getBytes());
output.write (request);
output.flush ();
// start reading server response headers
String line = readLine ();
if (XmlRpc.debug)
System.err.println (line);
int contentLength = -1;
try
{
StringTokenizer tokens = new StringTokenizer (line);
String httpversion = tokens.nextToken ();
String statusCode = tokens.nextToken();
String statusMsg = tokens.nextToken ("\n\r");
keepalive = XmlRpc.getKeepAlive() &&
"HTTP/1.1".equals (httpversion);
if (!"200".equals (statusCode))
throw new IOException ("Unexpected Response from Server: "+
statusMsg);
}
catch (IOException iox)
{
throw iox;
}
catch (Exception x)
{
// x.printStackTrace ();
throw new IOException ("Server returned invalid Response.");
}
do
{
line = readLine ();
if (line != null)
{
if (XmlRpc.debug)
System.err.println (line);
line = line.toLowerCase ();
if (line.startsWith ("content-length:"))
contentLength = Integer.parseInt (
line.substring (15).trim ());
if (line.startsWith ("connection:"))
keepalive = XmlRpc.getKeepAlive() &&
line.indexOf ("keep-alive") > -1;
}
}
while (line != null && ! line.equals(""))
;
return new ServerInputStream (input, contentLength);
}
byte[] buffer;
private String readLine () throws IOException
{
if (buffer == null)
buffer = new byte[512];
int next;
int count = 0;
while (true)
{
next = input.read();
if (next < 0 || next == '\n')
break;
if (next != '\r')
buffer[count++] = (byte) next;
if (count >= 512)
throw new IOException ("HTTP Header too long");
}
return new String (buffer, 0, count);
}
protected void finalize () throws Throwable
{
closeConnection ();
}
}
/**
* Just for testing.
*/
public static void main (String args[]) throws Exception
{
// XmlRpc.setDebug (true);
try
{
String url = args[0];
String method = args[1];
XmlRpcClientLite client = new XmlRpcClientLite (url);
Vector v = new Vector ();
for (int i = 2; i < args.length; i++)
try
{
v.addElement (
new Integer (Integer.parseInt (args[i])));
}
catch (NumberFormatException nfx)
{
v.addElement (args[i]);
}
// XmlRpc.setEncoding ("UTF-8");
try
{
System.err.println (client.execute (method, v));
}
catch (Exception ex)
{
System.err.println ("Error: "+ex.getMessage());
}
}
catch (Exception x)
{
System.err.println (x);
System.err.println ("Usage: java org.apache.xmlrpc.XmlRpcClient <url> <method> <arg> ....");
System.err.println ("Arguments are sent as integers or strings.");
}
}
}
| false | true | Object execute (String method, Vector params)
throws XmlRpcException, IOException
{
long now = System.currentTimeMillis ();
fault = false;
try
{
if (buffer == null)
{
buffer = new ByteArrayOutputStream();
}
else
{
buffer.reset();
}
XmlWriter writer = new XmlWriter (buffer);
writeRequest (writer, method, params);
writer.flush();
byte[] request = buffer.toByteArray();
// and send it to the server
if (client == null)
client = new HttpClient (url);
InputStream in = null;
// send request to the server and get an input stream
// from which to read the response
try {
in = client.sendRequest (request);
} catch (IOException iox) {
// if we get an exception while sending the request,
// and the connection is a keepalive connection, it may
// have been timed out by the server. Try again.
if (client.keepalive) {
client.closeConnection ();
client.initConnection ();
in = client.sendRequest (request);
}
}
// parse the response
parse (in);
// client keepalive is always false if XmlRpc.keepalive is false
if (!client.keepalive)
client.closeConnection ();
if (debug)
System.err.println ("result = "+result);
// check for errors from the XML parser
if (errorLevel == FATAL)
throw new Exception (errorMsg);
}
catch (IOException iox)
{
// this is a lower level problem, client could not talk to server for some reason.
throw iox;
}
catch (Exception x)
{
// same as above, but exception has to be converted to IOException.
if (XmlRpc.debug)
x.printStackTrace ();
String msg = x.getMessage ();
if (msg == null || msg.length () == 0)
msg = x.toString ();
throw new IOException (msg);
}
if (fault)
{
// this is an XML-RPC-level problem, i.e. the server reported an error.
// throw an XmlRpcException.
XmlRpcException exception = null;
try
{
Hashtable f = (Hashtable) result;
String faultString = (String) f.get ("faultString");
int faultCode = Integer.parseInt (
f.get ("faultCode").toString ());
exception = new XmlRpcException (faultCode,
faultString.trim ());
}
catch (Exception x)
{
throw new XmlRpcException (0, "Server returned an invalid fault response.");
}
throw exception;
}
if (debug)
System.err.println ("Spent "+
(System.currentTimeMillis () - now) + " millis in request");
return result;
}
| Object execute (String method, Vector params)
throws XmlRpcException, IOException
{
long now = System.currentTimeMillis ();
fault = false;
try
{
if (buffer == null)
{
buffer = new ByteArrayOutputStream();
}
else
{
buffer.reset();
}
XmlWriter writer = new XmlWriter (buffer);
writeRequest (writer, method, params);
writer.flush();
byte[] request = buffer.toByteArray();
// and send it to the server
if (client == null)
client = new HttpClient (url);
InputStream in = null;
// send request to the server and get an input stream
// from which to read the response
try {
in = client.sendRequest (request);
} catch (IOException iox) {
// if we get an exception while sending the request,
// and the connection is a keepalive connection, it may
// have been timed out by the server. Try again.
if (client.keepalive) {
client.closeConnection ();
client.initConnection ();
in = client.sendRequest (request);
} else {
throw iox;
}
}
// parse the response
parse (in);
// client keepalive is always false if XmlRpc.keepalive is false
if (!client.keepalive) {
client.closeConnection ();
client = null;
}
if (debug)
System.err.println ("result = "+result);
// check for errors from the XML parser
if (errorLevel == FATAL)
throw new Exception (errorMsg);
}
catch (IOException iox)
{
// this is a lower level problem, client could not talk to server for some reason.
throw iox;
}
catch (Exception x)
{
// same as above, but exception has to be converted to IOException.
if (XmlRpc.debug)
x.printStackTrace ();
String msg = x.getMessage ();
if (msg == null || msg.length () == 0)
msg = x.toString ();
throw new IOException (msg);
}
if (fault)
{
// this is an XML-RPC-level problem, i.e. the server reported an error.
// throw an XmlRpcException.
XmlRpcException exception = null;
try
{
Hashtable f = (Hashtable) result;
String faultString = (String) f.get ("faultString");
int faultCode = Integer.parseInt (
f.get ("faultCode").toString ());
exception = new XmlRpcException (faultCode,
faultString.trim ());
}
catch (Exception x)
{
throw new XmlRpcException (0, "Server returned an invalid fault response.");
}
throw exception;
}
if (debug)
System.err.println ("Spent "+
(System.currentTimeMillis () - now) + " millis in request");
return result;
}
|
diff --git a/modules/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ContentItemsSource.java b/modules/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ContentItemsSource.java
index d89d88875..20f75829b 100644
--- a/modules/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ContentItemsSource.java
+++ b/modules/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ContentItemsSource.java
@@ -1,180 +1,183 @@
package org.apache.lucene.benchmark.byTask.feeds;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.lucene.benchmark.byTask.utils.Config;
import org.apache.lucene.benchmark.byTask.utils.Format;
/**
* Base class for source of data for benchmarking
* <p>
* Keeps track of various statistics, such as how many data items were generated,
* size in bytes etc.
* <p>
* Supports the following configuration parameters:
* <ul>
* <li><b>content.source.forever</b> - specifies whether to generate items
* forever (<b>default=true</b>).
* <li><b>content.source.verbose</b> - specifies whether messages should be
* output by the content source (<b>default=false</b>).
* <li><b>content.source.encoding</b> - specifies which encoding to use when
* reading the files of that content source. Certain implementations may define
* a default value if this parameter is not specified. (<b>default=null</b>).
* <li><b>content.source.log.step</b> - specifies for how many items a
* message should be logged. If set to 0 it means no logging should occur.
* <b>NOTE:</b> if verbose is set to false, logging should not occur even if
* logStep is not 0 (<b>default=0</b>).
* </ul>
*/
public abstract class ContentItemsSource {
private long bytesCount;
private long totalBytesCount;
private int itemCount;
private int totalItemCount;
private Config config;
private int lastPrintedNumUniqueTexts = 0;
private long lastPrintedNumUniqueBytes = 0;
private int printNum = 0;
protected boolean forever;
protected int logStep;
protected boolean verbose;
protected String encoding;
/** update count of bytes generated by this source */
protected final synchronized void addBytes(long numBytes) {
bytesCount += numBytes;
totalBytesCount += numBytes;
}
/** update count of items generated by this source */
protected final synchronized void addItem() {
++itemCount;
++totalItemCount;
}
/**
* A convenience method for collecting all the files of a content source from
* a given directory. The collected {@link File} instances are stored in the
* given <code>files</code>.
*/
protected final void collectFiles(File dir, ArrayList<File> files) {
if (!dir.canRead()) {
return;
}
File[] dirFiles = dir.listFiles();
Arrays.sort(dirFiles);
for (int i = 0; i < dirFiles.length; i++) {
File file = dirFiles[i];
if (file.isDirectory()) {
collectFiles(file, files);
} else if (file.canRead()) {
files.add(file);
}
}
}
/**
* Returns true whether it's time to log a message (depending on verbose and
* the number of items generated).
*/
protected final boolean shouldLog() {
return verbose && logStep > 0 && itemCount % logStep == 0;
}
/** Called when reading from this content source is no longer required. */
public abstract void close() throws IOException;
/** Returns the number of bytes generated since last reset. */
public final long getBytesCount() { return bytesCount; }
/** Returns the number of generated items since last reset. */
public final int getItemsCount() { return itemCount; }
public final Config getConfig() { return config; }
/** Returns the total number of bytes that were generated by this source. */
public final long getTotalBytesCount() { return totalBytesCount; }
/** Returns the total number of generated items. */
public final int getTotalItemsCount() { return totalItemCount; }
/**
* Resets the input for this content source, so that the test would behave as
* if it was just started, input-wise.
* <p>
* <b>NOTE:</b> the default implementation resets the number of bytes and
* items generated since the last reset, so it's important to call
* super.resetInputs in case you override this method.
*/
@SuppressWarnings("unused")
public void resetInputs() throws IOException {
bytesCount = 0;
itemCount = 0;
}
/**
* Sets the {@link Config} for this content source. If you override this
* method, you must call super.setConfig.
*/
public void setConfig(Config config) {
this.config = config;
forever = config.get("content.source.forever", true);
logStep = config.get("content.source.log.step", 0);
verbose = config.get("content.source.verbose", false);
encoding = config.get("content.source.encoding", null);
}
public void printStatistics(String itemsName) {
+ if (!verbose) {
+ return;
+ }
boolean print = false;
String col = " ";
StringBuilder sb = new StringBuilder();
String newline = System.getProperty("line.separator");
sb.append("------------> ").append(getClass().getSimpleName()).append(" statistics (").append(printNum).append("): ").append(newline);
int nut = getTotalItemsCount();
if (nut > lastPrintedNumUniqueTexts) {
print = true;
sb.append("total count of "+itemsName+": ").append(Format.format(0,nut,col)).append(newline);
lastPrintedNumUniqueTexts = nut;
}
long nub = getTotalBytesCount();
if (nub > lastPrintedNumUniqueBytes) {
print = true;
sb.append("total bytes of "+itemsName+": ").append(Format.format(0,nub,col)).append(newline);
lastPrintedNumUniqueBytes = nub;
}
if (getItemsCount() > 0) {
print = true;
sb.append("num "+itemsName+" added since last inputs reset: ").append(Format.format(0,getItemsCount(),col)).append(newline);
sb.append("total bytes added for "+itemsName+" since last inputs reset: ").append(Format.format(0,getBytesCount(),col)).append(newline);
}
if (print) {
System.out.println(sb.append(newline).toString());
printNum++;
}
}
}
| true | true | public void printStatistics(String itemsName) {
boolean print = false;
String col = " ";
StringBuilder sb = new StringBuilder();
String newline = System.getProperty("line.separator");
sb.append("------------> ").append(getClass().getSimpleName()).append(" statistics (").append(printNum).append("): ").append(newline);
int nut = getTotalItemsCount();
if (nut > lastPrintedNumUniqueTexts) {
print = true;
sb.append("total count of "+itemsName+": ").append(Format.format(0,nut,col)).append(newline);
lastPrintedNumUniqueTexts = nut;
}
long nub = getTotalBytesCount();
if (nub > lastPrintedNumUniqueBytes) {
print = true;
sb.append("total bytes of "+itemsName+": ").append(Format.format(0,nub,col)).append(newline);
lastPrintedNumUniqueBytes = nub;
}
if (getItemsCount() > 0) {
print = true;
sb.append("num "+itemsName+" added since last inputs reset: ").append(Format.format(0,getItemsCount(),col)).append(newline);
sb.append("total bytes added for "+itemsName+" since last inputs reset: ").append(Format.format(0,getBytesCount(),col)).append(newline);
}
if (print) {
System.out.println(sb.append(newline).toString());
printNum++;
}
}
| public void printStatistics(String itemsName) {
if (!verbose) {
return;
}
boolean print = false;
String col = " ";
StringBuilder sb = new StringBuilder();
String newline = System.getProperty("line.separator");
sb.append("------------> ").append(getClass().getSimpleName()).append(" statistics (").append(printNum).append("): ").append(newline);
int nut = getTotalItemsCount();
if (nut > lastPrintedNumUniqueTexts) {
print = true;
sb.append("total count of "+itemsName+": ").append(Format.format(0,nut,col)).append(newline);
lastPrintedNumUniqueTexts = nut;
}
long nub = getTotalBytesCount();
if (nub > lastPrintedNumUniqueBytes) {
print = true;
sb.append("total bytes of "+itemsName+": ").append(Format.format(0,nub,col)).append(newline);
lastPrintedNumUniqueBytes = nub;
}
if (getItemsCount() > 0) {
print = true;
sb.append("num "+itemsName+" added since last inputs reset: ").append(Format.format(0,getItemsCount(),col)).append(newline);
sb.append("total bytes added for "+itemsName+" since last inputs reset: ").append(Format.format(0,getBytesCount(),col)).append(newline);
}
if (print) {
System.out.println(sb.append(newline).toString());
printNum++;
}
}
|
diff --git a/common/plugins/org.jboss.tools.common.ui/src/org/jboss/tools/common/ui/marker/ConfigureProblemSeverityResolutionGenerator.java b/common/plugins/org.jboss.tools.common.ui/src/org/jboss/tools/common/ui/marker/ConfigureProblemSeverityResolutionGenerator.java
index d687efeb6..8cc3405c4 100644
--- a/common/plugins/org.jboss.tools.common.ui/src/org/jboss/tools/common/ui/marker/ConfigureProblemSeverityResolutionGenerator.java
+++ b/common/plugins/org.jboss.tools.common.ui/src/org/jboss/tools/common/ui/marker/ConfigureProblemSeverityResolutionGenerator.java
@@ -1,111 +1,111 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.common.ui.marker;
import java.util.ArrayList;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.ui.IMarkerResolution;
import org.eclipse.ui.IMarkerResolutionGenerator2;
import org.jboss.tools.common.EclipseUtil;
import org.jboss.tools.common.ui.CommonUIPlugin;
import org.jboss.tools.common.validation.ValidationErrorManager;
/**
* @author Daniel Azarov
*/
public class ConfigureProblemSeverityResolutionGenerator implements
IMarkerResolutionGenerator2 {
@Override
public IMarkerResolution[] getResolutions(IMarker marker) {
ArrayList<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
int position = marker.getAttribute(IMarker.CHAR_START, 0);
try {
if(marker.getResource() instanceof IFile){
IFile file = (IFile)marker.getResource();
if(file != null){
String preferenceKey = getPreferenceKey(marker);
String preferencePageId = getPreferencePageId(marker);
if(preferenceKey != null && preferencePageId != null){
- resolutions.add(new ConfigureProblemSeverityMarkerResolution(preferencePageId, preferenceKey));
boolean enabled = marker.getAttribute(ValidationErrorManager.SUPPRESS_WARNINGS_ENABLED_ATTRIBUTE, false);
int severity = marker.getAttribute(IMarker.SEVERITY, 0);
if(enabled && severity == IMarker.SEVERITY_WARNING){
IJavaElement element = findJavaElement(file, position);
if(element != null){
if(element instanceof IMethod){
ILocalVariable parameter = findParameter((IMethod)element, position);
if(parameter != null){
resolutions.add(new AddSuppressWarningsMarkerResolution(file, parameter, preferenceKey));
}
}
resolutions.add(new AddSuppressWarningsMarkerResolution(file, element, preferenceKey));
}
}
+ resolutions.add(new ConfigureProblemSeverityMarkerResolution(preferencePageId, preferenceKey));
}
}
}
} catch (CoreException e) {
CommonUIPlugin.getDefault().logError(e);
}
return resolutions.toArray(new IMarkerResolution[] {});
}
private IJavaElement findJavaElement(IFile file, int position){
try {
ICompilationUnit compilationUnit = EclipseUtil.getCompilationUnit(file);
if(compilationUnit != null){
return compilationUnit.getElementAt(position);
}
} catch (CoreException e) {
CommonUIPlugin.getDefault().logError(e);
}
return null;
}
private ILocalVariable findParameter(IMethod method, int position) throws JavaModelException{
for(ILocalVariable parameter : method.getParameters()){
if(parameter.getSourceRange().getOffset() <= position && parameter.getSourceRange().getOffset()+parameter.getSourceRange().getLength() > position){
return parameter;
}
}
return null;
}
@Override
public boolean hasResolutions(IMarker marker) {
try {
return getPreferenceKey(marker) != null && getPreferencePageId(marker) != null;
} catch (CoreException ex) {
CommonUIPlugin.getDefault().logError(ex);
}
return false;
}
private String getPreferenceKey(IMarker marker)throws CoreException{
String attribute = marker.getAttribute(ValidationErrorManager.PREFERENCE_KEY_ATTRIBUTE_NAME, null);
return attribute;
}
private String getPreferencePageId(IMarker marker)throws CoreException{
String attribute = marker.getAttribute(ValidationErrorManager.PREFERENCE_PAGE_ID_NAME, null);
return attribute;
}
}
| false | true | public IMarkerResolution[] getResolutions(IMarker marker) {
ArrayList<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
int position = marker.getAttribute(IMarker.CHAR_START, 0);
try {
if(marker.getResource() instanceof IFile){
IFile file = (IFile)marker.getResource();
if(file != null){
String preferenceKey = getPreferenceKey(marker);
String preferencePageId = getPreferencePageId(marker);
if(preferenceKey != null && preferencePageId != null){
resolutions.add(new ConfigureProblemSeverityMarkerResolution(preferencePageId, preferenceKey));
boolean enabled = marker.getAttribute(ValidationErrorManager.SUPPRESS_WARNINGS_ENABLED_ATTRIBUTE, false);
int severity = marker.getAttribute(IMarker.SEVERITY, 0);
if(enabled && severity == IMarker.SEVERITY_WARNING){
IJavaElement element = findJavaElement(file, position);
if(element != null){
if(element instanceof IMethod){
ILocalVariable parameter = findParameter((IMethod)element, position);
if(parameter != null){
resolutions.add(new AddSuppressWarningsMarkerResolution(file, parameter, preferenceKey));
}
}
resolutions.add(new AddSuppressWarningsMarkerResolution(file, element, preferenceKey));
}
}
}
}
}
} catch (CoreException e) {
CommonUIPlugin.getDefault().logError(e);
}
return resolutions.toArray(new IMarkerResolution[] {});
}
| public IMarkerResolution[] getResolutions(IMarker marker) {
ArrayList<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
int position = marker.getAttribute(IMarker.CHAR_START, 0);
try {
if(marker.getResource() instanceof IFile){
IFile file = (IFile)marker.getResource();
if(file != null){
String preferenceKey = getPreferenceKey(marker);
String preferencePageId = getPreferencePageId(marker);
if(preferenceKey != null && preferencePageId != null){
boolean enabled = marker.getAttribute(ValidationErrorManager.SUPPRESS_WARNINGS_ENABLED_ATTRIBUTE, false);
int severity = marker.getAttribute(IMarker.SEVERITY, 0);
if(enabled && severity == IMarker.SEVERITY_WARNING){
IJavaElement element = findJavaElement(file, position);
if(element != null){
if(element instanceof IMethod){
ILocalVariable parameter = findParameter((IMethod)element, position);
if(parameter != null){
resolutions.add(new AddSuppressWarningsMarkerResolution(file, parameter, preferenceKey));
}
}
resolutions.add(new AddSuppressWarningsMarkerResolution(file, element, preferenceKey));
}
}
resolutions.add(new ConfigureProblemSeverityMarkerResolution(preferencePageId, preferenceKey));
}
}
}
} catch (CoreException e) {
CommonUIPlugin.getDefault().logError(e);
}
return resolutions.toArray(new IMarkerResolution[] {});
}
|
diff --git a/src/org/github/nas774/piax/piaxshell/PIAXShell.java b/src/org/github/nas774/piax/piaxshell/PIAXShell.java
index 44818aa..1e07e3a 100644
--- a/src/org/github/nas774/piax/piaxshell/PIAXShell.java
+++ b/src/org/github/nas774/piax/piaxshell/PIAXShell.java
@@ -1,829 +1,831 @@
package org.github.nas774.piax.piaxshell;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import org.piax.agent.AgentHome;
import org.piax.agent.AgentId;
import org.piax.agent.AgentPeer;
import org.piax.agent.NoSuchAgentException;
import org.piax.trans.common.PeerLocator;
import org.piax.trans.common.ReturnSet;
import org.piax.trans.ts.tcp.TcpLocator;
import org.piax.trans.util.LocalInetAddrs;
import org.piax.trans.util.MersenneTwister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PIAXShell {
private static final Logger logger = LoggerFactory
.getLogger(PIAXShell.class);
private static final String PROPERTY_FILE = "piaxshell.properties";
private static final int DEFAULT_PIAX_PORT = 12367;
private static final String DEFAULT_PEERNAME_PREFIX = "PEER";
private static final String DEFAULT_AGENT_DIRECTORY = "."; // Default AgentClassFile directory.
private static final boolean DEFAULT_PEER_AUTOJOIN = false;
private static final boolean DEFAULT_USE_INTERACTIVESHELL = true;
private AgentPeer peer = null;
protected String peerName = "";
private PeerLocator myLocator = null;
private Collection<PeerLocator> seeds = null;
private File[] agclassesdirs = null;
private boolean autojoin = DEFAULT_PEER_AUTOJOIN;
private boolean use_interactiveshell = DEFAULT_USE_INTERACTIVESHELL;
private File agprop = null;
public static void main(String[] args) {
PIAXShell shell = new PIAXShell();
if (!shell.initSettings(args)) {
printUsage();
return;
}
shell.startShell();
}
private static void printUsage() {
System.out
.println("Usage: PIAXShell [options] name\n"
+ " -j means join automatically after booted.\n"
+ " -I means use interactive shell. (default)\n"
+ " if add '-' after 'I', disables interactive shell.\n"
+ " -e <addr> sets piax address to <addr>\n"
+ " -r <port> sets piax port to <spec>\n"
+ " -s <seed> sets seed peer address to <seed>\n"
+ " <seed> to be host:port form\n"
+ " -p <property file> use <property file> instead of default property file\n"
+ " if add '-' after 'p', ignores default property file.\n"
+ " -a <agent dir> set agent class file directory to <agent dir>\n"
+ " -A <agent property> use agent property file or directory instead of default property to <agent property>\n"
+ " ex. PIAXShell -r 1000 root\n"
+ " ex. PIAXShell -r 1000 -s 192.168.1.101:2000 foo\n");
}
/**
* Initialize instance by command line argument.
*
* @param args
* command line argument.
* @return true:success false:false, maybe some errors occuered.
*/
protected boolean initSettings(String args[]) {
try {
String propfile = PROPERTY_FILE;
String tmp_peername = "";
String tmp_piaxaddress = "";
String tmp_piaxport = "";
String tmp_seed = "";
boolean tmp_autojoin = false;
- boolean tmp_use_interactiveshell = false;
+ boolean tmp_use_interactiveshell = true;
String tmp_agtdir = "";
String tmp_agentprops_str = "";
// Search 'p' option first.
// If 'p' option is found, read property from given file.
// If not, read default property file.
for (int i = 0; i < args.length; i++) {
if (args[i].charAt(1) == 'p') {
if (2 < args[i].length() && '-' == args[i].charAt(2)) {
propfile = null;
} else {
i++;
if (i < args.length) {
propfile = args[i];
}
}
}
}
if (propfile != null) {
File f = new File(propfile);
boolean fileexist = f.exists() && f.isFile();
if (!fileexist) {
logger.warn("Property file not found. : " + propfile);
} else {
if (PROPERTY_FILE.equals(propfile)) {
logger.info("Found default property file." );
}
logger.info("Load from property file. : " + propfile);
// Try to read property file.
Properties serverprop = new Properties();
try {
serverprop.load(new FileInputStream(propfile));
// may
if (serverprop.containsKey("piax.peer.name")) {
tmp_peername = serverprop.getProperty("piax.peer.name");
}
// may
if (serverprop.containsKey("piax.peer.address")) {
tmp_piaxaddress = serverprop.getProperty("piax.peer.address");
}
// may
if (serverprop.containsKey("piax.peer.port")) {
tmp_piaxport = serverprop.getProperty("piax.peer.port");
}
// may
if (serverprop.containsKey("piax.peer.seed")) {
tmp_seed = serverprop.getProperty("piax.peer.seed");
}
// may
if (serverprop.containsKey("piax.peer.autojoin")) {
String tmp_autojoin_str = serverprop
.getProperty("piax.peer.autojoin");
if (tmp_autojoin_str != null
&& !tmp_autojoin_str.equals("")
&& !tmp_autojoin_str.equals("0"))
tmp_autojoin = true;
}
// may
if (serverprop.containsKey("piax.shell.useinteractive")) {
String tmp_use_interactiveshell_str = serverprop
.getProperty("piax.shell.useinteractive");
- if (tmp_use_interactiveshell_str != null
- && !tmp_use_interactiveshell_str.equals("")
- && !tmp_use_interactiveshell_str.equals("0"))
- tmp_use_interactiveshell = true;
+ tmp_use_interactiveshell_str = tmp_use_interactiveshell_str.trim();
+ if (tmp_use_interactiveshell_str != null &&
+ !tmp_use_interactiveshell_str.equals("")) {
+ if (tmp_use_interactiveshell_str.equals("0"))
+ tmp_use_interactiveshell = false;
+ }
}
// may
if (serverprop.containsKey("piax.agent.directory")) {
tmp_agtdir = serverprop.getProperty("piax.agent.directory");
}
// may
if (serverprop.containsKey("piax.agentprops")) {
tmp_agentprops_str = serverprop
.getProperty("piax.agentprops");
}
} catch (FileNotFoundException e) {
logger.warn("Property file not found. : " + propfile);
} catch (IOException e) {
logger.warn("IO error at reading property file. : " + propfile);
}
}
}
boolean isFault = false;
// Read setting from command line options.
// Configurations in property file are overwritten by command-line options.
for (int i = 0; i < args.length; i++) {
String arg = args[i].trim();
if (args[i].startsWith("-")) {
switch (arg.charAt(1)) {
case 'e':
i++;
if (i < args.length) {
tmp_piaxaddress = args[i];
}
break;
case 'r':
i++;
if (i < args.length) {
tmp_piaxport = args[i];
}
break;
case 'j': {
tmp_autojoin = true;
String tmp_autojoin_str = arg.substring(2);
if (tmp_autojoin_str.equals("-"))
tmp_autojoin = false;
break;
}
case 'I': {
tmp_use_interactiveshell = true;
String tmp_use_interactiveshell_str = arg.substring(2);
if (tmp_use_interactiveshell_str.equals("-"))
tmp_use_interactiveshell = false;
break;
}
case 's':
i++;
if (i < args.length) {
tmp_seed = args[i];
}
break;
case 'p':
if (2 < args[i].length() && '-' == args[i].charAt(2)) {
} else {
i++;
}
// already proced.
break;
case 'A':
i++;
if (i < args.length) {
tmp_agentprops_str = args[i];
}
break;
case 'a':
i++;
if (i < args.length) {
tmp_agtdir = args[i];
}
break;
case '?':
return false;
default:
return false;
}
} else {
tmp_peername = arg;
}
}
// Setup instance fields.
if (tmp_peername.equals("")) {
logger.warn("Peer name is not specified. Set generated name.");
tmp_peername = DEFAULT_PEERNAME_PREFIX
+ new MersenneTwister().nextInt(10 * 6);
}
peerName = tmp_peername;
logger.info("Peer name : " + peerName);
if (tmp_agtdir.equals("")) {
logger.warn("Agent class file directory is not specified. Set default.");
tmp_agtdir = DEFAULT_AGENT_DIRECTORY;
}
File agtdir = new File(tmp_agtdir);
if (agtdir.exists()) {
logger.info("Agent class file directory : " + tmp_agtdir);
agclassesdirs = new File[] { agtdir };
} else {
logger.error("Agent class file directory you specified isn't found. : "
+ tmp_agtdir);
isFault = true;
}
autojoin = tmp_autojoin;
logger.info("Auto join : " + autojoin);
use_interactiveshell = tmp_use_interactiveshell;
logger.info("Use Interactive Shell : " + use_interactiveshell);
agprop = null;
if (tmp_agentprops_str != null && !tmp_agentprops_str.equals("")) {
File tmp_agprop = new File(tmp_agentprops_str);
if (!tmp_agprop.exists()) {
logger.warn("Agent property file or directory can not be found. : "
+ tmp_agentprops_str);
} else {
agprop = tmp_agprop;
}
}
if (agprop == null) {
logger.info("Agent property file or directory : <not use>");
} else {
if (agprop.isFile()) {
logger.info("Agent property file : "
+ agprop.getAbsolutePath());
} else if (agprop.isDirectory()) {
logger.info("Agent property directory : "
+ agprop.getAbsolutePath());
}
}
if (tmp_piaxaddress.equals("")) {
logger.warn("A PIAX address is not specified. Choose appropriate address.");
tmp_piaxaddress = LocalInetAddrs.choice().getHostAddress();
}
if (tmp_piaxport.equals("")) {
logger.warn("A PIAX port is not specified. Set default.");
tmp_piaxport = Integer.toString(DEFAULT_PIAX_PORT);
}
logger.info("PIAX address : " + tmp_piaxaddress);
logger.info("PIAX port : " + tmp_piaxport);
myLocator = new TcpLocator(new InetSocketAddress(tmp_piaxaddress, Integer.parseInt(tmp_piaxport)));
if (!tmp_seed.equals("")) {
String[] seedEle = tmp_seed.split(":");
seeds = Collections.singleton((PeerLocator) new TcpLocator(
new InetSocketAddress(seedEle[0], Integer
.parseInt(seedEle[1]))));
} else {
logger.info("Seed peers are not specified. Run as a seed peer.");
seeds = Collections.singleton(myLocator);
}
return !isFault;
} catch (Exception e) {
logger.error(e.getMessage(), e);
return false;
}
}
public void startShell() {
// - setup phase
// Initialize PIAX
try {
peer = new AgentPeer(null, peerName, myLocator, seeds, false,
agclassesdirs);
} catch (IOException e) {
logger.error("*** PIAX not started as IO Error.", e);
return;
} catch (IllegalArgumentException e) {
logger.error("*** PIAX not started as Argument Error.", e);
return;
}
// Create agents from agent property files.
if (agprop != null) {
if (agprop.isDirectory()) {
for (File file : agprop.listFiles()) {
createAgentFromPropertyFile(file);
}
} else {
createAgentFromPropertyFile(agprop);
}
}
// Auto join
if (autojoin) {
join(); // Join to PIAX network.
logger.info("PIAX joined.");
}
// Activate agents.
notifyActivate();
try {
logger.info("Finished initializing");
if (use_interactiveshell) {
// Run console interactive shell.
logger.info("Start interactive shell.");
mainLoop();
} else {
try {
while (true) {
Thread.sleep(5 * 60 * 1000);
}
} catch (InterruptedException e) {
}
}
// - Terminate phase
} catch (Exception e1) {
logger.error(e1.getMessage(), e1);
}
// Dispose all agents.
Set<AgentId> ags = new HashSet<AgentId>();
for (AgentId agId : peer.getHome().getAgentIds()) {
ags.add(agId);
}
for (AgentId agId : ags) {
try {
peer.getHome().destroyAgent(agId);
} catch (NoSuchAgentException e) {
logger.debug("Ignore a NoSuchAgentException.");
}
}
// Terminate PIAX
if (peer.isOnline())
leave(); // Leave from PIAX network.
peer.fin(); // Finalize PIAX.
}
/**
* Create agents from agent property files.
*
* @param file
* A directory which has agent property.
*/
private void createAgentFromPropertyFile(File file) {
logger.info("Opening property file : " + file.getName());
Properties agentprop = new Properties();
try {
agentprop.load(new FileInputStream(file));
} catch (FileNotFoundException e) {
logger.error("Agent property file not found.");
// Ignore unreadable file.
return;
} catch (IOException e) {
logger.error("IO error when loading agent property file.");
// Ignore unreadable file.
return;
}
String classname = agentprop.getProperty("piax.agent.class");
String agentname = agentprop.getProperty("piax.agent.name");
// Check null or empty element.
if (classname == null || classname.equals("")) {
logger.error("piax.agent.class is null : " + classname);
return;
}
if (agentname == null || agentname.equals("")) {
logger.error("piax.agent.name is null : " + agentname);
return;
}
try {
AgentHome home = peer.getHome();
AgentId agtid = home.createAgent(classname, agentname);
if (!(Boolean) home.call(agtid, "initAgent", new Object[] { file })) {
logger.error("Failed initializing Agent. Class:" + classname
+ " Name:" + agentname);
// Dispose if creating agent failed.
home.destroyAgent(agtid);
return;
}
logger.info("Craeted an agent named " + agentname + " based by " + classname + " as ID:" + agtid);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
private void notifyActivate() {
AgentHome home = peer.getHome();
for (AgentId aid : home.getAgentIds()) {
home.callOneway(aid, "activate", new Object[]{});
}
}
private void printHelp() {
System.out
.print(" *** PIAXShell Help ***\n"
+ " i)nfo show my peer information\n"
+ " \n"
+ " ag)ents [cat] list agents have specific category\n"
+ " \n"
+ " join join P2P net\n"
+ " leave leave from P2P net\n"
+ " \n"
+ " mk)agent class name [cat]\n"
+ " create new agent as class and set name and category\n"
+ " mk)agent file\n"
+ " create new agent by using file describes agent info\n"
+ " dup agent_NO duplicate agent from which indicated by agent_NO\n"
+ " sl)eep agent_NO sleep agent indicated by agent_NO\n"
+ " wa)ke agetn_NO wakeup agent indicated by agent_NO\n"
+ " fin agent_NO destroy agent indicated by agent_NO\n"
+ " dc,discover method arg ...\n"
+ " discoveryCall to agents in whole area\n"
+ " \n" + " c)all agent_NO method arg ...\n"
+ " call agent method\n" + " \n"
+ " ?,help show this help message\n"
+ " bye exit\n" + "\n");
}
private String[] split(String line) {
ArrayList<String> lines = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
lines.add(st.nextToken());
}
String[] rlines = new String[lines.size()];
return (String[]) lines.toArray(rlines);
}
private List<AgentId> agents;
long stime;
void mainLoop() {
agents = new ArrayList<AgentId>();
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
while (true) {
try {
System.out.print("Input Command >");
String input = null;
// countermeasure for background running with "< /dev/null".
while (true) {
input = reader.readLine();
if (input == null) {
Thread.sleep(500);
continue;
}
break;
}
String[] args = split(input);
if (args.length == 0) {
continue;
}
stime = System.currentTimeMillis();
if (args[0].equals("info") || args[0].equals("i")) {
if (args.length != 1) {
printHelp();
continue;
}
info();
} else if (args[0].equals("agents") || args[0].equals("ag")) {
if (args.length > 1) {
printHelp();
continue;
}
if (args.length == 1) {
agents();
}
} else if (args[0].equals("join")) {
if (args.length != 1) {
printHelp();
continue;
}
join();
} else if (args[0].equals("leave")) {
if (args.length != 1) {
printHelp();
continue;
}
leave();
} else if (args[0].equals("mkagent") || args[0].equals("mk")) {
if (args.length < 2 || args.length > 4) {
printHelp();
continue;
}
if (args.length == 2) {
mkagent(args[1]);
} else if (args.length == 3) {
mkagent(args[1], args[2]);
}
} else if (args[0].equals("dup")) {
if (args.length != 2) {
printHelp();
continue;
}
dup(Integer.parseInt(args[1]));
} else if (args[0].equals("sleep") || args[0].equals("sl")) {
if (args.length != 2) {
printHelp();
continue;
}
sleep(Integer.parseInt(args[1]));
} else if (args[0].equals("wake") || args[0].equals("wa")) {
if (args.length != 2) {
printHelp();
continue;
}
wake(Integer.parseInt(args[1]));
} else if (args[0].equals("fin")) {
if (args.length != 2) {
printHelp();
continue;
}
fin(Integer.parseInt(args[1]));
} else if (args[0].equals("discover") || args[0].equals("dc")) {
if (args.length < 2) {
printHelp();
continue;
}
Object[] cargs = new String[args.length - 2];
for (int i = 0; i < cargs.length; i++) {
cargs[i] = args[i + 2];
}
discover(args[1], cargs);
} else if (args[0].equals("call") || args[0].equals("c")) {
if (args.length < 3) {
printHelp();
continue;
}
Object[] cargs = new String[args.length - 3];
for (int i = 0; i < cargs.length; i++) {
cargs[i] = args[i + 3];
}
call(Integer.parseInt(args[1]), args[2], cargs);
} else if (args[0].equals("help") || args[0].equals("?")) {
printHelp();
continue;
} else if (args[0].equals("bye")) {
if (peer.isOnline()) {
leave();
}
return;
} else {
printHelp();
continue;
}
long etime = System.currentTimeMillis();
System.out.println("\t## time (msec): " + (etime - stime));
} catch (NumberFormatException e) {
System.out.println("\t>> arg should be number.");
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
void info() {
try {
System.out.println(" peerName: " + peerName);
System.out.println(" peerId: " + peer.getHome().getPeerId());
System.out.println(" locator: " + myLocator);
System.out.println(" location: " + peer.getHome().getLocation());
System.out.println(peer.getOverlayMgr().showTable());
} catch (Exception e) {
logger.warn(e.getMessage(), e);
}
}
void agents() {
try {
AgentHome home = peer.getHome();
agents.clear();
int i = 0;
for (AgentId agId : home.getAgentIds(null)) {
agents.add(agId);
String name = home.getAgentName(agId);
boolean isSleeping = home.isAgentSleeping(agId);
System.out.println(" " + i + ". name: " + name + ", ID: "
+ agId + (isSleeping ? " <sleep>" : ""));
i++;
}
} catch (NoSuchAgentException e) {
logger.warn(e.getMessage(), e);
}
}
void join() {
try {
peer.online();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
System.out.println("\t>> join failed.");
}
}
void leave() {
try {
peer.offline();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
System.out.println("\t>> leave failed.");
}
}
/* agents */
void mkagent(String clazz, String name) {
try {
peer.getHome().createAgent(clazz, name);
} catch (Exception e) {
logger.warn(e.getMessage(), e);
System.out.println("\t>> cannot create new agent.");
}
}
void mkagent(String file) {
String agentPath = System.getProperty("piaxPeer.agent.path");
File agentFile = new File(new File(agentPath), file);
if (!agentFile.isFile()) {
System.out
.println("\t>> " + file + " is not found at " + agentPath);
return;
}
try {
BufferedReader reader = new BufferedReader(
new FileReader(agentFile));
String line;
while ((line = reader.readLine()) != null) {
String[] items = split(line);
if (items.length == 2) {
peer.getHome().createAgent(items[0], items[1]);
}
}
} catch (Exception e) {
logger.warn(e.getMessage(), e);
System.out.println("\t>> cannot create new agent.");
}
}
void dup(int agentNo) {
if (agents.size() <= agentNo) {
System.out.println("\t>> invalid agent NO.");
return;
}
AgentId agId = agents.get(agentNo);
try {
peer.getHome().duplicateAgent(agId);
} catch (Exception e) {
logger.warn(e.getMessage(), e);
System.out.println("\t>> cannot duplicate agent.");
}
}
void sleep(int agentNo) {
if (agents.size() <= agentNo) {
System.out.println("\t>> invalid agent NO.");
return;
}
AgentId agId = agents.get(agentNo);
try {
peer.getHome().sleepAgent(agId);
} catch (Exception e) {
logger.warn(e.getMessage(), e);
System.out.println("\t>> cannot sleep agent.");
}
}
void wake(int agentNo) {
if (agents.size() <= agentNo) {
System.out.println("\t>> invalid agent NO.");
return;
}
AgentId agId = agents.get(agentNo);
try {
peer.getHome().wakeupAgent(agId);
} catch (Exception e) {
logger.warn(e.getMessage(), e);
System.out.println("\t>> cannot wakeup agent.");
}
}
void fin(int agentNo) {
if (agents.size() <= agentNo) {
System.out.println("\t>> invalid agent NO.");
return;
}
AgentId agId = agents.get(agentNo);
try {
peer.getHome().destroyAgent(agId);
} catch (Exception e) {
logger.warn(e.getMessage(), e);
System.out.println("\t>> cannot destroy agent.");
}
}
void discover(String method, Object... args) {
ReturnSet<Object> rset = null;
try {
rset = peer.getHome().discoveryCallAsync(
"location in rect(0,0,1,1)", method, args);
} catch (IllegalStateException e) {
System.out.println("\t>> not joined.");
return;
} catch (Exception e) {
logger.warn(e.getMessage(), e);
System.out.println("\t>> could not discovery call.");
return;
}
while (rset.hasNext()) {
Object value;
try {
value = rset.getNext(3000);
} catch (InterruptedException e) {
break;
} catch (NoSuchElementException e) {
break;
} catch (InvocationTargetException e) {
continue;
}
long etime = System.currentTimeMillis();
System.out.println(" value: " + value);
System.out.println(" peerId: " + rset.getThisPeerId());
AgentId agId = (AgentId) rset.getThisTargetId();
System.out.println(" agentId: " + agId);
System.out.println("\t## time (msec): " + (etime - stime));
}
}
void call(int agentNo, String method, Object... cargs) {
if (agents.size() <= agentNo) {
System.out.println("\t>> invalid agent NO.");
return;
}
AgentId agId = agents.get(agentNo);
try {
Object obj = peer.getHome().call(agId, method, cargs);
System.out.println(" return value: " + obj);
} catch (Exception e) {
logger.warn(e.getMessage(), e);
System.out.println("\t>> cannot call agent.");
}
}
}
| false | true | protected boolean initSettings(String args[]) {
try {
String propfile = PROPERTY_FILE;
String tmp_peername = "";
String tmp_piaxaddress = "";
String tmp_piaxport = "";
String tmp_seed = "";
boolean tmp_autojoin = false;
boolean tmp_use_interactiveshell = false;
String tmp_agtdir = "";
String tmp_agentprops_str = "";
// Search 'p' option first.
// If 'p' option is found, read property from given file.
// If not, read default property file.
for (int i = 0; i < args.length; i++) {
if (args[i].charAt(1) == 'p') {
if (2 < args[i].length() && '-' == args[i].charAt(2)) {
propfile = null;
} else {
i++;
if (i < args.length) {
propfile = args[i];
}
}
}
}
if (propfile != null) {
File f = new File(propfile);
boolean fileexist = f.exists() && f.isFile();
if (!fileexist) {
logger.warn("Property file not found. : " + propfile);
} else {
if (PROPERTY_FILE.equals(propfile)) {
logger.info("Found default property file." );
}
logger.info("Load from property file. : " + propfile);
// Try to read property file.
Properties serverprop = new Properties();
try {
serverprop.load(new FileInputStream(propfile));
// may
if (serverprop.containsKey("piax.peer.name")) {
tmp_peername = serverprop.getProperty("piax.peer.name");
}
// may
if (serverprop.containsKey("piax.peer.address")) {
tmp_piaxaddress = serverprop.getProperty("piax.peer.address");
}
// may
if (serverprop.containsKey("piax.peer.port")) {
tmp_piaxport = serverprop.getProperty("piax.peer.port");
}
// may
if (serverprop.containsKey("piax.peer.seed")) {
tmp_seed = serverprop.getProperty("piax.peer.seed");
}
// may
if (serverprop.containsKey("piax.peer.autojoin")) {
String tmp_autojoin_str = serverprop
.getProperty("piax.peer.autojoin");
if (tmp_autojoin_str != null
&& !tmp_autojoin_str.equals("")
&& !tmp_autojoin_str.equals("0"))
tmp_autojoin = true;
}
// may
if (serverprop.containsKey("piax.shell.useinteractive")) {
String tmp_use_interactiveshell_str = serverprop
.getProperty("piax.shell.useinteractive");
if (tmp_use_interactiveshell_str != null
&& !tmp_use_interactiveshell_str.equals("")
&& !tmp_use_interactiveshell_str.equals("0"))
tmp_use_interactiveshell = true;
}
// may
if (serverprop.containsKey("piax.agent.directory")) {
tmp_agtdir = serverprop.getProperty("piax.agent.directory");
}
// may
if (serverprop.containsKey("piax.agentprops")) {
tmp_agentprops_str = serverprop
.getProperty("piax.agentprops");
}
} catch (FileNotFoundException e) {
logger.warn("Property file not found. : " + propfile);
} catch (IOException e) {
logger.warn("IO error at reading property file. : " + propfile);
}
}
}
boolean isFault = false;
// Read setting from command line options.
// Configurations in property file are overwritten by command-line options.
for (int i = 0; i < args.length; i++) {
String arg = args[i].trim();
if (args[i].startsWith("-")) {
switch (arg.charAt(1)) {
case 'e':
i++;
if (i < args.length) {
tmp_piaxaddress = args[i];
}
break;
case 'r':
i++;
if (i < args.length) {
tmp_piaxport = args[i];
}
break;
case 'j': {
tmp_autojoin = true;
String tmp_autojoin_str = arg.substring(2);
if (tmp_autojoin_str.equals("-"))
tmp_autojoin = false;
break;
}
case 'I': {
tmp_use_interactiveshell = true;
String tmp_use_interactiveshell_str = arg.substring(2);
if (tmp_use_interactiveshell_str.equals("-"))
tmp_use_interactiveshell = false;
break;
}
case 's':
i++;
if (i < args.length) {
tmp_seed = args[i];
}
break;
case 'p':
if (2 < args[i].length() && '-' == args[i].charAt(2)) {
} else {
i++;
}
// already proced.
break;
case 'A':
i++;
if (i < args.length) {
tmp_agentprops_str = args[i];
}
break;
case 'a':
i++;
if (i < args.length) {
tmp_agtdir = args[i];
}
break;
case '?':
return false;
default:
return false;
}
} else {
tmp_peername = arg;
}
}
// Setup instance fields.
if (tmp_peername.equals("")) {
logger.warn("Peer name is not specified. Set generated name.");
tmp_peername = DEFAULT_PEERNAME_PREFIX
+ new MersenneTwister().nextInt(10 * 6);
}
peerName = tmp_peername;
logger.info("Peer name : " + peerName);
if (tmp_agtdir.equals("")) {
logger.warn("Agent class file directory is not specified. Set default.");
tmp_agtdir = DEFAULT_AGENT_DIRECTORY;
}
File agtdir = new File(tmp_agtdir);
if (agtdir.exists()) {
logger.info("Agent class file directory : " + tmp_agtdir);
agclassesdirs = new File[] { agtdir };
} else {
logger.error("Agent class file directory you specified isn't found. : "
+ tmp_agtdir);
isFault = true;
}
autojoin = tmp_autojoin;
logger.info("Auto join : " + autojoin);
use_interactiveshell = tmp_use_interactiveshell;
logger.info("Use Interactive Shell : " + use_interactiveshell);
agprop = null;
if (tmp_agentprops_str != null && !tmp_agentprops_str.equals("")) {
File tmp_agprop = new File(tmp_agentprops_str);
if (!tmp_agprop.exists()) {
logger.warn("Agent property file or directory can not be found. : "
+ tmp_agentprops_str);
} else {
agprop = tmp_agprop;
}
}
if (agprop == null) {
logger.info("Agent property file or directory : <not use>");
} else {
if (agprop.isFile()) {
logger.info("Agent property file : "
+ agprop.getAbsolutePath());
} else if (agprop.isDirectory()) {
logger.info("Agent property directory : "
+ agprop.getAbsolutePath());
}
}
if (tmp_piaxaddress.equals("")) {
logger.warn("A PIAX address is not specified. Choose appropriate address.");
tmp_piaxaddress = LocalInetAddrs.choice().getHostAddress();
}
if (tmp_piaxport.equals("")) {
logger.warn("A PIAX port is not specified. Set default.");
tmp_piaxport = Integer.toString(DEFAULT_PIAX_PORT);
}
logger.info("PIAX address : " + tmp_piaxaddress);
logger.info("PIAX port : " + tmp_piaxport);
myLocator = new TcpLocator(new InetSocketAddress(tmp_piaxaddress, Integer.parseInt(tmp_piaxport)));
if (!tmp_seed.equals("")) {
String[] seedEle = tmp_seed.split(":");
seeds = Collections.singleton((PeerLocator) new TcpLocator(
new InetSocketAddress(seedEle[0], Integer
.parseInt(seedEle[1]))));
} else {
logger.info("Seed peers are not specified. Run as a seed peer.");
seeds = Collections.singleton(myLocator);
}
return !isFault;
} catch (Exception e) {
logger.error(e.getMessage(), e);
return false;
}
}
| protected boolean initSettings(String args[]) {
try {
String propfile = PROPERTY_FILE;
String tmp_peername = "";
String tmp_piaxaddress = "";
String tmp_piaxport = "";
String tmp_seed = "";
boolean tmp_autojoin = false;
boolean tmp_use_interactiveshell = true;
String tmp_agtdir = "";
String tmp_agentprops_str = "";
// Search 'p' option first.
// If 'p' option is found, read property from given file.
// If not, read default property file.
for (int i = 0; i < args.length; i++) {
if (args[i].charAt(1) == 'p') {
if (2 < args[i].length() && '-' == args[i].charAt(2)) {
propfile = null;
} else {
i++;
if (i < args.length) {
propfile = args[i];
}
}
}
}
if (propfile != null) {
File f = new File(propfile);
boolean fileexist = f.exists() && f.isFile();
if (!fileexist) {
logger.warn("Property file not found. : " + propfile);
} else {
if (PROPERTY_FILE.equals(propfile)) {
logger.info("Found default property file." );
}
logger.info("Load from property file. : " + propfile);
// Try to read property file.
Properties serverprop = new Properties();
try {
serverprop.load(new FileInputStream(propfile));
// may
if (serverprop.containsKey("piax.peer.name")) {
tmp_peername = serverprop.getProperty("piax.peer.name");
}
// may
if (serverprop.containsKey("piax.peer.address")) {
tmp_piaxaddress = serverprop.getProperty("piax.peer.address");
}
// may
if (serverprop.containsKey("piax.peer.port")) {
tmp_piaxport = serverprop.getProperty("piax.peer.port");
}
// may
if (serverprop.containsKey("piax.peer.seed")) {
tmp_seed = serverprop.getProperty("piax.peer.seed");
}
// may
if (serverprop.containsKey("piax.peer.autojoin")) {
String tmp_autojoin_str = serverprop
.getProperty("piax.peer.autojoin");
if (tmp_autojoin_str != null
&& !tmp_autojoin_str.equals("")
&& !tmp_autojoin_str.equals("0"))
tmp_autojoin = true;
}
// may
if (serverprop.containsKey("piax.shell.useinteractive")) {
String tmp_use_interactiveshell_str = serverprop
.getProperty("piax.shell.useinteractive");
tmp_use_interactiveshell_str = tmp_use_interactiveshell_str.trim();
if (tmp_use_interactiveshell_str != null &&
!tmp_use_interactiveshell_str.equals("")) {
if (tmp_use_interactiveshell_str.equals("0"))
tmp_use_interactiveshell = false;
}
}
// may
if (serverprop.containsKey("piax.agent.directory")) {
tmp_agtdir = serverprop.getProperty("piax.agent.directory");
}
// may
if (serverprop.containsKey("piax.agentprops")) {
tmp_agentprops_str = serverprop
.getProperty("piax.agentprops");
}
} catch (FileNotFoundException e) {
logger.warn("Property file not found. : " + propfile);
} catch (IOException e) {
logger.warn("IO error at reading property file. : " + propfile);
}
}
}
boolean isFault = false;
// Read setting from command line options.
// Configurations in property file are overwritten by command-line options.
for (int i = 0; i < args.length; i++) {
String arg = args[i].trim();
if (args[i].startsWith("-")) {
switch (arg.charAt(1)) {
case 'e':
i++;
if (i < args.length) {
tmp_piaxaddress = args[i];
}
break;
case 'r':
i++;
if (i < args.length) {
tmp_piaxport = args[i];
}
break;
case 'j': {
tmp_autojoin = true;
String tmp_autojoin_str = arg.substring(2);
if (tmp_autojoin_str.equals("-"))
tmp_autojoin = false;
break;
}
case 'I': {
tmp_use_interactiveshell = true;
String tmp_use_interactiveshell_str = arg.substring(2);
if (tmp_use_interactiveshell_str.equals("-"))
tmp_use_interactiveshell = false;
break;
}
case 's':
i++;
if (i < args.length) {
tmp_seed = args[i];
}
break;
case 'p':
if (2 < args[i].length() && '-' == args[i].charAt(2)) {
} else {
i++;
}
// already proced.
break;
case 'A':
i++;
if (i < args.length) {
tmp_agentprops_str = args[i];
}
break;
case 'a':
i++;
if (i < args.length) {
tmp_agtdir = args[i];
}
break;
case '?':
return false;
default:
return false;
}
} else {
tmp_peername = arg;
}
}
// Setup instance fields.
if (tmp_peername.equals("")) {
logger.warn("Peer name is not specified. Set generated name.");
tmp_peername = DEFAULT_PEERNAME_PREFIX
+ new MersenneTwister().nextInt(10 * 6);
}
peerName = tmp_peername;
logger.info("Peer name : " + peerName);
if (tmp_agtdir.equals("")) {
logger.warn("Agent class file directory is not specified. Set default.");
tmp_agtdir = DEFAULT_AGENT_DIRECTORY;
}
File agtdir = new File(tmp_agtdir);
if (agtdir.exists()) {
logger.info("Agent class file directory : " + tmp_agtdir);
agclassesdirs = new File[] { agtdir };
} else {
logger.error("Agent class file directory you specified isn't found. : "
+ tmp_agtdir);
isFault = true;
}
autojoin = tmp_autojoin;
logger.info("Auto join : " + autojoin);
use_interactiveshell = tmp_use_interactiveshell;
logger.info("Use Interactive Shell : " + use_interactiveshell);
agprop = null;
if (tmp_agentprops_str != null && !tmp_agentprops_str.equals("")) {
File tmp_agprop = new File(tmp_agentprops_str);
if (!tmp_agprop.exists()) {
logger.warn("Agent property file or directory can not be found. : "
+ tmp_agentprops_str);
} else {
agprop = tmp_agprop;
}
}
if (agprop == null) {
logger.info("Agent property file or directory : <not use>");
} else {
if (agprop.isFile()) {
logger.info("Agent property file : "
+ agprop.getAbsolutePath());
} else if (agprop.isDirectory()) {
logger.info("Agent property directory : "
+ agprop.getAbsolutePath());
}
}
if (tmp_piaxaddress.equals("")) {
logger.warn("A PIAX address is not specified. Choose appropriate address.");
tmp_piaxaddress = LocalInetAddrs.choice().getHostAddress();
}
if (tmp_piaxport.equals("")) {
logger.warn("A PIAX port is not specified. Set default.");
tmp_piaxport = Integer.toString(DEFAULT_PIAX_PORT);
}
logger.info("PIAX address : " + tmp_piaxaddress);
logger.info("PIAX port : " + tmp_piaxport);
myLocator = new TcpLocator(new InetSocketAddress(tmp_piaxaddress, Integer.parseInt(tmp_piaxport)));
if (!tmp_seed.equals("")) {
String[] seedEle = tmp_seed.split(":");
seeds = Collections.singleton((PeerLocator) new TcpLocator(
new InetSocketAddress(seedEle[0], Integer
.parseInt(seedEle[1]))));
} else {
logger.info("Seed peers are not specified. Run as a seed peer.");
seeds = Collections.singleton(myLocator);
}
return !isFault;
} catch (Exception e) {
logger.error(e.getMessage(), e);
return false;
}
}
|
diff --git a/src/cytoscape/visual/ValueDisplayer.java b/src/cytoscape/visual/ValueDisplayer.java
index deb592a80..19300c88f 100755
--- a/src/cytoscape/visual/ValueDisplayer.java
+++ b/src/cytoscape/visual/ValueDisplayer.java
@@ -1,600 +1,598 @@
//----------------------------------------------------------------------------
// $Revision$
// $Date$
// $Author$
//----------------------------------------------------------------------------
package cytoscape.visual;
//----------------------------------------------------------------------------
import javax.swing.JButton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.event.*;
import java.util.HashMap;
import y.view.*;
import cytoscape.visual.ui.*;
//----------------------------------------------------------------------------
/**
* Given an Object, figures out the class of the object and creates a JButton
* suitable for displaying the value of that object. When the button is
* pressed, it should pop up a user interface to change the value.
*
* The class interested in the selection of the ValueDisplayer should add
* an ItemListener to the button. The ItemListener is triggered when the user's
* selection changes.
*/
public class ValueDisplayer extends JButton {
/**
* Formatting for numeric types.
*/
public static DecimalFormat formatter = new DecimalFormat("0.0####");
/**
* Display and get input for a color
*/
public static final byte COLOR = 0;
/**
* Display and get input for a linetype
*/
public static final byte LINETYPE = 1;
/**
* Display and get input for an arrowhead
*/
public static final byte ARROW = 2;
/**
* Display and get input for a string
*/
public static final byte STRING = 3;
/**
* Display and get input for a double
*/
public static final byte DOUBLE = 4;
/**
* Display and get input for node shape
*/
public static final byte NODESHAPE = 5;
/**
* Display and get input for an int
*/
public static final byte INT = 6;
/**
* Display and get input for a font
*/
public static final byte FONT = 7;
/**
* Holds the type of UI this ValueDisplayer will pop up.
*/
protected byte dispType;
/**
* Holds the object inputted by the user.
*/
private Object inputObj = null;
/**
* Input dialog title
*/
private String title;
/**
* Parent dialog
*/
private JDialog parent;
/**
* ActionListener that triggers input UI
*/
private ActionListener inputListener;
/**
* Enable/disable mouse listeners
*/
private boolean enabled;
/**
* Provided for convenience.
* @see #getValue
* @return User-selected object displayed by this ValueDisplayer
*/
public Object getSelectedItem() {
return this.getValue();
}
/**
* Returns an object representing the user input. The return value is always
* an object type. It may be a String, Number, Arrow, LineType, or Byte
* depending on what type the ValueDisplayer was initialized with.
*
* @return User-selected object displayed by this ValueDisplayer
*/
public Object getValue() {
return inputObj;
}
/**
* Returns the ActionListener that will pop up the input UI when triggered.
* Attach this to a component to trigger input on a click.
*/
public ActionListener getInputListener() {
return inputListener;
}
/**
* Returns the type of input this ValueDisplayer displays/gets input for
*/
public byte getType() {
return dispType;
}
/**
* Set the ValueDisplayer active/inactive.
*
* @param b true to enable, false to disable
*/
public void setEnabled(boolean b) {
this.enabled = b;
super.setEnabled(b);
}
/**
* This private constructor is used to create all ValueDisplayers.
* Use the static method getDisplayFor (@link #getDisplayFor) to
* get a new ValueDisplayer.
*/
private ValueDisplayer(JDialog parent, String labelText, String title,
byte dispType) {
super(labelText);
setBorderPainted(false);
this.parent = parent;
this.dispType = dispType;
this.title = title;
}
private ValueDisplayer(JDialog parent, String title, byte dispType) {
// can't find proper icon/label until later, so set label to null for now
this(parent, null, title, dispType);
}
public static ValueDisplayer getDisplayForColor(JDialog parent, String title,
Color c) {
String dispString = " "; // just display the color
ValueDisplayer v = new ValueDisplayer(parent, dispString, title, COLOR);
if (c != null) {
v.setOpaque(true);
v.setBackground(c);
v.inputObj = c;
}
v.setInputColorListener();
return v;
}
private void setInputColorListener() {
this.inputListener = new ColorListener(this);
addActionListener(this.inputListener);
}
/**
* This method fires the itemListeners. Item listeners are notified only when
* a new selection of the underlying value of the ValueDisplayer is made.
*
* Typically this should only be called by listeners that underlie the
* internal structure of the ValueDisplayer
*/
protected void fireItemSelected() {
this.fireItemStateChanged(new ItemEvent(this,
ItemEvent.ITEM_STATE_CHANGED,
inputObj,
ItemEvent.SELECTED));
}
/**
* Set the object displayed. Ensure that the class is the same.
* Fires an itemSelected event.
*
* @throws ClassCastException if caller attempts to set an object
* different from what was being represented.
*/
public void setObject(Object o) throws ClassCastException {
inputObj = o;
if (o instanceof Icon) {
setIcon((Icon) o);
}
else if (o instanceof Color) {
setBackground((Color) o);
}
else if (o instanceof Font) {
Font f = (Font) o;
setFont(f);
setText(f.getFontName());
}
else { // anything else must be a Double, Integer, or String
setText(o.toString());
}
fireItemSelected();
}
// internal class ColorListener
private class ColorListener extends AbstractAction {
ValueDisplayer parent;
ColorListener (ValueDisplayer parent) {
super("ValueDisplayer ColorListener");
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
if (enabled) {
Color tempColor = JColorChooser.showDialog(parent.parent,
parent.title,
(Color) parent.inputObj);
if (tempColor != null) {
parent.inputObj = tempColor;
parent.setBackground(tempColor);
parent.fireItemSelected();
}
}
}
}
private static ValueDisplayer getDisplayForFont(JDialog parent, String title,
Font startFont) {
ValueDisplayer v = new ValueDisplayer(parent, title, FONT);
v.setSelectedFont(startFont);
v.setInputFontListener();
return v;
}
private void setSelectedFont(Font f) {
this.inputObj = f;
String dispFontName = f.getFontName();
setFont(f.deriveFont(12F));
setText(dispFontName);
}
private void setInputFontListener() {
this.inputListener = new FontListener(this);
addActionListener(this.inputListener);
}
// internal class FontListener
private class FontListener extends AbstractAction {
ValueDisplayer parent;
JDialog popup;
FontListener (ValueDisplayer parent) {
super("ValueDisplayer FontListener");
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
if (enabled) {
FontChooser chooser = new FontChooser(((Font) inputObj).deriveFont(1F));
this.popup = new JDialog(parent.parent,
parent.title,
true);
JComboBox face = chooser.getFaceComboBox();
face.setSelectedItem(parent.inputObj);
JPanel butPanel = new JPanel(false);
// buttons - OK/Cancel
JButton okBut = new JButton("OK");
okBut.addActionListener(new OKListener(chooser));
JButton cancelBut = new JButton("Cancel");
cancelBut.addActionListener(new CancelListener());
butPanel.add(okBut);
butPanel.add(cancelBut);
Container content = popup.getContentPane();
content.setLayout(new BorderLayout());
content.add(chooser, BorderLayout.CENTER);
content.add(butPanel, BorderLayout.SOUTH);
popup.pack();
popup.show();
}
}
private class OKListener extends AbstractAction {
FontChooser chooser;
private OKListener (FontChooser chooser) {
this.chooser = chooser;
}
public void actionPerformed(ActionEvent e) {
setSelectedFont(chooser.getSelectedFont().deriveFont(12F));
//System.out.println("Set selected font to " + inputObj);
fireItemSelected();
popup.dispose();
}
}
private class CancelListener extends AbstractAction {
private CancelListener() {};
public void actionPerformed(ActionEvent e) {
popup.dispose();
}
}
}
private static ValueDisplayer getDisplayForIcons(JDialog parent,
String title,
Object startObj,
byte type) {
ValueDisplayer v = new ValueDisplayer(parent, title, type);
// has to be done this way because of static call
v.setInputIconListener(title, title, startObj, parent, type);
return v;
}
private void setInputIconListener(String title, String objectName,
Object startObject,
JDialog parentDialog, byte type) {
// set up button to display icon only
this.setContentAreaFilled(false);
// get icons - cannot be done from a static context
ImageIcon[] icons = null;
HashMap iToS = null;
HashMap sToI = null;
switch (type) {
case ARROW:
icons = MiscDialog.getArrowIcons();
iToS = MiscDialog.getArrowToStringHashMap(25);
sToI = MiscDialog.getStringToArrowHashMap(25);
break;
case NODESHAPE:
icons = MiscDialog.getShapeIcons();
iToS = MiscDialog.getShapeByteToStringHashMap();
sToI = MiscDialog.getStringToShapeByteHashMap();
break;
case LINETYPE:
icons = MiscDialog.getLineTypeIcons();
iToS = MiscDialog.getLineTypeToStringHashMap();
sToI = MiscDialog.getStringToLineTypeHashMap();
break;
}
ImageIcon currentIcon;
if (startObject == null) {
currentIcon = icons[0];
}
else {
// find the right icon
String ltName = (String)iToS.get(startObject);
int iconIndex = 0;
for ( ; icons[iconIndex].getDescription() != ltName; iconIndex++) {
}
- if (iconIndex > icons.length) { // didn't find the icon
+ currentIcon = icons[iconIndex];
+ if (iconIndex == icons.length) { // didn't find the icon
System.err.println("Icon for object " + startObject + " not found!");
currentIcon = icons[0];
}
- else {
- currentIcon = icons[iconIndex];
- }
}
// set currentIcon
this.setIcon(currentIcon);
this.inputObj = sToI.get(currentIcon.getDescription());
this.inputListener = new IconListener(title, objectName, icons, sToI,
currentIcon, parentDialog, this);
addActionListener(this.inputListener);
}
// internal class IconListener. Calls PopupIconChooser to get an icon from
// the user.
private class IconListener extends AbstractAction {
private PopupIconChooser chooser;
private ValueDisplayer parent;
private HashMap sToI; // map from the image icon description to type
IconListener(String title, String objectName, ImageIcon[] icons,
HashMap sToI, ImageIcon startIconObject, JDialog parentDialog,
ValueDisplayer parent) {
super("ValueDisplayer IconListener");
this.chooser = new PopupIconChooser(title,
objectName,
icons,
startIconObject,
parentDialog);
this.parent = parent;
this.sToI = sToI;
}
public void actionPerformed(ActionEvent e) {
if (enabled) {
ImageIcon icon = chooser.showDialog();
if (icon != null) {
// set the new icon to be displayed
parent.setIcon(icon);
// convert from ImageIcon description to expected type
// (see MiscDialog)
parent.inputObj = sToI.get(icon.getDescription());
parent.fireItemSelected();
}
}
}
}
private void addStringListener(String prompt, byte type) {
this.inputListener = new StringListener(prompt, type);
addActionListener(this.inputListener);
}
private static ValueDisplayer getDisplayForString(JDialog parent,
String title,
String init) {
ValueDisplayer v = new ValueDisplayer(parent, init, title, STRING);
v.addStringListener("Input a string:", STRING);
return v;
}
private static ValueDisplayer getDisplayForDouble(JDialog parent,
String title,
double init) {
ValueDisplayer v = new ValueDisplayer(parent, formatter.format(init), title,
DOUBLE);
v.addStringListener("Input a double:", DOUBLE);
return v;
}
private static ValueDisplayer getDisplayForInt(JDialog parent,
String title,
int init) {
ValueDisplayer v = new ValueDisplayer(parent, Integer.toString(init),
title, INT);
v.addStringListener("Input an integer:", INT);
return v;
}
// StringListener for String, Double, Int types
private class StringListener extends AbstractAction {
private byte type;
private String prompt;
StringListener (String prompt, byte type) {
super("ValueDisplayer StringListener");
this.prompt = prompt;
this.type = type;
}
public void actionPerformed (ActionEvent e) {
if (enabled) {
// keep prompting for input until a valid input is received
input:
while (true) {
String ret = (String) JOptionPane.showInputDialog(parent, prompt, title, JOptionPane.QUESTION_MESSAGE, null, null, inputObj);
if (ret == null) {
return;
}
else {
switch (type) {
case DOUBLE:
try {
inputObj = new Double(Double.parseDouble(ret));
break input;
}
catch (NumberFormatException exc) {
showErrorDialog("That is not a valid double");
continue input;
}
case INT:
try {
inputObj = new Integer(Integer.parseInt(ret));
break input;
}
catch (NumberFormatException exc) {
showErrorDialog("That is not a valid integer");
continue input;
}
default: // simple string assignment
inputObj = ret;
break input;
}
}
}
setText(inputObj.toString());
fireItemSelected();
}
}
}
private void showErrorDialog(String errorMsg) {
JOptionPane.showMessageDialog(parent, errorMsg, "Bad Input",
JOptionPane.ERROR_MESSAGE);
}
/**
* Get a blank or default display/input pair for a given type of input.
*
* @param parent
* The parent dialog for the returned ValueDisplayer
* @param title
* Title to display for input dialog
* @param type
* Type of input, one of {@link #COLOR}, {@link #LINETYPE},
* {@link #NODESHAPE}, {@link #ARROW}, {@link #STRING},
* {@link #DOUBLE}, {@link #INT}, {@link FONT}
*
* @return ValueDisplayer initialized for given input
* @throws ClassCastException if you didn't pass in a known type
*/
public static ValueDisplayer getBlankDisplayFor(JDialog parent, String title,
byte type) {
switch (type) {
case COLOR:
return getDisplayForColor(parent, title, null);
case LINETYPE:
return getDisplayForIcons(parent, title, null, LINETYPE);
case NODESHAPE:
return getDisplayForIcons(parent, title,
new Byte(ShapeNodeRealizer.ELLIPSE),
NODESHAPE);
case ARROW:
return getDisplayForIcons(parent, title, Arrow.STANDARD, ARROW);
case STRING:
return getDisplayForString(parent, title, null);
case DOUBLE:
return getDisplayForDouble(parent, title, 0);
case INT:
return getDisplayForInt(parent, title, 0);
case FONT:
return getDisplayForFont(parent, title, new Font(null, Font.PLAIN, 1));
default:
throw new ClassCastException("ValueDisplayer didn't understand type flag " + type);
}
}
/**
* Get a display/input pair initialized to a given type of input. If sending
* fonts, must send fonts as gotten from {@link GraphicsEnvrionment#getAllFonts}
*
* @param parent
* The parent dialog for the returned ValueDisplayer
* @param o
* Object to represent. Should be a {@link java.awt.Color Color},
* {@link y.view.LineType LineType}, node shape (byte), arrow,
* string, or number
* @return ValueDisplayer displaying the given object and accepting
* input for given object
* @throws ClassCastException if you didn't pass in a known type
*/
public static ValueDisplayer getDisplayFor(JDialog parent, String title,
Object o) throws ClassCastException {
if (o instanceof Color) {
return getDisplayForColor(parent, title, (Color)o );
} else if (o instanceof LineType) {
return getDisplayForIcons(parent, title, o, LINETYPE);
} else if (o instanceof Byte) {
return getDisplayForIcons(parent, title, o, NODESHAPE);
} else if (o instanceof Arrow) {
return getDisplayForIcons(parent, title, o, ARROW);
} else if (o instanceof String) {
return getDisplayForString(parent, title, (String)o );
} else if (o instanceof Number) {
if ( o instanceof Float || o instanceof Double ) {
return getDisplayForDouble(parent, title, ((Number)o).doubleValue() );
} else {
return getDisplayForInt(parent, title, ((Number)o).intValue() );
}
} else if (o instanceof Font) {
return getDisplayForFont(parent, title, (Font) o);
} else {//don't know what to do this this
throw new ClassCastException("ValueDisplayer doesn't know how to display type " + o.getClass().getName());
}
}
}
| false | true | private void setInputIconListener(String title, String objectName,
Object startObject,
JDialog parentDialog, byte type) {
// set up button to display icon only
this.setContentAreaFilled(false);
// get icons - cannot be done from a static context
ImageIcon[] icons = null;
HashMap iToS = null;
HashMap sToI = null;
switch (type) {
case ARROW:
icons = MiscDialog.getArrowIcons();
iToS = MiscDialog.getArrowToStringHashMap(25);
sToI = MiscDialog.getStringToArrowHashMap(25);
break;
case NODESHAPE:
icons = MiscDialog.getShapeIcons();
iToS = MiscDialog.getShapeByteToStringHashMap();
sToI = MiscDialog.getStringToShapeByteHashMap();
break;
case LINETYPE:
icons = MiscDialog.getLineTypeIcons();
iToS = MiscDialog.getLineTypeToStringHashMap();
sToI = MiscDialog.getStringToLineTypeHashMap();
break;
}
ImageIcon currentIcon;
if (startObject == null) {
currentIcon = icons[0];
}
else {
// find the right icon
String ltName = (String)iToS.get(startObject);
int iconIndex = 0;
for ( ; icons[iconIndex].getDescription() != ltName; iconIndex++) {
}
if (iconIndex > icons.length) { // didn't find the icon
System.err.println("Icon for object " + startObject + " not found!");
currentIcon = icons[0];
}
else {
currentIcon = icons[iconIndex];
}
}
// set currentIcon
this.setIcon(currentIcon);
this.inputObj = sToI.get(currentIcon.getDescription());
this.inputListener = new IconListener(title, objectName, icons, sToI,
currentIcon, parentDialog, this);
addActionListener(this.inputListener);
}
| private void setInputIconListener(String title, String objectName,
Object startObject,
JDialog parentDialog, byte type) {
// set up button to display icon only
this.setContentAreaFilled(false);
// get icons - cannot be done from a static context
ImageIcon[] icons = null;
HashMap iToS = null;
HashMap sToI = null;
switch (type) {
case ARROW:
icons = MiscDialog.getArrowIcons();
iToS = MiscDialog.getArrowToStringHashMap(25);
sToI = MiscDialog.getStringToArrowHashMap(25);
break;
case NODESHAPE:
icons = MiscDialog.getShapeIcons();
iToS = MiscDialog.getShapeByteToStringHashMap();
sToI = MiscDialog.getStringToShapeByteHashMap();
break;
case LINETYPE:
icons = MiscDialog.getLineTypeIcons();
iToS = MiscDialog.getLineTypeToStringHashMap();
sToI = MiscDialog.getStringToLineTypeHashMap();
break;
}
ImageIcon currentIcon;
if (startObject == null) {
currentIcon = icons[0];
}
else {
// find the right icon
String ltName = (String)iToS.get(startObject);
int iconIndex = 0;
for ( ; icons[iconIndex].getDescription() != ltName; iconIndex++) {
}
currentIcon = icons[iconIndex];
if (iconIndex == icons.length) { // didn't find the icon
System.err.println("Icon for object " + startObject + " not found!");
currentIcon = icons[0];
}
}
// set currentIcon
this.setIcon(currentIcon);
this.inputObj = sToI.get(currentIcon.getDescription());
this.inputListener = new IconListener(title, objectName, icons, sToI,
currentIcon, parentDialog, this);
addActionListener(this.inputListener);
}
|
diff --git a/src/main/java/de/cismet/cismap/commons/capabilities/AbstractVersionNegotiator.java b/src/main/java/de/cismet/cismap/commons/capabilities/AbstractVersionNegotiator.java
index 9c09d2da..fdf565e9 100644
--- a/src/main/java/de/cismet/cismap/commons/capabilities/AbstractVersionNegotiator.java
+++ b/src/main/java/de/cismet/cismap/commons/capabilities/AbstractVersionNegotiator.java
@@ -1,298 +1,299 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cismap.commons.capabilities;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import de.cismet.security.WebAccessManager;
import de.cismet.security.exceptions.AccessMethodIsNotSupportedException;
import de.cismet.security.exceptions.MissingArgumentException;
import de.cismet.security.exceptions.NoHandlerForURLException;
import de.cismet.security.exceptions.RequestFailedException;
/**
* DOCUMENT ME!
*
* @author therter
* @version $Revision$, $Date$
*/
public abstract class AbstractVersionNegotiator {
//~ Static fields/initializers ---------------------------------------------
private static Logger logger = Logger.getLogger(AbstractVersionNegotiator.class);
private static final String VERSION_STRING = "version"; // NOI18N
//~ Instance fields --------------------------------------------------------
// the constant SUPPORTED_VERSIONS contains all supported service versions. The array should
// be sorted and the first elements of the array should contain the oldest version.
protected String[] supportedVersions; // NOI18N
protected String currentVersion = null;
protected String serviceName;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new AbstractVersionNegotiator object.
*/
public AbstractVersionNegotiator() {
initVersion();
}
//~ Methods ----------------------------------------------------------------
/**
* This m,ethod must be overidden by the sub classes and should initialize the constant SUPPORTED_VERSIONS.
*/
protected abstract void initVersion();
/**
* Invokes the GetCapabilities operation of the server with an older version string.
*
* @param link DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws MalformedURLException DOCUMENT ME!
* @throws MissingArgumentException DOCUMENT ME!
* @throws AccessMethodIsNotSupportedException DOCUMENT ME!
* @throws RequestFailedException DOCUMENT ME!
* @throws NoHandlerForURLException DOCUMENT ME!
* @throws Exception DOCUMENT ME!
*/
protected String getOlderCapabilitiesDocument(String link) throws MalformedURLException,
MissingArgumentException,
AccessMethodIsNotSupportedException,
RequestFailedException,
NoHandlerForURLException,
Exception {
final StringBuilder document;
boolean olderVersionFound = false;
if (logger.isDebugEnabled()) {
logger.debug("try to use an older version number"); // NOI18N
}
for (int i = 1; i < supportedVersions.length; ++i) {
if (supportedVersions[i].equals(currentVersion)) {
currentVersion = supportedVersions[i - 1];
olderVersionFound = true;
}
}
if (olderVersionFound) {
if (logger.isDebugEnabled()) {
logger.debug("Older version found " + currentVersion); // NOI18N
}
if (link.toLowerCase().indexOf("?") != -1) { // NOI18N
link = link.substring(0, link.toLowerCase().indexOf("?")); // NOI18N
}
link += "?SERVICE=" + serviceName + "&REQUEST=GetCapabilities&VERSION=" + currentVersion; // NOI18N
document = readStringFromlink(link);
return document.toString();
}
return null;
}
/**
* DOCUMENT ME!
*
* @param link DOCUMENT ME!
*
* @return the capabilities document of the service with the given link. If the link already contains a version,
* then this version will be used as start version for the version negotation. Otherwise, the most recent
* version, that is supported by the client will be used as start version.
*
* @throws MalformedURLException DOCUMENT ME!
* @throws MissingArgumentException DOCUMENT ME!
* @throws AccessMethodIsNotSupportedException DOCUMENT ME!
* @throws RequestFailedException DOCUMENT ME!
* @throws NoHandlerForURLException DOCUMENT ME!
* @throws Exception DOCUMENT ME!
*/
protected String getCapabilitiesDocument(String link) throws MalformedURLException,
MissingArgumentException,
AccessMethodIsNotSupportedException,
RequestFailedException,
NoHandlerForURLException,
Exception {
String startVersion = getVersionFromLink(link);
final StringBuilder document;
if (startVersion == null) {
if (logger.isDebugEnabled()) {
logger.debug("No version string found in the link: " + link); // NOI18N
}
// set the version to the latest one
startVersion = supportedVersions[supportedVersions.length - 1];
}
if (link.indexOf("?") != -1) { // NOI18N
// some GetCapabilities links contains special parameter, which should not cut off
if (link.toLowerCase().indexOf("version") == -1) { // NOI18N
link += "&VERSION=" + startVersion;
} else {
String linkTmp = link.substring(0, link.toLowerCase().indexOf("version") + "version".length());
linkTmp += "=" + startVersion;
- int indexAfterVersionString;
- for (indexAfterVersionString = 0; indexAfterVersionString < link.length(); ++indexAfterVersionString) {
+ int indexAfterVersionString = link.toLowerCase().indexOf("version");
+ for (; indexAfterVersionString < link.length(); ++indexAfterVersionString) {
if (link.charAt(indexAfterVersionString) == '&') {
break;
}
}
if (indexAfterVersionString < link.length()) {
linkTmp += link.substring(indexAfterVersionString);
}
link = linkTmp;
}
} else {
link += "?SERVICE=" + serviceName + "&REQUEST=GetCapabilities&VERSION=" + startVersion; // NOI18N
}
if (logger.isDebugEnabled()) {
+ logger.debug("send request = " + link); // NOI18N
logger.debug("start version = " + startVersion); // NOI18N
}
document = readStringFromlink(link);
currentVersion = getDocumentVersion(document);
if (currentVersion == null) {
logger.error("No version string found in the GetCapabilities document from location " + link); // NOI18N
// try to parse the document
return document.toString();
}
if (!isVersionSupported(currentVersion)) {
logger.error("The client does not support the version of the received Getcapabilities document." // NOI18N
+ "\nLink: " + link + "\nresponse version " + currentVersion); // NOI18N
} else {
if (logger.isDebugEnabled()) {
logger.debug("Version negotation successfully. \nLink: " // NOI18N
+ link + "\nresponse version " + currentVersion); // NOI18N
}
}
return document.toString();
}
/**
* DOCUMENT ME!
*
* @param link DOCUMENT ME!
*
* @return the version string of the given link or null, if the given link does not contain any version string
*/
protected String getVersionFromLink(final String link) {
String version = null;
if (link.toLowerCase().indexOf(VERSION_STRING) != -1) {
version = link.substring(link.toLowerCase().indexOf(VERSION_STRING) + VERSION_STRING.length() + 1);
if (version.indexOf("&") != -1) { // NOI18N
version = version.substring(0, version.indexOf("&")); // NOI18N
}
}
return version;
}
/**
* DOCUMENT ME!
*
* @param version the version that should be checked
*
* @return true, if the given version is contained in the array constant <code>SUPPORTED_VERSIONS</code>
*/
private boolean isVersionSupported(final String version) {
for (int i = 0; i < supportedVersions.length; ++i) {
if (supportedVersions[i].equals(version)) {
return true;
}
}
return false;
}
/**
* DOCUMENT ME!
*
* @param document the GetCapabilities document
*
* @return the version of the given document or null, if no version string found
*/
protected String getDocumentVersion(final StringBuilder document) {
String documentVersion = null;
int startIndexOfVersion = -1;
if (document.indexOf("?>") != -1) { // NOI18N
startIndexOfVersion = document.indexOf(VERSION_STRING + "=\"", document.indexOf("?>")) // NOI18N
+ VERSION_STRING.length() + 2; // NOI18N
} else {
startIndexOfVersion = document.indexOf(VERSION_STRING + "=\"") + VERSION_STRING.length() + 2; // NOI18N
}
if (startIndexOfVersion != (VERSION_STRING.length() + 1)) {
// version string in document found
final int endIndexOfVersion = document.indexOf("\"", startIndexOfVersion); // NOI18N
documentVersion = document.substring(startIndexOfVersion, endIndexOfVersion);
}
if (logger.isDebugEnabled()) {
logger.debug("version of received GetCapabilities document: " + documentVersion); // NOI18N
}
return documentVersion;
}
/**
* read the document from the given link.
*
* @param url DOCUMENT ME!
*
* @return a StringBuilder that contains the content of the given url
*
* @throws MalformedURLException DOCUMENT ME!
* @throws MissingArgumentException DOCUMENT ME!
* @throws AccessMethodIsNotSupportedException DOCUMENT ME!
* @throws RequestFailedException DOCUMENT ME!
* @throws NoHandlerForURLException DOCUMENT ME!
* @throws Exception DOCUMENT ME!
*/
private StringBuilder readStringFromlink(final String url) throws MalformedURLException,
MissingArgumentException,
AccessMethodIsNotSupportedException,
RequestFailedException,
NoHandlerForURLException,
Exception {
final StringBuilder sb = new StringBuilder(""); // NOI18N
if (logger.isDebugEnabled()) {
logger.debug("send Getcapabilities request to the service: " + url); // NOI18N
}
final URL getCapURL = new URL(url);
final InputStream is = WebAccessManager.getInstance().doRequest(getCapURL);
final BufferedReader br = new BufferedReader(new InputStreamReader(is));
String buffer = br.readLine();
while (buffer != null) {
sb.append(buffer + "\n"); // NOI18N
buffer = br.readLine();
}
is.close();
return sb;
}
}
| false | true | protected String getCapabilitiesDocument(String link) throws MalformedURLException,
MissingArgumentException,
AccessMethodIsNotSupportedException,
RequestFailedException,
NoHandlerForURLException,
Exception {
String startVersion = getVersionFromLink(link);
final StringBuilder document;
if (startVersion == null) {
if (logger.isDebugEnabled()) {
logger.debug("No version string found in the link: " + link); // NOI18N
}
// set the version to the latest one
startVersion = supportedVersions[supportedVersions.length - 1];
}
if (link.indexOf("?") != -1) { // NOI18N
// some GetCapabilities links contains special parameter, which should not cut off
if (link.toLowerCase().indexOf("version") == -1) { // NOI18N
link += "&VERSION=" + startVersion;
} else {
String linkTmp = link.substring(0, link.toLowerCase().indexOf("version") + "version".length());
linkTmp += "=" + startVersion;
int indexAfterVersionString;
for (indexAfterVersionString = 0; indexAfterVersionString < link.length(); ++indexAfterVersionString) {
if (link.charAt(indexAfterVersionString) == '&') {
break;
}
}
if (indexAfterVersionString < link.length()) {
linkTmp += link.substring(indexAfterVersionString);
}
link = linkTmp;
}
} else {
link += "?SERVICE=" + serviceName + "&REQUEST=GetCapabilities&VERSION=" + startVersion; // NOI18N
}
if (logger.isDebugEnabled()) {
logger.debug("start version = " + startVersion); // NOI18N
}
document = readStringFromlink(link);
currentVersion = getDocumentVersion(document);
if (currentVersion == null) {
logger.error("No version string found in the GetCapabilities document from location " + link); // NOI18N
// try to parse the document
return document.toString();
}
if (!isVersionSupported(currentVersion)) {
logger.error("The client does not support the version of the received Getcapabilities document." // NOI18N
+ "\nLink: " + link + "\nresponse version " + currentVersion); // NOI18N
} else {
if (logger.isDebugEnabled()) {
logger.debug("Version negotation successfully. \nLink: " // NOI18N
+ link + "\nresponse version " + currentVersion); // NOI18N
}
}
return document.toString();
}
| protected String getCapabilitiesDocument(String link) throws MalformedURLException,
MissingArgumentException,
AccessMethodIsNotSupportedException,
RequestFailedException,
NoHandlerForURLException,
Exception {
String startVersion = getVersionFromLink(link);
final StringBuilder document;
if (startVersion == null) {
if (logger.isDebugEnabled()) {
logger.debug("No version string found in the link: " + link); // NOI18N
}
// set the version to the latest one
startVersion = supportedVersions[supportedVersions.length - 1];
}
if (link.indexOf("?") != -1) { // NOI18N
// some GetCapabilities links contains special parameter, which should not cut off
if (link.toLowerCase().indexOf("version") == -1) { // NOI18N
link += "&VERSION=" + startVersion;
} else {
String linkTmp = link.substring(0, link.toLowerCase().indexOf("version") + "version".length());
linkTmp += "=" + startVersion;
int indexAfterVersionString = link.toLowerCase().indexOf("version");
for (; indexAfterVersionString < link.length(); ++indexAfterVersionString) {
if (link.charAt(indexAfterVersionString) == '&') {
break;
}
}
if (indexAfterVersionString < link.length()) {
linkTmp += link.substring(indexAfterVersionString);
}
link = linkTmp;
}
} else {
link += "?SERVICE=" + serviceName + "&REQUEST=GetCapabilities&VERSION=" + startVersion; // NOI18N
}
if (logger.isDebugEnabled()) {
logger.debug("send request = " + link); // NOI18N
logger.debug("start version = " + startVersion); // NOI18N
}
document = readStringFromlink(link);
currentVersion = getDocumentVersion(document);
if (currentVersion == null) {
logger.error("No version string found in the GetCapabilities document from location " + link); // NOI18N
// try to parse the document
return document.toString();
}
if (!isVersionSupported(currentVersion)) {
logger.error("The client does not support the version of the received Getcapabilities document." // NOI18N
+ "\nLink: " + link + "\nresponse version " + currentVersion); // NOI18N
} else {
if (logger.isDebugEnabled()) {
logger.debug("Version negotation successfully. \nLink: " // NOI18N
+ link + "\nresponse version " + currentVersion); // NOI18N
}
}
return document.toString();
}
|
diff --git a/src/generator/com/operationaldynamics/codegen/ProxiedArrayThing.java b/src/generator/com/operationaldynamics/codegen/ProxiedArrayThing.java
index 984de9e2..6372c2e3 100644
--- a/src/generator/com/operationaldynamics/codegen/ProxiedArrayThing.java
+++ b/src/generator/com/operationaldynamics/codegen/ProxiedArrayThing.java
@@ -1,90 +1,89 @@
/*
* ProxiedArrayThing.java
*
* Copyright (c) 2007 Operational Dynamics Consulting Pty Ltd
*
* The code in this file, and the library it is a part of, are made available
* to you by the authors under the terms of the "GNU General Public Licence,
* version 2" See the LICENCE file for the terms governing usage and
* redistribution.
*/
package com.operationaldynamics.codegen;
import com.operationaldynamics.driver.DefsFile;
/**
* Represent arrays of Proxies, or a Proxy used as an out parameter, that
* needs to be wrapped as an array in Java.
*
* @author Vreixo Formoso
*/
public class ProxiedArrayThing extends ArrayThing
{
public ProxiedArrayThing(String gType, Thing type) {
super(gType, type);
}
protected ProxiedArrayThing() {}
String translationToJava(String name, DefsFile data) {
String newArray = "new " + type.javaTypeInContext(data) + "[" + name + ".length]";
if (type instanceof ObjectThing) {
return "(" + javaTypeInContext(data) + ") objectArrayFor(" + name + ", " + newArray + ")";
} else {
return "(" + javaTypeInContext(data) + ") boxedArrayFor(" + type.javaTypeInContext(data)
+ ".class, " + name + ", " + newArray + ")";
}
}
String translationToNative(String name) {
return "_" + name;
}
String jniConversionDecode(String name) {
return "bindings_java_convert_jarray_to_gpointer(env, _" + name + ")";
}
String jniConversionCleanup(String name) {
return "bindings_java_convert_gpointer_to_jarray(env, (gpointer*)" + name + ", _" + name + ")";
}
/*
* FIXME we would need a way to figure out the size of the array, and then
* create a new java array with NewXXXArray and copy there the elements.
* This is a clear candidate for code override, as it seems to be very
* hard to manage in an automatic way.
*/
String jniReturnEncode(String name) {
System.out.println("Warning: Not supported return of GObject/GBoxed array.");
return "NULL";
}
String jniReturnErrorValue() {
return "NULL";
}
String extraTranslationToJava(String name, DefsFile data) {
if (type instanceof InterfaceThing) {
return "fillObjectArray((Object[])" + name + ", _" + name + ")";
- }
- if (type instanceof ObjectThing) {
+ } else if (type instanceof ObjectThing) {
return "fillObjectArray(" + name + ", _" + name + ")";
} else {
return "fillBoxedArray(" + type.javaTypeInContext(data) + ".class, " + name + ", _" + name
+ ")";
}
}
String extraTranslationToNative(String name) {
if (type instanceof InterfaceThing) {
return "pointersOf((Object[])" + name + ")";
} else {
return "pointersOf(" + name + ")";
}
}
boolean needExtraTranslation() {
return true;
}
}
| true | true | String extraTranslationToJava(String name, DefsFile data) {
if (type instanceof InterfaceThing) {
return "fillObjectArray((Object[])" + name + ", _" + name + ")";
}
if (type instanceof ObjectThing) {
return "fillObjectArray(" + name + ", _" + name + ")";
} else {
return "fillBoxedArray(" + type.javaTypeInContext(data) + ".class, " + name + ", _" + name
+ ")";
}
}
| String extraTranslationToJava(String name, DefsFile data) {
if (type instanceof InterfaceThing) {
return "fillObjectArray((Object[])" + name + ", _" + name + ")";
} else if (type instanceof ObjectThing) {
return "fillObjectArray(" + name + ", _" + name + ")";
} else {
return "fillBoxedArray(" + type.javaTypeInContext(data) + ".class, " + name + ", _" + name
+ ")";
}
}
|
diff --git a/src/esmska/Main.java b/src/esmska/Main.java
index db1d95d5..9a47b7c6 100644
--- a/src/esmska/Main.java
+++ b/src/esmska/Main.java
@@ -1,333 +1,334 @@
package esmska;
import esmska.gui.ThemeManager;
import esmska.update.LegacyUpdater;
import java.beans.IntrospectionException;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import esmska.data.Config;
import esmska.data.CountryPrefix;
import esmska.gui.MainFrame;
import esmska.gui.ExceptionDialog;
import esmska.gui.InitWizardDialog;
import esmska.persistence.PersistenceManager;
import esmska.transfer.ProxyManager;
import esmska.utils.L10N;
import esmska.utils.LogSupport;
import esmska.utils.RuntimeUtils;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.apache.commons.lang.ArrayUtils;
/** Starter class for the whole program
*
* @author ripper
*/
public class Main {
private static final Logger logger = Logger.getLogger(Main.class.getName());
private static final ResourceBundle l10n = L10N.l10nBundle;
private static String configPath; //path to config files
/** Program starter method
* @param args the command line arguments
*/
public static void main(String[] args) {
//initialize logging
LogSupport.init();
//store records for pushing it to logfile later
LogSupport.storeRecords(true);
//handle uncaught exceptions
Thread.setDefaultUncaughtExceptionHandler(ExceptionDialog.getExceptionHandler());
//workaround for Java 6 to process uncaught exceptions from modal dialogs
//read more at http://code.google.com/p/esmska/issues/detail?id=256
System.setProperty("sun.awt.exception.handler",
ExceptionDialog.AwtHandler.class.getName());
//detect JVM and warn if not not supported
if (!RuntimeUtils.isSupportedJava()) {
logger.warning("You are probably running the program on an unsupported "
+ "Java version! Program might not work correctly with it! "
+ "The tested Java versions are: Sun Java 6, OpenJDK 6, Apple Java 6.");
}
// halt for Webstart on OpenJDK, it currently doesn't work
+ // see http://code.google.com/p/esmska/issues/detail?id=335
// see http://code.google.com/p/esmska/issues/detail?id=357
// see http://code.google.com/p/esmska/issues/detail?id=358
if (RuntimeUtils.isOpenJDK() && RuntimeUtils.isRunAsWebStart()) {
logger.severe("Running as Java WebStart on OpenJDK, that's currently unsupported! Quitting.");
JOptionPane.showMessageDialog(null, l10n.getString("Main.brokenWebstart"), "Esmska", JOptionPane.ERROR_MESSAGE);
System.exit(99);
}
//parse commandline arguments
CommandLineParser clp = new CommandLineParser();
if (! clp.parseArgs(args)) {
System.exit(1);
}
//log some basic stuff for debugging
logger.fine("Esmska " + Config.getLatestVersion() + " starting...");
logger.finer("System info: " + RuntimeUtils.getSystemInfo());
//portable mode
configPath = clp.getConfigPath();
if (clp.isPortable() && configPath == null) {
logger.fine("Entering portable mode");
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not set system Look and Feel", ex);
}
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setApproveButtonText(l10n.getString("Select"));
chooser.setDialogTitle(l10n.getString("Main.choose_config_files"));
chooser.setFileHidingEnabled(false);
chooser.setMultiSelectionEnabled(false);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
configPath = chooser.getSelectedFile().getPath();
logger.config("New config path: " + configPath);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display file chooser for portable mode", e);
}
}
//get persistence manager
PersistenceManager pm = null;
try {
if (configPath != null) {
PersistenceManager.setCustomDirs(configPath, configPath);
}
PersistenceManager.instantiate();
pm = Context.persistenceManager;
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not create program dir or read config files", ex);
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null,
new JLabel(MessageFormat.format(l10n.getString("Main.cant_read_config"),
PersistenceManager.getConfigDir().getAbsolutePath(),
PersistenceManager.getDataDir().getAbsolutePath())),
null, JOptionPane.ERROR_MESSAGE);
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
} finally {
//if it is not possible to access config dir, we don't want to
//run anymore
System.exit(5);
}
}
//backup files
try {
pm.backupConfigFiles();
} catch (IOException ex) {
logger.log(Level.SEVERE, "Could not back up configuration", ex);
}
//initialize file logging
File logFile = pm.getLogFile();
try {
LogSupport.initFileHandler(logFile);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Could not start logging into " + logFile.getAbsolutePath(), ex);
} finally {
//no need to store records anymore
LogSupport.storeRecords(false);
}
//load user files
try {
pm.loadConfig();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load config file", ex);
}
try {
pm.loadGateways();
} catch (IntrospectionException ex) { //it seems there is not JavaScript support
logger.log(Level.SEVERE, "Current JRE doesn't support JavaScript execution", ex);
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, l10n.getString("Main.no_javascript"),
null, JOptionPane.ERROR_MESSAGE);
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
}
System.exit(2);
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load gateways", ex);
}
try {
pm.loadContacts();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load contacts file", ex);
}
try {
pm.loadQueue();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load queue file", ex);
}
try {
pm.loadHistory();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load history file", ex);
}
try {
pm.loadKeyring();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load keyring file", ex);
}
try {
pm.loadGatewayProperties();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load gateway properties file", ex);
}
//initialize logging if set from Config
if (Config.getInstance().isDebugMode()) {
//set "full" logging, but don't log to console
LogSupport.enableHttpClientLogging();
LogSupport.getEsmskaLogger().setLevel(Level.ALL);
}
//warn if other program instance is already running
if (!pm.isFirstInstance()) {
logger.warning("Some other instance of the program is already running");
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
String runOption = l10n.getString("Main.run_anyway");
String quitOption = l10n.getString("Quit");
String[] options = new String[]{runOption, quitOption};
options = RuntimeUtils.sortDialogOptions(options);
int result = JOptionPane.showOptionDialog(null, l10n.getString("Main.already_running"),
null, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, quitOption);
if (result != ArrayUtils.indexOf(options, runOption)) {
System.exit(0);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
}
}
//warn if configuration files are newer than program version (user has
//executed an older program version)
Config config = Config.getInstance();
final String dataVersion = config.getVersion();
final String programVersion = Config.getLatestVersion();
if (Config.compareProgramVersions(dataVersion, programVersion) > 0) {
logger.warning("Configuration files are newer (" + dataVersion +
") then current program version (" + programVersion + ")! " +
"Data corruption may occur!");
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
String runOption = l10n.getString("Main.run_anyway");
String quitOption = l10n.getString("Quit");
String[] options = new String[]{runOption, quitOption};
options = RuntimeUtils.sortDialogOptions(options);
int result = JOptionPane.showOptionDialog(null,
new JLabel(MessageFormat.format(l10n.getString("Main.configsNewer"),
dataVersion, programVersion)),
null, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, quitOption);
if (result != ArrayUtils.indexOf(options, runOption)) {
System.exit(0);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
}
}
//do some initialization if this is the first run
if (config.isFirstRun()) {
logger.fine("First run, doing initialization...");
//set country prefix from locale
config.setCountryPrefix(
CountryPrefix.getCountryPrefix(Locale.getDefault().getCountry()));
//set suggested LaF for this platform
config.setLookAndFeel(ThemeManager.suggestBestLAF());
//show first run wizard
InitWizardDialog dialog = new InitWizardDialog(null, true);
dialog.setVisible(true);
}
//update from older versions
if (!config.isFirstRun()) {
LegacyUpdater.update();
}
//set L&F
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
ThemeManager.setLaF();
} catch (Throwable ex) {
logger.log(Level.WARNING, "Could not set Look and Feel", ex);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Setting LaF interrupted", e);
}
//set proxy
if (config.isUseProxy()) {
ProxyManager.setProxy(config.getHttpProxy(),
config.getHttpsProxy(), config.getSocksProxy());
}
//do some changes for unstable version
if (!Config.isStableVersion()) {
config.setAnnounceUnstableUpdates(true);
}
//start main frame
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
MainFrame.instantiate();
Context.mainFrame.startAndShow();
}
});
}
}
| true | true | public static void main(String[] args) {
//initialize logging
LogSupport.init();
//store records for pushing it to logfile later
LogSupport.storeRecords(true);
//handle uncaught exceptions
Thread.setDefaultUncaughtExceptionHandler(ExceptionDialog.getExceptionHandler());
//workaround for Java 6 to process uncaught exceptions from modal dialogs
//read more at http://code.google.com/p/esmska/issues/detail?id=256
System.setProperty("sun.awt.exception.handler",
ExceptionDialog.AwtHandler.class.getName());
//detect JVM and warn if not not supported
if (!RuntimeUtils.isSupportedJava()) {
logger.warning("You are probably running the program on an unsupported "
+ "Java version! Program might not work correctly with it! "
+ "The tested Java versions are: Sun Java 6, OpenJDK 6, Apple Java 6.");
}
// halt for Webstart on OpenJDK, it currently doesn't work
// see http://code.google.com/p/esmska/issues/detail?id=357
// see http://code.google.com/p/esmska/issues/detail?id=358
if (RuntimeUtils.isOpenJDK() && RuntimeUtils.isRunAsWebStart()) {
logger.severe("Running as Java WebStart on OpenJDK, that's currently unsupported! Quitting.");
JOptionPane.showMessageDialog(null, l10n.getString("Main.brokenWebstart"), "Esmska", JOptionPane.ERROR_MESSAGE);
System.exit(99);
}
//parse commandline arguments
CommandLineParser clp = new CommandLineParser();
if (! clp.parseArgs(args)) {
System.exit(1);
}
//log some basic stuff for debugging
logger.fine("Esmska " + Config.getLatestVersion() + " starting...");
logger.finer("System info: " + RuntimeUtils.getSystemInfo());
//portable mode
configPath = clp.getConfigPath();
if (clp.isPortable() && configPath == null) {
logger.fine("Entering portable mode");
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not set system Look and Feel", ex);
}
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setApproveButtonText(l10n.getString("Select"));
chooser.setDialogTitle(l10n.getString("Main.choose_config_files"));
chooser.setFileHidingEnabled(false);
chooser.setMultiSelectionEnabled(false);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
configPath = chooser.getSelectedFile().getPath();
logger.config("New config path: " + configPath);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display file chooser for portable mode", e);
}
}
//get persistence manager
PersistenceManager pm = null;
try {
if (configPath != null) {
PersistenceManager.setCustomDirs(configPath, configPath);
}
PersistenceManager.instantiate();
pm = Context.persistenceManager;
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not create program dir or read config files", ex);
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null,
new JLabel(MessageFormat.format(l10n.getString("Main.cant_read_config"),
PersistenceManager.getConfigDir().getAbsolutePath(),
PersistenceManager.getDataDir().getAbsolutePath())),
null, JOptionPane.ERROR_MESSAGE);
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
} finally {
//if it is not possible to access config dir, we don't want to
//run anymore
System.exit(5);
}
}
//backup files
try {
pm.backupConfigFiles();
} catch (IOException ex) {
logger.log(Level.SEVERE, "Could not back up configuration", ex);
}
//initialize file logging
File logFile = pm.getLogFile();
try {
LogSupport.initFileHandler(logFile);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Could not start logging into " + logFile.getAbsolutePath(), ex);
} finally {
//no need to store records anymore
LogSupport.storeRecords(false);
}
//load user files
try {
pm.loadConfig();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load config file", ex);
}
try {
pm.loadGateways();
} catch (IntrospectionException ex) { //it seems there is not JavaScript support
logger.log(Level.SEVERE, "Current JRE doesn't support JavaScript execution", ex);
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, l10n.getString("Main.no_javascript"),
null, JOptionPane.ERROR_MESSAGE);
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
}
System.exit(2);
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load gateways", ex);
}
try {
pm.loadContacts();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load contacts file", ex);
}
try {
pm.loadQueue();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load queue file", ex);
}
try {
pm.loadHistory();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load history file", ex);
}
try {
pm.loadKeyring();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load keyring file", ex);
}
try {
pm.loadGatewayProperties();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load gateway properties file", ex);
}
//initialize logging if set from Config
if (Config.getInstance().isDebugMode()) {
//set "full" logging, but don't log to console
LogSupport.enableHttpClientLogging();
LogSupport.getEsmskaLogger().setLevel(Level.ALL);
}
//warn if other program instance is already running
if (!pm.isFirstInstance()) {
logger.warning("Some other instance of the program is already running");
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
String runOption = l10n.getString("Main.run_anyway");
String quitOption = l10n.getString("Quit");
String[] options = new String[]{runOption, quitOption};
options = RuntimeUtils.sortDialogOptions(options);
int result = JOptionPane.showOptionDialog(null, l10n.getString("Main.already_running"),
null, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, quitOption);
if (result != ArrayUtils.indexOf(options, runOption)) {
System.exit(0);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
}
}
//warn if configuration files are newer than program version (user has
//executed an older program version)
Config config = Config.getInstance();
final String dataVersion = config.getVersion();
final String programVersion = Config.getLatestVersion();
if (Config.compareProgramVersions(dataVersion, programVersion) > 0) {
logger.warning("Configuration files are newer (" + dataVersion +
") then current program version (" + programVersion + ")! " +
"Data corruption may occur!");
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
String runOption = l10n.getString("Main.run_anyway");
String quitOption = l10n.getString("Quit");
String[] options = new String[]{runOption, quitOption};
options = RuntimeUtils.sortDialogOptions(options);
int result = JOptionPane.showOptionDialog(null,
new JLabel(MessageFormat.format(l10n.getString("Main.configsNewer"),
dataVersion, programVersion)),
null, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, quitOption);
if (result != ArrayUtils.indexOf(options, runOption)) {
System.exit(0);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
}
}
//do some initialization if this is the first run
if (config.isFirstRun()) {
logger.fine("First run, doing initialization...");
//set country prefix from locale
config.setCountryPrefix(
CountryPrefix.getCountryPrefix(Locale.getDefault().getCountry()));
//set suggested LaF for this platform
config.setLookAndFeel(ThemeManager.suggestBestLAF());
//show first run wizard
InitWizardDialog dialog = new InitWizardDialog(null, true);
dialog.setVisible(true);
}
//update from older versions
if (!config.isFirstRun()) {
LegacyUpdater.update();
}
//set L&F
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
ThemeManager.setLaF();
} catch (Throwable ex) {
logger.log(Level.WARNING, "Could not set Look and Feel", ex);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Setting LaF interrupted", e);
}
//set proxy
if (config.isUseProxy()) {
ProxyManager.setProxy(config.getHttpProxy(),
config.getHttpsProxy(), config.getSocksProxy());
}
//do some changes for unstable version
if (!Config.isStableVersion()) {
config.setAnnounceUnstableUpdates(true);
}
//start main frame
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
MainFrame.instantiate();
Context.mainFrame.startAndShow();
}
});
}
| public static void main(String[] args) {
//initialize logging
LogSupport.init();
//store records for pushing it to logfile later
LogSupport.storeRecords(true);
//handle uncaught exceptions
Thread.setDefaultUncaughtExceptionHandler(ExceptionDialog.getExceptionHandler());
//workaround for Java 6 to process uncaught exceptions from modal dialogs
//read more at http://code.google.com/p/esmska/issues/detail?id=256
System.setProperty("sun.awt.exception.handler",
ExceptionDialog.AwtHandler.class.getName());
//detect JVM and warn if not not supported
if (!RuntimeUtils.isSupportedJava()) {
logger.warning("You are probably running the program on an unsupported "
+ "Java version! Program might not work correctly with it! "
+ "The tested Java versions are: Sun Java 6, OpenJDK 6, Apple Java 6.");
}
// halt for Webstart on OpenJDK, it currently doesn't work
// see http://code.google.com/p/esmska/issues/detail?id=335
// see http://code.google.com/p/esmska/issues/detail?id=357
// see http://code.google.com/p/esmska/issues/detail?id=358
if (RuntimeUtils.isOpenJDK() && RuntimeUtils.isRunAsWebStart()) {
logger.severe("Running as Java WebStart on OpenJDK, that's currently unsupported! Quitting.");
JOptionPane.showMessageDialog(null, l10n.getString("Main.brokenWebstart"), "Esmska", JOptionPane.ERROR_MESSAGE);
System.exit(99);
}
//parse commandline arguments
CommandLineParser clp = new CommandLineParser();
if (! clp.parseArgs(args)) {
System.exit(1);
}
//log some basic stuff for debugging
logger.fine("Esmska " + Config.getLatestVersion() + " starting...");
logger.finer("System info: " + RuntimeUtils.getSystemInfo());
//portable mode
configPath = clp.getConfigPath();
if (clp.isPortable() && configPath == null) {
logger.fine("Entering portable mode");
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not set system Look and Feel", ex);
}
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setApproveButtonText(l10n.getString("Select"));
chooser.setDialogTitle(l10n.getString("Main.choose_config_files"));
chooser.setFileHidingEnabled(false);
chooser.setMultiSelectionEnabled(false);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
configPath = chooser.getSelectedFile().getPath();
logger.config("New config path: " + configPath);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display file chooser for portable mode", e);
}
}
//get persistence manager
PersistenceManager pm = null;
try {
if (configPath != null) {
PersistenceManager.setCustomDirs(configPath, configPath);
}
PersistenceManager.instantiate();
pm = Context.persistenceManager;
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not create program dir or read config files", ex);
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null,
new JLabel(MessageFormat.format(l10n.getString("Main.cant_read_config"),
PersistenceManager.getConfigDir().getAbsolutePath(),
PersistenceManager.getDataDir().getAbsolutePath())),
null, JOptionPane.ERROR_MESSAGE);
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
} finally {
//if it is not possible to access config dir, we don't want to
//run anymore
System.exit(5);
}
}
//backup files
try {
pm.backupConfigFiles();
} catch (IOException ex) {
logger.log(Level.SEVERE, "Could not back up configuration", ex);
}
//initialize file logging
File logFile = pm.getLogFile();
try {
LogSupport.initFileHandler(logFile);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Could not start logging into " + logFile.getAbsolutePath(), ex);
} finally {
//no need to store records anymore
LogSupport.storeRecords(false);
}
//load user files
try {
pm.loadConfig();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load config file", ex);
}
try {
pm.loadGateways();
} catch (IntrospectionException ex) { //it seems there is not JavaScript support
logger.log(Level.SEVERE, "Current JRE doesn't support JavaScript execution", ex);
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, l10n.getString("Main.no_javascript"),
null, JOptionPane.ERROR_MESSAGE);
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
}
System.exit(2);
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load gateways", ex);
}
try {
pm.loadContacts();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load contacts file", ex);
}
try {
pm.loadQueue();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load queue file", ex);
}
try {
pm.loadHistory();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load history file", ex);
}
try {
pm.loadKeyring();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load keyring file", ex);
}
try {
pm.loadGatewayProperties();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Could not load gateway properties file", ex);
}
//initialize logging if set from Config
if (Config.getInstance().isDebugMode()) {
//set "full" logging, but don't log to console
LogSupport.enableHttpClientLogging();
LogSupport.getEsmskaLogger().setLevel(Level.ALL);
}
//warn if other program instance is already running
if (!pm.isFirstInstance()) {
logger.warning("Some other instance of the program is already running");
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
String runOption = l10n.getString("Main.run_anyway");
String quitOption = l10n.getString("Quit");
String[] options = new String[]{runOption, quitOption};
options = RuntimeUtils.sortDialogOptions(options);
int result = JOptionPane.showOptionDialog(null, l10n.getString("Main.already_running"),
null, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, quitOption);
if (result != ArrayUtils.indexOf(options, runOption)) {
System.exit(0);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
}
}
//warn if configuration files are newer than program version (user has
//executed an older program version)
Config config = Config.getInstance();
final String dataVersion = config.getVersion();
final String programVersion = Config.getLatestVersion();
if (Config.compareProgramVersions(dataVersion, programVersion) > 0) {
logger.warning("Configuration files are newer (" + dataVersion +
") then current program version (" + programVersion + ")! " +
"Data corruption may occur!");
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
String runOption = l10n.getString("Main.run_anyway");
String quitOption = l10n.getString("Quit");
String[] options = new String[]{runOption, quitOption};
options = RuntimeUtils.sortDialogOptions(options);
int result = JOptionPane.showOptionDialog(null,
new JLabel(MessageFormat.format(l10n.getString("Main.configsNewer"),
dataVersion, programVersion)),
null, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, quitOption);
if (result != ArrayUtils.indexOf(options, runOption)) {
System.exit(0);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't display error message", e);
}
}
//do some initialization if this is the first run
if (config.isFirstRun()) {
logger.fine("First run, doing initialization...");
//set country prefix from locale
config.setCountryPrefix(
CountryPrefix.getCountryPrefix(Locale.getDefault().getCountry()));
//set suggested LaF for this platform
config.setLookAndFeel(ThemeManager.suggestBestLAF());
//show first run wizard
InitWizardDialog dialog = new InitWizardDialog(null, true);
dialog.setVisible(true);
}
//update from older versions
if (!config.isFirstRun()) {
LegacyUpdater.update();
}
//set L&F
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
ThemeManager.setLaF();
} catch (Throwable ex) {
logger.log(Level.WARNING, "Could not set Look and Feel", ex);
}
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Setting LaF interrupted", e);
}
//set proxy
if (config.isUseProxy()) {
ProxyManager.setProxy(config.getHttpProxy(),
config.getHttpsProxy(), config.getSocksProxy());
}
//do some changes for unstable version
if (!Config.isStableVersion()) {
config.setAnnounceUnstableUpdates(true);
}
//start main frame
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
MainFrame.instantiate();
Context.mainFrame.startAndShow();
}
});
}
|
diff --git a/src/minecraft/co/uk/flansmods/client/model/ModelVehicle.java b/src/minecraft/co/uk/flansmods/client/model/ModelVehicle.java
index 9ebd419e..f5a79029 100644
--- a/src/minecraft/co/uk/flansmods/client/model/ModelVehicle.java
+++ b/src/minecraft/co/uk/flansmods/client/model/ModelVehicle.java
@@ -1,310 +1,310 @@
package co.uk.flansmods.client.model;
import net.minecraft.client.model.ModelBase;
import co.uk.flansmods.client.tmt.ModelRendererTurbo;
import co.uk.flansmods.common.driveables.EntityDriveable;
import co.uk.flansmods.common.driveables.EntityPlane;
import co.uk.flansmods.common.driveables.EntitySeat;
import co.uk.flansmods.common.driveables.EntityVehicle;
import co.uk.flansmods.common.driveables.EnumDriveablePart;
//Extensible ModelVehicle class for rendering vehicle models
public class ModelVehicle extends ModelDriveable
{
@Override
public void render(EntityDriveable driveable, float f1)
{
render(0.0625F, (EntityVehicle)driveable, f1);
}
@Override
/** GUI render method */
public void render()
{
super.render();
renderPart(leftBackWheelModel);
renderPart(rightBackWheelModel);
renderPart(leftFrontWheelModel);
renderPart(rightFrontWheelModel);
renderPart(bodyDoorCloseModel);
renderPart(trailerModel);
renderPart(turretModel);
renderPart(barrelModel);
renderPart(steeringWheelModel);
}
public void render(float f5, EntityVehicle vehicle, float f)
{
boolean rotateWheels = vehicle.getVehicleType().rotateWheels;
//Rendering the body
if(vehicle.isPartIntact(EnumDriveablePart.core))
{
for(int i = 0; i < bodyModel.length; i++)
{
bodyModel[i].render(f5);
}
for(int i = 0; i < bodyDoorOpenModel.length; i++)
{
if(vehicle.varDoor == true)
bodyDoorOpenModel[i].render(f5);
}
for(int i = 0; i < bodyDoorCloseModel.length; i++)
{
if(vehicle.varDoor == false)
bodyDoorCloseModel[i].render(f5);
}
for(int i = 0; i < steeringWheelModel.length; i++)
{
steeringWheelModel[i].rotateAngleX = vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
steeringWheelModel[i].render(f5);
}
}
//Wheels
if(vehicle.isPartIntact(EnumDriveablePart.backLeftWheel))
{
for(int i = 0; i < leftBackWheelModel.length; i++)
{
leftBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
leftBackWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.backRightWheel))
{
for(int i = 0; i < rightBackWheelModel.length; i++)
{
rightBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
rightBackWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.frontLeftWheel))
{
for(int i = 0; i < leftFrontWheelModel.length; i++)
{
leftFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
leftFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
leftFrontWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.frontRightWheel))
{
for(int i = 0; i < rightFrontWheelModel.length; i++)
{
rightFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
rightFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
rightFrontWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.frontWheel))
{
for(int i = 0; i < frontWheelModel.length; i++)
{
frontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
frontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
frontWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.backWheel))
{
for(int i = 0; i < backWheelModel.length; i++)
{
- backWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
+ backWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
backWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.leftTrack))
{
for(int i = 0; i < leftTrackModel.length; i++)
{
leftTrackModel[i].render(f5);
}
for(int i = 0; i < leftTrackWheelModels.length; i++)
{
- leftTrackModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
+ leftTrackModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
leftTrackModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.rightTrack))
{
for(int i = 0; i < rightTrackModel.length; i++)
{
rightTrackModel[i].render(f5);
}
for(int i = 0; i < rightTrackWheelModels.length; i++)
{
- rightTrackWheelModels[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
+ rightTrackWheelModels[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
rightTrackWheelModels[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.trailer))
{
for(int i = 0; i < trailerModel.length; i++)
{
trailerModel[i].render(f5);
}
}
//Render guns
for(EntitySeat seat : vehicle.seats)
{
//If the seat has a gun model attached
if(seat != null && seat.seatInfo != null && seat.seatInfo.gunName != null && gunModels.get(seat.seatInfo.gunName) != null && vehicle.isPartIntact(seat.seatInfo.part))// && !vehicle.rotateWithTurret(seat.seatInfo))
{
float yaw = seat.prevLooking.getYaw() + (seat.looking.getYaw() - seat.prevLooking.getYaw()) * f;
float pitch = seat.prevLooking.getPitch() + (seat.looking.getPitch() - seat.prevLooking.getPitch()) * f;
//Iterate over the parts of that model
ModelRendererTurbo[][] gunModel = gunModels.get(seat.seatInfo.gunName);
//Yaw only parts
for(ModelRendererTurbo gunModelPart : gunModel[0])
{
//Yaw and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.render(f5);
}
//Yaw and pitch, no recoil parts
for(ModelRendererTurbo gunModelPart : gunModel[1])
{
//Yaw, pitch and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F;
gunModelPart.render(f5);
}
//Yaw, pitch and recoil parts
for(ModelRendererTurbo gunModelPart : gunModel[2])
{
//Yaw, pitch, recoil and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F;
gunModelPart.render(f5);
}
}
}
}
/** Render the tank turret */
public void renderTurret(float f, float f1, float f2, float f3, float f4, float f5, EntityVehicle vehicle)
{
//Render main turret barrel
{
float yaw = vehicle.seats[0].looking.getYaw();
float pitch = vehicle.seats[0].looking.getPitch();
for(int i = 0; i < turretModel.length; i++)
{
turretModel[i].render(f5);
}
for(int i = 0; i < barrelModel.length; i++)
{
barrelModel[i].rotateAngleZ = -pitch * 3.14159265F / 180F;
barrelModel[i].render(f5);
}
}
//Render turret guns
/*for(EntitySeat seat : vehicle.seats)
{
//If the seat has a gun model attached
if(seat != null && seat.seatInfo != null && seat.seatInfo.gunName != null && gunModels.get(seat.seatInfo.gunName) != null && vehicle.isPartIntact(seat.seatInfo.part) && vehicle.rotateWithTurret(seat.seatInfo))
{
float yaw = seat.prevLooking.getYaw() + (seat.looking.getYaw() - seat.prevLooking.getYaw()) * f;
float pitch = seat.prevLooking.getPitch() + (seat.looking.getPitch() - seat.prevLooking.getPitch()) * f;
//Iterate over the parts of that model
ModelRendererTurbo[][] gunModel = gunModels.get(seat.seatInfo.gunName);
//Yaw only parts
for(ModelRendererTurbo gunModelPart : gunModel[0])
{
//Yaw and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.render(f5);
}
//Yaw and pitch, no recoil parts
for(ModelRendererTurbo gunModelPart : gunModel[1])
{
//Yaw, pitch and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F;
gunModelPart.render(f5);
}
//Yaw, pitch and recoil parts
for(ModelRendererTurbo gunModelPart : gunModel[2])
{
//Yaw, pitch, recoil and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F;
gunModelPart.render(f5);
}
}
}*/
}
@Override
public void flipAll()
{
super.flipAll();
flip(turretModel);
flip(barrelModel);
flip(leftFrontWheelModel);
flip(rightFrontWheelModel);
flip(leftBackWheelModel);
flip(rightBackWheelModel);
flip(bodyDoorOpenModel);
flip(bodyDoorCloseModel);
flip(rightTrackModel);
flip(leftTrackModel);
flip(rightTrackWheelModels);
flip(leftTrackWheelModels);
flip(trailerModel);
flip(steeringWheelModel);
}
public void translateAll(int y)
{
translate(bodyModel, y);
translate(turretModel, y);
translate(barrelModel, y);
translate(leftFrontWheelModel, y);
translate(rightFrontWheelModel, y);
translate(leftBackWheelModel, y);
translate(rightBackWheelModel, y);
translate(bodyDoorOpenModel, y);
translate(bodyDoorCloseModel, y);
translate(rightTrackModel, y);
translate(leftTrackModel, y);
translate(rightTrackWheelModels, y);
translate(leftTrackWheelModels, y);
translate(trailerModel, y);
translate(steeringWheelModel, y);
}
protected void translate(ModelRendererTurbo[] model, int y)
{
for(ModelRendererTurbo mod : model)
{
mod.rotationPointY += y;
}
}
public ModelRendererTurbo turretModel[] = new ModelRendererTurbo[0]; //The turret (for tanks)
public ModelRendererTurbo barrelModel[] = new ModelRendererTurbo[0]; //The barrel of the main turret
public ModelRendererTurbo frontWheelModel[] = new ModelRendererTurbo[0]; //Front and back wheels are for bicycles and motorbikes and whatnot
public ModelRendererTurbo backWheelModel[] = new ModelRendererTurbo[0];
public ModelRendererTurbo leftFrontWheelModel[] = new ModelRendererTurbo[0]; //This set of 4 wheels are for 4 or more wheeled things
public ModelRendererTurbo rightFrontWheelModel[] = new ModelRendererTurbo[0]; //The front wheels will turn as the player steers, and the back ones will not
public ModelRendererTurbo leftBackWheelModel[] = new ModelRendererTurbo[0]; //They will all turn as the car drives if the option to do so is set on
public ModelRendererTurbo rightBackWheelModel[] = new ModelRendererTurbo[0]; //In the vehicle type file
public ModelRendererTurbo rightTrackModel[] = new ModelRendererTurbo[0];
public ModelRendererTurbo leftTrackModel[] = new ModelRendererTurbo[0];
public ModelRendererTurbo rightTrackWheelModels[] = new ModelRendererTurbo[0]; //These go with the tracks but rotate
public ModelRendererTurbo leftTrackWheelModels[] = new ModelRendererTurbo[0];
public ModelRendererTurbo bodyDoorOpenModel[] = new ModelRendererTurbo[0];
public ModelRendererTurbo bodyDoorCloseModel[] = new ModelRendererTurbo[0];
public ModelRendererTurbo trailerModel[] = new ModelRendererTurbo[0];
public ModelRendererTurbo steeringWheelModel[] = new ModelRendererTurbo[0];
}
| false | true | public void render(float f5, EntityVehicle vehicle, float f)
{
boolean rotateWheels = vehicle.getVehicleType().rotateWheels;
//Rendering the body
if(vehicle.isPartIntact(EnumDriveablePart.core))
{
for(int i = 0; i < bodyModel.length; i++)
{
bodyModel[i].render(f5);
}
for(int i = 0; i < bodyDoorOpenModel.length; i++)
{
if(vehicle.varDoor == true)
bodyDoorOpenModel[i].render(f5);
}
for(int i = 0; i < bodyDoorCloseModel.length; i++)
{
if(vehicle.varDoor == false)
bodyDoorCloseModel[i].render(f5);
}
for(int i = 0; i < steeringWheelModel.length; i++)
{
steeringWheelModel[i].rotateAngleX = vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
steeringWheelModel[i].render(f5);
}
}
//Wheels
if(vehicle.isPartIntact(EnumDriveablePart.backLeftWheel))
{
for(int i = 0; i < leftBackWheelModel.length; i++)
{
leftBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
leftBackWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.backRightWheel))
{
for(int i = 0; i < rightBackWheelModel.length; i++)
{
rightBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
rightBackWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.frontLeftWheel))
{
for(int i = 0; i < leftFrontWheelModel.length; i++)
{
leftFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
leftFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
leftFrontWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.frontRightWheel))
{
for(int i = 0; i < rightFrontWheelModel.length; i++)
{
rightFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
rightFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
rightFrontWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.frontWheel))
{
for(int i = 0; i < frontWheelModel.length; i++)
{
frontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
frontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
frontWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.backWheel))
{
for(int i = 0; i < backWheelModel.length; i++)
{
backWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
backWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.leftTrack))
{
for(int i = 0; i < leftTrackModel.length; i++)
{
leftTrackModel[i].render(f5);
}
for(int i = 0; i < leftTrackWheelModels.length; i++)
{
leftTrackModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
leftTrackModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.rightTrack))
{
for(int i = 0; i < rightTrackModel.length; i++)
{
rightTrackModel[i].render(f5);
}
for(int i = 0; i < rightTrackWheelModels.length; i++)
{
rightTrackWheelModels[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
rightTrackWheelModels[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.trailer))
{
for(int i = 0; i < trailerModel.length; i++)
{
trailerModel[i].render(f5);
}
}
//Render guns
for(EntitySeat seat : vehicle.seats)
{
//If the seat has a gun model attached
if(seat != null && seat.seatInfo != null && seat.seatInfo.gunName != null && gunModels.get(seat.seatInfo.gunName) != null && vehicle.isPartIntact(seat.seatInfo.part))// && !vehicle.rotateWithTurret(seat.seatInfo))
{
float yaw = seat.prevLooking.getYaw() + (seat.looking.getYaw() - seat.prevLooking.getYaw()) * f;
float pitch = seat.prevLooking.getPitch() + (seat.looking.getPitch() - seat.prevLooking.getPitch()) * f;
//Iterate over the parts of that model
ModelRendererTurbo[][] gunModel = gunModels.get(seat.seatInfo.gunName);
//Yaw only parts
for(ModelRendererTurbo gunModelPart : gunModel[0])
{
//Yaw and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.render(f5);
}
//Yaw and pitch, no recoil parts
for(ModelRendererTurbo gunModelPart : gunModel[1])
{
//Yaw, pitch and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F;
gunModelPart.render(f5);
}
//Yaw, pitch and recoil parts
for(ModelRendererTurbo gunModelPart : gunModel[2])
{
//Yaw, pitch, recoil and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F;
gunModelPart.render(f5);
}
}
}
}
| public void render(float f5, EntityVehicle vehicle, float f)
{
boolean rotateWheels = vehicle.getVehicleType().rotateWheels;
//Rendering the body
if(vehicle.isPartIntact(EnumDriveablePart.core))
{
for(int i = 0; i < bodyModel.length; i++)
{
bodyModel[i].render(f5);
}
for(int i = 0; i < bodyDoorOpenModel.length; i++)
{
if(vehicle.varDoor == true)
bodyDoorOpenModel[i].render(f5);
}
for(int i = 0; i < bodyDoorCloseModel.length; i++)
{
if(vehicle.varDoor == false)
bodyDoorCloseModel[i].render(f5);
}
for(int i = 0; i < steeringWheelModel.length; i++)
{
steeringWheelModel[i].rotateAngleX = vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
steeringWheelModel[i].render(f5);
}
}
//Wheels
if(vehicle.isPartIntact(EnumDriveablePart.backLeftWheel))
{
for(int i = 0; i < leftBackWheelModel.length; i++)
{
leftBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
leftBackWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.backRightWheel))
{
for(int i = 0; i < rightBackWheelModel.length; i++)
{
rightBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
rightBackWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.frontLeftWheel))
{
for(int i = 0; i < leftFrontWheelModel.length; i++)
{
leftFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
leftFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
leftFrontWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.frontRightWheel))
{
for(int i = 0; i < rightFrontWheelModel.length; i++)
{
rightFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
rightFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
rightFrontWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.frontWheel))
{
for(int i = 0; i < frontWheelModel.length; i++)
{
frontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
frontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F;
frontWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.backWheel))
{
for(int i = 0; i < backWheelModel.length; i++)
{
backWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
backWheelModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.leftTrack))
{
for(int i = 0; i < leftTrackModel.length; i++)
{
leftTrackModel[i].render(f5);
}
for(int i = 0; i < leftTrackWheelModels.length; i++)
{
leftTrackModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
leftTrackModel[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.rightTrack))
{
for(int i = 0; i < rightTrackModel.length; i++)
{
rightTrackModel[i].render(f5);
}
for(int i = 0; i < rightTrackWheelModels.length; i++)
{
rightTrackWheelModels[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0;
rightTrackWheelModels[i].render(f5);
}
}
if(vehicle.isPartIntact(EnumDriveablePart.trailer))
{
for(int i = 0; i < trailerModel.length; i++)
{
trailerModel[i].render(f5);
}
}
//Render guns
for(EntitySeat seat : vehicle.seats)
{
//If the seat has a gun model attached
if(seat != null && seat.seatInfo != null && seat.seatInfo.gunName != null && gunModels.get(seat.seatInfo.gunName) != null && vehicle.isPartIntact(seat.seatInfo.part))// && !vehicle.rotateWithTurret(seat.seatInfo))
{
float yaw = seat.prevLooking.getYaw() + (seat.looking.getYaw() - seat.prevLooking.getYaw()) * f;
float pitch = seat.prevLooking.getPitch() + (seat.looking.getPitch() - seat.prevLooking.getPitch()) * f;
//Iterate over the parts of that model
ModelRendererTurbo[][] gunModel = gunModels.get(seat.seatInfo.gunName);
//Yaw only parts
for(ModelRendererTurbo gunModelPart : gunModel[0])
{
//Yaw and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.render(f5);
}
//Yaw and pitch, no recoil parts
for(ModelRendererTurbo gunModelPart : gunModel[1])
{
//Yaw, pitch and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F;
gunModelPart.render(f5);
}
//Yaw, pitch and recoil parts
for(ModelRendererTurbo gunModelPart : gunModel[2])
{
//Yaw, pitch, recoil and render
gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F;
gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F;
gunModelPart.render(f5);
}
}
}
}
|
diff --git a/svn/branches/1.3-dev/src/org/cfeclipse/cfml/editors/actions/GenericEncloserAction.java b/svn/branches/1.3-dev/src/org/cfeclipse/cfml/editors/actions/GenericEncloserAction.java
index bc5c81bc..d0b9f907 100644
--- a/svn/branches/1.3-dev/src/org/cfeclipse/cfml/editors/actions/GenericEncloserAction.java
+++ b/svn/branches/1.3-dev/src/org/cfeclipse/cfml/editors/actions/GenericEncloserAction.java
@@ -1,119 +1,119 @@
/*
* Created on Feb 18, 2004
*
* The MIT License
* Copyright (c) 2004 Rob Rohan
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.cfeclipse.cfml.editors.actions;
import org.cfeclipse.cfml.CFMLPlugin;
import org.cfeclipse.cfml.editors.CFMLEditor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.ITextEditor;
/**
* @author Rob
*
* This is the base class for actions that enclose stuff. Like auto adding ##
* or quotes etc - it is also used for what other products call snippets
*/
public class GenericEncloserAction extends Encloser implements IEditorActionDelegate
{
protected ITextEditor editor = null;
protected String start = "";
protected String end = "";
public GenericEncloserAction()
{
super();
}
public GenericEncloserAction(String start, String end)
{
super();
setEnclosingStrings(start,end);
}
public void setEnclosingStrings(String start, String end)
{
this.start = start;
this.end = end;
}
public void setActiveEditor(IAction action, IEditorPart targetEditor)
{
//System.err.println(targetEditor);
//System.out.println( "Changin (" + start + ")(" + end + ")" );
if( targetEditor instanceof ITextEditor || targetEditor instanceof CFMLEditor ){
editor = (ITextEditor)targetEditor;
}
}
public void run()
{
run(null);
}
public void run(IAction action)
{
// IEditorInput input = editor.getEditorInput();
// FileEditorInput fInput = (FileEditorInput)input;
// System.out.println("Is this readonly" + fInput.getFile().isReadOnly());
if(editor != null && editor.isEditable())
{
/*
* to fix the fact that you can run this function on readonly files, we
* are going to check the document here The resutlts of editor.isEditable()
* dont seem to tally up with the method definition
*System.out.println("you may edit this? But I shouldnt be able to
* save you: " + editor.isEditable());
*/
// EFS.getStore(null);
IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput());
ISelection sel = editor.getSelectionProvider().getSelection();
this.enclose(doc,(ITextSelection)sel,start,end);
//move the cursor to before the end of the new insert
int offset = ((ITextSelection)sel).getOffset();
offset += ((ITextSelection)sel).getLength();
- offset += start.length();
+ offset += start.length()+1;
editor.setHighlightRange(offset,0,true);
// Tell the plugin's Last Encloser Manager that this was the last one used for this editor
CFMLPlugin.getDefault().getLastActionManager().setLastAction(editor, this);
}
}
public void selectionChanged(IAction action, ISelection selection){;}
}
| true | true | public void run(IAction action)
{
// IEditorInput input = editor.getEditorInput();
// FileEditorInput fInput = (FileEditorInput)input;
// System.out.println("Is this readonly" + fInput.getFile().isReadOnly());
if(editor != null && editor.isEditable())
{
/*
* to fix the fact that you can run this function on readonly files, we
* are going to check the document here The resutlts of editor.isEditable()
* dont seem to tally up with the method definition
*System.out.println("you may edit this? But I shouldnt be able to
* save you: " + editor.isEditable());
*/
// EFS.getStore(null);
IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput());
ISelection sel = editor.getSelectionProvider().getSelection();
this.enclose(doc,(ITextSelection)sel,start,end);
//move the cursor to before the end of the new insert
int offset = ((ITextSelection)sel).getOffset();
offset += ((ITextSelection)sel).getLength();
offset += start.length();
editor.setHighlightRange(offset,0,true);
// Tell the plugin's Last Encloser Manager that this was the last one used for this editor
CFMLPlugin.getDefault().getLastActionManager().setLastAction(editor, this);
}
}
| public void run(IAction action)
{
// IEditorInput input = editor.getEditorInput();
// FileEditorInput fInput = (FileEditorInput)input;
// System.out.println("Is this readonly" + fInput.getFile().isReadOnly());
if(editor != null && editor.isEditable())
{
/*
* to fix the fact that you can run this function on readonly files, we
* are going to check the document here The resutlts of editor.isEditable()
* dont seem to tally up with the method definition
*System.out.println("you may edit this? But I shouldnt be able to
* save you: " + editor.isEditable());
*/
// EFS.getStore(null);
IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput());
ISelection sel = editor.getSelectionProvider().getSelection();
this.enclose(doc,(ITextSelection)sel,start,end);
//move the cursor to before the end of the new insert
int offset = ((ITextSelection)sel).getOffset();
offset += ((ITextSelection)sel).getLength();
offset += start.length()+1;
editor.setHighlightRange(offset,0,true);
// Tell the plugin's Last Encloser Manager that this was the last one used for this editor
CFMLPlugin.getDefault().getLastActionManager().setLastAction(editor, this);
}
}
|
diff --git a/src/org/jetbrains/plugins/clojure/formatter/processors/ClojureIndentProcessor.java b/src/org/jetbrains/plugins/clojure/formatter/processors/ClojureIndentProcessor.java
index 57adebf..89550b8 100644
--- a/src/org/jetbrains/plugins/clojure/formatter/processors/ClojureIndentProcessor.java
+++ b/src/org/jetbrains/plugins/clojure/formatter/processors/ClojureIndentProcessor.java
@@ -1,35 +1,35 @@
package org.jetbrains.plugins.clojure.formatter.processors;
import com.intellij.formatting.Indent;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import org.jetbrains.plugins.clojure.formatter.ClojureBlock;
import org.jetbrains.plugins.clojure.parser.ClojureElementTypes;
import org.jetbrains.plugins.clojure.psi.api.ClojureFile;
/**
* @author ilyas
*/
public class ClojureIndentProcessor implements ClojureElementTypes{
public static Indent getChildIndent(ClojureBlock parent, ASTNode prevChildNode, ASTNode child) {
ASTNode astNode = parent.getNode();
final PsiElement psiParent = astNode.getPsi();
// For Groovy file
if (psiParent instanceof ClojureFile) {
return Indent.getNoneIndent();
}
ASTNode node = parent.getNode();
final TokenSet L_BRACES = TokenSet.create(LEFT_CURLY, LEFT_PAREN, LEFT_SQUARE);
if (LIST_LIKE_FORMS.contains(node.getElementType())) {
if (L_BRACES.contains(child.getElementType())) {
return Indent.getNoneIndent();
} else {
- return Indent.getNormalIndent();
+ return Indent.getNormalIndent(true);
}
}
return Indent.getNoneIndent();
}
}
| true | true | public static Indent getChildIndent(ClojureBlock parent, ASTNode prevChildNode, ASTNode child) {
ASTNode astNode = parent.getNode();
final PsiElement psiParent = astNode.getPsi();
// For Groovy file
if (psiParent instanceof ClojureFile) {
return Indent.getNoneIndent();
}
ASTNode node = parent.getNode();
final TokenSet L_BRACES = TokenSet.create(LEFT_CURLY, LEFT_PAREN, LEFT_SQUARE);
if (LIST_LIKE_FORMS.contains(node.getElementType())) {
if (L_BRACES.contains(child.getElementType())) {
return Indent.getNoneIndent();
} else {
return Indent.getNormalIndent();
}
}
return Indent.getNoneIndent();
}
| public static Indent getChildIndent(ClojureBlock parent, ASTNode prevChildNode, ASTNode child) {
ASTNode astNode = parent.getNode();
final PsiElement psiParent = astNode.getPsi();
// For Groovy file
if (psiParent instanceof ClojureFile) {
return Indent.getNoneIndent();
}
ASTNode node = parent.getNode();
final TokenSet L_BRACES = TokenSet.create(LEFT_CURLY, LEFT_PAREN, LEFT_SQUARE);
if (LIST_LIKE_FORMS.contains(node.getElementType())) {
if (L_BRACES.contains(child.getElementType())) {
return Indent.getNoneIndent();
} else {
return Indent.getNormalIndent(true);
}
}
return Indent.getNoneIndent();
}
|
diff --git a/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/core/MylarPlugin.java b/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/core/MylarPlugin.java
index cc9e697c1..a7469a7d0 100644
--- a/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/core/MylarPlugin.java
+++ b/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/core/MylarPlugin.java
@@ -1,461 +1,458 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.Map.Entry;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.mylar.internal.core.MylarContextManager;
import org.eclipse.mylar.internal.core.MylarPreferenceContstants;
import org.eclipse.mylar.internal.core.search.MylarWorkingSetUpdater;
import org.eclipse.mylar.internal.core.util.MylarStatusHandler;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* @author Mik Kersten
*/
public class MylarPlugin extends AbstractUIPlugin {
public static final String PLUGIN_ID = "org.eclipse.mylar.core";
public static final String CONTENT_TYPE_ANY = "*";
private static final String NAME_DATA_DIR = ".mylar";
private Map<String, IMylarStructureBridge> bridges = new HashMap<String, IMylarStructureBridge>();
private Map<IMylarStructureBridge, ImageDescriptor> activeSearchIcons = new HashMap<IMylarStructureBridge, ImageDescriptor>();
private Map<IMylarStructureBridge, String> activeSearchLabels = new HashMap<IMylarStructureBridge, String>();
private IMylarStructureBridge defaultBridge = null;
private List<AbstractUserInteractionMonitor> selectionMonitors = new ArrayList<AbstractUserInteractionMonitor>();
private List<AbstractCommandMonitor> commandMonitors = new ArrayList<AbstractCommandMonitor>();
private List<MylarWorkingSetUpdater> workingSetUpdaters = null;
/**
* TODO: this could be merged with context interaction events rather than
* requiring update from the monitor.
*/
private List<IInteractionEventListener> interactionListeners = new ArrayList<IInteractionEventListener>();
private static MylarPlugin INSTANCE;
private static MylarContextManager contextManager;
private ResourceBundle resourceBundle;
private static final IMylarStructureBridge DEFAULT_BRIDGE = new IMylarStructureBridge() {
public String getContentType() {
return null;
}
public String getHandleIdentifier(Object object) {
throw new RuntimeException("null bridge for object: " + object.getClass());
}
public Object getObjectForHandle(String handle) {
MylarStatusHandler.log("null bridge for handle: " + handle, this);
return null;
}
public String getParentHandle(String handle) {
MylarStatusHandler.log("null bridge for handle: " + handle, this);
return null;
}
public String getName(Object object) {
MylarStatusHandler.log("null bridge for object: " + object.getClass(), this);
return "";
}
public boolean canBeLandmark(String handle) {
return false;
}
public boolean acceptsObject(Object object) {
throw new RuntimeException("null bridge for object: " + object.getClass());
}
public boolean canFilter(Object element) {
return true;
}
public boolean isDocument(String handle) {
// return false;
throw new RuntimeException("null adapter for handle: " + handle);
}
public IProject getProjectForObject(Object object) {
// return null;
throw new RuntimeException("null brige for object: " + object);
}
public String getContentType(String elementHandle) {
return getContentType();
}
public List<AbstractRelationProvider> getRelationshipProviders() {
return Collections.emptyList();
}
public List<IDegreeOfSeparation> getDegreesOfSeparation() {
return Collections.emptyList();
}
public String getHandleForOffsetInObject(Object resource, int offset) {
MylarStatusHandler.log("null bridge for marker: " + resource.getClass(), this);
return null;
}
public void setParentBridge(IMylarStructureBridge bridge) {
// ignore
}
public List<String> getChildHandles(String handle) {
return Collections.emptyList();
}
};
public MylarPlugin() {
INSTANCE = this;
}
/**
* Initialization order is important.
*/
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
getPreferenceStore().setDefault(MylarPreferenceContstants.PREF_DATA_DIR, getDefaultDataDirectory());
if (contextManager == null)
contextManager = new MylarContextManager();
}
public String getDefaultDataDirectory() {
return ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + NAME_DATA_DIR;
}
@Override
public void stop(BundleContext context) throws Exception {
try {
super.stop(context);
INSTANCE = null;
resourceBundle = null;
// Stop all running jobs when we exit if the plugin didn't do it
Map<String, IMylarStructureBridge> bridges = getStructureBridges();
for (Entry<String, IMylarStructureBridge> entry : bridges.entrySet()) {
IMylarStructureBridge bridge = entry.getValue();// bridges.get(extension);
List<AbstractRelationProvider> providers = bridge.getRelationshipProviders();
if (providers == null)
continue;
for (AbstractRelationProvider provider : providers) {
provider.stopAllRunningJobs();
}
}
} catch (Exception e) {
MylarStatusHandler.fail(e, "Mylar Core stop failed", false);
}
}
public String getDataDirectory() {
return getPreferenceStore().getString(MylarPreferenceContstants.PREF_DATA_DIR);
}
public void setDataDirectory(String newPath) {
getPreferenceStore().setValue(MylarPreferenceContstants.PREF_DATA_DIR, newPath);
}
public static MylarPlugin getDefault() {
return INSTANCE;
}
public static MylarContextManager getContextManager() {
return contextManager;
}
public List<AbstractUserInteractionMonitor> getSelectionMonitors() {
return selectionMonitors;
}
public Map<String, IMylarStructureBridge> getStructureBridges() {
if (!CoreExtensionPointReader.extensionsRead)
CoreExtensionPointReader.initExtensions();
return bridges;
}
public IMylarStructureBridge getStructureBridge(String contentType) {
if (!CoreExtensionPointReader.extensionsRead)
CoreExtensionPointReader.initExtensions();
IMylarStructureBridge bridge = bridges.get(contentType);
if (bridge != null) {
return bridge;
} else if (defaultBridge != null) {
return defaultBridge;
} else {
return DEFAULT_BRIDGE;
}
}
public Set<String> getKnownContentTypes() {
return bridges.keySet();
}
private void setActiveSearchIcon(IMylarStructureBridge bridge, ImageDescriptor descriptor) {
activeSearchIcons.put(bridge, descriptor);
}
public ImageDescriptor getActiveSearchIcon(IMylarStructureBridge bridge) {
if (!CoreExtensionPointReader.extensionsRead)
CoreExtensionPointReader.initExtensions();
return activeSearchIcons.get(bridge);
}
private void setActiveSearchLabel(IMylarStructureBridge bridge, String label) {
activeSearchLabels.put(bridge, label);
}
public String getActiveSearchLabel(IMylarStructureBridge bridge) {
if (!CoreExtensionPointReader.extensionsRead)
CoreExtensionPointReader.initExtensions();
return activeSearchLabels.get(bridge);
}
/**
* TODO: cache this to improve performance?
*
* @return null if there are no bridges loaded, null bridge otherwise
*/
public IMylarStructureBridge getStructureBridge(Object object) {
if (!CoreExtensionPointReader.extensionsRead)
CoreExtensionPointReader.initExtensions();
IMylarStructureBridge bridge = null;
// if (bridges.size() == 0) {
// MylarStatusHandler.log("no bridges installed", this);
// return DEFAULT_BRIDGE;
// }
for (IMylarStructureBridge structureBridge : bridges.values()) {
if (structureBridge.acceptsObject(object)) {
bridge = structureBridge;
break;
}
}
if (bridge != null) {
return bridge;
} else {
if (defaultBridge != null && defaultBridge.acceptsObject(object)) {
return defaultBridge;
} else {
return DEFAULT_BRIDGE;
}
}
}
private void internalAddBridge(IMylarStructureBridge bridge) {
// MylarStatusHandler.log("> adding: " + bridge.getClass(), this);
if (bridge.getRelationshipProviders() != null) {
for (AbstractRelationProvider provider : bridge.getRelationshipProviders()) {
getContextManager().addListener(provider);
}
}
if (bridge.getContentType().equals(CONTENT_TYPE_ANY)) {
defaultBridge = bridge;
} else {
bridges.put(bridge.getContentType(), bridge);
}
}
public List<AbstractCommandMonitor> getCommandMonitors() {
return commandMonitors;
}
/**
* Returns the string from the plugin's resource bundle, or 'key' if not
* found.
*/
public static String getResourceString(String key) {
ResourceBundle bundle = MylarPlugin.getDefault().getResourceBundle();
try {
return (bundle != null) ? bundle.getString(key) : key;
} catch (MissingResourceException e) {
return key;
}
}
/**
* Returns the plugin's resource bundle,
*/
public ResourceBundle getResourceBundle() {
try {
if (resourceBundle == null)
resourceBundle = ResourceBundle.getBundle("org.eclipse.mylar.core.MylarPluginResources");
} catch (MissingResourceException x) {
resourceBundle = null;
}
return resourceBundle;
}
public boolean suppressWizardsOnStartup() {
List<String> commandLineArgs = Arrays.asList(Platform.getCommandLineArgs());
if (commandLineArgs.contains("-showmylarwizards")) {
return false;
} else {
return commandLineArgs.contains("-pdelaunch");
}
}
/**
* TODO: remove
*/
public void setDefaultBridge(IMylarStructureBridge defaultBridge) {
this.defaultBridge = defaultBridge;
}
public void addInteractionListener(IInteractionEventListener listener) {
interactionListeners.add(listener);
}
public void removeInteractionListener(IInteractionEventListener listener) {
interactionListeners.remove(listener);
}
/**
* TODO: refactor this, it's awkward
*/
public void notifyInteractionObserved(InteractionEvent interactionEvent) {
for (IInteractionEventListener listener : interactionListeners) {
listener.interactionObserved(interactionEvent);
}
}
public List<IInteractionEventListener> getInteractionListeners() {
return interactionListeners;
}
public void addWorkingSetUpdater(MylarWorkingSetUpdater updater) {
if (workingSetUpdaters == null)
workingSetUpdaters = new ArrayList<MylarWorkingSetUpdater>();
workingSetUpdaters.add(updater);
MylarPlugin.getContextManager().addListener(updater);
}
public MylarWorkingSetUpdater getWorkingSetUpdater() {
if (workingSetUpdaters == null)
return null;
else
return workingSetUpdaters.get(0);
}
static class CoreExtensionPointReader {
private static boolean extensionsRead = false;
public static void initExtensions() {
// based on Contributing to Eclipse
// MylarStatusHandler.log("reading extensions", null);
if (!extensionsRead) {
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint extensionPoint = registry
.getExtensionPoint(CoreExtensionPointReader.EXTENSION_ID_CONTEXT);
IExtension[] extensions = extensionPoint.getExtensions();
for (int i = 0; i < extensions.length; i++) {
IConfigurationElement[] elements = extensions[i].getConfigurationElements();
for (int j = 0; j < elements.length; j++) {
if (elements[j].getName().compareTo(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE) == 0) {
readBridge(elements[j]);
}
}
}
extensionsRead = true;
}
}
private static void readBridge(IConfigurationElement element) {
try {
Object object = element
.createExecutableExtension(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_CLASS);
- // MylarStatusHandler.log("> reading bridge: " +
- // object.getClass(), null);
if (object instanceof IMylarStructureBridge) {
IMylarStructureBridge bridge = (IMylarStructureBridge) object;
MylarPlugin.getDefault().internalAddBridge(bridge);
if (element.getAttribute(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_PARENT) != null) {
Object parent = element
.createExecutableExtension(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_PARENT);
if (parent instanceof IMylarStructureBridge) {
((IMylarStructureBridge) bridge).setParentBridge(((IMylarStructureBridge) parent));
- // ((IMylarStructureBridge)parent).addChildBridge(((IMylarStructureBridge)bridge));
} else {
MylarStatusHandler.log("Could not load parent bridge: "
+ parent.getClass().getCanonicalName() + " must implement "
+ IMylarStructureBridge.class.getCanonicalName(), null);
}
}
String iconPath = element
.getAttribute(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_SEARCH_ICON);
if (iconPath != null) {
ImageDescriptor descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(element.getNamespace(),
iconPath);
if (descriptor != null) {
MylarPlugin.getDefault().setActiveSearchIcon(bridge, descriptor);
}
}
String label = element.getAttribute(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_SEARCH_LABEL);
if (label != null) {
MylarPlugin.getDefault().setActiveSearchLabel(bridge, label);
}
} else {
MylarStatusHandler.log("Could not load bridge: " + object.getClass().getCanonicalName()
+ " must implement " + IMylarStructureBridge.class.getCanonicalName(), null);
}
} catch (CoreException e) {
MylarStatusHandler.log(e, "Could not load bridge extension");
}
}
public static final String EXTENSION_ID_CONTEXT = "org.eclipse.mylar.core.context";
public static final String ELEMENT_STRUCTURE_BRIDGE = "structureBridge";
public static final String ELEMENT_STRUCTURE_BRIDGE_CLASS = "class";
public static final String ELEMENT_STRUCTURE_BRIDGE_PARENT = "parent";
public static final String ELEMENT_STRUCTURE_BRIDGE_SEARCH_ICON = "activeSearchIcon";
public static final String ELEMENT_STRUCTURE_BRIDGE_SEARCH_LABEL = "activeSearchLabel";
}
}
| false | true | private static void readBridge(IConfigurationElement element) {
try {
Object object = element
.createExecutableExtension(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_CLASS);
// MylarStatusHandler.log("> reading bridge: " +
// object.getClass(), null);
if (object instanceof IMylarStructureBridge) {
IMylarStructureBridge bridge = (IMylarStructureBridge) object;
MylarPlugin.getDefault().internalAddBridge(bridge);
if (element.getAttribute(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_PARENT) != null) {
Object parent = element
.createExecutableExtension(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_PARENT);
if (parent instanceof IMylarStructureBridge) {
((IMylarStructureBridge) bridge).setParentBridge(((IMylarStructureBridge) parent));
// ((IMylarStructureBridge)parent).addChildBridge(((IMylarStructureBridge)bridge));
} else {
MylarStatusHandler.log("Could not load parent bridge: "
+ parent.getClass().getCanonicalName() + " must implement "
+ IMylarStructureBridge.class.getCanonicalName(), null);
}
}
String iconPath = element
.getAttribute(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_SEARCH_ICON);
if (iconPath != null) {
ImageDescriptor descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(element.getNamespace(),
iconPath);
if (descriptor != null) {
MylarPlugin.getDefault().setActiveSearchIcon(bridge, descriptor);
}
}
String label = element.getAttribute(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_SEARCH_LABEL);
if (label != null) {
MylarPlugin.getDefault().setActiveSearchLabel(bridge, label);
}
} else {
MylarStatusHandler.log("Could not load bridge: " + object.getClass().getCanonicalName()
+ " must implement " + IMylarStructureBridge.class.getCanonicalName(), null);
}
} catch (CoreException e) {
MylarStatusHandler.log(e, "Could not load bridge extension");
}
}
| private static void readBridge(IConfigurationElement element) {
try {
Object object = element
.createExecutableExtension(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_CLASS);
if (object instanceof IMylarStructureBridge) {
IMylarStructureBridge bridge = (IMylarStructureBridge) object;
MylarPlugin.getDefault().internalAddBridge(bridge);
if (element.getAttribute(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_PARENT) != null) {
Object parent = element
.createExecutableExtension(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_PARENT);
if (parent instanceof IMylarStructureBridge) {
((IMylarStructureBridge) bridge).setParentBridge(((IMylarStructureBridge) parent));
} else {
MylarStatusHandler.log("Could not load parent bridge: "
+ parent.getClass().getCanonicalName() + " must implement "
+ IMylarStructureBridge.class.getCanonicalName(), null);
}
}
String iconPath = element
.getAttribute(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_SEARCH_ICON);
if (iconPath != null) {
ImageDescriptor descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(element.getNamespace(),
iconPath);
if (descriptor != null) {
MylarPlugin.getDefault().setActiveSearchIcon(bridge, descriptor);
}
}
String label = element.getAttribute(CoreExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE_SEARCH_LABEL);
if (label != null) {
MylarPlugin.getDefault().setActiveSearchLabel(bridge, label);
}
} else {
MylarStatusHandler.log("Could not load bridge: " + object.getClass().getCanonicalName()
+ " must implement " + IMylarStructureBridge.class.getCanonicalName(), null);
}
} catch (CoreException e) {
MylarStatusHandler.log(e, "Could not load bridge extension");
}
}
|
diff --git a/src/main/java/com/treasure_data/bulk_import/writer/FileWriter.java b/src/main/java/com/treasure_data/bulk_import/writer/FileWriter.java
index fc049e2..fb2a244 100644
--- a/src/main/java/com/treasure_data/bulk_import/writer/FileWriter.java
+++ b/src/main/java/com/treasure_data/bulk_import/writer/FileWriter.java
@@ -1,133 +1,133 @@
//
// Treasure Data Bulk-Import Tool in Java
//
// Copyright (C) 2012 - 2013 Muga Nishizawa
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package com.treasure_data.bulk_import.writer;
import java.io.Closeable;
import java.io.IOException;
import java.util.Set;
import java.util.logging.Logger;
import com.treasure_data.bulk_import.Configuration;
import com.treasure_data.bulk_import.model.ColumnType;
import com.treasure_data.bulk_import.model.DoubleColumnValue;
import com.treasure_data.bulk_import.model.IntColumnValue;
import com.treasure_data.bulk_import.model.LongColumnValue;
import com.treasure_data.bulk_import.model.Row;
import com.treasure_data.bulk_import.model.StringColumnValue;
import com.treasure_data.bulk_import.model.TimeColumnValue;
import com.treasure_data.bulk_import.prepare_parts.PrepareConfiguration;
import com.treasure_data.bulk_import.prepare_parts.PreparePartsException;
import com.treasure_data.bulk_import.prepare_parts.PrepareProcessor;
public abstract class FileWriter implements Closeable {
private static final Logger LOG = Logger
.getLogger(FileWriter.class.getName());
protected PrepareConfiguration conf;
protected PrepareProcessor.Task task;
protected long rowNum = 0;
protected String[] columnNames;
protected ColumnType[] columnTypes;
protected Set<Integer> skipColumns;
protected FileWriter(PrepareConfiguration conf) {
this.conf = conf;
}
public void setColumnNames(String[] columnNames) {
this.columnNames = columnNames;
}
public void setColumnTypes(ColumnType[] columnTypes) {
this.columnTypes = columnTypes;
}
public void setSkipColumns(Set<Integer> skipColumns) {
this.skipColumns = skipColumns;
}
public void configure(PrepareProcessor.Task task)
throws PreparePartsException {
this.task = task;
}
public void next(Row row) throws PreparePartsException {
int size = row.getValues().length;
// begin writing
if (row.needAdditionalTimeColumn()) {
// if the row doesn't have 'time' column, new 'time' column needs
// to be appended to it.
- writeBeginRow(size + 1);
+ writeBeginRow(size + skipColumns.size() - 1);
} else {
- writeBeginRow(size);
+ writeBeginRow(size + skipColumns.size());
}
// write columns
for (int i = 0; i < size; i++) {
if (skipColumns.contains(i)) {
continue;
}
write(columnNames[i]);
if (i == row.getTimeColumnIndex()) {
row.getTimeColumnValue().write(row.getValue(i), this);
} else {
row.getValue(i).write(this);
}
}
if (row.needAdditionalTimeColumn()) {
write(Configuration.BI_PREPARE_PARTS_TIMECOLUMN_DEFAULTVALUE);
TimeColumnValue tcValue = row.getTimeColumnValue();
tcValue.write(row.getValue(tcValue.getIndex()), this);
}
// end
writeEndRow();
}
public abstract void writeBeginRow(int size) throws PreparePartsException;
public abstract void writeNil() throws PreparePartsException;
public abstract void write(String v) throws PreparePartsException;
public abstract void write(int v) throws PreparePartsException;
public abstract void write(long v) throws PreparePartsException;
public abstract void write(double v) throws PreparePartsException;
public abstract void write(TimeColumnValue filter, StringColumnValue v) throws PreparePartsException;
public abstract void write(TimeColumnValue filter, IntColumnValue v) throws PreparePartsException;
public abstract void write(TimeColumnValue filter, LongColumnValue v) throws PreparePartsException;
public abstract void write(TimeColumnValue filter, DoubleColumnValue v) throws PreparePartsException;
public abstract void writeEndRow() throws PreparePartsException;
public void resetRowNum() {
rowNum = 0;
}
public void incrementRowNum() {
rowNum++;
}
public long getRowNum() {
return rowNum;
}
// Closeable#close()
public abstract void close() throws IOException;
}
| false | true | public void next(Row row) throws PreparePartsException {
int size = row.getValues().length;
// begin writing
if (row.needAdditionalTimeColumn()) {
// if the row doesn't have 'time' column, new 'time' column needs
// to be appended to it.
writeBeginRow(size + 1);
} else {
writeBeginRow(size);
}
// write columns
for (int i = 0; i < size; i++) {
if (skipColumns.contains(i)) {
continue;
}
write(columnNames[i]);
if (i == row.getTimeColumnIndex()) {
row.getTimeColumnValue().write(row.getValue(i), this);
} else {
row.getValue(i).write(this);
}
}
if (row.needAdditionalTimeColumn()) {
write(Configuration.BI_PREPARE_PARTS_TIMECOLUMN_DEFAULTVALUE);
TimeColumnValue tcValue = row.getTimeColumnValue();
tcValue.write(row.getValue(tcValue.getIndex()), this);
}
// end
writeEndRow();
}
| public void next(Row row) throws PreparePartsException {
int size = row.getValues().length;
// begin writing
if (row.needAdditionalTimeColumn()) {
// if the row doesn't have 'time' column, new 'time' column needs
// to be appended to it.
writeBeginRow(size + skipColumns.size() - 1);
} else {
writeBeginRow(size + skipColumns.size());
}
// write columns
for (int i = 0; i < size; i++) {
if (skipColumns.contains(i)) {
continue;
}
write(columnNames[i]);
if (i == row.getTimeColumnIndex()) {
row.getTimeColumnValue().write(row.getValue(i), this);
} else {
row.getValue(i).write(this);
}
}
if (row.needAdditionalTimeColumn()) {
write(Configuration.BI_PREPARE_PARTS_TIMECOLUMN_DEFAULTVALUE);
TimeColumnValue tcValue = row.getTimeColumnValue();
tcValue.write(row.getValue(tcValue.getIndex()), this);
}
// end
writeEndRow();
}
|
diff --git a/PolyMeal/src/main/java/com/mustangexchange/polymeal/Parser.java b/PolyMeal/src/main/java/com/mustangexchange/polymeal/Parser.java
index 578fe32..07612c0 100644
--- a/PolyMeal/src/main/java/com/mustangexchange/polymeal/Parser.java
+++ b/PolyMeal/src/main/java/com/mustangexchange/polymeal/Parser.java
@@ -1,194 +1,192 @@
package com.mustangexchange.polymeal;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.math.BigDecimal;
import java.util.ArrayList;
/**
* Created by Blake on 8/6/13.
*/
public class Parser
{
private Item item;
private ItemSet items;
private ArrayList<ItemSet> listItems;
//counter for getting each h2 element since they are not a part of the the html table
private int counter;
private boolean parseDesc;
private boolean price;
private boolean name;
private boolean soupAndSalad = false;
private Document doc;
public Parser(ArrayList<ItemSet> listItems,Document doc)
{
this.listItems = listItems;
this.doc = doc;
}
//receives doc to parse and a boolean that determines whether the breakfast table is valid or not.
public void parse(boolean breakfast)
{
Elements h2Eles = doc.getElementsByTag("h2");
Elements tables = doc.select("table");
- String tempName = "";
- String tempPrice = "";
//parses html with tag hierarchy starting with each table the moving to each table row, then table data and then each strong tag
for(Element table : tables)
{
items = new ItemSet();
String h2 = h2Eles.get(counter).text();
items.setTitle(h2);
for(Element tr : table.select("tr"))
{
String itemName = null;
BigDecimal itemPrice = null;
String itemDesc = null;
//for storing each part of soup and salad
String one = null;
String two = null;
BigDecimal priceOne = null;
BigDecimal priceTwo = null;
for(Element td : tr.select("td"))
{
String strongName = td.select("strong").text();
String description = tr.select("td").text();
//handle special cases and remove unnecessary part of string for looks.
if(!strongName.equals("")&&!h2.equals("Breakfast"))
{
if(!strongName.contains("$"))
{
name = true;
parseDesc = false;
if(strongName.contains("Combos - "))
{
itemName = strongName.replace("Combos - ","");
}
else if(strongName.contains("Just Burgers - "))
{
itemName = strongName.replace("Just Burgers - ","");
}
else if(strongName.contains("Just Sandwiches - "))
{
itemName = strongName.replace("Just Sandwiches - ","");
}
else if(strongName.contains("Just Sandwiches - "))
{
itemName = strongName.replace("Just Sandwiches- ","");
}
else if(strongName.contains("Soup and Salad"))
{
soupAndSalad = true;
one = strongName.substring(0,5);
two = strongName.substring(9,14);
}
else
{
itemName = strongName;
}
}
else if(strongName.contains("$"))
{
price = true;
parseDesc = true;
strongName = strongName.replace(",",".");
//automatically calculates tax if any.
if(strongName.contains("plus tax"))
{
strongName = strongName.replace(" plus tax","");
strongName = strongName.replace("$","");
//set.getPrices().add(df.format(new Double(strongName)+new Double(strongName)*.08)+"");
itemPrice = (new BigDecimal(strongName).add(new BigDecimal(strongName))).multiply(new BigDecimal(".08"));
}
//gets proper values for anything per oz items by substringing them out.
else if(strongName.contains("per oz"))
{
priceOne = new BigDecimal(strongName.substring(7,11));
priceTwo = new BigDecimal(strongName.substring(26,30));
}
else
{
strongName = strongName.replace("$","");
itemPrice = new BigDecimal(strongName);
}
}
- itemDesc = descParse(tempName,tempPrice,description);
+ itemDesc = descParse(itemName,itemPrice.toString(),description);
}
else if(h2.equals("Breakfast")&&breakfast)
{
if(strongName.contains("$"))
{
parseDesc = true;
itemPrice = new BigDecimal(strongName.replace("$",""));
}
else
{
parseDesc = false;
itemName = strongName;
}
- itemDesc = descParse(tempName,tempPrice,description);
+ itemDesc = descParse(itemName,itemPrice.toString(),description);
}
}
if(itemName!=null)
{
if(soupAndSalad)
{
Item itemOne = new Item(one,priceOne,itemDesc,true);
Item itemTwo = new Item(two,priceTwo,itemDesc,true);
itemOne.setOunces(true);
itemTwo.setOunces(true);
items.add(itemOne);
items.add(itemTwo);
soupAndSalad = false;
}
else if(price&&name)
{
items.add(new Item(itemName,itemPrice,itemDesc,true));
price = false;
name = false;
}
else
{
items.add(new Item(itemName,itemPrice,itemDesc,false));
price = false;
name = false;
}
}
}
//adds each table to itemset arraylist then adds one to counter to allow h2 tag selection(workaround for Cal Poly table formatting)
listItems.add(items);
counter++;
}
}
private String descParse(String tempName,String tempPrice,String description)
{
if(parseDesc)
{
//if it is a price value remove both the name and price from the description string.
description = description.replace(tempName,"");
description = description.replace(tempPrice,"");
description = description.replace("$","");
if(description.equals(" "))
{
return "No Description Available!";
}
else
{
return description.replaceFirst(" ", "");
}
}
return "";
}
}
| false | true | public void parse(boolean breakfast)
{
Elements h2Eles = doc.getElementsByTag("h2");
Elements tables = doc.select("table");
String tempName = "";
String tempPrice = "";
//parses html with tag hierarchy starting with each table the moving to each table row, then table data and then each strong tag
for(Element table : tables)
{
items = new ItemSet();
String h2 = h2Eles.get(counter).text();
items.setTitle(h2);
for(Element tr : table.select("tr"))
{
String itemName = null;
BigDecimal itemPrice = null;
String itemDesc = null;
//for storing each part of soup and salad
String one = null;
String two = null;
BigDecimal priceOne = null;
BigDecimal priceTwo = null;
for(Element td : tr.select("td"))
{
String strongName = td.select("strong").text();
String description = tr.select("td").text();
//handle special cases and remove unnecessary part of string for looks.
if(!strongName.equals("")&&!h2.equals("Breakfast"))
{
if(!strongName.contains("$"))
{
name = true;
parseDesc = false;
if(strongName.contains("Combos - "))
{
itemName = strongName.replace("Combos - ","");
}
else if(strongName.contains("Just Burgers - "))
{
itemName = strongName.replace("Just Burgers - ","");
}
else if(strongName.contains("Just Sandwiches - "))
{
itemName = strongName.replace("Just Sandwiches - ","");
}
else if(strongName.contains("Just Sandwiches - "))
{
itemName = strongName.replace("Just Sandwiches- ","");
}
else if(strongName.contains("Soup and Salad"))
{
soupAndSalad = true;
one = strongName.substring(0,5);
two = strongName.substring(9,14);
}
else
{
itemName = strongName;
}
}
else if(strongName.contains("$"))
{
price = true;
parseDesc = true;
strongName = strongName.replace(",",".");
//automatically calculates tax if any.
if(strongName.contains("plus tax"))
{
strongName = strongName.replace(" plus tax","");
strongName = strongName.replace("$","");
//set.getPrices().add(df.format(new Double(strongName)+new Double(strongName)*.08)+"");
itemPrice = (new BigDecimal(strongName).add(new BigDecimal(strongName))).multiply(new BigDecimal(".08"));
}
//gets proper values for anything per oz items by substringing them out.
else if(strongName.contains("per oz"))
{
priceOne = new BigDecimal(strongName.substring(7,11));
priceTwo = new BigDecimal(strongName.substring(26,30));
}
else
{
strongName = strongName.replace("$","");
itemPrice = new BigDecimal(strongName);
}
}
itemDesc = descParse(tempName,tempPrice,description);
}
else if(h2.equals("Breakfast")&&breakfast)
{
if(strongName.contains("$"))
{
parseDesc = true;
itemPrice = new BigDecimal(strongName.replace("$",""));
}
else
{
parseDesc = false;
itemName = strongName;
}
itemDesc = descParse(tempName,tempPrice,description);
}
}
if(itemName!=null)
{
if(soupAndSalad)
{
Item itemOne = new Item(one,priceOne,itemDesc,true);
Item itemTwo = new Item(two,priceTwo,itemDesc,true);
itemOne.setOunces(true);
itemTwo.setOunces(true);
items.add(itemOne);
items.add(itemTwo);
soupAndSalad = false;
}
else if(price&&name)
{
items.add(new Item(itemName,itemPrice,itemDesc,true));
price = false;
name = false;
}
else
{
items.add(new Item(itemName,itemPrice,itemDesc,false));
price = false;
name = false;
}
}
}
//adds each table to itemset arraylist then adds one to counter to allow h2 tag selection(workaround for Cal Poly table formatting)
listItems.add(items);
counter++;
}
}
| public void parse(boolean breakfast)
{
Elements h2Eles = doc.getElementsByTag("h2");
Elements tables = doc.select("table");
//parses html with tag hierarchy starting with each table the moving to each table row, then table data and then each strong tag
for(Element table : tables)
{
items = new ItemSet();
String h2 = h2Eles.get(counter).text();
items.setTitle(h2);
for(Element tr : table.select("tr"))
{
String itemName = null;
BigDecimal itemPrice = null;
String itemDesc = null;
//for storing each part of soup and salad
String one = null;
String two = null;
BigDecimal priceOne = null;
BigDecimal priceTwo = null;
for(Element td : tr.select("td"))
{
String strongName = td.select("strong").text();
String description = tr.select("td").text();
//handle special cases and remove unnecessary part of string for looks.
if(!strongName.equals("")&&!h2.equals("Breakfast"))
{
if(!strongName.contains("$"))
{
name = true;
parseDesc = false;
if(strongName.contains("Combos - "))
{
itemName = strongName.replace("Combos - ","");
}
else if(strongName.contains("Just Burgers - "))
{
itemName = strongName.replace("Just Burgers - ","");
}
else if(strongName.contains("Just Sandwiches - "))
{
itemName = strongName.replace("Just Sandwiches - ","");
}
else if(strongName.contains("Just Sandwiches - "))
{
itemName = strongName.replace("Just Sandwiches- ","");
}
else if(strongName.contains("Soup and Salad"))
{
soupAndSalad = true;
one = strongName.substring(0,5);
two = strongName.substring(9,14);
}
else
{
itemName = strongName;
}
}
else if(strongName.contains("$"))
{
price = true;
parseDesc = true;
strongName = strongName.replace(",",".");
//automatically calculates tax if any.
if(strongName.contains("plus tax"))
{
strongName = strongName.replace(" plus tax","");
strongName = strongName.replace("$","");
//set.getPrices().add(df.format(new Double(strongName)+new Double(strongName)*.08)+"");
itemPrice = (new BigDecimal(strongName).add(new BigDecimal(strongName))).multiply(new BigDecimal(".08"));
}
//gets proper values for anything per oz items by substringing them out.
else if(strongName.contains("per oz"))
{
priceOne = new BigDecimal(strongName.substring(7,11));
priceTwo = new BigDecimal(strongName.substring(26,30));
}
else
{
strongName = strongName.replace("$","");
itemPrice = new BigDecimal(strongName);
}
}
itemDesc = descParse(itemName,itemPrice.toString(),description);
}
else if(h2.equals("Breakfast")&&breakfast)
{
if(strongName.contains("$"))
{
parseDesc = true;
itemPrice = new BigDecimal(strongName.replace("$",""));
}
else
{
parseDesc = false;
itemName = strongName;
}
itemDesc = descParse(itemName,itemPrice.toString(),description);
}
}
if(itemName!=null)
{
if(soupAndSalad)
{
Item itemOne = new Item(one,priceOne,itemDesc,true);
Item itemTwo = new Item(two,priceTwo,itemDesc,true);
itemOne.setOunces(true);
itemTwo.setOunces(true);
items.add(itemOne);
items.add(itemTwo);
soupAndSalad = false;
}
else if(price&&name)
{
items.add(new Item(itemName,itemPrice,itemDesc,true));
price = false;
name = false;
}
else
{
items.add(new Item(itemName,itemPrice,itemDesc,false));
price = false;
name = false;
}
}
}
//adds each table to itemset arraylist then adds one to counter to allow h2 tag selection(workaround for Cal Poly table formatting)
listItems.add(items);
counter++;
}
}
|
diff --git a/src/main/java/de/tuberlin/dima/presslufthammer/data/hierarchical/json/JSONRecordFileIterator.java b/src/main/java/de/tuberlin/dima/presslufthammer/data/hierarchical/json/JSONRecordFileIterator.java
index a3e1ea6..666dbb9 100644
--- a/src/main/java/de/tuberlin/dima/presslufthammer/data/hierarchical/json/JSONRecordFileIterator.java
+++ b/src/main/java/de/tuberlin/dima/presslufthammer/data/hierarchical/json/JSONRecordFileIterator.java
@@ -1,39 +1,42 @@
package de.tuberlin.dima.presslufthammer.data.hierarchical.json;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import de.tuberlin.dima.presslufthammer.data.SchemaNode;
import de.tuberlin.dima.presslufthammer.data.hierarchical.RecordDecoder;
import de.tuberlin.dima.presslufthammer.data.hierarchical.RecordIterator;
class JSONRecordFileIterator implements RecordIterator {
private Scanner scan;
private SchemaNode schema;
public JSONRecordFileIterator(SchemaNode schema, String filename) {
this.schema = schema;
try {
scan = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
scan = null;
}
}
public RecordDecoder next() {
if (scan == null) {
return null;
}
- if (scan.hasNextLine()) {
- JSONObject job = (JSONObject) JSONValue.parse(scan.nextLine());
+ while (scan.hasNextLine()) {
+ String line = scan.nextLine();
+ if (line.equals("")) {
+ continue;
+ }
+ JSONObject job = (JSONObject) JSONValue.parse(line);
RecordDecoder decoder = new JSONRecordDecoder(schema, job);
return decoder;
- } else {
- return null;
}
+ return null;
}
}
| false | true | public RecordDecoder next() {
if (scan == null) {
return null;
}
if (scan.hasNextLine()) {
JSONObject job = (JSONObject) JSONValue.parse(scan.nextLine());
RecordDecoder decoder = new JSONRecordDecoder(schema, job);
return decoder;
} else {
return null;
}
}
| public RecordDecoder next() {
if (scan == null) {
return null;
}
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.equals("")) {
continue;
}
JSONObject job = (JSONObject) JSONValue.parse(line);
RecordDecoder decoder = new JSONRecordDecoder(schema, job);
return decoder;
}
return null;
}
|
diff --git a/src/org/usfirst/frc4682/Audacity/commands/CommandBase.java b/src/org/usfirst/frc4682/Audacity/commands/CommandBase.java
index a37a8d8..2b7f9b9 100644
--- a/src/org/usfirst/frc4682/Audacity/commands/CommandBase.java
+++ b/src/org/usfirst/frc4682/Audacity/commands/CommandBase.java
@@ -1,43 +1,43 @@
package org.usfirst.frc4682.Audacity.commands;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc4682.Audacity.OI;
import org.usfirst.frc4682.Audacity.subsystems.*;
/**
* The base for all commands. All atomic commands should subclass CommandBase.
* CommandBase stores creates and stores each control system. To access a
* subsystem elsewhere in your code in your code use CommandBase.exampleSubsystem
* @author Author
*/
public abstract class CommandBase extends Command {
public static OI oi;
// Create a single static instance of all of your subsystems
public static DriveTrain driveTrain = new DriveTrain();
public static Shooter shooter = new Shooter();
public static Feeder feeder = new Feeder();
public static void init() {
// This MUST be here. If the OI creates Commands (which it very likely
// will), constructing it during the construction of CommandBase (from
// which commands extend), subsystems are not guaranteed to be
// yet. Thus, their requires() statements may grab null pointers. Bad
// news. Don't move it.
oi = new OI();
// Show what command your subsystem is running on the SmartDashboard
SmartDashboard.putData(driveTrain);
SmartDashboard.putData(shooter);
- SmartDashboard.putdata(feeder);
+ SmartDashboard.putData(feeder);
}
public CommandBase(String name) {
super(name);
}
public CommandBase() {
super();
}
}
| true | true | public static void init() {
// This MUST be here. If the OI creates Commands (which it very likely
// will), constructing it during the construction of CommandBase (from
// which commands extend), subsystems are not guaranteed to be
// yet. Thus, their requires() statements may grab null pointers. Bad
// news. Don't move it.
oi = new OI();
// Show what command your subsystem is running on the SmartDashboard
SmartDashboard.putData(driveTrain);
SmartDashboard.putData(shooter);
SmartDashboard.putdata(feeder);
}
| public static void init() {
// This MUST be here. If the OI creates Commands (which it very likely
// will), constructing it during the construction of CommandBase (from
// which commands extend), subsystems are not guaranteed to be
// yet. Thus, their requires() statements may grab null pointers. Bad
// news. Don't move it.
oi = new OI();
// Show what command your subsystem is running on the SmartDashboard
SmartDashboard.putData(driveTrain);
SmartDashboard.putData(shooter);
SmartDashboard.putData(feeder);
}
|
diff --git a/src/java/org/powertac/common/interfaces/Customer.java b/src/java/org/powertac/common/interfaces/Customer.java
index 06b7b08..7dd31d0 100644
--- a/src/java/org/powertac/common/interfaces/Customer.java
+++ b/src/java/org/powertac/common/interfaces/Customer.java
@@ -1,48 +1,48 @@
/*
* Copyright 2009-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.powertac.common.interfaces;
import org.powertac.common.CustomerInfo;
/**
* Interface that specifies common methods a Customer module needs to implement.
*
* @author Carsten Block
* @version 0.1 - January 2nd, 2011
*/
public interface Customer
{
/**
* Called to make the customer model produce its "real consumption" / real production
* based on the given subscription (which includes current and future prices), and on
* "real weather data" (which might only be relevant to customer
* models that react to weather impact, such as PV or wind turbine customers.
*
* @param weather real measured weather data for a particular timeslot
* @return real consumption / production of the customer for the timeslot specified in the given {@link Weather}
*/
//public TariffTransaction generateMeterReading(TariffSubscription subscription, Weather weather);
/**
* As soon as this method is called the customer model is required to store / update
* its own {@link org.powertac.common.Customer} instance in the database, which is used to publicly report some common properties describing the customer model
* @see org.powertac.common.Customer
* @return a customer object that contains customer master data (i.e. a generic description of the customer)
*/
- public CustomerInfo generateCustomerInfo();
+ public CustomerInfo[] generateCustomerInfoList();
}
| true | true | public CustomerInfo generateCustomerInfo();
| public CustomerInfo[] generateCustomerInfoList();
|
diff --git a/src/dungeonCrawler/GameElements/Player.java b/src/dungeonCrawler/GameElements/Player.java
index db414d3..28cc6e7 100644
--- a/src/dungeonCrawler/GameElements/Player.java
+++ b/src/dungeonCrawler/GameElements/Player.java
@@ -1,80 +1,81 @@
package dungeonCrawler.GameElements;
import java.awt.Color;
import java.awt.Graphics;
import java.util.EnumSet;
import java.util.LinkedList;
import dungeonCrawler.ElementType;
import dungeonCrawler.EventType;
import dungeonCrawler.GameElement;
import dungeonCrawler.GameEvent;
import dungeonCrawler.GameLogic;
import dungeonCrawler.GameObject;
import dungeonCrawler.Vector2d;
/**
* @author Tissen
*
*/
public class Player extends GameElement {
private int Health=1000;
private int lives=2;
private LinkedList<GameObject> inventar = new LinkedList<GameObject>();
/**
* @param position
* @param size
*/
public Player(Vector2d position, Vector2d size) {
super(position, size, "PLAYER", EnumSet.of(ElementType.MOVABLE));
}
@Override
public void draw(Graphics g) {
// TODO Auto-generated method stub
g.setColor(Color.BLUE);
g.fillRect(0, 0, size.getX(), size.getY());
}
public void setPosition(Vector2d pos) {
this.position = pos;
}
public void add(GameObject object){
inventar.add(object);
}
@Override
public void GameEventPerformed(GameEvent e) {
// TODO Auto-generated method stub
}
public void setHealt(int Health) {
this.Health = Health;
}
public void reduceHealth(int Health, GameLogic logic) {
if (this.Health-Health > 0){
- System.out.println("!" + (this.Health-Health));
this.Health = this.Health-Health;
System.out.println("Health verloren! Health: " + this.Health);
}
else {
lives--;
if(lives<=0){
this.Health -= Health;
System.out.println("!TOT! (x.x) Health: " + this.Health);
} else {
+ this.Health -= Health;
+ System.out.println("!TOT! (x.x) Health: " + this.Health);
this.Health = 1000;
logic.teleportElement(this, logic.getCheckPoint());
}
}
}
public int getHealt() {
return this.Health;
}
}
| false | true | public void reduceHealth(int Health, GameLogic logic) {
if (this.Health-Health > 0){
System.out.println("!" + (this.Health-Health));
this.Health = this.Health-Health;
System.out.println("Health verloren! Health: " + this.Health);
}
else {
lives--;
if(lives<=0){
this.Health -= Health;
System.out.println("!TOT! (x.x) Health: " + this.Health);
} else {
this.Health = 1000;
logic.teleportElement(this, logic.getCheckPoint());
}
}
}
| public void reduceHealth(int Health, GameLogic logic) {
if (this.Health-Health > 0){
this.Health = this.Health-Health;
System.out.println("Health verloren! Health: " + this.Health);
}
else {
lives--;
if(lives<=0){
this.Health -= Health;
System.out.println("!TOT! (x.x) Health: " + this.Health);
} else {
this.Health -= Health;
System.out.println("!TOT! (x.x) Health: " + this.Health);
this.Health = 1000;
logic.teleportElement(this, logic.getCheckPoint());
}
}
}
|
diff --git a/src/com/personalityextractor/entity/resolver/ViterbiResolver.java b/src/com/personalityextractor/entity/resolver/ViterbiResolver.java
index d340c64..e2ff199 100644
--- a/src/com/personalityextractor/entity/resolver/ViterbiResolver.java
+++ b/src/com/personalityextractor/entity/resolver/ViterbiResolver.java
@@ -1,326 +1,326 @@
package com.personalityextractor.entity.resolver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import com.personalityextractor.data.source.Wikiminer;
import com.personalityextractor.entity.Entity;
import com.personalityextractor.entity.WikipediaEntity;
import cs224n.util.CounterMap;
public class ViterbiResolver extends BaseEntityResolver {
public ViterbiResolver() {
}
/*
* get wikimimer compare() scores between all entities
*/
private CounterMap<String, String> populateCompareScores(
List<String> twEntities,
HashMap<String, ArrayList<WikipediaEntity>> tweetEntityTowikiEntities) {
CounterMap<String, String> probabilites = new CounterMap<String, String>();
for(int i=0;i<tweetEntityTowikiEntities.get(twEntities.get(1)).size();i++){
probabilites.setCount("-1", tweetEntityTowikiEntities.get(twEntities.get(1)).get(i).getWikiminerID(), 0.0000001);
probabilites.setCount(tweetEntityTowikiEntities.get(twEntities.get(1)).get(i).getWikiminerID(), "-1", 0.0000001);
}
for (int i = 1; i < twEntities.size(); i++) {
String twEntity = twEntities.get(i);
ArrayList<WikipediaEntity> wikiEntities = tweetEntityTowikiEntities
.get(twEntity);
for (int j = 0; j < wikiEntities.size(); j++) {
// iterate over ALL wikiEntities and get compare score for
// wikiEntities[i]
for (int k = i + 1; k < twEntities.size(); k++) {
ArrayList<WikipediaEntity> wEntities = tweetEntityTowikiEntities
.get(twEntities.get(k));
for (WikipediaEntity wEntity : wEntities) {
if (wEntity.getText().equalsIgnoreCase("void_node") || wEntity.getText().equalsIgnoreCase("start_node") ||wEntity.getText().equalsIgnoreCase("end_node")) {
probabilites.setCount(wikiEntities.get(j)
.getWikiminerID(),
wEntity.getWikiminerID(), 0.0000001);
probabilites.setCount(wEntity.getWikiminerID(),
wikiEntities.get(j).getWikiminerID(),
0.0000001);
continue;
}
probabilites.setCount(wikiEntities.get(j)
.getWikiminerID(), wEntity.getWikiminerID(),
Wikiminer.compare(wikiEntities.get(j)
.getWikiminerID(), wEntity
.getWikiminerID()));
probabilites.setCount(wEntity.getWikiminerID(),
wikiEntities.get(j).getWikiminerID(), Wikiminer
.compare(wikiEntities.get(j)
.getWikiminerID(), wEntity
.getWikiminerID()));
}
}
}
}
return probabilites;
}
private HashMap<String, String> buildwikiIDToTweetEntityMap(
HashMap<String, ArrayList<WikipediaEntity>> tweetEntityTowikiEntities) {
// assuming that wikipedia ids are unique
HashMap<String, String> wikiIDToTweetEntity = new HashMap<String, String>();
Object[] objArray = tweetEntityTowikiEntities.keySet().toArray();
List<String> twEntities = Arrays.asList(Arrays.copyOf(objArray,
objArray.length, String[].class));
for (int i = 0; i < twEntities.size(); i++) {
ArrayList<WikipediaEntity> wikiEntities = tweetEntityTowikiEntities
.get(twEntities.get(i));
for (WikipediaEntity we : wikiEntities) {
wikiIDToTweetEntity.put(we.getWikiminerID(), twEntities.get(i));
}
}
return wikiIDToTweetEntity;
}
private HashMap<String, ArrayList<WikipediaEntity>> getWikiSenses(List<String> entities) {
HashMap<String, ArrayList<WikipediaEntity>> tweetEntityTowikiEntities = new HashMap<String, ArrayList<WikipediaEntity>>();
//start node
ArrayList<WikipediaEntity> start = new ArrayList<WikipediaEntity>();
start.add(new WikipediaEntity("start_node", "-1", "0.0000001"));
tweetEntityTowikiEntities.put("start_node", start);
//end node
ArrayList<WikipediaEntity> end = new ArrayList<WikipediaEntity>();
end.add(new WikipediaEntity("end_node", "-2", "0.0000001"));
tweetEntityTowikiEntities.put("end_node", end);
for (String entity : entities) {
List<WikipediaEntity> wikiEntities = new ArrayList<WikipediaEntity>();
String xml = Wikiminer.getXML(entity, false);
if (xml == null)
continue;
ArrayList<String[]> weentities = Wikiminer.getWikipediaSenses(xml,
true);
if (weentities.size() == 0)
continue;
ArrayList<WikipediaEntity> ids = new ArrayList<WikipediaEntity>();
for (String[] arr : weentities) {
WikipediaEntity we = new WikipediaEntity(arr[0], arr[1], arr[2]);
ids.add(we);
wikiEntities.add(we);
}
// adding a void entity
WikipediaEntity we = new WikipediaEntity("void_node", "0", "0.0000001");
ids.add(we);
tweetEntityTowikiEntities.put(entity, ids);
}
return tweetEntityTowikiEntities;
}
private static List<String> swap(List<String> l, int p) {
int x = p;
int y = p + 1;
if (p == l.size() - 1) {
y = 0;
}
List<String> sList = new ArrayList<String>();
for (int i = 0; i < l.size(); i++) {
if (i == x) {
sList.add(l.get(y));
} else if (i == y) {
sList.add(l.get(x));
} else {
sList.add(l.get(i));
}
}
return sList;
}
public List<WikipediaEntity> resolve(List<String> entities) {
- ArrayList<Entity> entityList = new ArrayList<Entity>();
+ List<WikipediaEntity> entityList = new ArrayList<WikipediaEntity>();
double bestProbability = (-1)*Integer.MAX_VALUE;
String bestPath = "";
List<String> bestSequence=null;
// find potential wiki entities for each entity
HashMap<String, ArrayList<WikipediaEntity>> tweetEntityTowikiEntities = getWikiSenses(entities);
// remove entities which have no wikipedia senses
Object[] objArray = tweetEntityTowikiEntities.keySet().toArray();
List<String> twEntities = Arrays.asList(Arrays.copyOf(objArray,
objArray.length, String[].class));
for (int i = 0; i < entities.size(); i++) {
if (!twEntities.contains(entities.get(i))) {
entities.remove(i);
i--;
}
}
twEntities = entities;
// try all permutations of entities
for (int x = 0; x < entities.size(); x++) {
//// for (int x = 0; x < 1; x++) {
for (int z = 0; z < entities.size() - 1; z++) {
//// for (int z = 0; z < 1; z++)
twEntities = swap(twEntities, z);
//add start and end nodes
twEntities.add(0, "start_node");
twEntities.add(twEntities.size(), "end_node");
// pre-calculate all compare scores between wikipedia entities.
CounterMap<String, String> probabilites = populateCompareScores(twEntities,
tweetEntityTowikiEntities);
// declare the dp matrix and initialize it for the first state
HashMap<String, String[]> prev_BestPaths = new HashMap<String, String[]>();
ArrayList<WikipediaEntity> first_entities = tweetEntityTowikiEntities.get(twEntities.get(0));
for (WikipediaEntity we : first_entities) {
prev_BestPaths.put(we.getWikiminerID(), new String[] {
we.getCommonness(), we.getWikiminerID(), we.getCommonness() });
}
// System.out.println("Start viterbi");
// not worrying about the order of entities for now
for (int i = 1; i < twEntities.size(); i++) {
if(i==twEntities.size()-2){
System.out.println("");
}
for (String key : prev_BestPaths.keySet()) {
// System.out.println(Arrays.asList(prev_BestPaths.get(key)));
}
HashMap<String, String[]> next_BestPaths = new HashMap<String, String[]>();
ArrayList<WikipediaEntity> next_WikiSenses = tweetEntityTowikiEntities.get(twEntities.get(i));
for (int j = 0; j < next_WikiSenses.size(); j++) {
double total = 0;
String maxpath = "";
double maxprob = (-1) * Integer.MAX_VALUE;
double prob = 1;
String v_path = "";
double v_prob = 1;
ArrayList<WikipediaEntity> previous_WikiSenses = tweetEntityTowikiEntities.get(twEntities.get(i - 1));
for (int k = 0; k < previous_WikiSenses.size(); k++) {
String[] objs = prev_BestPaths
.get(previous_WikiSenses.get(k)
.getWikiminerID());
prob = Double.parseDouble(objs[0]);
v_path = (String) objs[1];
v_prob = Double.parseDouble(objs[2]);
double count = probabilites
.getCount(previous_WikiSenses.get(k)
.getWikiminerID(), next_WikiSenses
.get(j).getWikiminerID());
// System.out.println("Comparing "
// + previous_WikiSenses.get(k).getWikiminerID()
// + ", "
// + next_WikiSenses.get(j).getWikiminerID()
// + " : " + count);
double compareScore;
if (count == 0.0) {
compareScore = 0.0;
} else {
compareScore = Math.log(count);
}
prob += (compareScore + Double.valueOf(previous_WikiSenses.get(k).getCommonness()));
v_prob += (compareScore + Double.valueOf(previous_WikiSenses.get(k).getCommonness()));
total += Math.exp(prob);
double check = Math.log(total);
if (v_prob > maxprob) {
maxprob = v_prob;
maxpath = v_path
+ ","
+ next_WikiSenses.get(j)
.getWikiminerID();
}
}
next_BestPaths.put(next_WikiSenses.get(j)
.getWikiminerID(),
new String[] { String.valueOf(Math.log(total)),
maxpath, String.valueOf(maxprob) });
}
prev_BestPaths = next_BestPaths;
}
for (String key : prev_BestPaths.keySet()) {
// System.out.println("Entity: " + key);
// System.out.println(Arrays.asList(prev_BestPaths.get(key)));
}
double total = 0;
String maxpath = "";
double maxprob = (-1) * Integer.MAX_VALUE;
double prob = 1;
String v_path = "";
double v_prob = 1;
for (String s : prev_BestPaths.keySet()) {
String[] info = prev_BestPaths.get(s);
prob = Double.parseDouble(info[0]);
v_path = info[1];
v_prob = Double.parseDouble(info[2]);
total += Math.exp(prob);
if (v_prob > maxprob) {
maxpath = v_path;
maxprob = v_prob;
}
}
if(maxprob > bestProbability){
bestPath = maxpath;
bestProbability = maxprob;
bestSequence = new ArrayList<String>(twEntities);
}
System.out.println("Entities : " + twEntities);
System.out.println("MaxPath: " + maxpath + "\tMaxProb: "
+ maxprob + "\n");
twEntities.remove(0);
twEntities.remove(twEntities.size()-1);
}
}
System.out.println("BestPath: " + bestPath + "\tBestProb: "
+ bestProbability + "\n");
String[] ids = bestPath.split(",");
for(int l=0; l<ids.length; l++) {
entityList.add(new WikipediaEntity(bestSequence.get(l), ids[l]));
}
return entityList;
}
public static void main(String args[]) {
ViterbiResolver vr = new ViterbiResolver();
ArrayList<String> entities = new ArrayList<String>();
entities.add("apple");
entities.add("iphone");
entities.add("jobs");
vr.resolve(entities);
}
}
| true | true | public List<WikipediaEntity> resolve(List<String> entities) {
ArrayList<Entity> entityList = new ArrayList<Entity>();
double bestProbability = (-1)*Integer.MAX_VALUE;
String bestPath = "";
List<String> bestSequence=null;
// find potential wiki entities for each entity
HashMap<String, ArrayList<WikipediaEntity>> tweetEntityTowikiEntities = getWikiSenses(entities);
// remove entities which have no wikipedia senses
Object[] objArray = tweetEntityTowikiEntities.keySet().toArray();
List<String> twEntities = Arrays.asList(Arrays.copyOf(objArray,
objArray.length, String[].class));
for (int i = 0; i < entities.size(); i++) {
if (!twEntities.contains(entities.get(i))) {
entities.remove(i);
i--;
}
}
twEntities = entities;
// try all permutations of entities
for (int x = 0; x < entities.size(); x++) {
//// for (int x = 0; x < 1; x++) {
for (int z = 0; z < entities.size() - 1; z++) {
//// for (int z = 0; z < 1; z++)
twEntities = swap(twEntities, z);
//add start and end nodes
twEntities.add(0, "start_node");
twEntities.add(twEntities.size(), "end_node");
// pre-calculate all compare scores between wikipedia entities.
CounterMap<String, String> probabilites = populateCompareScores(twEntities,
tweetEntityTowikiEntities);
// declare the dp matrix and initialize it for the first state
HashMap<String, String[]> prev_BestPaths = new HashMap<String, String[]>();
ArrayList<WikipediaEntity> first_entities = tweetEntityTowikiEntities.get(twEntities.get(0));
for (WikipediaEntity we : first_entities) {
prev_BestPaths.put(we.getWikiminerID(), new String[] {
we.getCommonness(), we.getWikiminerID(), we.getCommonness() });
}
// System.out.println("Start viterbi");
// not worrying about the order of entities for now
for (int i = 1; i < twEntities.size(); i++) {
if(i==twEntities.size()-2){
System.out.println("");
}
for (String key : prev_BestPaths.keySet()) {
// System.out.println(Arrays.asList(prev_BestPaths.get(key)));
}
HashMap<String, String[]> next_BestPaths = new HashMap<String, String[]>();
ArrayList<WikipediaEntity> next_WikiSenses = tweetEntityTowikiEntities.get(twEntities.get(i));
for (int j = 0; j < next_WikiSenses.size(); j++) {
double total = 0;
String maxpath = "";
double maxprob = (-1) * Integer.MAX_VALUE;
double prob = 1;
String v_path = "";
double v_prob = 1;
ArrayList<WikipediaEntity> previous_WikiSenses = tweetEntityTowikiEntities.get(twEntities.get(i - 1));
for (int k = 0; k < previous_WikiSenses.size(); k++) {
String[] objs = prev_BestPaths
.get(previous_WikiSenses.get(k)
.getWikiminerID());
prob = Double.parseDouble(objs[0]);
v_path = (String) objs[1];
v_prob = Double.parseDouble(objs[2]);
double count = probabilites
.getCount(previous_WikiSenses.get(k)
.getWikiminerID(), next_WikiSenses
.get(j).getWikiminerID());
// System.out.println("Comparing "
// + previous_WikiSenses.get(k).getWikiminerID()
// + ", "
// + next_WikiSenses.get(j).getWikiminerID()
// + " : " + count);
double compareScore;
if (count == 0.0) {
compareScore = 0.0;
} else {
compareScore = Math.log(count);
}
prob += (compareScore + Double.valueOf(previous_WikiSenses.get(k).getCommonness()));
v_prob += (compareScore + Double.valueOf(previous_WikiSenses.get(k).getCommonness()));
total += Math.exp(prob);
double check = Math.log(total);
if (v_prob > maxprob) {
maxprob = v_prob;
maxpath = v_path
+ ","
+ next_WikiSenses.get(j)
.getWikiminerID();
}
}
next_BestPaths.put(next_WikiSenses.get(j)
.getWikiminerID(),
new String[] { String.valueOf(Math.log(total)),
maxpath, String.valueOf(maxprob) });
}
prev_BestPaths = next_BestPaths;
}
for (String key : prev_BestPaths.keySet()) {
// System.out.println("Entity: " + key);
// System.out.println(Arrays.asList(prev_BestPaths.get(key)));
}
double total = 0;
String maxpath = "";
double maxprob = (-1) * Integer.MAX_VALUE;
double prob = 1;
String v_path = "";
double v_prob = 1;
for (String s : prev_BestPaths.keySet()) {
String[] info = prev_BestPaths.get(s);
prob = Double.parseDouble(info[0]);
v_path = info[1];
v_prob = Double.parseDouble(info[2]);
total += Math.exp(prob);
if (v_prob > maxprob) {
maxpath = v_path;
maxprob = v_prob;
}
}
if(maxprob > bestProbability){
bestPath = maxpath;
bestProbability = maxprob;
bestSequence = new ArrayList<String>(twEntities);
}
System.out.println("Entities : " + twEntities);
System.out.println("MaxPath: " + maxpath + "\tMaxProb: "
+ maxprob + "\n");
twEntities.remove(0);
twEntities.remove(twEntities.size()-1);
}
}
System.out.println("BestPath: " + bestPath + "\tBestProb: "
+ bestProbability + "\n");
String[] ids = bestPath.split(",");
for(int l=0; l<ids.length; l++) {
entityList.add(new WikipediaEntity(bestSequence.get(l), ids[l]));
}
return entityList;
}
| public List<WikipediaEntity> resolve(List<String> entities) {
List<WikipediaEntity> entityList = new ArrayList<WikipediaEntity>();
double bestProbability = (-1)*Integer.MAX_VALUE;
String bestPath = "";
List<String> bestSequence=null;
// find potential wiki entities for each entity
HashMap<String, ArrayList<WikipediaEntity>> tweetEntityTowikiEntities = getWikiSenses(entities);
// remove entities which have no wikipedia senses
Object[] objArray = tweetEntityTowikiEntities.keySet().toArray();
List<String> twEntities = Arrays.asList(Arrays.copyOf(objArray,
objArray.length, String[].class));
for (int i = 0; i < entities.size(); i++) {
if (!twEntities.contains(entities.get(i))) {
entities.remove(i);
i--;
}
}
twEntities = entities;
// try all permutations of entities
for (int x = 0; x < entities.size(); x++) {
//// for (int x = 0; x < 1; x++) {
for (int z = 0; z < entities.size() - 1; z++) {
//// for (int z = 0; z < 1; z++)
twEntities = swap(twEntities, z);
//add start and end nodes
twEntities.add(0, "start_node");
twEntities.add(twEntities.size(), "end_node");
// pre-calculate all compare scores between wikipedia entities.
CounterMap<String, String> probabilites = populateCompareScores(twEntities,
tweetEntityTowikiEntities);
// declare the dp matrix and initialize it for the first state
HashMap<String, String[]> prev_BestPaths = new HashMap<String, String[]>();
ArrayList<WikipediaEntity> first_entities = tweetEntityTowikiEntities.get(twEntities.get(0));
for (WikipediaEntity we : first_entities) {
prev_BestPaths.put(we.getWikiminerID(), new String[] {
we.getCommonness(), we.getWikiminerID(), we.getCommonness() });
}
// System.out.println("Start viterbi");
// not worrying about the order of entities for now
for (int i = 1; i < twEntities.size(); i++) {
if(i==twEntities.size()-2){
System.out.println("");
}
for (String key : prev_BestPaths.keySet()) {
// System.out.println(Arrays.asList(prev_BestPaths.get(key)));
}
HashMap<String, String[]> next_BestPaths = new HashMap<String, String[]>();
ArrayList<WikipediaEntity> next_WikiSenses = tweetEntityTowikiEntities.get(twEntities.get(i));
for (int j = 0; j < next_WikiSenses.size(); j++) {
double total = 0;
String maxpath = "";
double maxprob = (-1) * Integer.MAX_VALUE;
double prob = 1;
String v_path = "";
double v_prob = 1;
ArrayList<WikipediaEntity> previous_WikiSenses = tweetEntityTowikiEntities.get(twEntities.get(i - 1));
for (int k = 0; k < previous_WikiSenses.size(); k++) {
String[] objs = prev_BestPaths
.get(previous_WikiSenses.get(k)
.getWikiminerID());
prob = Double.parseDouble(objs[0]);
v_path = (String) objs[1];
v_prob = Double.parseDouble(objs[2]);
double count = probabilites
.getCount(previous_WikiSenses.get(k)
.getWikiminerID(), next_WikiSenses
.get(j).getWikiminerID());
// System.out.println("Comparing "
// + previous_WikiSenses.get(k).getWikiminerID()
// + ", "
// + next_WikiSenses.get(j).getWikiminerID()
// + " : " + count);
double compareScore;
if (count == 0.0) {
compareScore = 0.0;
} else {
compareScore = Math.log(count);
}
prob += (compareScore + Double.valueOf(previous_WikiSenses.get(k).getCommonness()));
v_prob += (compareScore + Double.valueOf(previous_WikiSenses.get(k).getCommonness()));
total += Math.exp(prob);
double check = Math.log(total);
if (v_prob > maxprob) {
maxprob = v_prob;
maxpath = v_path
+ ","
+ next_WikiSenses.get(j)
.getWikiminerID();
}
}
next_BestPaths.put(next_WikiSenses.get(j)
.getWikiminerID(),
new String[] { String.valueOf(Math.log(total)),
maxpath, String.valueOf(maxprob) });
}
prev_BestPaths = next_BestPaths;
}
for (String key : prev_BestPaths.keySet()) {
// System.out.println("Entity: " + key);
// System.out.println(Arrays.asList(prev_BestPaths.get(key)));
}
double total = 0;
String maxpath = "";
double maxprob = (-1) * Integer.MAX_VALUE;
double prob = 1;
String v_path = "";
double v_prob = 1;
for (String s : prev_BestPaths.keySet()) {
String[] info = prev_BestPaths.get(s);
prob = Double.parseDouble(info[0]);
v_path = info[1];
v_prob = Double.parseDouble(info[2]);
total += Math.exp(prob);
if (v_prob > maxprob) {
maxpath = v_path;
maxprob = v_prob;
}
}
if(maxprob > bestProbability){
bestPath = maxpath;
bestProbability = maxprob;
bestSequence = new ArrayList<String>(twEntities);
}
System.out.println("Entities : " + twEntities);
System.out.println("MaxPath: " + maxpath + "\tMaxProb: "
+ maxprob + "\n");
twEntities.remove(0);
twEntities.remove(twEntities.size()-1);
}
}
System.out.println("BestPath: " + bestPath + "\tBestProb: "
+ bestProbability + "\n");
String[] ids = bestPath.split(",");
for(int l=0; l<ids.length; l++) {
entityList.add(new WikipediaEntity(bestSequence.get(l), ids[l]));
}
return entityList;
}
|
diff --git a/src/org/antlr/works/ate/swing/ATEKeyBindings.java b/src/org/antlr/works/ate/swing/ATEKeyBindings.java
index e31eb66..72bb54e 100644
--- a/src/org/antlr/works/ate/swing/ATEKeyBindings.java
+++ b/src/org/antlr/works/ate/swing/ATEKeyBindings.java
@@ -1,188 +1,188 @@
/*
[The "BSD licence"]
Copyright (c) 2005 Jean Bovet
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.antlr.works.ate.swing;
import org.antlr.works.ate.ATETextPane;
import org.antlr.xjlib.foundation.XJSystem;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class ATEKeyBindings {
private ATETextPane textComponent = null;
public ATEKeyBindings(ATETextPane textComponent) {
this.textComponent = textComponent;
if(XJSystem.isMacOS()) {
addEmacsKeyBindings();
}
addStandardKeyBindings();
}
public void addStandardKeyBindings() {
InputMap inputMap = textComponent.getInputMap();
// HOME to move cursor to begin of line
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0);
inputMap.put(key, DefaultEditorKit.beginLineAction);
// SHIFT-HOME to move cursor to begin of line and select
key = KeyStroke.getKeyStroke(KeyEvent.VK_HOME, Event.SHIFT_MASK);
inputMap.put(key, DefaultEditorKit.selectionBeginLineAction);
// END to move cursor to end of line
key = KeyStroke.getKeyStroke(KeyEvent.VK_END, 0);
inputMap.put(key, DefaultEditorKit.endLineAction);
// SHIFT-END to move cursor to end of line and select
key = KeyStroke.getKeyStroke(KeyEvent.VK_END, Event.SHIFT_MASK);
inputMap.put(key, DefaultEditorKit.selectionEndLineAction);
// Add shift-delete to act as the standard delete key
addKeyBinding("SHIFT_DELETE", KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, Event.SHIFT_MASK), new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
if(!textComponent.isWritable()) return;
textComponent.getActionMap().get(DefaultEditorKit.deleteNextCharAction).actionPerformed(actionEvent);
}
});
}
public void addEmacsKeyBindings() {
InputMap inputMap = textComponent.getInputMap();
// Ctrl-b to go backward one character
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.backwardAction);
// Ctrl-f to go forward one character
key = KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.forwardAction);
// Ctrl-p to go up one line
key = KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.upAction);
// Ctrl-n to go down one line
key = KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.downAction);
// Ctrl-a to move cursor to begin of line
key = KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.beginLineAction);
// Ctrl-e to move cursor to end of line
key = KeyStroke.getKeyStroke(KeyEvent.VK_E, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.endLineAction);
// Ctrl-d to delete the character under the cursor
- addKeyBinding("CONTROL_D", KeyStroke.getKeyStroke(KeyEvent.VK_K, Event.CTRL_MASK), new AbstractAction() {
+ addKeyBinding("CONTROL_D", KeyStroke.getKeyStroke(KeyEvent.VK_D, Event.CTRL_MASK), new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
if(!textComponent.isWritable()) return;
textComponent.getActionMap().get(DefaultEditorKit.deleteNextCharAction).actionPerformed(actionEvent);
}
});
// Ctrl-k to delete the characters from the current position to the end of the line
// Has to create a custom action to handle this one.
addKeyBinding("CONTROL_K", KeyStroke.getKeyStroke(KeyEvent.VK_K, Event.CTRL_MASK), new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if(!textComponent.isWritable()) return;
int start = textComponent.getCaretPosition();
Document doc = textComponent.getDocument();
String t;
try {
t = doc.getText(start, doc.getLength()-start);
} catch (BadLocationException e1) {
e1.printStackTrace();
return;
}
int end = 0;
while(end<t.length() && t.charAt(end) != '\n' && t.charAt(end) != '\r') {
end++;
}
try {
end = Math.max(1, end);
String content = doc.getText(start, end);
doc.remove(start, end);
// Copy the deleted portion of text into the system clipboard
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
cb.setContents(new StringSelection(content), null);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
// Ctrl-t swap the two characters before and after the current position
// Has to create a custom action to handle this one.
addKeyBinding("CONTROL_T", KeyStroke.getKeyStroke(KeyEvent.VK_T, Event.CTRL_MASK), new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if(!textComponent.isWritable()) return;
int p = textComponent.getCaretPosition();
Document doc = textComponent.getDocument();
if(p < 1 || p >= doc.getLength())
return;
try {
String before = doc.getText(p-1, 1);
doc.remove(p-1, 1);
doc.insertString(p, before, null);
textComponent.setCaretPosition(p);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
}
public void addKeyBinding(String name, KeyStroke keystroke, AbstractAction action) {
textComponent.getActionMap().put(name, action);
textComponent.getInputMap().put(keystroke, name);
}
}
| true | true | public void addEmacsKeyBindings() {
InputMap inputMap = textComponent.getInputMap();
// Ctrl-b to go backward one character
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.backwardAction);
// Ctrl-f to go forward one character
key = KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.forwardAction);
// Ctrl-p to go up one line
key = KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.upAction);
// Ctrl-n to go down one line
key = KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.downAction);
// Ctrl-a to move cursor to begin of line
key = KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.beginLineAction);
// Ctrl-e to move cursor to end of line
key = KeyStroke.getKeyStroke(KeyEvent.VK_E, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.endLineAction);
// Ctrl-d to delete the character under the cursor
addKeyBinding("CONTROL_D", KeyStroke.getKeyStroke(KeyEvent.VK_K, Event.CTRL_MASK), new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
if(!textComponent.isWritable()) return;
textComponent.getActionMap().get(DefaultEditorKit.deleteNextCharAction).actionPerformed(actionEvent);
}
});
// Ctrl-k to delete the characters from the current position to the end of the line
// Has to create a custom action to handle this one.
addKeyBinding("CONTROL_K", KeyStroke.getKeyStroke(KeyEvent.VK_K, Event.CTRL_MASK), new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if(!textComponent.isWritable()) return;
int start = textComponent.getCaretPosition();
Document doc = textComponent.getDocument();
String t;
try {
t = doc.getText(start, doc.getLength()-start);
} catch (BadLocationException e1) {
e1.printStackTrace();
return;
}
int end = 0;
while(end<t.length() && t.charAt(end) != '\n' && t.charAt(end) != '\r') {
end++;
}
try {
end = Math.max(1, end);
String content = doc.getText(start, end);
doc.remove(start, end);
// Copy the deleted portion of text into the system clipboard
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
cb.setContents(new StringSelection(content), null);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
// Ctrl-t swap the two characters before and after the current position
// Has to create a custom action to handle this one.
addKeyBinding("CONTROL_T", KeyStroke.getKeyStroke(KeyEvent.VK_T, Event.CTRL_MASK), new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if(!textComponent.isWritable()) return;
int p = textComponent.getCaretPosition();
Document doc = textComponent.getDocument();
if(p < 1 || p >= doc.getLength())
return;
try {
String before = doc.getText(p-1, 1);
doc.remove(p-1, 1);
doc.insertString(p, before, null);
textComponent.setCaretPosition(p);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
}
| public void addEmacsKeyBindings() {
InputMap inputMap = textComponent.getInputMap();
// Ctrl-b to go backward one character
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.backwardAction);
// Ctrl-f to go forward one character
key = KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.forwardAction);
// Ctrl-p to go up one line
key = KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.upAction);
// Ctrl-n to go down one line
key = KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.downAction);
// Ctrl-a to move cursor to begin of line
key = KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.beginLineAction);
// Ctrl-e to move cursor to end of line
key = KeyStroke.getKeyStroke(KeyEvent.VK_E, Event.CTRL_MASK);
inputMap.put(key, DefaultEditorKit.endLineAction);
// Ctrl-d to delete the character under the cursor
addKeyBinding("CONTROL_D", KeyStroke.getKeyStroke(KeyEvent.VK_D, Event.CTRL_MASK), new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
if(!textComponent.isWritable()) return;
textComponent.getActionMap().get(DefaultEditorKit.deleteNextCharAction).actionPerformed(actionEvent);
}
});
// Ctrl-k to delete the characters from the current position to the end of the line
// Has to create a custom action to handle this one.
addKeyBinding("CONTROL_K", KeyStroke.getKeyStroke(KeyEvent.VK_K, Event.CTRL_MASK), new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if(!textComponent.isWritable()) return;
int start = textComponent.getCaretPosition();
Document doc = textComponent.getDocument();
String t;
try {
t = doc.getText(start, doc.getLength()-start);
} catch (BadLocationException e1) {
e1.printStackTrace();
return;
}
int end = 0;
while(end<t.length() && t.charAt(end) != '\n' && t.charAt(end) != '\r') {
end++;
}
try {
end = Math.max(1, end);
String content = doc.getText(start, end);
doc.remove(start, end);
// Copy the deleted portion of text into the system clipboard
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
cb.setContents(new StringSelection(content), null);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
// Ctrl-t swap the two characters before and after the current position
// Has to create a custom action to handle this one.
addKeyBinding("CONTROL_T", KeyStroke.getKeyStroke(KeyEvent.VK_T, Event.CTRL_MASK), new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if(!textComponent.isWritable()) return;
int p = textComponent.getCaretPosition();
Document doc = textComponent.getDocument();
if(p < 1 || p >= doc.getLength())
return;
try {
String before = doc.getText(p-1, 1);
doc.remove(p-1, 1);
doc.insertString(p, before, null);
textComponent.setCaretPosition(p);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
}
|
diff --git a/src/main/java/de/beimax/simplespleef/SimpleSpleef.java b/src/main/java/de/beimax/simplespleef/SimpleSpleef.java
index 68af7db..14c914c 100644
--- a/src/main/java/de/beimax/simplespleef/SimpleSpleef.java
+++ b/src/main/java/de/beimax/simplespleef/SimpleSpleef.java
@@ -1,472 +1,472 @@
package de.beimax.simplespleef;
import java.io.File;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.util.config.Configuration;
import com.nijiko.permissions.PermissionHandler;
import org.bukkit.Server;
import com.iConomy.iConomy;
/**
* SimpleSpleef for Bukkit
*
* @author maxkalus
*/
public class SimpleSpleef extends JavaPlugin {
public static Logger log = Logger.getLogger("Minecraft");
private SimpleSpleefGame game;
private SimpleSpleefPlayerListener playerListener;
public Configuration conf; // General configuration
public Configuration ll; // Language configuration
private static PluginListener PluginListener = null;
private static Server Server = null;
/**
* Permissions
*/
private static PermissionHandler Permissions;
/**
* iConomy
*/
private static iConomy iConomy;
/**
* @return BukkitServer
*/
public static Server getBukkitServer() {
return Server;
}
/**
* @return Permissions instance or null
*/
public static PermissionHandler getPermissions() {
return Permissions;
}
/**
* @param plugin
* Permissions plugin setter
* @return true if set
*/
public static boolean setPermissions(PermissionHandler plugin) {
if (Permissions == null) {
Permissions = plugin;
} else {
return false;
}
return true;
}
/**
* @return iConomy instance or null
*/
public static iConomy getiConomy() {
return iConomy;
}
/**
* @return true if iConomy exists
*/
public static boolean checkiConomy() {
if (iConomy != null)
return true;
return false;
}
/**
* @param plugin
* iConomy plugin setter
* @return true if set
*/
public static boolean setiConomy(iConomy plugin) {
if (iConomy == null) {
iConomy = plugin;
} else {
return false;
}
return true;
}
/**
* initialize object, load config mainly
*/
public void init() {
// create plugin dir, if needed
new File("plugins" + File.separator + "SimpleSpleef" + File.separator)
.mkdirs();
// check files
File confFile = new File("plugins" + File.separator + "SimpleSpleef",
"SimpleSpleef.yml");
File enFile = new File("plugins" + File.separator + "SimpleSpleef",
"lang_en.yml");
File deFile = new File("plugins" + File.separator + "SimpleSpleef",
"lang_de.yml");
File langFile;
// load configuration
conf = new Configuration(confFile);
// check file
if (!confFile.exists()) {
log.info("[SimpleSpleef] Creating new configuration file.");
try {
FileWriter fw = new FileWriter(confFile);
fw.write("lang: en\ngiveprizes: true\nprizes:\n- APPLE\n- BED\n- BOOK\n- CAKE\n- CHAINMAIL_HELMET\n- CLAY_BALL\n- COMPASS\n- COOKED_FISH\n- DIAMOND\n- FLINT_AND_STEEL\n- GOLD_INGOT\n- GLOWSTONE\n- GOLD_HELMET\n- INK_SACK\n- IRON_INGOT\n- IRON_HELMET\n- OBSIDIAN\n- RED_ROSE\n- SNOW_BLOCK\n- STRING\n- SULPHUR\n- TNT\n- YELLOW_FLOWER\n");
fw.close();
} catch (Exception e) {
log.warning("[SimpleSpleef] Could not write SimpleSpleef.yml: "
+ e.getMessage());
}
}
conf.load(); // load conf file
// check config file
boolean changed = false; // flag to set config change
// new elements
if (conf.getProperty("giveprizes") == null) { // no giveprizes property
// exists
conf.setProperty("giveprizes", true);
changed = true;
} else if (conf.getProperty("prices") != null) { // change prices to
// giveprizes
conf.setProperty("giveprizes", conf.getBoolean("prices", true));
conf.removeProperty("prices"); // delete property
changed = true;
}
if (conf.getProperty("prizes") == null) { // define default wins
String[] defaultWins = { "APPLE", "BED", "BOOK", "CAKE",
"CHAINMAIL_HELMET", "CLAY_BALL", "COMPASS", "COOKED_FISH",
"DIAMOND", "FLINT_AND_STEEL", "GOLD_INGOT", "GLOWSTONE",
"GOLD_HELMET", "INK_SACK", "IRON_INGOT", "IRON_HELMET",
"OBSIDIAN", "RED_ROSE", "SNOW_BLOCK", "STRING", "SULPHUR",
"TNT", "YELLOW_FLOWER" };
conf.setProperty("prizes", defaultWins);
changed = true;
}
if (conf.getProperty("entryfee") == null) {
conf.setProperty("entryfee", 5);
changed = true;
}
if (conf.getProperty("prizemoney_fixed") == null) {
conf.setProperty("prizemoney_fixed", 0);
changed = true;
}
- if (conf.getProperty("prizemoey_perplayer") == null) {
- conf.setProperty("prizemoey_perplayer", 5);
+ if (conf.getProperty("prizemoney_perplayer") == null) {
+ conf.setProperty("prizemoney_perplayer", 5);
changed = true;
}
// config has been changed: save it
if (changed) {
log.info("[SimpleSpleef] Updating configuration file to new version.");
conf.save();
}
// load language files
if (!enFile.exists()) {
log.info("[SimpleSpleef] Creating new English language file.");
try {
FileWriter fw = new FileWriter(enFile);
fw.write("teamred: red\n"
+ "teamblue: blue\n"
+ "announce_noteam: '[PLAYER] has announced a new spleef game - you are all invited to\n"
+ " join!'\n"
+ "announce_team: '[PLAYER] has announced a new spleef game in the team [TEAM] - you\n"
+ " are all invited to join!'\n"
+ "announce_join: '[PLAYER] joined spleef!'\n"
+ "announce_team_join: '[PLAYER] joined spleef in team [TEAM].'\n"
+ "announce_team_change: '[PLAYER] changed to to team [TEAM].'\n"
+ "announce_leave: '[PLAYER] left the game - what a whimp!'\n"
+ "announce_player_logout: Player has left the game - whimp!\n"
+ "announce_dropped_out: Player [PLAYER] dropped into the water and out of the game.\n"
+ "announce_won: Player [PLAYER] has won the spleef game. Congratulations!\n"
+ "announce_won_team: 'Team [TEAM] has won the spleef game. Congratulations go to: [PLAYERS].'\n"
+ "announce_grats: 'You have won a prize: [WIN].'\n"
+ "announce_grats_all: '[PLAYER] has won a prize: [WIN].'\n"
+ "announce_gamestopped: Game has been stopped, please stay where you are.\n"
+ "announce_gamedeleted: Game was stopped and deleted.\n"
+ "countdown_start: Starting spleef game. There can only be one!\n"
+ "countdown_prefix: 'Spleef: '\n"
+ "countdown_go: Goooo!\n"
+ "countdown_interrupted: Countdown interrupted.\n"
+ "list: 'Dog-eats-dog game with following players: [PLAYERS].'\n"
+ "list_team: 'Team [TEAM]: [PLAYERS].'\n"
+ "list_nospleefers: No spleefers present.\n"
+ "err_game_nospleefers: There are no spleefers in the game!\n"
+ "err_gameinprogress: A game is already in progress! Please wait until it is finished.\n"
+ "err_gameteamgame: The current game has been declared a team game. Please join one of the teams.\n"
+ "err_minplayers_team: There must be at least one player in each team!\n"
+ "err_leave_notjoined: You have not joined the game anyway.\n"
+ "err_gameinprogress_short: A game is already in progress!\n"
+ "err_gamenotinprogress: There is no game in progress!\n"
+ "err_joined_already: You have already joined the game.\n"
+ "err_minplayers: A minimum of two players is needed to start the game!\n"
+ "err_gamenoteamgame: The current game has not been declared a team game. Please join by typing /spleef join.\n"
+ "err_joined_team_already: You have already joined this team.\n"
+ "fee_entry: You paid an entry fee of [MONEY].\n"
+ "fee_entry_err: Insufficient funds - you need at least [MONEY].\n"
+ "prize_money: Player [PLAYER] has won [MONEY] of prize money.\n"
+ "prize_money_team: Each member of the team received [MONEY] prize money.\n");
fw.close();
} catch (Exception e) {
log.warning("[SimpleSpleef] Could not write lang_en.yml: "
+ e.getMessage());
}
}
if (!deFile.exists()) {
log.info("[SimpleSpleef] Creating new German language file.");
try {
FileWriter fw = new FileWriter(deFile);
fw.write("teamred: rot\n"
+ "teamblue: blau\n"
+ "announce_noteam: '[PLAYER] hat ein neues Spleef-Spiel angekündigt - kommt alle zur\n"
+ " Arena!'\n"
+ "announce_team: '[PLAYER] hat ein neues Spleef-Spiel im Team [TEAM] angekündigt - kommt\n"
+ " alle zur Arena!'\n"
+ "announce_join: '[PLAYER] spielt Spleef mit!'\n"
+ "announce_team_join: '[PLAYER] spielt Spleef im Team [TEAM].'\n"
+ "announce_team_change: '[PLAYER] wechselt zum Spleef-Team [TEAM].'\n"
+ "announce_leave: '[PLAYER] verlässt das Spleef-Spiel. So ein Feigling!'\n"
+ "announce_player_logout: '[PLAYER] hat das Spleef-Spiel verlassen - Feigling!'\n"
+ "announce_dropped_out: '[PLAYER] ist ausgeschieden!'\n"
+ "announce_won: '[PLAYER] hat gewonnen. Herzlichen Glückwunsch!'\n"
+ "announce_won_team: 'Team [TEAM] hat gewonnen. Herzlichen Glückwunsch an: [PLAYERS].'\n"
+ "announce_grats: 'Herzlichen Glückwunsch zum Sieg! Du hast gewonnen: [WIN].'\n"
+ "announce_grats_all: '[PLAYER] hat einen Preis gewonnen: [WIN].'\n"
+ "announce_gamestopped: Spleef-Spiel wurde unterbrochen - bitte alle Stehenbleiben!\n"
+ "announce_gamedeleted: Spleef-Spiel wurde gestoppt und gelöscht!\n"
+ "countdown_start: 'Starte Spleef-Spiel: Es kann nur einen geben!'\n"
+ "countdown_prefix: 'Spleef: '\n"
+ "countdown_go: LOOOOOS!\n"
+ "countdown_interrupted: Countdown abgebrochen.\n"
+ "list: 'Jeder-gegen-jeden-Spiel mit folgenden Spielern: [PLAYERS].'\n"
+ "list_team: 'Team [TEAM]: [PLAYERS].'\n"
+ "list_nospleefers: Keine Spleefer im Spiel.\n"
+ "err_game_nospleefers: Es gibt keine Spleefer im Spiel\n"
+ "err_gameinprogress: Es läuft gerade ein Spiel! Bitte warte, bis es beendet ist.\n"
+ "err_gameteamgame: Das aktuelle Spiel ist ein Team-Spiel. Bitte melde dich in einem der beiden Teams an!\n"
+ "err_minplayers_team: In beiden Teams muss sich mindestens ein Spieler befinden!\n"
+ "err_leave_notjoined: Du spielst ja sowieso nicht mit!\n"
+ "err_gameinprogress_short: Das Spiel läuft bereits!\n"
+ "err_gamenotinprogress: Es läuft gerade kein Spleef-Spiel!\n"
+ "err_joined_already: Du bist bereits im Spiel angemeldet!\n"
+ "err_minplayers: Mindestens zwei Spleefer müssen am Spiel teilnehmen!\n"
+ "err_gamenoteamgame: Das aktuelle Spiel ist nicht als Team-Spiel angekündigt. Bitte melde dich einfach mit /spleef join an.\n"
+ "err_joined_team_already: Du bist bereits in diesem Team angemeldet!\n"
+ "fee_entry: Du hast ein Startgeld von [MONEY] gezahlt.\n"
+ "fee_entry_err: Du hast nicht die benötigten [MONEY] Startgeld.\n"
+ "prize_money: Spieler [PLAYER] hat ein Preisgeld in Höhe von [MONEY] gewonnen.\n"
+ "prize_money_team: Jeder Spieler des Teams hat ein Preisgeld in Höhe von [MONEY] gewonnen.\n");
fw.close();
} catch (Exception e) {
log.warning("[SimpleSpleef] Could not write lang_de.yml: "
+ e.getMessage());
}
}
// Now load configuration file
langFile = new File("plugins" + File.separator + "SimpleSpleef",
"lang_" + conf.getString("lang", "en") + ".yml");
ll = new Configuration(langFile);
ll.load();
}
/**
* called on enable
*/
public void onEnable() {
init(); // load init
if (!createGame()) { // try to create game
log.warning("[SimpleSpleef] could not correctly initialize plugin. Disabling it.");
return;
}
// set server
Server = getServer();
// register enable events from other plugins
PluginListener = new PluginListener();
getServer().getPluginManager().registerEvent(Event.Type.PLUGIN_ENABLE,
PluginListener, Priority.Monitor, this);
// Register our events
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_MOVE, playerListener,
Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, playerListener,
Priority.Normal, this);
PluginDescriptionFile pdfFile = this.getDescription();
System.out.println("[SimpleSpleef] " + pdfFile.getName() + " version "
+ pdfFile.getVersion() + " is enabled!");
}
/**
* tries to create a game
*
* @return true, if correctly created, false if there was a problem
*/
protected boolean createGame() {
// try to load list of wins
List<String> wins = conf.getStringList("prizes", null);
// list empty - should not happen, but might be...
if (wins == null) {
log.warning("[SimpleSpleef] Could not load prize list - it was empty or malformed.");
return false;
}
// load materials into list
LinkedList<Material> winsMat = new LinkedList<Material>();
// iterate through string and transform them to a material
for (String win : wins) {
Material m = Material.getMaterial(win);
if (m == null)
log.warning("[SimpleSpleef] Could not find a block or material called "
+ win + ". Ignoring it!");
else
winsMat.add(m); // add to list
}
// check, if list is still empty after transformation
if (winsMat.isEmpty()) {
log.warning("[SimpleSpleef] Could not load prize list - it was empty in the end.");
return false;
}
// turn list into array
Material[] randomWins = new Material[winsMat.size()];
randomWins = winsMat.toArray(randomWins);
// ok, now load game
game = new SimpleSpleefGame(this, randomWins);
playerListener = new SimpleSpleefPlayerListener(this, game);
return true;
}
/**
* Catch commands
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd,
String commandLabel, String[] args) {
// ignore commands if disabled
if (game == null)
return true;
String command = cmd.getName();
// only players
if (!(sender instanceof Player))
return false;
Player player = (Player) sender;
// command without any parameters
if (args.length != 1) {
return false;
} else {
command = args[0];
// check aliases
if (command.equalsIgnoreCase("blue"))
command = "1"; // alias for team 1
else if (command.equalsIgnoreCase("red"))
command = "2"; // alias for team 2
// check actual commands
if (command.equalsIgnoreCase("join")) {
if (!checkPermission(player, "play"))
return true; // check permission
game.addPlayer(player, null); // join no-team spleef
} else if (command.equalsIgnoreCase("1")) {
if (!checkPermission(player, "team"))
return true; // check permission
game.addPlayer(player, 1); // add player to team 1
} else if (command.equalsIgnoreCase("2")) {
if (!checkPermission(player, "team"))
return true; // check permission
game.addPlayer(player, 2); // add player to team 2
} else if (command.equalsIgnoreCase("leave")) {
if (!checkPermission(player, "leave"))
return true; // check permission
game.leavePlayer(player); // player leaves spleef
} else if (command.equalsIgnoreCase("list")) {
if (!checkPermission(player, "list"))
return true; // check permission
game.listSpleefers(player); // print a list of
// spleefers
} else if (command.equalsIgnoreCase("start")) {
if (!checkPermission(player, "start"))
return true; // check permission
game.startGame(player); // start a game
} else if (command.equalsIgnoreCase("stop")) {
if (!checkPermission(player, "stop"))
return true; // check permission
game.stopGame(player); // stop a game
} else if (command.equalsIgnoreCase("delete")) {
if (!checkPermission(player, "delete"))
return true; // check permission
game.deleteGame(player); // delete a game
} else
return false;
}
return true;
}
/**
* helper method to check permission
*
* @param player
* player to check
* @param permission
* String of part of permission like "join"
* @return
*/
private boolean checkPermission(Player player, String permission) {
// no permissions set - everybody may do everything
if (SimpleSpleef.Permissions == null)
return true;
// if op, allow!
if (player.isOp())
return true;
// permission checked
if (SimpleSpleef.Permissions.has(player, "simplespleef." + permission)) {
// inform player
player.sendMessage(ChatColor.RED
+ "You do not have the permission to use this command!");
return true;
}
// all others may not do this!
return false;
}
/**
* called on disable
*/
public void onDisable() {
PluginDescriptionFile pdfFile = this.getDescription();
System.out.println("[SimpleSpleef] " + pdfFile.getName() + " version "
+ pdfFile.getVersion() + " was disabled!");
}
}
| true | true | public void init() {
// create plugin dir, if needed
new File("plugins" + File.separator + "SimpleSpleef" + File.separator)
.mkdirs();
// check files
File confFile = new File("plugins" + File.separator + "SimpleSpleef",
"SimpleSpleef.yml");
File enFile = new File("plugins" + File.separator + "SimpleSpleef",
"lang_en.yml");
File deFile = new File("plugins" + File.separator + "SimpleSpleef",
"lang_de.yml");
File langFile;
// load configuration
conf = new Configuration(confFile);
// check file
if (!confFile.exists()) {
log.info("[SimpleSpleef] Creating new configuration file.");
try {
FileWriter fw = new FileWriter(confFile);
fw.write("lang: en\ngiveprizes: true\nprizes:\n- APPLE\n- BED\n- BOOK\n- CAKE\n- CHAINMAIL_HELMET\n- CLAY_BALL\n- COMPASS\n- COOKED_FISH\n- DIAMOND\n- FLINT_AND_STEEL\n- GOLD_INGOT\n- GLOWSTONE\n- GOLD_HELMET\n- INK_SACK\n- IRON_INGOT\n- IRON_HELMET\n- OBSIDIAN\n- RED_ROSE\n- SNOW_BLOCK\n- STRING\n- SULPHUR\n- TNT\n- YELLOW_FLOWER\n");
fw.close();
} catch (Exception e) {
log.warning("[SimpleSpleef] Could not write SimpleSpleef.yml: "
+ e.getMessage());
}
}
conf.load(); // load conf file
// check config file
boolean changed = false; // flag to set config change
// new elements
if (conf.getProperty("giveprizes") == null) { // no giveprizes property
// exists
conf.setProperty("giveprizes", true);
changed = true;
} else if (conf.getProperty("prices") != null) { // change prices to
// giveprizes
conf.setProperty("giveprizes", conf.getBoolean("prices", true));
conf.removeProperty("prices"); // delete property
changed = true;
}
if (conf.getProperty("prizes") == null) { // define default wins
String[] defaultWins = { "APPLE", "BED", "BOOK", "CAKE",
"CHAINMAIL_HELMET", "CLAY_BALL", "COMPASS", "COOKED_FISH",
"DIAMOND", "FLINT_AND_STEEL", "GOLD_INGOT", "GLOWSTONE",
"GOLD_HELMET", "INK_SACK", "IRON_INGOT", "IRON_HELMET",
"OBSIDIAN", "RED_ROSE", "SNOW_BLOCK", "STRING", "SULPHUR",
"TNT", "YELLOW_FLOWER" };
conf.setProperty("prizes", defaultWins);
changed = true;
}
if (conf.getProperty("entryfee") == null) {
conf.setProperty("entryfee", 5);
changed = true;
}
if (conf.getProperty("prizemoney_fixed") == null) {
conf.setProperty("prizemoney_fixed", 0);
changed = true;
}
if (conf.getProperty("prizemoey_perplayer") == null) {
conf.setProperty("prizemoey_perplayer", 5);
changed = true;
}
// config has been changed: save it
if (changed) {
log.info("[SimpleSpleef] Updating configuration file to new version.");
conf.save();
}
// load language files
if (!enFile.exists()) {
log.info("[SimpleSpleef] Creating new English language file.");
try {
FileWriter fw = new FileWriter(enFile);
fw.write("teamred: red\n"
+ "teamblue: blue\n"
+ "announce_noteam: '[PLAYER] has announced a new spleef game - you are all invited to\n"
+ " join!'\n"
+ "announce_team: '[PLAYER] has announced a new spleef game in the team [TEAM] - you\n"
+ " are all invited to join!'\n"
+ "announce_join: '[PLAYER] joined spleef!'\n"
+ "announce_team_join: '[PLAYER] joined spleef in team [TEAM].'\n"
+ "announce_team_change: '[PLAYER] changed to to team [TEAM].'\n"
+ "announce_leave: '[PLAYER] left the game - what a whimp!'\n"
+ "announce_player_logout: Player has left the game - whimp!\n"
+ "announce_dropped_out: Player [PLAYER] dropped into the water and out of the game.\n"
+ "announce_won: Player [PLAYER] has won the spleef game. Congratulations!\n"
+ "announce_won_team: 'Team [TEAM] has won the spleef game. Congratulations go to: [PLAYERS].'\n"
+ "announce_grats: 'You have won a prize: [WIN].'\n"
+ "announce_grats_all: '[PLAYER] has won a prize: [WIN].'\n"
+ "announce_gamestopped: Game has been stopped, please stay where you are.\n"
+ "announce_gamedeleted: Game was stopped and deleted.\n"
+ "countdown_start: Starting spleef game. There can only be one!\n"
+ "countdown_prefix: 'Spleef: '\n"
+ "countdown_go: Goooo!\n"
+ "countdown_interrupted: Countdown interrupted.\n"
+ "list: 'Dog-eats-dog game with following players: [PLAYERS].'\n"
+ "list_team: 'Team [TEAM]: [PLAYERS].'\n"
+ "list_nospleefers: No spleefers present.\n"
+ "err_game_nospleefers: There are no spleefers in the game!\n"
+ "err_gameinprogress: A game is already in progress! Please wait until it is finished.\n"
+ "err_gameteamgame: The current game has been declared a team game. Please join one of the teams.\n"
+ "err_minplayers_team: There must be at least one player in each team!\n"
+ "err_leave_notjoined: You have not joined the game anyway.\n"
+ "err_gameinprogress_short: A game is already in progress!\n"
+ "err_gamenotinprogress: There is no game in progress!\n"
+ "err_joined_already: You have already joined the game.\n"
+ "err_minplayers: A minimum of two players is needed to start the game!\n"
+ "err_gamenoteamgame: The current game has not been declared a team game. Please join by typing /spleef join.\n"
+ "err_joined_team_already: You have already joined this team.\n"
+ "fee_entry: You paid an entry fee of [MONEY].\n"
+ "fee_entry_err: Insufficient funds - you need at least [MONEY].\n"
+ "prize_money: Player [PLAYER] has won [MONEY] of prize money.\n"
+ "prize_money_team: Each member of the team received [MONEY] prize money.\n");
fw.close();
} catch (Exception e) {
log.warning("[SimpleSpleef] Could not write lang_en.yml: "
+ e.getMessage());
}
}
if (!deFile.exists()) {
log.info("[SimpleSpleef] Creating new German language file.");
try {
FileWriter fw = new FileWriter(deFile);
fw.write("teamred: rot\n"
+ "teamblue: blau\n"
+ "announce_noteam: '[PLAYER] hat ein neues Spleef-Spiel angekündigt - kommt alle zur\n"
+ " Arena!'\n"
+ "announce_team: '[PLAYER] hat ein neues Spleef-Spiel im Team [TEAM] angekündigt - kommt\n"
+ " alle zur Arena!'\n"
+ "announce_join: '[PLAYER] spielt Spleef mit!'\n"
+ "announce_team_join: '[PLAYER] spielt Spleef im Team [TEAM].'\n"
+ "announce_team_change: '[PLAYER] wechselt zum Spleef-Team [TEAM].'\n"
+ "announce_leave: '[PLAYER] verlässt das Spleef-Spiel. So ein Feigling!'\n"
+ "announce_player_logout: '[PLAYER] hat das Spleef-Spiel verlassen - Feigling!'\n"
+ "announce_dropped_out: '[PLAYER] ist ausgeschieden!'\n"
+ "announce_won: '[PLAYER] hat gewonnen. Herzlichen Glückwunsch!'\n"
+ "announce_won_team: 'Team [TEAM] hat gewonnen. Herzlichen Glückwunsch an: [PLAYERS].'\n"
+ "announce_grats: 'Herzlichen Glückwunsch zum Sieg! Du hast gewonnen: [WIN].'\n"
+ "announce_grats_all: '[PLAYER] hat einen Preis gewonnen: [WIN].'\n"
+ "announce_gamestopped: Spleef-Spiel wurde unterbrochen - bitte alle Stehenbleiben!\n"
+ "announce_gamedeleted: Spleef-Spiel wurde gestoppt und gelöscht!\n"
+ "countdown_start: 'Starte Spleef-Spiel: Es kann nur einen geben!'\n"
+ "countdown_prefix: 'Spleef: '\n"
+ "countdown_go: LOOOOOS!\n"
+ "countdown_interrupted: Countdown abgebrochen.\n"
+ "list: 'Jeder-gegen-jeden-Spiel mit folgenden Spielern: [PLAYERS].'\n"
+ "list_team: 'Team [TEAM]: [PLAYERS].'\n"
+ "list_nospleefers: Keine Spleefer im Spiel.\n"
+ "err_game_nospleefers: Es gibt keine Spleefer im Spiel\n"
+ "err_gameinprogress: Es läuft gerade ein Spiel! Bitte warte, bis es beendet ist.\n"
+ "err_gameteamgame: Das aktuelle Spiel ist ein Team-Spiel. Bitte melde dich in einem der beiden Teams an!\n"
+ "err_minplayers_team: In beiden Teams muss sich mindestens ein Spieler befinden!\n"
+ "err_leave_notjoined: Du spielst ja sowieso nicht mit!\n"
+ "err_gameinprogress_short: Das Spiel läuft bereits!\n"
+ "err_gamenotinprogress: Es läuft gerade kein Spleef-Spiel!\n"
+ "err_joined_already: Du bist bereits im Spiel angemeldet!\n"
+ "err_minplayers: Mindestens zwei Spleefer müssen am Spiel teilnehmen!\n"
+ "err_gamenoteamgame: Das aktuelle Spiel ist nicht als Team-Spiel angekündigt. Bitte melde dich einfach mit /spleef join an.\n"
+ "err_joined_team_already: Du bist bereits in diesem Team angemeldet!\n"
+ "fee_entry: Du hast ein Startgeld von [MONEY] gezahlt.\n"
+ "fee_entry_err: Du hast nicht die benötigten [MONEY] Startgeld.\n"
+ "prize_money: Spieler [PLAYER] hat ein Preisgeld in Höhe von [MONEY] gewonnen.\n"
+ "prize_money_team: Jeder Spieler des Teams hat ein Preisgeld in Höhe von [MONEY] gewonnen.\n");
fw.close();
} catch (Exception e) {
log.warning("[SimpleSpleef] Could not write lang_de.yml: "
+ e.getMessage());
}
}
// Now load configuration file
langFile = new File("plugins" + File.separator + "SimpleSpleef",
"lang_" + conf.getString("lang", "en") + ".yml");
ll = new Configuration(langFile);
ll.load();
}
| public void init() {
// create plugin dir, if needed
new File("plugins" + File.separator + "SimpleSpleef" + File.separator)
.mkdirs();
// check files
File confFile = new File("plugins" + File.separator + "SimpleSpleef",
"SimpleSpleef.yml");
File enFile = new File("plugins" + File.separator + "SimpleSpleef",
"lang_en.yml");
File deFile = new File("plugins" + File.separator + "SimpleSpleef",
"lang_de.yml");
File langFile;
// load configuration
conf = new Configuration(confFile);
// check file
if (!confFile.exists()) {
log.info("[SimpleSpleef] Creating new configuration file.");
try {
FileWriter fw = new FileWriter(confFile);
fw.write("lang: en\ngiveprizes: true\nprizes:\n- APPLE\n- BED\n- BOOK\n- CAKE\n- CHAINMAIL_HELMET\n- CLAY_BALL\n- COMPASS\n- COOKED_FISH\n- DIAMOND\n- FLINT_AND_STEEL\n- GOLD_INGOT\n- GLOWSTONE\n- GOLD_HELMET\n- INK_SACK\n- IRON_INGOT\n- IRON_HELMET\n- OBSIDIAN\n- RED_ROSE\n- SNOW_BLOCK\n- STRING\n- SULPHUR\n- TNT\n- YELLOW_FLOWER\n");
fw.close();
} catch (Exception e) {
log.warning("[SimpleSpleef] Could not write SimpleSpleef.yml: "
+ e.getMessage());
}
}
conf.load(); // load conf file
// check config file
boolean changed = false; // flag to set config change
// new elements
if (conf.getProperty("giveprizes") == null) { // no giveprizes property
// exists
conf.setProperty("giveprizes", true);
changed = true;
} else if (conf.getProperty("prices") != null) { // change prices to
// giveprizes
conf.setProperty("giveprizes", conf.getBoolean("prices", true));
conf.removeProperty("prices"); // delete property
changed = true;
}
if (conf.getProperty("prizes") == null) { // define default wins
String[] defaultWins = { "APPLE", "BED", "BOOK", "CAKE",
"CHAINMAIL_HELMET", "CLAY_BALL", "COMPASS", "COOKED_FISH",
"DIAMOND", "FLINT_AND_STEEL", "GOLD_INGOT", "GLOWSTONE",
"GOLD_HELMET", "INK_SACK", "IRON_INGOT", "IRON_HELMET",
"OBSIDIAN", "RED_ROSE", "SNOW_BLOCK", "STRING", "SULPHUR",
"TNT", "YELLOW_FLOWER" };
conf.setProperty("prizes", defaultWins);
changed = true;
}
if (conf.getProperty("entryfee") == null) {
conf.setProperty("entryfee", 5);
changed = true;
}
if (conf.getProperty("prizemoney_fixed") == null) {
conf.setProperty("prizemoney_fixed", 0);
changed = true;
}
if (conf.getProperty("prizemoney_perplayer") == null) {
conf.setProperty("prizemoney_perplayer", 5);
changed = true;
}
// config has been changed: save it
if (changed) {
log.info("[SimpleSpleef] Updating configuration file to new version.");
conf.save();
}
// load language files
if (!enFile.exists()) {
log.info("[SimpleSpleef] Creating new English language file.");
try {
FileWriter fw = new FileWriter(enFile);
fw.write("teamred: red\n"
+ "teamblue: blue\n"
+ "announce_noteam: '[PLAYER] has announced a new spleef game - you are all invited to\n"
+ " join!'\n"
+ "announce_team: '[PLAYER] has announced a new spleef game in the team [TEAM] - you\n"
+ " are all invited to join!'\n"
+ "announce_join: '[PLAYER] joined spleef!'\n"
+ "announce_team_join: '[PLAYER] joined spleef in team [TEAM].'\n"
+ "announce_team_change: '[PLAYER] changed to to team [TEAM].'\n"
+ "announce_leave: '[PLAYER] left the game - what a whimp!'\n"
+ "announce_player_logout: Player has left the game - whimp!\n"
+ "announce_dropped_out: Player [PLAYER] dropped into the water and out of the game.\n"
+ "announce_won: Player [PLAYER] has won the spleef game. Congratulations!\n"
+ "announce_won_team: 'Team [TEAM] has won the spleef game. Congratulations go to: [PLAYERS].'\n"
+ "announce_grats: 'You have won a prize: [WIN].'\n"
+ "announce_grats_all: '[PLAYER] has won a prize: [WIN].'\n"
+ "announce_gamestopped: Game has been stopped, please stay where you are.\n"
+ "announce_gamedeleted: Game was stopped and deleted.\n"
+ "countdown_start: Starting spleef game. There can only be one!\n"
+ "countdown_prefix: 'Spleef: '\n"
+ "countdown_go: Goooo!\n"
+ "countdown_interrupted: Countdown interrupted.\n"
+ "list: 'Dog-eats-dog game with following players: [PLAYERS].'\n"
+ "list_team: 'Team [TEAM]: [PLAYERS].'\n"
+ "list_nospleefers: No spleefers present.\n"
+ "err_game_nospleefers: There are no spleefers in the game!\n"
+ "err_gameinprogress: A game is already in progress! Please wait until it is finished.\n"
+ "err_gameteamgame: The current game has been declared a team game. Please join one of the teams.\n"
+ "err_minplayers_team: There must be at least one player in each team!\n"
+ "err_leave_notjoined: You have not joined the game anyway.\n"
+ "err_gameinprogress_short: A game is already in progress!\n"
+ "err_gamenotinprogress: There is no game in progress!\n"
+ "err_joined_already: You have already joined the game.\n"
+ "err_minplayers: A minimum of two players is needed to start the game!\n"
+ "err_gamenoteamgame: The current game has not been declared a team game. Please join by typing /spleef join.\n"
+ "err_joined_team_already: You have already joined this team.\n"
+ "fee_entry: You paid an entry fee of [MONEY].\n"
+ "fee_entry_err: Insufficient funds - you need at least [MONEY].\n"
+ "prize_money: Player [PLAYER] has won [MONEY] of prize money.\n"
+ "prize_money_team: Each member of the team received [MONEY] prize money.\n");
fw.close();
} catch (Exception e) {
log.warning("[SimpleSpleef] Could not write lang_en.yml: "
+ e.getMessage());
}
}
if (!deFile.exists()) {
log.info("[SimpleSpleef] Creating new German language file.");
try {
FileWriter fw = new FileWriter(deFile);
fw.write("teamred: rot\n"
+ "teamblue: blau\n"
+ "announce_noteam: '[PLAYER] hat ein neues Spleef-Spiel angekündigt - kommt alle zur\n"
+ " Arena!'\n"
+ "announce_team: '[PLAYER] hat ein neues Spleef-Spiel im Team [TEAM] angekündigt - kommt\n"
+ " alle zur Arena!'\n"
+ "announce_join: '[PLAYER] spielt Spleef mit!'\n"
+ "announce_team_join: '[PLAYER] spielt Spleef im Team [TEAM].'\n"
+ "announce_team_change: '[PLAYER] wechselt zum Spleef-Team [TEAM].'\n"
+ "announce_leave: '[PLAYER] verlässt das Spleef-Spiel. So ein Feigling!'\n"
+ "announce_player_logout: '[PLAYER] hat das Spleef-Spiel verlassen - Feigling!'\n"
+ "announce_dropped_out: '[PLAYER] ist ausgeschieden!'\n"
+ "announce_won: '[PLAYER] hat gewonnen. Herzlichen Glückwunsch!'\n"
+ "announce_won_team: 'Team [TEAM] hat gewonnen. Herzlichen Glückwunsch an: [PLAYERS].'\n"
+ "announce_grats: 'Herzlichen Glückwunsch zum Sieg! Du hast gewonnen: [WIN].'\n"
+ "announce_grats_all: '[PLAYER] hat einen Preis gewonnen: [WIN].'\n"
+ "announce_gamestopped: Spleef-Spiel wurde unterbrochen - bitte alle Stehenbleiben!\n"
+ "announce_gamedeleted: Spleef-Spiel wurde gestoppt und gelöscht!\n"
+ "countdown_start: 'Starte Spleef-Spiel: Es kann nur einen geben!'\n"
+ "countdown_prefix: 'Spleef: '\n"
+ "countdown_go: LOOOOOS!\n"
+ "countdown_interrupted: Countdown abgebrochen.\n"
+ "list: 'Jeder-gegen-jeden-Spiel mit folgenden Spielern: [PLAYERS].'\n"
+ "list_team: 'Team [TEAM]: [PLAYERS].'\n"
+ "list_nospleefers: Keine Spleefer im Spiel.\n"
+ "err_game_nospleefers: Es gibt keine Spleefer im Spiel\n"
+ "err_gameinprogress: Es läuft gerade ein Spiel! Bitte warte, bis es beendet ist.\n"
+ "err_gameteamgame: Das aktuelle Spiel ist ein Team-Spiel. Bitte melde dich in einem der beiden Teams an!\n"
+ "err_minplayers_team: In beiden Teams muss sich mindestens ein Spieler befinden!\n"
+ "err_leave_notjoined: Du spielst ja sowieso nicht mit!\n"
+ "err_gameinprogress_short: Das Spiel läuft bereits!\n"
+ "err_gamenotinprogress: Es läuft gerade kein Spleef-Spiel!\n"
+ "err_joined_already: Du bist bereits im Spiel angemeldet!\n"
+ "err_minplayers: Mindestens zwei Spleefer müssen am Spiel teilnehmen!\n"
+ "err_gamenoteamgame: Das aktuelle Spiel ist nicht als Team-Spiel angekündigt. Bitte melde dich einfach mit /spleef join an.\n"
+ "err_joined_team_already: Du bist bereits in diesem Team angemeldet!\n"
+ "fee_entry: Du hast ein Startgeld von [MONEY] gezahlt.\n"
+ "fee_entry_err: Du hast nicht die benötigten [MONEY] Startgeld.\n"
+ "prize_money: Spieler [PLAYER] hat ein Preisgeld in Höhe von [MONEY] gewonnen.\n"
+ "prize_money_team: Jeder Spieler des Teams hat ein Preisgeld in Höhe von [MONEY] gewonnen.\n");
fw.close();
} catch (Exception e) {
log.warning("[SimpleSpleef] Could not write lang_de.yml: "
+ e.getMessage());
}
}
// Now load configuration file
langFile = new File("plugins" + File.separator + "SimpleSpleef",
"lang_" + conf.getString("lang", "en") + ".yml");
ll = new Configuration(langFile);
ll.load();
}
|
diff --git a/plugins/src/kg/apc/jmeter/perfmon/PerfMonCollector.java b/plugins/src/kg/apc/jmeter/perfmon/PerfMonCollector.java
index b0595baf..7ab6da71 100644
--- a/plugins/src/kg/apc/jmeter/perfmon/PerfMonCollector.java
+++ b/plugins/src/kg/apc/jmeter/perfmon/PerfMonCollector.java
@@ -1,304 +1,307 @@
package kg.apc.jmeter.perfmon;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.*;
import kg.apc.jmeter.JMeterPluginsUtils;
import kg.apc.jmeter.reporters.LoadosophiaUploadingNotifier;
import kg.apc.jmeter.vizualizers.CorrectedResultCollector;
import kg.apc.perfmon.PerfMonMetricGetter;
import kg.apc.perfmon.client.Transport;
import kg.apc.perfmon.client.TransportFactory;
import kg.apc.perfmon.metrics.MetricParams;
import org.apache.jmeter.samplers.SampleEvent;
import org.apache.jmeter.samplers.SampleSaveConfiguration;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
/**
*
* @author APC
*/
public class PerfMonCollector
extends CorrectedResultCollector
implements Runnable, PerfMonSampleGenerator {
private static boolean autoGenerateFiles = false;
public static final long MEGABYTE = 1024L * 1024L;
private static final String PERFMON = "PerfMon";
private static final Logger log = LoggingManager.getLoggerForClass();
public static final String DATA_PROPERTY = "metricConnections";
private int interval;
private Thread workerThread;
private Map<Object, PerfMonAgentConnector> connectors = new HashMap<Object, PerfMonAgentConnector>();
private HashMap<String, Long> oldValues = new HashMap<String, Long>();
private static String autoFileBaseName = null;
private static int counter = 0;
private LoadosophiaUploadingNotifier perfMonNotifier = LoadosophiaUploadingNotifier.getInstance();
static {
autoGenerateFiles = (JMeterUtils.getPropDefault("forcePerfmonFile", "false")).trim().equalsIgnoreCase("true");
}
private static synchronized String getAutoFileName() {
String ret = "";
counter++;
if (autoFileBaseName == null) {
Calendar now = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd-HHmmss");
autoFileBaseName = "perfMon_" + formatter.format(now.getTime());
}
ret = ret + autoFileBaseName;
if (counter > 1) {
ret = ret + "_" + counter;
}
ret = ret + ".csv";
return ret;
}
public PerfMonCollector() {
// TODO: document it
interval = JMeterUtils.getPropDefault("jmeterPlugin.perfmon.interval", 1000);
}
public void setData(CollectionProperty rows) {
setProperty(rows);
}
public JMeterProperty getMetricSettings() {
return getProperty(DATA_PROPERTY);
}
@Override
public void sampleOccurred(SampleEvent event) {
// just dropping regular test samples
}
@Override
public synchronized void run() {
while (true) {
processConnectors();
try {
this.wait(interval);
} catch (InterruptedException ex) {
log.debug("Monitoring thread was interrupted", ex);
break;
}
}
}
@Override
public void testStarted(String host) {
//ensure the data will be saved
if (getProperty(FILENAME) == null || getProperty(FILENAME).getStringValue().trim().length() == 0) {
if (autoGenerateFiles) {
setupSaving(getAutoFileName());
} else {
try {
File tmpFile = File.createTempFile("perfmon_", ".jtl");
tmpFile.delete(); // required to have CSV header
setupSaving(tmpFile.getAbsolutePath());
} catch (IOException ex) {
log.info("PerfMon metrics will not be recorded! Please run the test with -JforcePerfmonFile=true", ex);
}
}
}
log.debug("PerfMon metrics will be stored in " + getPropertyAsString(FILENAME));
if (!getSaveConfig().saveAsXml() && getSaveConfig().saveFieldNames()) {
perfMonNotifier.addFile(getPropertyAsString(FILENAME));
} else {
log.warn("Perfmon file saving setting is not CSV with header line, cannot upload it to Loadosophia.org: " + getPropertyAsString(FILENAME));
}
initiateConnectors();
workerThread = new Thread(this);
workerThread.start();
super.testStarted(host);
}
private void setupSaving(String fileName) {
SampleSaveConfiguration config = getSaveConfig();
JMeterPluginsUtils.doBestCSVSetup(config);
setSaveConfig(config);
setFilename(fileName);
log.info("PerfMon metrics will be stored in " + new File(fileName).getAbsolutePath());
}
@Override
public void testEnded(String host) {
workerThread.interrupt();
shutdownConnectors();
//reset autoFileName for next test run
autoFileBaseName = null;
counter = 0;
super.testEnded(host);
}
private void initiateConnectors() {
oldValues.clear();
JMeterProperty prop = getMetricSettings();
connectors.clear();
if (!(prop instanceof CollectionProperty)) {
log.warn("Got unexpected property: " + prop);
return;
}
CollectionProperty rows = (CollectionProperty) prop;
for (int i = 0; i < rows.size(); i++) {
ArrayList<Object> row = (ArrayList<Object>) rows.get(i).getObjectValue();
String host = ((JMeterProperty) row.get(0)).getStringValue();
int port = ((JMeterProperty) row.get(1)).getIntValue();
String metric = ((JMeterProperty) row.get(2)).getStringValue();
String params = ((JMeterProperty) row.get(3)).getStringValue();
initiateConnector(host, port, i, metric, params);
}
Iterator<Object> it = connectors.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
try {
connectors.get(key).connect();
} catch (IOException ex) {
log.error("Error connecting to agent", ex);
connectors.put(key, new UnavailableAgentConnector(ex));
}
}
}
private void initiateConnector(String host, int port, int index, String metric, String params) {
InetSocketAddress addr = new InetSocketAddress(host, port);
String stringKey = addr.toString() + "#" + index;
// handle label parameter
MetricParams paramsParsed = MetricParams.createFromString(params);
String label;
if (paramsParsed.getLabel().isEmpty()) {
- label = host + " " + metric + " " + params;
+ label = host + " " + metric;
+ if(params != null && !params.isEmpty()) {
+ label = label + " " + params;
+ }
} else {
label = host + " " + metric + " " + paramsParsed.getLabel();
String[] tokens = params.split("(?<!\\\\)" + PerfMonMetricGetter.DVOETOCHIE);
params = "";
for (int i = 0; i < tokens.length; i++) {
if (!tokens[i].startsWith("label=")) {
if (params.length() != 0) {
params = params + PerfMonMetricGetter.DVOETOCHIE;
}
params = params + tokens[i];
}
}
}
try {
if (connectors.containsKey(addr)) {
connectors.get(addr).addMetric(metric, params, label);
} else {
PerfMonAgentConnector connector = getConnector(host, port);
connector.addMetric(metric, params, label);
if (connector instanceof OldAgentConnector) {
connectors.put(stringKey, connector);
} else {
connectors.put(addr, connector);
}
}
} catch (IOException e) {
log.error("Problems creating connector", e);
connectors.put(stringKey, new UnavailableAgentConnector(e));
}
}
protected PerfMonAgentConnector getConnector(String host, int port) throws IOException {
try {
log.debug("Trying new connector");
Transport transport = TransportFactory.getTransport(new InetSocketAddress(host, port));
NewAgentConnector conn = new NewAgentConnector();
conn.setTransport(transport);
return conn;
} catch (IOException e) {
log.debug("Using old connector");
return new OldAgentConnector(host, port);
}
}
private void shutdownConnectors() {
log.debug("Shutting down connectors");
Iterator<Object> it = connectors.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
final PerfMonAgentConnector conn = connectors.get(key);
log.debug("Shutting down " + conn.toString());
//Fix ConcurrentModificationException if more than one host
//connectors.remove(key);
it.remove();
conn.disconnect();
}
}
private void processConnectors() {
Iterator<Object> it = connectors.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
PerfMonAgentConnector connector = connectors.get(key);
try {
connector.generateSamples(this);
} catch (IOException e) {
log.error(e.getMessage());
connectors.put(key, new UnavailableAgentConnector(e));
}
}
}
//need floating point precision for memory and cpu
@Override
public void generateSample(double value, String label) {
if (value != AgentConnector.AGENT_ERROR) {
PerfMonSampleResult res = new PerfMonSampleResult();
res.setSampleLabel(label);
res.setValue(value);
res.setSuccessful(true);
SampleEvent e = new SampleEvent(res, PERFMON);
super.sampleOccurred(e);
}
}
@Override
public void generateErrorSample(String label, String errorMsg) {
PerfMonSampleResult res = new PerfMonSampleResult();
res.setSampleLabel(label);
res.setValue(-1L);
res.setResponseMessage(errorMsg);
res.setSuccessful(false);
SampleEvent e = new SampleEvent(res, PERFMON);
super.sampleOccurred(e);
log.error("Perfmon plugin error: " + errorMsg);
}
@Override
public void generate2Samples(long[] values, String label1, String label2) {
generate2Samples(values, label1, label2, 1d);
}
//float precision required for net io
@Override
public void generate2Samples(long[] values, String label1, String label2, double dividingFactor) {
if (oldValues.containsKey(label1) && oldValues.containsKey(label2)) {
generateSample(((double) (values[0] - oldValues.get(label1).longValue())) / dividingFactor, label1);
generateSample(((double) (values[1] - oldValues.get(label2).longValue())) / dividingFactor, label2);
}
oldValues.put(label1, new Long(values[0]));
oldValues.put(label2, new Long(values[1]));
}
}
| true | true | private void initiateConnector(String host, int port, int index, String metric, String params) {
InetSocketAddress addr = new InetSocketAddress(host, port);
String stringKey = addr.toString() + "#" + index;
// handle label parameter
MetricParams paramsParsed = MetricParams.createFromString(params);
String label;
if (paramsParsed.getLabel().isEmpty()) {
label = host + " " + metric + " " + params;
} else {
label = host + " " + metric + " " + paramsParsed.getLabel();
String[] tokens = params.split("(?<!\\\\)" + PerfMonMetricGetter.DVOETOCHIE);
params = "";
for (int i = 0; i < tokens.length; i++) {
if (!tokens[i].startsWith("label=")) {
if (params.length() != 0) {
params = params + PerfMonMetricGetter.DVOETOCHIE;
}
params = params + tokens[i];
}
}
}
try {
if (connectors.containsKey(addr)) {
connectors.get(addr).addMetric(metric, params, label);
} else {
PerfMonAgentConnector connector = getConnector(host, port);
connector.addMetric(metric, params, label);
if (connector instanceof OldAgentConnector) {
connectors.put(stringKey, connector);
} else {
connectors.put(addr, connector);
}
}
} catch (IOException e) {
log.error("Problems creating connector", e);
connectors.put(stringKey, new UnavailableAgentConnector(e));
}
}
| private void initiateConnector(String host, int port, int index, String metric, String params) {
InetSocketAddress addr = new InetSocketAddress(host, port);
String stringKey = addr.toString() + "#" + index;
// handle label parameter
MetricParams paramsParsed = MetricParams.createFromString(params);
String label;
if (paramsParsed.getLabel().isEmpty()) {
label = host + " " + metric;
if(params != null && !params.isEmpty()) {
label = label + " " + params;
}
} else {
label = host + " " + metric + " " + paramsParsed.getLabel();
String[] tokens = params.split("(?<!\\\\)" + PerfMonMetricGetter.DVOETOCHIE);
params = "";
for (int i = 0; i < tokens.length; i++) {
if (!tokens[i].startsWith("label=")) {
if (params.length() != 0) {
params = params + PerfMonMetricGetter.DVOETOCHIE;
}
params = params + tokens[i];
}
}
}
try {
if (connectors.containsKey(addr)) {
connectors.get(addr).addMetric(metric, params, label);
} else {
PerfMonAgentConnector connector = getConnector(host, port);
connector.addMetric(metric, params, label);
if (connector instanceof OldAgentConnector) {
connectors.put(stringKey, connector);
} else {
connectors.put(addr, connector);
}
}
} catch (IOException e) {
log.error("Problems creating connector", e);
connectors.put(stringKey, new UnavailableAgentConnector(e));
}
}
|
diff --git a/Slick/src/org/newdawn/slick/geom/Vector2f.java b/Slick/src/org/newdawn/slick/geom/Vector2f.java
index ab84b5f..e038734 100644
--- a/Slick/src/org/newdawn/slick/geom/Vector2f.java
+++ b/Slick/src/org/newdawn/slick/geom/Vector2f.java
@@ -1,346 +1,346 @@
package org.newdawn.slick.geom;
import org.newdawn.slick.util.FastTrig;
/**
* A two dimensional vector
*
* @author Kevin Glass
*/
public strictfp class Vector2f {
/** The x component of this vector */
public float x;
/** The y component of this vector */
public float y;
/**
* Create an empty vector
*/
public Vector2f() {
}
/**
* Create a new vector based on an angle
*
* @param theta The angle of the vector in degrees
*/
public Vector2f(double theta) {
x = 1;
y = 0;
setTheta(theta);
}
/**
* Calculate the components of the vectors based on a angle
*
* @param theta The angle to calculate the components from (in degrees)
*/
public void setTheta(double theta) {
// Next lines are to prevent numbers like -1.8369701E-16
// when working with negative numbers
if ((theta < -360) || (theta > 360)) {
theta = theta % 360;
}
if (theta < 0) {
theta = 360 + theta;
}
double oldTheta = getTheta();
if ((theta < -360) || (theta > 360)) {
oldTheta = oldTheta % 360;
}
if (theta < 0) {
oldTheta = 360 + oldTheta;
}
float len = length();
- x = -len * (float) FastTrig.cos(StrictMath.toRadians(theta));
+ x = len * (float) FastTrig.cos(StrictMath.toRadians(theta));
y = len * (float) FastTrig.sin(StrictMath.toRadians(theta));
// x = x / (float) FastTrig.cos(StrictMath.toRadians(oldTheta))
// * (float) FastTrig.cos(StrictMath.toRadians(theta));
// y = x / (float) FastTrig.sin(StrictMath.toRadians(oldTheta))
// * (float) FastTrig.sin(StrictMath.toRadians(theta));
}
/**
* Adjust this vector by a given angle
*
* @param theta
* The angle to adjust the angle by (in degrees)
* @return This vector - useful for chaining operations
*
*/
public Vector2f add(double theta) {
setTheta(getTheta() + theta);
return this;
}
/**
* Adjust this vector by a given angle
*
* @param theta The angle to adjust the angle by (in degrees)
* @return This vector - useful for chaining operations
*/
public Vector2f sub(double theta) {
setTheta(getTheta() - theta);
return this;
}
/**
* Get the angle this vector is at
*
* @return The angle this vector is at (in degrees)
*/
public double getTheta() {
double theta = StrictMath.toDegrees(StrictMath.atan2(y, x));
if ((theta < -360) || (theta > 360)) {
theta = theta % 360;
}
if (theta < 0) {
theta = 360 + theta;
}
return theta;
}
/**
* Get the x component
*
* @return The x component
*/
public float getX() {
return x;
}
/**
* Get the y component
*
* @return The y component
*/
public float getY() {
return y;
}
/**
* Create a new vector based on another
*
* @param other The other vector to copy into this one
*/
public Vector2f(Vector2f other) {
this(other.getX(),other.getY());
}
/**
* Create a new vector
*
* @param x The x component to assign
* @param y The y component to assign
*/
public Vector2f(float x, float y) {
this.x = x;
this.y = y;
}
/**
* Set the value of this vector
*
* @param other The values to set into the vector
*/
public void set(Vector2f other) {
set(other.getX(),other.getY());
}
/**
* Dot this vector against another
*
* @param other The other vector dot agianst
* @return The dot product of the two vectors
*/
public float dot(Vector2f other) {
return (x * other.getX()) + (y * other.getY());
}
/**
* Set the values in this vector
*
* @param x The x component to set
* @param y The y component to set
* @return This vector - useful for chaning operations
*/
public Vector2f set(float x, float y) {
this.x = x;
this.y = y;
return this;
}
/**
* Negate this vector
*
* @return A copy of this vector negated
*/
public Vector2f negate() {
return new Vector2f(-x, -y);
}
/**
* Negate this vector without creating a new copy
*
* @return This vector - useful for chaning operations
*/
public Vector2f negateLocal() {
x = -x;
y = -y;
return this;
}
/**
* Add a vector to this vector
*
* @param v The vector to add
* @return This vector - useful for chaning operations
*/
public Vector2f add(Vector2f v)
{
x += v.getX();
y += v.getY();
return this;
}
/**
* Subtract a vector from this vector
*
* @param v The vector subtract
* @return This vector - useful for chaining operations
*/
public Vector2f sub(Vector2f v)
{
x -= v.getX();
y -= v.getY();
return this;
}
/**
* Scale this vector by a value
*
* @param a The value to scale this vector by
* @return This vector - useful for chaining operations
*/
public Vector2f scale(float a)
{
x *= a;
y *= a;
return this;
}
/**
* Normalise the vector
*
* @return This vector - useful for chaning operations
*/
public Vector2f normalise() {
float l = length();
x /= l;
y /= l;
return this;
}
/**
* The normal of the vector
*
* @return A unit vector with the same direction as the vector
*/
public Vector2f getNormal() {
Vector2f cp = copy();
cp.normalise();
return cp;
}
/**
* The length of the vector squared
*
* @return The length of the vector squared
*/
public float lengthSquared() {
return (x * x) + (y * y);
}
/**
* Get the length of this vector
*
* @return The length of this vector
*/
public float length()
{
return (float) Math.sqrt(lengthSquared());
}
/**
* Project this vector onto another
*
* @param b The vector to project onto
* @param result The projected vector
*/
public void projectOntoUnit(Vector2f b, Vector2f result) {
float dp = b.dot(this);
result.x = dp * b.getX();
result.y = dp * b.getY();
}
/**
* Return a copy of this vector
*
* @return The new instance that copies this vector
*/
public Vector2f copy() {
return new Vector2f(x,y);
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return "[Vector2f "+x+","+y+" ("+length()+")]";
}
/**
* Get the distance from this point to another
*
* @param other The other point we're measuring to
* @return The distance to the other point
*/
public float distance(Vector2f other) {
float dx = other.getX() - getX();
float dy = other.getY() - getY();
return (float) Math.sqrt((dx*dx)+(dy*dy));
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return 997 * ((int)x) ^ 991 * ((int)y); //large primes!
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object other) {
if (other instanceof Vector2f) {
Vector2f o = ((Vector2f) other);
return (o.x == x) && (o.y == y);
}
return false;
}
}
| true | true | public void setTheta(double theta) {
// Next lines are to prevent numbers like -1.8369701E-16
// when working with negative numbers
if ((theta < -360) || (theta > 360)) {
theta = theta % 360;
}
if (theta < 0) {
theta = 360 + theta;
}
double oldTheta = getTheta();
if ((theta < -360) || (theta > 360)) {
oldTheta = oldTheta % 360;
}
if (theta < 0) {
oldTheta = 360 + oldTheta;
}
float len = length();
x = -len * (float) FastTrig.cos(StrictMath.toRadians(theta));
y = len * (float) FastTrig.sin(StrictMath.toRadians(theta));
// x = x / (float) FastTrig.cos(StrictMath.toRadians(oldTheta))
// * (float) FastTrig.cos(StrictMath.toRadians(theta));
// y = x / (float) FastTrig.sin(StrictMath.toRadians(oldTheta))
// * (float) FastTrig.sin(StrictMath.toRadians(theta));
}
| public void setTheta(double theta) {
// Next lines are to prevent numbers like -1.8369701E-16
// when working with negative numbers
if ((theta < -360) || (theta > 360)) {
theta = theta % 360;
}
if (theta < 0) {
theta = 360 + theta;
}
double oldTheta = getTheta();
if ((theta < -360) || (theta > 360)) {
oldTheta = oldTheta % 360;
}
if (theta < 0) {
oldTheta = 360 + oldTheta;
}
float len = length();
x = len * (float) FastTrig.cos(StrictMath.toRadians(theta));
y = len * (float) FastTrig.sin(StrictMath.toRadians(theta));
// x = x / (float) FastTrig.cos(StrictMath.toRadians(oldTheta))
// * (float) FastTrig.cos(StrictMath.toRadians(theta));
// y = x / (float) FastTrig.sin(StrictMath.toRadians(oldTheta))
// * (float) FastTrig.sin(StrictMath.toRadians(theta));
}
|
diff --git a/src/server/j2se/com/sun/sgs/impl/kernel/TaskHandler.java b/src/server/j2se/com/sun/sgs/impl/kernel/TaskHandler.java
index 164855dae..a0d464f6a 100644
--- a/src/server/j2se/com/sun/sgs/impl/kernel/TaskHandler.java
+++ b/src/server/j2se/com/sun/sgs/impl/kernel/TaskHandler.java
@@ -1,146 +1,146 @@
package com.sun.sgs.impl.kernel;
import com.sun.sgs.app.TransactionNotActiveException;
import com.sun.sgs.impl.service.transaction.TransactionCoordinator;
import com.sun.sgs.impl.service.transaction.TransactionHandle;
import com.sun.sgs.impl.util.LoggerWrapper;
import com.sun.sgs.kernel.KernelRunnable;
import com.sun.sgs.kernel.TaskOwner;
import com.sun.sgs.service.Transaction;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This utility class provided by the kernel is used to run tasks. Unlike the
* scheduler, which accepts tasks to run at some point in the future,
* <code>TaskHandler</code> is the facility that actually invokes tasks.
* It is needed to set the owner of tasks and create transactional context
* for transactional tasks.
* <p>
* Note that this class enforces a singleton pattern. While anyone may
* use this class to create transactional context, only with a reference
* to the single instance may the owner of a task be changed, and only
* trusted components are provided with this reference. Most components
* outside the kernel will use the <code>TaskScheduler</code> or the
* <code>TaskService</code> to run tasks.
*
* @since 1.0
* @author Seth Proctor
*/
public final class TaskHandler {
// logger for this class
private static final LoggerWrapper logger =
new LoggerWrapper(Logger.getLogger(TaskHandler.class.getName()));
// the single instance used for creating transactions
private static TransactionCoordinator transactionCoordinator = null;
/**
* Package-private constructor used by the kernel to create the single
* instance of <code>TaskHandler</code>.
*
* @param transactionCoordinator the <code>TransactionCoordinator</code>
* used to create new transactions
*
* @throws IllegalStateException if there already exists an instance
* of <code>TaskHandler</code>
*/
TaskHandler(TransactionCoordinator transactionCoordinator) {
if (TaskHandler.transactionCoordinator != null)
throw new IllegalStateException("an instance already exists");
if (transactionCoordinator == null)
throw new NullPointerException("null coordinator not allowed");
logger.log(Level.CONFIG, "Creating the Task Handler");
TaskHandler.transactionCoordinator = transactionCoordinator;
}
/**
* Changes context to that of the given <code>TaskOwner</code> and
* runs the given <code>KernelRunnable</code>. This is a non-static
* method, and so only trusted components that have a reference to the
* valid <code>TaskHandler</code> may run tasks as different owners.
*
* @param task the <code>KernelRunnable</code> to run
* @param owner the <code>TaskOwner</code> for the given task
*
* @throws Exception if there are any failures running the task
*/
public void runTaskAsOwner(KernelRunnable task, TaskOwner owner)
throws Exception
{
if (logger.isLoggable(Level.FINEST))
logger.log(Level.FINEST, "running a task as {0}", owner);
// get the thread and the calling owner
TaskThread thread = (TaskThread)(Thread.currentThread());
TaskOwner parent = thread.getCurrentOwner();
// change to the context of the new owner and run the task
thread.setCurrentOwner(owner);
try {
task.run();
} finally {
// always restore the previous owner
thread.setCurrentOwner(parent);
}
}
/**
* Runs the given task in a transactional state, committing the
* transaction on completion of the task.
*
* @param task the <code>KernelRunnable</code> to run transactionally
*
* @throws Exception if there is any failure in running the task or
* committing the transaction
*/
public static void runTransactionalTask(KernelRunnable task)
throws Exception
{
if (logger.isLoggable(Level.FINEST))
logger.log(Level.FINEST, "starting a new transactional context");
// create a new transaction and set it as currently active
TransactionHandle handle = transactionCoordinator.createTransaction();
Transaction transaction = handle.getTransaction();
TransactionalTaskThread thread =
(TransactionalTaskThread)(Thread.currentThread());
thread.setCurrentTransaction(transaction);
// run the task, watching for any exceptions
try {
task.run();
} catch (Exception e) {
// make sure that the transaction is aborted, then re-throw the
// original exception
try {
handle.abort();
} catch (TransactionNotActiveException tnae) {
// this isn't a problem, since it just means that some
// participant aborted the transaction before throwing the
// original exception
- logger.log(Log.FINEST, "Transaction was already aborted");
+ logger.log(Level.FINEST, "Transaction was already aborted");
}
throw e;
} finally {
// regardless of the outcome, always clear the current state
thread.clearCurrentTransaction(transaction);
}
// finally, actually commit the transaction, allowing any exceptions
// to be thrown, since they will indicate whether this task is
// re-tried
handle.commit();
}
}
| true | true | public static void runTransactionalTask(KernelRunnable task)
throws Exception
{
if (logger.isLoggable(Level.FINEST))
logger.log(Level.FINEST, "starting a new transactional context");
// create a new transaction and set it as currently active
TransactionHandle handle = transactionCoordinator.createTransaction();
Transaction transaction = handle.getTransaction();
TransactionalTaskThread thread =
(TransactionalTaskThread)(Thread.currentThread());
thread.setCurrentTransaction(transaction);
// run the task, watching for any exceptions
try {
task.run();
} catch (Exception e) {
// make sure that the transaction is aborted, then re-throw the
// original exception
try {
handle.abort();
} catch (TransactionNotActiveException tnae) {
// this isn't a problem, since it just means that some
// participant aborted the transaction before throwing the
// original exception
logger.log(Log.FINEST, "Transaction was already aborted");
}
throw e;
} finally {
// regardless of the outcome, always clear the current state
thread.clearCurrentTransaction(transaction);
}
// finally, actually commit the transaction, allowing any exceptions
// to be thrown, since they will indicate whether this task is
// re-tried
handle.commit();
}
| public static void runTransactionalTask(KernelRunnable task)
throws Exception
{
if (logger.isLoggable(Level.FINEST))
logger.log(Level.FINEST, "starting a new transactional context");
// create a new transaction and set it as currently active
TransactionHandle handle = transactionCoordinator.createTransaction();
Transaction transaction = handle.getTransaction();
TransactionalTaskThread thread =
(TransactionalTaskThread)(Thread.currentThread());
thread.setCurrentTransaction(transaction);
// run the task, watching for any exceptions
try {
task.run();
} catch (Exception e) {
// make sure that the transaction is aborted, then re-throw the
// original exception
try {
handle.abort();
} catch (TransactionNotActiveException tnae) {
// this isn't a problem, since it just means that some
// participant aborted the transaction before throwing the
// original exception
logger.log(Level.FINEST, "Transaction was already aborted");
}
throw e;
} finally {
// regardless of the outcome, always clear the current state
thread.clearCurrentTransaction(transaction);
}
// finally, actually commit the transaction, allowing any exceptions
// to be thrown, since they will indicate whether this task is
// re-tried
handle.commit();
}
|
diff --git a/src/me/libraryaddict/Hungergames/Listeners/LibsFeastManager.java b/src/me/libraryaddict/Hungergames/Listeners/LibsFeastManager.java
index d1302ed..2fd905c 100644
--- a/src/me/libraryaddict/Hungergames/Listeners/LibsFeastManager.java
+++ b/src/me/libraryaddict/Hungergames/Listeners/LibsFeastManager.java
@@ -1,162 +1,164 @@
package me.libraryaddict.Hungergames.Listeners;
import java.util.Random;
import lombok.Getter;
import lombok.Setter;
import me.libraryaddict.Hungergames.Configs.FeastConfig;
import me.libraryaddict.Hungergames.Events.FeastAnnouncedEvent;
import me.libraryaddict.Hungergames.Events.FeastSpawnedEvent;
import me.libraryaddict.Hungergames.Events.TimeSecondEvent;
import me.libraryaddict.Hungergames.Interfaces.ChestManager;
import me.libraryaddict.Hungergames.Managers.ConfigManager;
import me.libraryaddict.Hungergames.Managers.GenerationManager;
import me.libraryaddict.Hungergames.Managers.ScoreboardManager;
import me.libraryaddict.Hungergames.Types.HungergamesApi;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scoreboard.DisplaySlot;
public class LibsFeastManager implements Listener {
@Getter
@Setter
private static LibsFeastManager feastManager = new LibsFeastManager();
protected FeastConfig config = HungergamesApi.getConfigManager().getFeastConfig();
protected Location feastLocation;
protected GenerationManager gen = HungergamesApi.getGenerationManager();
private boolean isEnabled;
/**
* Generates the chests. Height is the amount of chests. There will be a enchanting table on top of this putting the total at
* 4 blocks high.
*
* @param loc
* @param height
* of chests
*/
public void generateChests(final Location loc, final int height) {
ChestManager cm = HungergamesApi.getChestManager();
ConfigManager config = HungergamesApi.getConfigManager();
for (Player p : Bukkit.getOnlinePlayers()) {
Location l = p.getLocation().clone();
l.setY(loc.getY());
if (l.distance(loc) < height && p.getLocation().getY() >= l.getY() && p.getLocation().getY() - l.getY() <= height) {
l.setY(l.getY() + height + 1);
p.teleport(l);
}
}
ItemStack feastInside = config.getFeastConfig().getFeastInsides();
ItemStack feastBlock = config.getFeastConfig().getFeastFeastBlock();
for (int x = -height; x < height + 1; x++) {
for (int z = -height; z < height + 1; z++) {
// Get whichever number is higher
int y = Math.abs(x);
if (Math.abs(z) > y)
y = Math.abs(z);
// Got the highest..
// Now invert it and add on the height to get a pillar thats higher when closer to spanw
y = -y + height;
Block block = loc.clone().add(x, y, z).getBlock();
Block b = block;
// while repeated > 0
for (int yLevel = y; yLevel > 0; yLevel--) {
b = b.getRelative(BlockFace.DOWN);
if (y - 1 >= yLevel)
gen.setBlockFast(b, feastInside.getTypeId(), feastInside.getDurability());
else
gen.setBlockFast(b, feastBlock.getTypeId(), feastBlock.getDurability());
}
if (x == 0 && z == 0) {
gen.setBlockFast(block, Material.ENCHANTMENT_TABLE.getId(), (byte) 0);
gen.setBlockFast(block.getRelative(BlockFace.DOWN), feastInside.getTypeId(),
(feastInside.getType() == Material.TNT ? 1 : feastInside.getDurability()));
} else if (Math.abs(x + z) % 2 == 0) {
gen.addToProcessedBlocks(block);
- boolean unload = b.getWorld().isChunkLoaded(b.getChunk().getX(), b.getChunk().getZ());
- if (unload)
+ boolean unload = !b.getWorld().isChunkLoaded(b.getChunk().getX(), b.getChunk().getZ());
+ if (unload) {
b.getWorld().loadChunk(b.getChunk().getX(), b.getChunk().getZ());
+ }
block.setType(Material.CHEST);
Chest chest = (Chest) block.getState();
cm.fillChest(chest.getInventory());
chest.update();
- if (unload)
+ if (unload) {
b.getWorld().unloadChunk(b.getChunk().getX(), b.getChunk().getZ());
+ }
} else
gen.setBlockFast(block, feastBlock.getTypeId(), feastBlock.getDurability());
}
}
}
public void generatePlatform(Location loc, int chestLayers, int platformSize) {
ItemStack item = HungergamesApi.getConfigManager().getFeastConfig().getFeastGroundBlock();
gen.generatePlatform(loc, chestLayers, platformSize, item.getType(), item.getDurability());
if (config.isPillarsEnabled())
gen.generatePillars(loc, platformSize, config.getPillarCorners().getTypeId(), config.getPillarCorners()
.getDurability(), config.getPillarInsides().getTypeId(), config.getPillarInsides().getDurability());
}
public Location getFeastLocation() {
if (feastLocation == null) {
Location spawn = HungergamesApi.getHungergames().world.getSpawnLocation();
int dist = config.getFeastMaxDistanceFromSpawn();
feastLocation = new Location(spawn.getWorld(), spawn.getX() + (new Random().nextInt(dist * 2) - dist), -1,
spawn.getZ() + (new Random().nextInt(dist * 2) - dist));
}
return feastLocation;
}
@EventHandler
public void onSecond(TimeSecondEvent event) {
int currentTime = HungergamesApi.getHungergames().currentTime;
if (currentTime == config.getFeastPlatformGenerateTime()) {
Location feastLoc = getFeastLocation();
int feastHeight = gen.getSpawnHeight(getFeastLocation(), config.getFeastSize());
feastLoc.setY(feastHeight);
setFeastLocation(feastLoc);
generatePlatform(getFeastLocation(), feastHeight, config.getFeastSize());
HungergamesApi.getInventoryManager().updateSpectatorHeads();
Bukkit.getPluginManager().callEvent(new FeastAnnouncedEvent());
}
if (currentTime == config.getFeastGenerateTime()) {
ScoreboardManager.hideScore("Main", DisplaySlot.SIDEBAR, config.getScoreboardFeastStartingIn());
generateChests(getFeastLocation(), config.getChestLayersHeight());
World world = HungergamesApi.getHungergames().world;
world.playSound(world.getSpawnLocation(), Sound.IRONGOLEM_DEATH, 1000, 0);
Bukkit.getPluginManager().callEvent(new FeastSpawnedEvent());
} else if (currentTime > config.getFeastPlatformGenerateTime() && currentTime < config.getFeastGenerateTime()) {
ScoreboardManager.makeScore("Main", DisplaySlot.SIDEBAR, config.getScoreboardFeastStartingIn(),
config.getFeastGenerateTime() - currentTime);
}
if (config.getFeastAdvertisements().containsKey(currentTime)) {
Bukkit.broadcastMessage(String.format(config.getFeastAdvertisements().get(currentTime), getFeastLocation().getX(),
getFeastLocation().getY(), getFeastLocation().getZ(),
HungergamesApi.getHungergames().returnTime(currentTime - config.getFeastGenerateTime())));
}
}
public void setEnabled(boolean enabled) {
if (enabled != isEnabled) {
isEnabled = enabled;
if (enabled) {
Bukkit.getPluginManager().registerEvents(this, HungergamesApi.getHungergames());
} else {
HandlerList.unregisterAll(this);
}
}
}
public void setFeastLocation(Location newFeastLocation) {
feastLocation = newFeastLocation;
}
}
| false | true | public void generateChests(final Location loc, final int height) {
ChestManager cm = HungergamesApi.getChestManager();
ConfigManager config = HungergamesApi.getConfigManager();
for (Player p : Bukkit.getOnlinePlayers()) {
Location l = p.getLocation().clone();
l.setY(loc.getY());
if (l.distance(loc) < height && p.getLocation().getY() >= l.getY() && p.getLocation().getY() - l.getY() <= height) {
l.setY(l.getY() + height + 1);
p.teleport(l);
}
}
ItemStack feastInside = config.getFeastConfig().getFeastInsides();
ItemStack feastBlock = config.getFeastConfig().getFeastFeastBlock();
for (int x = -height; x < height + 1; x++) {
for (int z = -height; z < height + 1; z++) {
// Get whichever number is higher
int y = Math.abs(x);
if (Math.abs(z) > y)
y = Math.abs(z);
// Got the highest..
// Now invert it and add on the height to get a pillar thats higher when closer to spanw
y = -y + height;
Block block = loc.clone().add(x, y, z).getBlock();
Block b = block;
// while repeated > 0
for (int yLevel = y; yLevel > 0; yLevel--) {
b = b.getRelative(BlockFace.DOWN);
if (y - 1 >= yLevel)
gen.setBlockFast(b, feastInside.getTypeId(), feastInside.getDurability());
else
gen.setBlockFast(b, feastBlock.getTypeId(), feastBlock.getDurability());
}
if (x == 0 && z == 0) {
gen.setBlockFast(block, Material.ENCHANTMENT_TABLE.getId(), (byte) 0);
gen.setBlockFast(block.getRelative(BlockFace.DOWN), feastInside.getTypeId(),
(feastInside.getType() == Material.TNT ? 1 : feastInside.getDurability()));
} else if (Math.abs(x + z) % 2 == 0) {
gen.addToProcessedBlocks(block);
boolean unload = b.getWorld().isChunkLoaded(b.getChunk().getX(), b.getChunk().getZ());
if (unload)
b.getWorld().loadChunk(b.getChunk().getX(), b.getChunk().getZ());
block.setType(Material.CHEST);
Chest chest = (Chest) block.getState();
cm.fillChest(chest.getInventory());
chest.update();
if (unload)
b.getWorld().unloadChunk(b.getChunk().getX(), b.getChunk().getZ());
} else
gen.setBlockFast(block, feastBlock.getTypeId(), feastBlock.getDurability());
}
}
}
| public void generateChests(final Location loc, final int height) {
ChestManager cm = HungergamesApi.getChestManager();
ConfigManager config = HungergamesApi.getConfigManager();
for (Player p : Bukkit.getOnlinePlayers()) {
Location l = p.getLocation().clone();
l.setY(loc.getY());
if (l.distance(loc) < height && p.getLocation().getY() >= l.getY() && p.getLocation().getY() - l.getY() <= height) {
l.setY(l.getY() + height + 1);
p.teleport(l);
}
}
ItemStack feastInside = config.getFeastConfig().getFeastInsides();
ItemStack feastBlock = config.getFeastConfig().getFeastFeastBlock();
for (int x = -height; x < height + 1; x++) {
for (int z = -height; z < height + 1; z++) {
// Get whichever number is higher
int y = Math.abs(x);
if (Math.abs(z) > y)
y = Math.abs(z);
// Got the highest..
// Now invert it and add on the height to get a pillar thats higher when closer to spanw
y = -y + height;
Block block = loc.clone().add(x, y, z).getBlock();
Block b = block;
// while repeated > 0
for (int yLevel = y; yLevel > 0; yLevel--) {
b = b.getRelative(BlockFace.DOWN);
if (y - 1 >= yLevel)
gen.setBlockFast(b, feastInside.getTypeId(), feastInside.getDurability());
else
gen.setBlockFast(b, feastBlock.getTypeId(), feastBlock.getDurability());
}
if (x == 0 && z == 0) {
gen.setBlockFast(block, Material.ENCHANTMENT_TABLE.getId(), (byte) 0);
gen.setBlockFast(block.getRelative(BlockFace.DOWN), feastInside.getTypeId(),
(feastInside.getType() == Material.TNT ? 1 : feastInside.getDurability()));
} else if (Math.abs(x + z) % 2 == 0) {
gen.addToProcessedBlocks(block);
boolean unload = !b.getWorld().isChunkLoaded(b.getChunk().getX(), b.getChunk().getZ());
if (unload) {
b.getWorld().loadChunk(b.getChunk().getX(), b.getChunk().getZ());
}
block.setType(Material.CHEST);
Chest chest = (Chest) block.getState();
cm.fillChest(chest.getInventory());
chest.update();
if (unload) {
b.getWorld().unloadChunk(b.getChunk().getX(), b.getChunk().getZ());
}
} else
gen.setBlockFast(block, feastBlock.getTypeId(), feastBlock.getDurability());
}
}
}
|
diff --git a/tests/src/java/org/apache/log4j/util/JunitTestRunnerFilter.java b/tests/src/java/org/apache/log4j/util/JunitTestRunnerFilter.java
index 341bd348..43214d77 100644
--- a/tests/src/java/org/apache/log4j/util/JunitTestRunnerFilter.java
+++ b/tests/src/java/org/apache/log4j/util/JunitTestRunnerFilter.java
@@ -1,51 +1,53 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.log4j.util;
import org.apache.oro.text.perl.Perl5Util;
public class JunitTestRunnerFilter implements Filter {
Perl5Util util = new Perl5Util();
/**
* Filter out stack trace lines coming from the various JUnit TestRunners.
*/
public String filter(String in) {
if (in == null) {
return null;
}
if (
util.match(
"/at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner/", in)) {
return null;
} else if (
util.match(
"/at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner/",
in)) {
return null;
} else if (in.indexOf("at junit.") >= 0 && in.indexOf("ui.TestRunner") >= 0) {
return null;
+ } else if (in.indexOf("org.apache.maven") >= 0) {
+ return null;
} else if (util.match("/\\sat /", in)) {
return "\t" + in.trim();
} else {
return in;
}
}
}
| true | true | public String filter(String in) {
if (in == null) {
return null;
}
if (
util.match(
"/at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner/", in)) {
return null;
} else if (
util.match(
"/at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner/",
in)) {
return null;
} else if (in.indexOf("at junit.") >= 0 && in.indexOf("ui.TestRunner") >= 0) {
return null;
} else if (util.match("/\\sat /", in)) {
return "\t" + in.trim();
} else {
return in;
}
}
| public String filter(String in) {
if (in == null) {
return null;
}
if (
util.match(
"/at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner/", in)) {
return null;
} else if (
util.match(
"/at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner/",
in)) {
return null;
} else if (in.indexOf("at junit.") >= 0 && in.indexOf("ui.TestRunner") >= 0) {
return null;
} else if (in.indexOf("org.apache.maven") >= 0) {
return null;
} else if (util.match("/\\sat /", in)) {
return "\t" + in.trim();
} else {
return in;
}
}
|
diff --git a/src/org/harleydroid/HarleyDroidService.java b/src/org/harleydroid/HarleyDroidService.java
index 73721b0..6260a20 100644
--- a/src/org/harleydroid/HarleyDroidService.java
+++ b/src/org/harleydroid/HarleyDroidService.java
@@ -1,331 +1,331 @@
//
// HarleyDroid: Harley Davidson J1850 Data Analyser for Android.
//
// Copyright (C) 2010,2011 Stelian Pop <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package org.harleydroid;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.zip.GZIPOutputStream;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class HarleyDroidService extends Service
{
private static final boolean D = true;
private static final String TAG = HarleyDroidService.class.getSimpleName();
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final int AT_TIMEOUT = 2000;
private static final int ATZ_TIMEOUT = 5000;
private static final int ATMA_TIMEOUT = 2000;
private static final int MAX_ERRORS = 10;
private final IBinder binder = new HarleyDroidServiceBinder();
private HarleyData mHD;
private NotificationManager mNM;
private Handler mHandler = null;
private ThreadELM mThread = null;
private OutputStream mLog = null;
private SimpleDateFormat mDateFormat;
@Override
public void onCreate() {
super.onCreate();
if (D) Log.d(TAG, "onCreate()");
mHD = new HarleyData();
mDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
CharSequence text = getText(R.string.notification_start);
Notification notification = new Notification(R.drawable.stat_notify_car_mode, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, HarleyDroid.class), 0);
notification.setLatestEventInfo(this, getText(R.string.notification_label), text, contentIntent);
mNM.notify(R.string.notification_label, notification);
}
public void onDestroy() {
super.onDestroy();
if (D) Log.d(TAG, "onDestroy()");
mNM.cancel(R.string.notification_label);
}
@Override
public IBinder onBind(Intent intent) {
if (D) Log.d(TAG, "onBind()");
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (D) Log.d(TAG, "onStartCommand()");
return START_STICKY;
}
public void setHandler(Handler handler) {
if (D) Log.d(TAG, "setHandler()");
mHandler = handler;
mHD.setHandler(handler);
}
public void startService(BluetoothDevice dev, boolean logging) {
if (D) Log.d(TAG, "startService()");
// open logfile if possible
if (logging)
startLog();
mThread = new ThreadELM(dev);
mThread.start();
}
public void stopService() {
if (D) Log.d(TAG, "stopService()");
stopLog();
mThread.stop = true;
mThread = null;
}
private void startLog() {
try {
File path = new File(Environment.getExternalStorageDirectory(), "/Android/data/org.harleydroid/files/");
path.mkdirs();
File logFile = new File(path, "harley-" + mDateFormat.format(new Date()) + ".log.gz");
mLog = new GZIPOutputStream(new FileOutputStream(logFile, true));
String header = "Starting at " + mDateFormat.format(new Date()) + "\n";
mLog.write(header.getBytes());
} catch (IOException e) {
Log.d(TAG, "Logfile open " + e);
}
}
private void stopLog() {
if (mLog != null) {
String header = "Stopping at " + mDateFormat.format(new Date()) + "\n";
try {
mLog.write(header.getBytes());
mLog.close();
} catch (IOException e) {
}
}
mLog = null;
}
public boolean isRunning() {
if (D) Log.d(TAG, "isRunning()");
return (mThread != null);
}
public class HarleyDroidServiceBinder extends Binder {
HarleyDroidService getService() {
return HarleyDroidService.this;
}
}
private class ThreadELM extends Thread {
private BluetoothDevice mDevice;
private BufferedReader mIn;
private OutputStream mOut;
private BluetoothSocket mSock;
private Timer mTimer;
boolean stop = false;
class CancelTimer extends TimerTask {
public void run() {
if (D) Log.d(TAG, "CANCEL AT " + System.currentTimeMillis());
try {
mSock.close();
} catch (IOException e) {
}
}
};
public ThreadELM(BluetoothDevice device) {
mDevice = device;
mTimer = new Timer();
}
private String readLine(long timeout) throws IOException {
CancelTimer t = new CancelTimer();
mTimer.schedule(t, timeout);
if (D) Log.d(TAG, "READLINE AT " + System.currentTimeMillis());
String line = mIn.readLine();
t.cancel();
if (D) Log.d(TAG, "read (" + line.length() + "): " + line);
if (mLog != null) {
mLog.write(line.getBytes());
mLog.write('\n');
}
return line;
}
private void writeLine(String line) throws IOException {
line += "\r";
if (D) Log.d(TAG, "write: " + line);
mOut.write(line.getBytes());
mOut.flush();
}
private void chat(String send, String expect, long timeout) throws IOException {
String line = null;
writeLine(send);
long start = System.currentTimeMillis();
while (timeout > 0) {
line = readLine(timeout);
long now = System.currentTimeMillis();
if (line.indexOf(expect) != -1)
return;
timeout -= (now - start);
start = now;
}
throw new IOException("timeout");
}
public void run() {
int errors = 0;
//int cnt = 0;
if (!HarleyDroid.EMULATOR) {
try {
if (D) Log.d(TAG, "started");
mSock = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
mSock.connect();
if (D) Log.d(TAG, "connected");
mIn = new BufferedReader(new InputStreamReader(mSock.getInputStream()), 128);
mOut = mSock.getOutputStream();
} catch (IOException e1) {
try {
mSock.close();
} catch (IOException e2) {
}
mHandler.obtainMessage(HarleyDroid.STATUS_ERROR, -1, -1).sendToTarget();
finish();
return;
}
try {
chat("AT", "", AT_TIMEOUT);
try {
Thread.sleep(1000);
} catch (InterruptedException e2) {
}
chat("ATZ", "ELM327", ATZ_TIMEOUT);
chat("ATE1", "OK", AT_TIMEOUT);
chat("ATH1", "OK", AT_TIMEOUT);
chat("ATSP2", "OK", AT_TIMEOUT);
chat("ATMA", "", AT_TIMEOUT);
} catch (IOException e1) {
mHandler.obtainMessage(HarleyDroid.STATUS_ERRORAT, -1, -1).sendToTarget();
finish();
return;
}
} // !EMULATOR
if (D) Log.d(TAG, "ready");
mHandler.obtainMessage(HarleyDroid.STATUS_CONNECTED, -1, -1).sendToTarget();
while (!stop) {
String line;
if (HarleyDroid.EMULATOR) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
// RPM at 1053
line = "28 1B 10 02 10 74 4C";
// Speed at 100 mph
line = "48 29 10 02 4E 20 D4";
// Odometer
//line = "a8 69 10 06 00 00 FF 61";
}
else {
try {
line = readLine(ATMA_TIMEOUT);
} catch (IOException e1) {
mHandler.obtainMessage(HarleyDroid.STATUS_NODATA, -1, -1).sendToTarget();
- stop = true;
- break;
+ finish();
+ return;
}
}
try {
J1850.parse(line.getBytes(), mHD);
errors = 0;
} catch (Exception e1) {
if (D) Log.d(TAG, "Error: " + e1.getMessage());
++errors;
if (errors > MAX_ERRORS) {
mHandler.obtainMessage(HarleyDroid.STATUS_TOOMANYERRORS, -1, -1).sendToTarget();
stop = true;
break;
}
}
//mHandler.obtainMessage(HarleyDroid.UPDATE_ODOMETER, cnt, -1).sendToTarget();
//cnt += 5;
}
if (!HarleyDroid.EMULATOR) {
try {
writeLine("");
} catch (IOException e1) {
}
try {
mSock.close();
} catch (IOException e3) {
}
}
finish();
}
private void finish() {
stopLog();
mTimer.cancel();
stopSelf();
}
}
}
| true | true | public void run() {
int errors = 0;
//int cnt = 0;
if (!HarleyDroid.EMULATOR) {
try {
if (D) Log.d(TAG, "started");
mSock = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
mSock.connect();
if (D) Log.d(TAG, "connected");
mIn = new BufferedReader(new InputStreamReader(mSock.getInputStream()), 128);
mOut = mSock.getOutputStream();
} catch (IOException e1) {
try {
mSock.close();
} catch (IOException e2) {
}
mHandler.obtainMessage(HarleyDroid.STATUS_ERROR, -1, -1).sendToTarget();
finish();
return;
}
try {
chat("AT", "", AT_TIMEOUT);
try {
Thread.sleep(1000);
} catch (InterruptedException e2) {
}
chat("ATZ", "ELM327", ATZ_TIMEOUT);
chat("ATE1", "OK", AT_TIMEOUT);
chat("ATH1", "OK", AT_TIMEOUT);
chat("ATSP2", "OK", AT_TIMEOUT);
chat("ATMA", "", AT_TIMEOUT);
} catch (IOException e1) {
mHandler.obtainMessage(HarleyDroid.STATUS_ERRORAT, -1, -1).sendToTarget();
finish();
return;
}
} // !EMULATOR
if (D) Log.d(TAG, "ready");
mHandler.obtainMessage(HarleyDroid.STATUS_CONNECTED, -1, -1).sendToTarget();
while (!stop) {
String line;
if (HarleyDroid.EMULATOR) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
// RPM at 1053
line = "28 1B 10 02 10 74 4C";
// Speed at 100 mph
line = "48 29 10 02 4E 20 D4";
// Odometer
//line = "a8 69 10 06 00 00 FF 61";
}
else {
try {
line = readLine(ATMA_TIMEOUT);
} catch (IOException e1) {
mHandler.obtainMessage(HarleyDroid.STATUS_NODATA, -1, -1).sendToTarget();
stop = true;
break;
}
}
try {
J1850.parse(line.getBytes(), mHD);
errors = 0;
} catch (Exception e1) {
if (D) Log.d(TAG, "Error: " + e1.getMessage());
++errors;
if (errors > MAX_ERRORS) {
mHandler.obtainMessage(HarleyDroid.STATUS_TOOMANYERRORS, -1, -1).sendToTarget();
stop = true;
break;
}
}
//mHandler.obtainMessage(HarleyDroid.UPDATE_ODOMETER, cnt, -1).sendToTarget();
//cnt += 5;
}
if (!HarleyDroid.EMULATOR) {
try {
writeLine("");
} catch (IOException e1) {
}
try {
mSock.close();
} catch (IOException e3) {
}
}
finish();
}
| public void run() {
int errors = 0;
//int cnt = 0;
if (!HarleyDroid.EMULATOR) {
try {
if (D) Log.d(TAG, "started");
mSock = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
mSock.connect();
if (D) Log.d(TAG, "connected");
mIn = new BufferedReader(new InputStreamReader(mSock.getInputStream()), 128);
mOut = mSock.getOutputStream();
} catch (IOException e1) {
try {
mSock.close();
} catch (IOException e2) {
}
mHandler.obtainMessage(HarleyDroid.STATUS_ERROR, -1, -1).sendToTarget();
finish();
return;
}
try {
chat("AT", "", AT_TIMEOUT);
try {
Thread.sleep(1000);
} catch (InterruptedException e2) {
}
chat("ATZ", "ELM327", ATZ_TIMEOUT);
chat("ATE1", "OK", AT_TIMEOUT);
chat("ATH1", "OK", AT_TIMEOUT);
chat("ATSP2", "OK", AT_TIMEOUT);
chat("ATMA", "", AT_TIMEOUT);
} catch (IOException e1) {
mHandler.obtainMessage(HarleyDroid.STATUS_ERRORAT, -1, -1).sendToTarget();
finish();
return;
}
} // !EMULATOR
if (D) Log.d(TAG, "ready");
mHandler.obtainMessage(HarleyDroid.STATUS_CONNECTED, -1, -1).sendToTarget();
while (!stop) {
String line;
if (HarleyDroid.EMULATOR) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
// RPM at 1053
line = "28 1B 10 02 10 74 4C";
// Speed at 100 mph
line = "48 29 10 02 4E 20 D4";
// Odometer
//line = "a8 69 10 06 00 00 FF 61";
}
else {
try {
line = readLine(ATMA_TIMEOUT);
} catch (IOException e1) {
mHandler.obtainMessage(HarleyDroid.STATUS_NODATA, -1, -1).sendToTarget();
finish();
return;
}
}
try {
J1850.parse(line.getBytes(), mHD);
errors = 0;
} catch (Exception e1) {
if (D) Log.d(TAG, "Error: " + e1.getMessage());
++errors;
if (errors > MAX_ERRORS) {
mHandler.obtainMessage(HarleyDroid.STATUS_TOOMANYERRORS, -1, -1).sendToTarget();
stop = true;
break;
}
}
//mHandler.obtainMessage(HarleyDroid.UPDATE_ODOMETER, cnt, -1).sendToTarget();
//cnt += 5;
}
if (!HarleyDroid.EMULATOR) {
try {
writeLine("");
} catch (IOException e1) {
}
try {
mSock.close();
} catch (IOException e3) {
}
}
finish();
}
|
diff --git a/eqtl-mapping-pipeline/src/main/java/eqtlmappingpipeline/normalization/NormalizationConsoleGUI.java b/eqtl-mapping-pipeline/src/main/java/eqtlmappingpipeline/normalization/NormalizationConsoleGUI.java
index dad68a24..110c1947 100644
--- a/eqtl-mapping-pipeline/src/main/java/eqtlmappingpipeline/normalization/NormalizationConsoleGUI.java
+++ b/eqtl-mapping-pipeline/src/main/java/eqtlmappingpipeline/normalization/NormalizationConsoleGUI.java
@@ -1,167 +1,167 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eqtlmappingpipeline.normalization;
import java.io.IOException;
import umcg.genetica.io.Gpio;
/**
*
* @author harmjan
*/
public class NormalizationConsoleGUI {
public NormalizationConsoleGUI(String[] args) {
String in = null;
String out = null;
String cov = null;
boolean fullNorm = true;
boolean runLogTransform = false;
boolean runMTransform = false;
boolean runQQNorm = false;
boolean runCenterScale = false;
boolean runCovariateAdjustment = false;
boolean runPCAdjustment = false;
boolean orthogonalizecovariates = false;
boolean forceMissingValues = false;
boolean forceReplacementOfMissingValues = false;
boolean forceReplacementOfMissingValues2 = false;
int maxPcaToRemove = 100;
int stepSizePcaRemoval = 5;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
String val = null;
if (i + 1 < args.length) {
val = args[i + 1];
}
if (arg.equals("--in")) {
in = val;
}
if (arg.equals("--out")) {
out = val;
}
if (arg.equals("--logtransform")) {
runLogTransform = true;
fullNorm = false;
}
if (arg.equals("--Mtransform")) {
runMTransform = true;
fullNorm = false;
}
if (arg.equals("--qqnorm")) {
runQQNorm = true;
fullNorm = false;
}
if (arg.equals("--centerscale")) {
runCenterScale = true;
fullNorm = false;
}
if (arg.equals("--adjustcovariates")) {
runCovariateAdjustment = true;
fullNorm = false;
}
if (arg.equals("--adjustPCA")) {
runPCAdjustment = true;
fullNorm = false;
}
if (arg.equals("--cov")) {
cov = val;
}
if (arg.equals("--covpca")) {
orthogonalizecovariates = true;
}
if (arg.equals("--maxnrpcaremoved")) {
maxPcaToRemove = Integer.parseInt(val);
}
if (arg.equals("--stepsizepcaremoval")) {
stepSizePcaRemoval = Integer.parseInt(val);
}
if (arg.equals("--forceReplacementOfMissingValuesSampleBased")) {
forceReplacementOfMissingValues = true;
}
if (arg.equals("--forceReplacementOfMissingValuesProbeBased")) {
forceReplacementOfMissingValues2 = true;
}
if (arg.equals("--forceMissingValues")) {
forceMissingValues = true;
}
}
if (in == null) {
System.out.println("Please supply your data file.\n");
printUsage();
System.exit(0);
}
if (!Gpio.exists(in)) {
System.out.println("Error: the file you specified does not exist.\n");
System.out.println("Could not find file: " + in);
System.exit(0);
}
if (runLogTransform && runMTransform) {
System.out.println("Error: cant perform both log and M-value transformation");
- System.exit(0);
+ System.exit(-1);
}
if((forceMissingValues && (forceReplacementOfMissingValues || forceReplacementOfMissingValues2)) || (forceReplacementOfMissingValues && (forceMissingValues || forceReplacementOfMissingValues2)) || (forceReplacementOfMissingValues2 && (forceReplacementOfMissingValues || forceMissingValues))){
- System.out.println("Warning: only one missing value option allowed.");
+ System.out.println("Error: only one missing value option allowed.");
System.exit(-1);
}
try {
Normalizer p = new Normalizer();
if (!fullNorm) {
p.normalize(in, maxPcaToRemove, stepSizePcaRemoval, cov, orthogonalizecovariates, out,
runQQNorm, runLogTransform, runMTransform, runCenterScale, runPCAdjustment,
runCovariateAdjustment, forceMissingValues, forceReplacementOfMissingValues, forceReplacementOfMissingValues2);
} else {
// run full normalization
p.normalize(in, maxPcaToRemove, stepSizePcaRemoval, cov, orthogonalizecovariates, out,
true, true, false, true, true, true, false, false, false);
}
System.out.println("Done.");
} catch (IOException e) {
e.printStackTrace();
}
}
private void printUsage() {
System.out.println("Normalization tool\n"
+ "Parameters for full normalization (which includes the following procedures in order: qqnorm, log2transform, centerscale, [covariate adjustment], PCA adjustment):\n"
+ "--in\t\t\tstring\t\tProvide the location of the expression data matrix\n"
+ "--out\t\t\tdir\t\tProvide the directory to output files [optional; default is --in directory]\n"
+ "\n"
+ "Specific normalization methodologies (if multiple methodologies are specified, they will follow the order of full normalization; see above):\n"
+ "--qqnorm\t\t\t\tQuantile normalization\n"
+ "--logtransform\t\t\t\tRun log2 transformation\n"
+ "--Mtransform\t\t\t\tRun M-val (log) transformation for methylation Beta values\n"
+ "--adjustcovariates\t\t\tRun covariate adjustment\n"
+ "--centerscale\t\t\t\tCenter the mean to 0, linearly scale using standard deviation\n"
+ "--adjustPCA\t\t\t\tRun PCA adjustment \n"
+ "\n"
+ "Covariate adjustment parameters:\n"
+ "--cov\t\t\tstring\t\tCovariates to remove\n"
+ "--covpca\t\t\t\tOrthogonalize covariates using PCA before regression\n"
+ "\n"
+ "PCA parameters\n"
+ "--maxnrpcaremoved\tinteger\t\tMaximum number of PCs to remove\n"
+ "--stepsizepcaremoval\tinteger\t\tStep size for PC removal\n"
+"\n"
+"Additional QN missing value parameters (only one option is allowed.) \n"
+"--forceMissingValues\tUses a Quantile normalization strategy where missing values are ignored. If chosen only QN will be performed.\n"
+"--forceReplacementOfMissingValuesSampleBased\tUses a Quantile normalization strategy where missing values are ignored and replaced by sample mean.\n"
+"--forceReplacementOfMissingValuesProbeBased\tUses a Quantile normalization strategy where missing values are ignored and replaced by probe mean.");
}
}
| false | true | public NormalizationConsoleGUI(String[] args) {
String in = null;
String out = null;
String cov = null;
boolean fullNorm = true;
boolean runLogTransform = false;
boolean runMTransform = false;
boolean runQQNorm = false;
boolean runCenterScale = false;
boolean runCovariateAdjustment = false;
boolean runPCAdjustment = false;
boolean orthogonalizecovariates = false;
boolean forceMissingValues = false;
boolean forceReplacementOfMissingValues = false;
boolean forceReplacementOfMissingValues2 = false;
int maxPcaToRemove = 100;
int stepSizePcaRemoval = 5;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
String val = null;
if (i + 1 < args.length) {
val = args[i + 1];
}
if (arg.equals("--in")) {
in = val;
}
if (arg.equals("--out")) {
out = val;
}
if (arg.equals("--logtransform")) {
runLogTransform = true;
fullNorm = false;
}
if (arg.equals("--Mtransform")) {
runMTransform = true;
fullNorm = false;
}
if (arg.equals("--qqnorm")) {
runQQNorm = true;
fullNorm = false;
}
if (arg.equals("--centerscale")) {
runCenterScale = true;
fullNorm = false;
}
if (arg.equals("--adjustcovariates")) {
runCovariateAdjustment = true;
fullNorm = false;
}
if (arg.equals("--adjustPCA")) {
runPCAdjustment = true;
fullNorm = false;
}
if (arg.equals("--cov")) {
cov = val;
}
if (arg.equals("--covpca")) {
orthogonalizecovariates = true;
}
if (arg.equals("--maxnrpcaremoved")) {
maxPcaToRemove = Integer.parseInt(val);
}
if (arg.equals("--stepsizepcaremoval")) {
stepSizePcaRemoval = Integer.parseInt(val);
}
if (arg.equals("--forceReplacementOfMissingValuesSampleBased")) {
forceReplacementOfMissingValues = true;
}
if (arg.equals("--forceReplacementOfMissingValuesProbeBased")) {
forceReplacementOfMissingValues2 = true;
}
if (arg.equals("--forceMissingValues")) {
forceMissingValues = true;
}
}
if (in == null) {
System.out.println("Please supply your data file.\n");
printUsage();
System.exit(0);
}
if (!Gpio.exists(in)) {
System.out.println("Error: the file you specified does not exist.\n");
System.out.println("Could not find file: " + in);
System.exit(0);
}
if (runLogTransform && runMTransform) {
System.out.println("Error: cant perform both log and M-value transformation");
System.exit(0);
}
if((forceMissingValues && (forceReplacementOfMissingValues || forceReplacementOfMissingValues2)) || (forceReplacementOfMissingValues && (forceMissingValues || forceReplacementOfMissingValues2)) || (forceReplacementOfMissingValues2 && (forceReplacementOfMissingValues || forceMissingValues))){
System.out.println("Warning: only one missing value option allowed.");
System.exit(-1);
}
try {
Normalizer p = new Normalizer();
if (!fullNorm) {
p.normalize(in, maxPcaToRemove, stepSizePcaRemoval, cov, orthogonalizecovariates, out,
runQQNorm, runLogTransform, runMTransform, runCenterScale, runPCAdjustment,
runCovariateAdjustment, forceMissingValues, forceReplacementOfMissingValues, forceReplacementOfMissingValues2);
} else {
// run full normalization
p.normalize(in, maxPcaToRemove, stepSizePcaRemoval, cov, orthogonalizecovariates, out,
true, true, false, true, true, true, false, false, false);
}
System.out.println("Done.");
} catch (IOException e) {
e.printStackTrace();
}
}
| public NormalizationConsoleGUI(String[] args) {
String in = null;
String out = null;
String cov = null;
boolean fullNorm = true;
boolean runLogTransform = false;
boolean runMTransform = false;
boolean runQQNorm = false;
boolean runCenterScale = false;
boolean runCovariateAdjustment = false;
boolean runPCAdjustment = false;
boolean orthogonalizecovariates = false;
boolean forceMissingValues = false;
boolean forceReplacementOfMissingValues = false;
boolean forceReplacementOfMissingValues2 = false;
int maxPcaToRemove = 100;
int stepSizePcaRemoval = 5;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
String val = null;
if (i + 1 < args.length) {
val = args[i + 1];
}
if (arg.equals("--in")) {
in = val;
}
if (arg.equals("--out")) {
out = val;
}
if (arg.equals("--logtransform")) {
runLogTransform = true;
fullNorm = false;
}
if (arg.equals("--Mtransform")) {
runMTransform = true;
fullNorm = false;
}
if (arg.equals("--qqnorm")) {
runQQNorm = true;
fullNorm = false;
}
if (arg.equals("--centerscale")) {
runCenterScale = true;
fullNorm = false;
}
if (arg.equals("--adjustcovariates")) {
runCovariateAdjustment = true;
fullNorm = false;
}
if (arg.equals("--adjustPCA")) {
runPCAdjustment = true;
fullNorm = false;
}
if (arg.equals("--cov")) {
cov = val;
}
if (arg.equals("--covpca")) {
orthogonalizecovariates = true;
}
if (arg.equals("--maxnrpcaremoved")) {
maxPcaToRemove = Integer.parseInt(val);
}
if (arg.equals("--stepsizepcaremoval")) {
stepSizePcaRemoval = Integer.parseInt(val);
}
if (arg.equals("--forceReplacementOfMissingValuesSampleBased")) {
forceReplacementOfMissingValues = true;
}
if (arg.equals("--forceReplacementOfMissingValuesProbeBased")) {
forceReplacementOfMissingValues2 = true;
}
if (arg.equals("--forceMissingValues")) {
forceMissingValues = true;
}
}
if (in == null) {
System.out.println("Please supply your data file.\n");
printUsage();
System.exit(0);
}
if (!Gpio.exists(in)) {
System.out.println("Error: the file you specified does not exist.\n");
System.out.println("Could not find file: " + in);
System.exit(0);
}
if (runLogTransform && runMTransform) {
System.out.println("Error: cant perform both log and M-value transformation");
System.exit(-1);
}
if((forceMissingValues && (forceReplacementOfMissingValues || forceReplacementOfMissingValues2)) || (forceReplacementOfMissingValues && (forceMissingValues || forceReplacementOfMissingValues2)) || (forceReplacementOfMissingValues2 && (forceReplacementOfMissingValues || forceMissingValues))){
System.out.println("Error: only one missing value option allowed.");
System.exit(-1);
}
try {
Normalizer p = new Normalizer();
if (!fullNorm) {
p.normalize(in, maxPcaToRemove, stepSizePcaRemoval, cov, orthogonalizecovariates, out,
runQQNorm, runLogTransform, runMTransform, runCenterScale, runPCAdjustment,
runCovariateAdjustment, forceMissingValues, forceReplacementOfMissingValues, forceReplacementOfMissingValues2);
} else {
// run full normalization
p.normalize(in, maxPcaToRemove, stepSizePcaRemoval, cov, orthogonalizecovariates, out,
true, true, false, true, true, true, false, false, false);
}
System.out.println("Done.");
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/grails-app/services/org/chai/kevin/util/Utils.java b/grails-app/services/org/chai/kevin/util/Utils.java
index 65c2f95a..6a5b2d93 100644
--- a/grails-app/services/org/chai/kevin/util/Utils.java
+++ b/grails-app/services/org/chai/kevin/util/Utils.java
@@ -1,188 +1,182 @@
/**
* Copyright (c) 2011, Clinton Health Access Initiative.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.chai.kevin.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.chai.kevin.LanguageService;
import org.chai.kevin.data.Enum;
import org.chai.kevin.data.EnumOption;
import org.chai.kevin.data.EnumService;
import org.chai.kevin.data.Type;
import org.chai.kevin.location.DataLocationType;
import org.chai.kevin.value.Value;
/**
* @author Jean Kahigiso M.
*
*/
public class Utils {
private static EnumService enumService;
private static LanguageService languageService;
private final static String DATE_FORMAT = "dd-MM-yyyy";
private final static String DATE_FORMAT_TIME = "dd-MM-yyyy hh:mm:ss";
private final static String CSV_FILE_EXTENSION = ".csv";
private final static String ZIP_FILE_EXTENSION = ".zip";
public static Set<String> split(String string) {
Set<String> result = new HashSet<String>();
if (string != null) result.addAll(Arrays.asList(StringUtils.split(string, ',')));
return result;
}
public static String unsplit(Object list) {
List<String> result = new ArrayList<String>();
if (list instanceof String) result.add((String) list);
if (list instanceof Collection) result.addAll((Collection<String>)list);
else result.addAll(Arrays.asList((String[]) list));
for (String string : new ArrayList<String>(result)) {
if (string.isEmpty()) result.remove(string);
}
return StringUtils.join(result, ',');
}
@SuppressWarnings("unused")
private static boolean matches(String text, String value) {
if (value == null) return false;
return value.matches("(?i).*"+text+".*");
}
public static Set<String> getUuids(List<DataLocationType> types) {
Set<String> result = new HashSet<String>();
for (DataLocationType type : types) {
result.add(type.getCode());
}
return result;
}
public static String formatDate(Date date) {
if (date == null) return null;
return new SimpleDateFormat(DATE_FORMAT).format(date);
}
public static String formatDateWithTime(Date date) {
if (date == null) return null;
return new SimpleDateFormat(DATE_FORMAT_TIME).format(date);
}
public static Date parseDate(String string) throws ParseException {
return new SimpleDateFormat(DATE_FORMAT).parse(string);
}
public static boolean containsId(String string, Long id) {
return string.matches(".*\\$"+id+"(\\z|\\D|$).*");
}
public static String stripHtml(String htmlString, Integer num) {
String noHtmlString;
Integer length = num;
if (htmlString != null){
noHtmlString = htmlString.replace(" ", " ");
noHtmlString = noHtmlString.replaceAll("<.*?>", " ");
noHtmlString = StringEscapeUtils.unescapeHtml(noHtmlString);
noHtmlString = noHtmlString.trim();
}
else noHtmlString = htmlString;
if (num == null || noHtmlString.length() <= num) return noHtmlString;
return noHtmlString.substring(0, length);
}
public static String getValueString(Type type, Value value){
if(value != null && !value.isNull()){
switch (type.getType()) {
case NUMBER:
return value.getNumberValue().toString();
case BOOL:
return value.getBooleanValue().toString();
case STRING:
return value.getStringValue();
case TEXT:
return value.getStringValue();
case DATE:
if(value.getDateValue() != null) return Utils.formatDate(value.getDateValue());
else return value.getStringValue();
case ENUM:
- String enumCode = type.getEnumCode();
- Enum enume = enumService.getEnumByCode(enumCode);
- if(enume != null){
- EnumOption enumOption = enume.getOptionForValue(value.getEnumValue());
- if (enumOption != null) return languageService.getText(enumOption.getNames());
- }
return value.getStringValue();
default:
throw new IllegalArgumentException("get value string can only be called on simple type");
}
}
return "";
}
public static File getZipFile(File file, String filename) throws IOException {
File zipFile = File.createTempFile(filename, ZIP_FILE_EXTENSION);
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
FileInputStream fileInputStream = new FileInputStream(file);
try {
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(zipEntry);
IOUtils.copy(fileInputStream, zipOutputStream);
zipOutputStream.closeEntry();
} catch (IOException e) {
throw e;
} finally {
IOUtils.closeQuietly(zipOutputStream);
IOUtils.closeQuietly(zipOutputStream);
}
return zipFile;
}
}
| true | true | public static String getValueString(Type type, Value value){
if(value != null && !value.isNull()){
switch (type.getType()) {
case NUMBER:
return value.getNumberValue().toString();
case BOOL:
return value.getBooleanValue().toString();
case STRING:
return value.getStringValue();
case TEXT:
return value.getStringValue();
case DATE:
if(value.getDateValue() != null) return Utils.formatDate(value.getDateValue());
else return value.getStringValue();
case ENUM:
String enumCode = type.getEnumCode();
Enum enume = enumService.getEnumByCode(enumCode);
if(enume != null){
EnumOption enumOption = enume.getOptionForValue(value.getEnumValue());
if (enumOption != null) return languageService.getText(enumOption.getNames());
}
return value.getStringValue();
default:
throw new IllegalArgumentException("get value string can only be called on simple type");
}
}
return "";
}
| public static String getValueString(Type type, Value value){
if(value != null && !value.isNull()){
switch (type.getType()) {
case NUMBER:
return value.getNumberValue().toString();
case BOOL:
return value.getBooleanValue().toString();
case STRING:
return value.getStringValue();
case TEXT:
return value.getStringValue();
case DATE:
if(value.getDateValue() != null) return Utils.formatDate(value.getDateValue());
else return value.getStringValue();
case ENUM:
return value.getStringValue();
default:
throw new IllegalArgumentException("get value string can only be called on simple type");
}
}
return "";
}
|
diff --git a/src/directi/androidteam/training/chatclient/Chat/ChatListAdaptor.java b/src/directi/androidteam/training/chatclient/Chat/ChatListAdaptor.java
index 98a4a1a..24b2aa8 100644
--- a/src/directi/androidteam/training/chatclient/Chat/ChatListAdaptor.java
+++ b/src/directi/androidteam/training/chatclient/Chat/ChatListAdaptor.java
@@ -1,76 +1,76 @@
package directi.androidteam.training.chatclient.Chat;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import directi.androidteam.training.chatclient.R;
import java.util.Vector;
/**
* Created with IntelliJ IDEA.
* User: vinayak
* Date: 13/9/12
* Time: 2:51 PM
* To change this template use File | Settings | File Templates.
*/
public class ChatListAdaptor extends ArrayAdapter<ChatListItem> {
Context context;
public ChatListAdaptor(Context context, Vector<ChatListItem> objects) {
super(context, R.layout.chatlistitem, objects);
this.context=context;
}
@Override
public View getView(int position,View view,ViewGroup viewg){
Log.d("isSenderView","hey "+(new Integer(position)).toString());
View row = view;
if(row==null) {
LayoutInflater vi = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = vi.inflate(R.layout.chatlistitem,null);
}
ChatListItem cli = getItem(position);
getItem(position);
if(cli!=null) {
int layoutResourceId = cli.getResourceID();
Log.d("isSenderCli",cli.isSender()+""+cli.getMessage()+" "+(new Integer(position)).toString());
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, viewg, false);
ChatListHolder holder = new ChatListHolder();
if(cli.isSender()){
holder.status = (TextView)row.findViewById(R.id.chatlistitem_status);
holder.username = (TextView)row.findViewById(R.id.send_mess_name);
holder.message = (TextView)row.findViewById(R.id.send_mess_body);
holder.time = (TextView)row.findViewById(R.id.chatlistitem_time);
}
else{
holder.username = (TextView)row.findViewById(R.id.receive_mess_name);
holder.message = (TextView)row.findViewById(R.id.receive_mess_body);
holder.time = (TextView)row.findViewById(R.id.chatlistitemR_time);
}
row.setTag(holder);
if(!cli.isSender()){
holder.username.setText(cli.getUsername().split("@")[0]);
}
holder.message.setText(cli.getMessage());
holder.time.setText(cli.getTime());
- if(!cli.isStatus())
+ if(!cli.isStatus() && holder.status!=null)
holder.status.setVisibility(0);
}
return row;
}
static class ChatListHolder{
TextView username;
TextView message;
TextView time;
TextView status;
}
}
| true | true | public View getView(int position,View view,ViewGroup viewg){
Log.d("isSenderView","hey "+(new Integer(position)).toString());
View row = view;
if(row==null) {
LayoutInflater vi = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = vi.inflate(R.layout.chatlistitem,null);
}
ChatListItem cli = getItem(position);
getItem(position);
if(cli!=null) {
int layoutResourceId = cli.getResourceID();
Log.d("isSenderCli",cli.isSender()+""+cli.getMessage()+" "+(new Integer(position)).toString());
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, viewg, false);
ChatListHolder holder = new ChatListHolder();
if(cli.isSender()){
holder.status = (TextView)row.findViewById(R.id.chatlistitem_status);
holder.username = (TextView)row.findViewById(R.id.send_mess_name);
holder.message = (TextView)row.findViewById(R.id.send_mess_body);
holder.time = (TextView)row.findViewById(R.id.chatlistitem_time);
}
else{
holder.username = (TextView)row.findViewById(R.id.receive_mess_name);
holder.message = (TextView)row.findViewById(R.id.receive_mess_body);
holder.time = (TextView)row.findViewById(R.id.chatlistitemR_time);
}
row.setTag(holder);
if(!cli.isSender()){
holder.username.setText(cli.getUsername().split("@")[0]);
}
holder.message.setText(cli.getMessage());
holder.time.setText(cli.getTime());
if(!cli.isStatus())
holder.status.setVisibility(0);
}
return row;
}
| public View getView(int position,View view,ViewGroup viewg){
Log.d("isSenderView","hey "+(new Integer(position)).toString());
View row = view;
if(row==null) {
LayoutInflater vi = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = vi.inflate(R.layout.chatlistitem,null);
}
ChatListItem cli = getItem(position);
getItem(position);
if(cli!=null) {
int layoutResourceId = cli.getResourceID();
Log.d("isSenderCli",cli.isSender()+""+cli.getMessage()+" "+(new Integer(position)).toString());
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, viewg, false);
ChatListHolder holder = new ChatListHolder();
if(cli.isSender()){
holder.status = (TextView)row.findViewById(R.id.chatlistitem_status);
holder.username = (TextView)row.findViewById(R.id.send_mess_name);
holder.message = (TextView)row.findViewById(R.id.send_mess_body);
holder.time = (TextView)row.findViewById(R.id.chatlistitem_time);
}
else{
holder.username = (TextView)row.findViewById(R.id.receive_mess_name);
holder.message = (TextView)row.findViewById(R.id.receive_mess_body);
holder.time = (TextView)row.findViewById(R.id.chatlistitemR_time);
}
row.setTag(holder);
if(!cli.isSender()){
holder.username.setText(cli.getUsername().split("@")[0]);
}
holder.message.setText(cli.getMessage());
holder.time.setText(cli.getTime());
if(!cli.isStatus() && holder.status!=null)
holder.status.setVisibility(0);
}
return row;
}
|
diff --git a/src/com/android/email/RecipientAdapter.java b/src/com/android/email/RecipientAdapter.java
index 0a990f95..03a58ee1 100644
--- a/src/com/android/email/RecipientAdapter.java
+++ b/src/com/android/email/RecipientAdapter.java
@@ -1,70 +1,71 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email;
import com.android.ex.chips.BaseRecipientAdapter;
import com.android.ex.chips.RecipientEditTextView;
import android.accounts.Account;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class RecipientAdapter extends BaseRecipientAdapter {
public RecipientAdapter(Context context, RecipientEditTextView list) {
super(context);
Resources r = context.getResources();
Bitmap def = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
list.setChipDimensions(
r.getDrawable(R.drawable.chip_background),
r.getDrawable(R.drawable.chip_background_selected),
r.getDrawable(R.drawable.chip_background_invalid),
r.getDrawable(R.drawable.chip_delete), def, R.layout.more_item,
R.layout.chips_alternate_item,
r.getDimension(R.dimen.chip_height),
r.getDimension(R.dimen.chip_padding),
- r.getDimension(R.dimen.chip_text_size));
+ r.getDimension(R.dimen.chip_text_size),
+ R.layout.copy_chip_dialog_layout);
}
/**
* Set the account when known. Causes the search to prioritize contacts from
* that account.
*/
public void setAccount(Account account) {
if (account != null) {
// TODO: figure out how to infer the contacts account
// type from the email account
super.setAccount(new android.accounts.Account(account.name, "unknown"));
}
}
@Override
protected int getDefaultPhotoResource() {
return R.drawable.ic_contact_picture;
}
@Override
protected int getItemLayout() {
return R.layout.chips_recipient_dropdown_item;
}
@Override
protected int getWaitingForDirectorySearchLayout() {
return R.layout.chips_waiting_for_directory_search;
}
}
| true | true | public RecipientAdapter(Context context, RecipientEditTextView list) {
super(context);
Resources r = context.getResources();
Bitmap def = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
list.setChipDimensions(
r.getDrawable(R.drawable.chip_background),
r.getDrawable(R.drawable.chip_background_selected),
r.getDrawable(R.drawable.chip_background_invalid),
r.getDrawable(R.drawable.chip_delete), def, R.layout.more_item,
R.layout.chips_alternate_item,
r.getDimension(R.dimen.chip_height),
r.getDimension(R.dimen.chip_padding),
r.getDimension(R.dimen.chip_text_size));
}
| public RecipientAdapter(Context context, RecipientEditTextView list) {
super(context);
Resources r = context.getResources();
Bitmap def = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
list.setChipDimensions(
r.getDrawable(R.drawable.chip_background),
r.getDrawable(R.drawable.chip_background_selected),
r.getDrawable(R.drawable.chip_background_invalid),
r.getDrawable(R.drawable.chip_delete), def, R.layout.more_item,
R.layout.chips_alternate_item,
r.getDimension(R.dimen.chip_height),
r.getDimension(R.dimen.chip_padding),
r.getDimension(R.dimen.chip_text_size),
R.layout.copy_chip_dialog_layout);
}
|
diff --git a/smoketester/src/test/java/SmokeTest.java b/smoketester/src/test/java/SmokeTest.java
index 00fa312..184884f 100644
--- a/smoketester/src/test/java/SmokeTest.java
+++ b/smoketester/src/test/java/SmokeTest.java
@@ -1,30 +1,30 @@
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.containsString;
public class SmokeTest {
private static DefaultHttpClient client;
@BeforeClass
public static void setupClass() {
client = new DefaultHttpClient();
}
@Test
public void should_display_front_page() throws IOException {
HttpResponse response = client.execute(new HttpGet("http://localhost:9080/smidig2011/index.jsp"));
String content = EntityUtils.toString(response.getEntity());
- assertThat(content, containsString("woop woop"));
+ assertThat(content, containsString("shoop shoop"));
}
}
| true | true | public void should_display_front_page() throws IOException {
HttpResponse response = client.execute(new HttpGet("http://localhost:9080/smidig2011/index.jsp"));
String content = EntityUtils.toString(response.getEntity());
assertThat(content, containsString("woop woop"));
}
| public void should_display_front_page() throws IOException {
HttpResponse response = client.execute(new HttpGet("http://localhost:9080/smidig2011/index.jsp"));
String content = EntityUtils.toString(response.getEntity());
assertThat(content, containsString("shoop shoop"));
}
|
diff --git a/src/java/org/codehaus/groovy/grails/web/metaclass/RedirectDynamicMethod.java b/src/java/org/codehaus/groovy/grails/web/metaclass/RedirectDynamicMethod.java
index 5fe537e88..492965457 100644
--- a/src/java/org/codehaus/groovy/grails/web/metaclass/RedirectDynamicMethod.java
+++ b/src/java/org/codehaus/groovy/grails/web/metaclass/RedirectDynamicMethod.java
@@ -1,225 +1,224 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.web.metaclass;
import grails.util.GrailsNameUtils;
import groovy.lang.Closure;
import groovy.lang.GroovyObject;
import groovy.lang.MissingMethodException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.ControllerArtefactHandler;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.commons.metaclass.AbstractDynamicMethodInvocation;
import org.codehaus.groovy.grails.web.mapping.UrlCreator;
import org.codehaus.groovy.grails.web.mapping.UrlMappingsHolder;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.servlet.mvc.RedirectEventListener;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.CannotRedirectException;
import org.springframework.context.ApplicationContext;
import org.springframework.validation.Errors;
import org.springframework.web.context.request.RequestContextHolder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Implements the "redirect" Controller method for action redirection
*
* @author Graeme Rocher
* @since 0.2
*
* Created Oct 27, 2005
*/
public class RedirectDynamicMethod extends AbstractDynamicMethodInvocation {
public static final String METHOD_SIGNATURE = "redirect";
public static final Pattern METHOD_PATTERN = Pattern.compile('^'+METHOD_SIGNATURE+'$');
public static final String ARGUMENT_URI = "uri";
public static final String ARGUMENT_URL = "url";
public static final String ARGUMENT_CONTROLLER = "controller";
public static final String ARGUMENT_ACTION = "action";
public static final String ARGUMENT_ID = "id";
public static final String ARGUMENT_PARAMS = "params";
public static final String GRAILS_VIEWS_ENABLE_JSESSIONID = "grails.views.enable.jsessionid";
public static final String GRAILS_REDIRECT_ISSUED = "org.codehaus.groovy.grails.REDIRECT_ISSUED";
private static final String ARGUMENT_FRAGMENT = "fragment";
public static final String ARGUMENT_ERRORS = "errors";
private static final Log LOG = LogFactory.getLog(RedirectDynamicMethod.class);
private UrlMappingsHolder urlMappingsHolder;
private boolean useJessionId = false;
private ApplicationContext applicationContext;
public RedirectDynamicMethod(ApplicationContext applicationContext) {
super(METHOD_PATTERN);
if(applicationContext.containsBean(UrlMappingsHolder.BEAN_ID))
this.urlMappingsHolder = (UrlMappingsHolder)applicationContext.getBean(UrlMappingsHolder.BEAN_ID);
GrailsApplication application = (GrailsApplication) applicationContext.getBean(GrailsApplication.APPLICATION_ID);
Object o = application.getFlatConfig().get(GRAILS_VIEWS_ENABLE_JSESSIONID);
if(o instanceof Boolean) {
useJessionId = (Boolean) o;
}
this.applicationContext = applicationContext;
}
public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
Map argMap = arguments[0] instanceof Map ? (Map)arguments[0] : Collections.EMPTY_MAP;
if(argMap.size() == 0){
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
if(request.getAttribute(GRAILS_REDIRECT_ISSUED)!=null) {
throw new CannotRedirectException("Cannot issue a redirect(..) here. A previous call to redirect(..) has already redirected the response.");
}
if(response.isCommitted()) {
throw new CannotRedirectException("Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.");
}
Object actionRef = argMap.get(ARGUMENT_ACTION);
String controllerName = getControllerName(target, argMap);
Object id = argMap.get(ARGUMENT_ID);
String frag = argMap.get(ARGUMENT_FRAGMENT) != null ? argMap.get(ARGUMENT_FRAGMENT).toString() : null;
Object uri = argMap.get(ARGUMENT_URI);
String url = argMap.containsKey(ARGUMENT_URL) ? argMap.get(ARGUMENT_URL).toString() : null;
Map params = (Map)argMap.get(ARGUMENT_PARAMS);
if(params==null)params = new HashMap();
Errors errors = (Errors)argMap.get(ARGUMENT_ERRORS);
GroovyObject controller = (GroovyObject)target;
// if there are errors add it to the list of errors
Errors controllerErrors = (Errors)controller.getProperty( ControllerDynamicMethods.ERRORS_PROPERTY );
if(controllerErrors != null) {
controllerErrors.addAllErrors(errors);
}
else {
controller.setProperty( ControllerDynamicMethods.ERRORS_PROPERTY, errors);
}
String actualUri;
GrailsApplicationAttributes attrs = webRequest.getAttributes();
if(uri != null) {
actualUri = attrs.getApplicationUri(request) + uri.toString();
}
else if(url != null) {
actualUri = url;
}
else {
String actionName = establishActionName(actionRef, target, webRequest);
controllerName = controllerName != null ? controllerName : webRequest.getControllerName();
if(LOG.isDebugEnabled()) {
LOG.debug("Dynamic method [redirect] looking up URL mapping for controller ["+controllerName+"] and action ["+actionName+"] and params ["+params+"] with ["+urlMappingsHolder+"]");
}
try {
if( id != null ) params.put( ARGUMENT_ID, id );
UrlCreator urlMapping = urlMappingsHolder.getReverseMapping( controllerName, actionName, params );
if( LOG.isDebugEnabled() && urlMapping == null ) {
LOG.debug( "Dynamic method [redirect] no URL mapping found for params [" + params + "]" );
}
- String action = actionName != null ? actionName : webRequest.getActionName();
- actualUri = urlMapping.createURL( controllerName, action, params, request.getCharacterEncoding(), frag );
+ actualUri = urlMapping.createURL( controllerName, actionName, params, request.getCharacterEncoding(), frag );
if( LOG.isDebugEnabled() ) {
LOG.debug( "Dynamic method [redirect] mapped to URL [" + actualUri + "]" );
}
} finally {
if( id != null ) params.remove( ARGUMENT_ID );
}
}
return redirectResponse(actualUri, request,response);
}
private String getControllerName(Object target, Map argMap) {
return argMap.containsKey(ARGUMENT_CONTROLLER) ? argMap.get(ARGUMENT_CONTROLLER).toString() : GrailsNameUtils.getLogicalPropertyName(target.getClass().getName(), ControllerArtefactHandler.TYPE);
}
/*
* Redirects the response the the given URI
*/
private Object redirectResponse(String actualUri, HttpServletRequest request, HttpServletResponse response) {
if(LOG.isDebugEnabled()) {
LOG.debug("Dynamic method [redirect] forwarding request to ["+actualUri +"]");
}
try {
if(LOG.isDebugEnabled()) {
LOG.debug("Executing redirect with response ["+response+"]");
}
String redirectUrl = useJessionId ? response.encodeRedirectURL(actualUri) : actualUri;
response.sendRedirect(redirectUrl);
Map<String, RedirectEventListener> redirectListeners = applicationContext.getBeansOfType(RedirectEventListener.class);
for (RedirectEventListener redirectEventListener : redirectListeners.values()) {
redirectEventListener.responseRedirected(redirectUrl);
}
request.setAttribute(GRAILS_REDIRECT_ISSUED, true);
} catch (IOException e) {
throw new CannotRedirectException("Error redirecting request for url ["+actualUri +"]: " + e.getMessage(),e);
}
return null;
}
/*
* Figures out the action name from the specified action reference (either a string or closure)
*/
private String establishActionName(Object actionRef, Object target, GrailsWebRequest webRequest) {
String actionName = null;
if(actionRef instanceof String) {
actionName = (String)actionRef;
}
else if(actionRef instanceof Closure) {
Closure c = (Closure)actionRef;
actionName = GrailsClassUtils.findPropertyNameForValue(target, c);
}
return actionName;
}
}
| true | true | public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
Map argMap = arguments[0] instanceof Map ? (Map)arguments[0] : Collections.EMPTY_MAP;
if(argMap.size() == 0){
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
if(request.getAttribute(GRAILS_REDIRECT_ISSUED)!=null) {
throw new CannotRedirectException("Cannot issue a redirect(..) here. A previous call to redirect(..) has already redirected the response.");
}
if(response.isCommitted()) {
throw new CannotRedirectException("Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.");
}
Object actionRef = argMap.get(ARGUMENT_ACTION);
String controllerName = getControllerName(target, argMap);
Object id = argMap.get(ARGUMENT_ID);
String frag = argMap.get(ARGUMENT_FRAGMENT) != null ? argMap.get(ARGUMENT_FRAGMENT).toString() : null;
Object uri = argMap.get(ARGUMENT_URI);
String url = argMap.containsKey(ARGUMENT_URL) ? argMap.get(ARGUMENT_URL).toString() : null;
Map params = (Map)argMap.get(ARGUMENT_PARAMS);
if(params==null)params = new HashMap();
Errors errors = (Errors)argMap.get(ARGUMENT_ERRORS);
GroovyObject controller = (GroovyObject)target;
// if there are errors add it to the list of errors
Errors controllerErrors = (Errors)controller.getProperty( ControllerDynamicMethods.ERRORS_PROPERTY );
if(controllerErrors != null) {
controllerErrors.addAllErrors(errors);
}
else {
controller.setProperty( ControllerDynamicMethods.ERRORS_PROPERTY, errors);
}
String actualUri;
GrailsApplicationAttributes attrs = webRequest.getAttributes();
if(uri != null) {
actualUri = attrs.getApplicationUri(request) + uri.toString();
}
else if(url != null) {
actualUri = url;
}
else {
String actionName = establishActionName(actionRef, target, webRequest);
controllerName = controllerName != null ? controllerName : webRequest.getControllerName();
if(LOG.isDebugEnabled()) {
LOG.debug("Dynamic method [redirect] looking up URL mapping for controller ["+controllerName+"] and action ["+actionName+"] and params ["+params+"] with ["+urlMappingsHolder+"]");
}
try {
if( id != null ) params.put( ARGUMENT_ID, id );
UrlCreator urlMapping = urlMappingsHolder.getReverseMapping( controllerName, actionName, params );
if( LOG.isDebugEnabled() && urlMapping == null ) {
LOG.debug( "Dynamic method [redirect] no URL mapping found for params [" + params + "]" );
}
String action = actionName != null ? actionName : webRequest.getActionName();
actualUri = urlMapping.createURL( controllerName, action, params, request.getCharacterEncoding(), frag );
if( LOG.isDebugEnabled() ) {
LOG.debug( "Dynamic method [redirect] mapped to URL [" + actualUri + "]" );
}
} finally {
if( id != null ) params.remove( ARGUMENT_ID );
}
}
return redirectResponse(actualUri, request,response);
}
| public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
Map argMap = arguments[0] instanceof Map ? (Map)arguments[0] : Collections.EMPTY_MAP;
if(argMap.size() == 0){
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
if(request.getAttribute(GRAILS_REDIRECT_ISSUED)!=null) {
throw new CannotRedirectException("Cannot issue a redirect(..) here. A previous call to redirect(..) has already redirected the response.");
}
if(response.isCommitted()) {
throw new CannotRedirectException("Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.");
}
Object actionRef = argMap.get(ARGUMENT_ACTION);
String controllerName = getControllerName(target, argMap);
Object id = argMap.get(ARGUMENT_ID);
String frag = argMap.get(ARGUMENT_FRAGMENT) != null ? argMap.get(ARGUMENT_FRAGMENT).toString() : null;
Object uri = argMap.get(ARGUMENT_URI);
String url = argMap.containsKey(ARGUMENT_URL) ? argMap.get(ARGUMENT_URL).toString() : null;
Map params = (Map)argMap.get(ARGUMENT_PARAMS);
if(params==null)params = new HashMap();
Errors errors = (Errors)argMap.get(ARGUMENT_ERRORS);
GroovyObject controller = (GroovyObject)target;
// if there are errors add it to the list of errors
Errors controllerErrors = (Errors)controller.getProperty( ControllerDynamicMethods.ERRORS_PROPERTY );
if(controllerErrors != null) {
controllerErrors.addAllErrors(errors);
}
else {
controller.setProperty( ControllerDynamicMethods.ERRORS_PROPERTY, errors);
}
String actualUri;
GrailsApplicationAttributes attrs = webRequest.getAttributes();
if(uri != null) {
actualUri = attrs.getApplicationUri(request) + uri.toString();
}
else if(url != null) {
actualUri = url;
}
else {
String actionName = establishActionName(actionRef, target, webRequest);
controllerName = controllerName != null ? controllerName : webRequest.getControllerName();
if(LOG.isDebugEnabled()) {
LOG.debug("Dynamic method [redirect] looking up URL mapping for controller ["+controllerName+"] and action ["+actionName+"] and params ["+params+"] with ["+urlMappingsHolder+"]");
}
try {
if( id != null ) params.put( ARGUMENT_ID, id );
UrlCreator urlMapping = urlMappingsHolder.getReverseMapping( controllerName, actionName, params );
if( LOG.isDebugEnabled() && urlMapping == null ) {
LOG.debug( "Dynamic method [redirect] no URL mapping found for params [" + params + "]" );
}
actualUri = urlMapping.createURL( controllerName, actionName, params, request.getCharacterEncoding(), frag );
if( LOG.isDebugEnabled() ) {
LOG.debug( "Dynamic method [redirect] mapped to URL [" + actualUri + "]" );
}
} finally {
if( id != null ) params.remove( ARGUMENT_ID );
}
}
return redirectResponse(actualUri, request,response);
}
|
diff --git a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaRepositoryConnector.java b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaRepositoryConnector.java
index bddaaf394..59d2d0fce 100644
--- a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaRepositoryConnector.java
+++ b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaRepositoryConnector.java
@@ -1,678 +1,682 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.internal.bugzilla.core;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.mylyn.monitor.core.StatusHandler;
import org.eclipse.mylyn.tasks.core.AbstractAttachmentHandler;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryQuery;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.AbstractTaskDataHandler;
import org.eclipse.mylyn.tasks.core.ITaskCollector;
import org.eclipse.mylyn.tasks.core.ITaskFactory;
import org.eclipse.mylyn.tasks.core.QueryHitCollector;
import org.eclipse.mylyn.tasks.core.RepositoryTaskAttribute;
import org.eclipse.mylyn.tasks.core.RepositoryTaskData;
import org.eclipse.mylyn.tasks.core.TaskComment;
import org.eclipse.mylyn.tasks.core.TaskList;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.AbstractTask.PriorityLevel;
/**
* @author Mik Kersten
* @author Rob Elves
*/
public class BugzillaRepositoryConnector extends AbstractRepositoryConnector {
private static final String BUG_ID = "&bug_id=";
private static final String CHANGED_BUGS_CGI_ENDDATE = "&chfieldto=Now";
private static final String CHANGED_BUGS_CGI_QUERY = "/buglist.cgi?query_format=advanced&chfieldfrom=";
private static final String CLIENT_LABEL = "Bugzilla (supports uncustomized 2.18-3.0)";
private static final String COMMENT_FORMAT = "yyyy-MM-dd HH:mm";
private static final String DEADLINE_FORMAT = "yyyy-MM-dd";
private BugzillaAttachmentHandler attachmentHandler;
private BugzillaTaskDataHandler taskDataHandler;
private BugzillaClientManager clientManager;
@Override
public void init(TaskList taskList) {
super.init(taskList);
this.taskDataHandler = new BugzillaTaskDataHandler(this);
this.attachmentHandler = new BugzillaAttachmentHandler(this);
BugzillaCorePlugin.setConnector(this);
}
@Override
public String getLabel() {
return CLIENT_LABEL;
}
@Override
public AbstractAttachmentHandler getAttachmentHandler() {
return attachmentHandler;
}
@Override
public AbstractTaskDataHandler getTaskDataHandler() {
return taskDataHandler;
}
@Override
public String getConnectorKind() {
return BugzillaCorePlugin.REPOSITORY_KIND;
}
@Override
public AbstractTask createTask(String repositoryUrl, String id, String summary) {
BugzillaTask task = new BugzillaTask(repositoryUrl, id, summary);
task.setCreationDate(new Date());
return task;
}
@Override
public void updateTaskFromTaskData(TaskRepository repository, AbstractTask repositoryTask,
RepositoryTaskData taskData) {
BugzillaTask bugzillaTask = (BugzillaTask) repositoryTask;
if (taskData != null) {
//// // subtasks
// repositoryTask.dropSubTasks();
// Set<String> subTaskIds = taskDataHandler.getSubTaskIds(taskData);
// if (subTaskIds != null && !subTaskIds.isEmpty()) {
// for (String subId : subTaskIds) {
// ITask subTask = taskList.getTask(repository.getUrl(), subId);
//// if (subTask == null && retrieveSubTasks) {
//// if (!subId.trim().equals(taskData.getId()) && !subId.equals("")) {
//// try {
//// subTask = createTaskFromExistingId(repository, subId, false, new NullProgressMonitor());
//// } catch (CoreException e) {
//// // ignore
//// }
//// }
//// }
// if (subTask != null) {
// bugzillaTask.addSubTask(subTask);
// }
// }
// }
// Summary
String summary = taskData.getSummary();
bugzillaTask.setSummary(summary);
// Owner
String owner = taskData.getAssignedTo();
if (owner != null && !owner.equals("")) {
bugzillaTask.setOwner(owner);
}
// Creation Date
String createdString = taskData.getCreated();
if (createdString != null && createdString.length() > 0) {
Date dateCreated = taskData.getAttributeFactory().getDateForAttributeType(
RepositoryTaskAttribute.DATE_CREATION, taskData.getCreated());
if (dateCreated != null) {
bugzillaTask.setCreationDate(dateCreated);
}
}
// Completed
boolean isComplete = false;
// TODO: use repository configuration to determine what -completed-
// states are
if (taskData.getStatus() != null) {
isComplete = taskData.getStatus().equals(IBugzillaConstants.VALUE_STATUS_RESOLVED)
|| taskData.getStatus().equals(IBugzillaConstants.VALUE_STATUS_CLOSED)
|| taskData.getStatus().equals(IBugzillaConstants.VALUE_STATUS_VERIFIED);
}
bugzillaTask.setCompleted(isComplete);
// Completion Date
if (isComplete) {
Date completionDate = null;
try {
List<TaskComment> taskComments = taskData.getComments();
if (taskComments != null && !taskComments.isEmpty()) {
// TODO: fix not to be based on comment
completionDate = new SimpleDateFormat(COMMENT_FORMAT).parse(taskComments.get(
taskComments.size() - 1).getCreated());
}
} catch (Exception e) {
}
if (bugzillaTask.getCompletionDate() != null && completionDate != null) {
// if changed:
// TODO: get taskListManger.setDueDate(ITask task, Date
// dueDate)
}
bugzillaTask.setCompletionDate(completionDate);
}
// Priority
String priority = PriorityLevel.getDefault().toString();
if (taskData.getAttribute(RepositoryTaskAttribute.PRIORITY) != null) {
priority = taskData.getAttribute(RepositoryTaskAttribute.PRIORITY).getValue();
}
bugzillaTask.setPriority(priority);
// Task Web Url
String url = getTaskUrl(repository.getUrl(), taskData.getId());
if (url != null) {
bugzillaTask.setUrl(url);
}
// Bugzilla Specific Attributes
// Product
if (taskData.getProduct() != null) {
bugzillaTask.setProduct(taskData.getProduct());
}
// Severity
String severity = taskData.getAttributeValue(BugzillaReportElement.BUG_SEVERITY.getKeyString());
if (severity != null && !severity.equals("")) {
bugzillaTask.setSeverity(severity);
}
// Due Date
if (taskData.getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()) != null) {
Date dueDate = null;
// HACK: if estimated_time field exists, time tracking is
// enabled
try {
String dueStr = taskData.getAttributeValue(BugzillaReportElement.DEADLINE.getKeyString());
if (dueStr != null) {
dueDate = new SimpleDateFormat(DEADLINE_FORMAT).parse(dueStr);
}
} catch (Exception e) {
// ignore
}
bugzillaTask.setDueDate(dueDate);
}
}
}
@Override
public boolean updateTaskFromQueryHit(TaskRepository repository, AbstractTask existingTask, AbstractTask newTask) {
// these properties are not provided by Bugzilla queries
newTask.setCompleted(existingTask.isCompleted());
// newTask.setCompletionDate(existingTask.getCompletionDate());
boolean changed = super.updateTaskFromQueryHit(repository, existingTask, newTask);
if (existingTask instanceof BugzillaTask && newTask instanceof BugzillaTask) {
BugzillaTask existingBugzillaTask = (BugzillaTask) existingTask;
BugzillaTask newBugzillaTask = (BugzillaTask) newTask;
if (hasTaskPropertyChanged(existingBugzillaTask.getSeverity(), newBugzillaTask.getSeverity())) {
existingBugzillaTask.setSeverity(newBugzillaTask.getSeverity());
changed = true;
}
if (hasTaskPropertyChanged(existingBugzillaTask.getProduct(), newBugzillaTask.getProduct())) {
existingBugzillaTask.setProduct(newBugzillaTask.getProduct());
changed = true;
}
}
return changed;
}
@Override
public boolean markStaleTasks(TaskRepository repository, Set<AbstractTask> tasks, IProgressMonitor monitor)
throws CoreException {
try {
monitor.beginTask("Checking for changed tasks", IProgressMonitor.UNKNOWN);
if (repository.getSynchronizationTimeStamp() == null) {
for (AbstractTask task : tasks) {
task.setStale(true);
}
return true;
}
String dateString = repository.getSynchronizationTimeStamp();
if (dateString == null) {
dateString = "";
}
String urlQueryBase = repository.getUrl() + CHANGED_BUGS_CGI_QUERY
+ URLEncoder.encode(dateString, repository.getCharacterEncoding()) + CHANGED_BUGS_CGI_ENDDATE;
String urlQueryString = urlQueryBase + BUG_ID;
// Need to replace this with query that would return list of tasks since last sync
// the trouble is that bugzilla only have 1 hour granularity for "changed since" query
// so, we can't say that no tasks has changed in repository
Set<AbstractTask> changedTasks = new HashSet<AbstractTask>();
int queryCounter = -1;
Iterator<AbstractTask> itr = tasks.iterator();
while (itr.hasNext()) {
queryCounter++;
AbstractTask task = itr.next();
String newurlQueryString = URLEncoder.encode(task.getTaskId() + ",", repository.getCharacterEncoding());
if ((urlQueryString.length() + newurlQueryString.length() + IBugzillaConstants.CONTENT_TYPE_RDF.length()) > IBugzillaConstants.MAX_URL_LENGTH) {
queryForChanged(repository, changedTasks, urlQueryString);
queryCounter = 0;
urlQueryString = urlQueryBase + BUG_ID;
}
urlQueryString += newurlQueryString;
if (!itr.hasNext()) {
queryForChanged(repository, changedTasks, urlQueryString);
}
}
for (AbstractTask task : tasks) {
if (changedTasks.contains(task)) {
task.setStale(true);
}
}
// for (AbstractTask task : changedTasks) {
// task.setStale(true);
// }
// FIXME check if new tasks were added
//return changedTasks.isEmpty();
return true;
} catch (UnsupportedEncodingException e) {
// XXX throw CoreException instead?
StatusHandler.fail(e, "Repository configured with unsupported encoding: "
+ repository.getCharacterEncoding() + "\n\n Unable to determine changed tasks.", true);
return false;
} finally {
monitor.done();
}
}
private void queryForChanged(final TaskRepository repository, Set<AbstractTask> changedTasks, String urlQueryString)
throws UnsupportedEncodingException, CoreException {
QueryHitCollector collector = new QueryHitCollector(new ITaskFactory() {
public AbstractTask createTask(RepositoryTaskData taskData, IProgressMonitor monitor) {
// do not construct actual task objects here as query shouldn't result in new tasks
return taskList.getTask(taskData.getRepositoryUrl(), taskData.getId());
}
});
BugzillaRepositoryQuery query = new BugzillaRepositoryQuery(repository.getUrl(), urlQueryString, "");
performQuery(query, repository, new NullProgressMonitor(), collector);
changedTasks.addAll(collector.getTasks());
// for (AbstractTask taskHit : collector.getTaskHits()) {
// // String handle =
// // AbstractTask.getHandle(repository.getUrl(),
// // hit.getId());
// if (taskHit != null && taskHit instanceof AbstractTask) {
// AbstractTask repositoryTask = (AbstractTask) taskHit;
// // Hack to avoid re-syncing last task from previous
// // synchronization
// // This can be removed once we are getting a query timestamp
// // from the repository rather than
// // using the last modified stamp of the last task modified in
// // the return hits.
// // (or the changeddate field in the hit rdf becomes consistent,
// // currently it doesn't return a proper modified date string)
// // if (repositoryTask.getTaskData() != null
// // &&
// // repositoryTask.getTaskData().getLastModified().equals(repository.getSyncTimeStamp()))
// // {
// // // String taskId =
// // //
// // RepositoryTaskHandleUtil.getTaskId(repositoryTask.getHandleIdentifier());
// // RepositoryTaskData taskData =
// // getTaskDataHandler().getTaskData(repository,
// // repositoryTask.getTaskId());
// // if (taskData != null &&
// // taskData.getLastModified().equals(repository.getSyncTimeStamp()))
// // {
// // continue;
// // }
// // }
// changedTasks.add(repositoryTask);
// }
// }
}
@Override
public boolean canCreateTaskFromKey(TaskRepository repository) {
return true;
}
@Override
public boolean canCreateNewTask(TaskRepository repository) {
return true;
}
@Override
public IStatus performQuery(final AbstractRepositoryQuery query, TaskRepository repository,
IProgressMonitor monitor, ITaskCollector resultCollector) {
try {
monitor.beginTask("Running query", IProgressMonitor.UNKNOWN);
BugzillaClient client = getClientManager().getClient(repository);
boolean hitsReceived = client.getSearchHits(query, resultCollector);
if (!hitsReceived) {
// XXX: HACK in case of ip change bugzilla can return 0 hits
// due to invalid authorization token, forcing relogin fixes
client.logout();
client.getSearchHits(query, resultCollector);
}
return Status.OK_STATUS;
} catch (UnrecognizedReponseException e) {
return new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, Status.INFO,
"Unrecognized response from server", e);
} catch (IOException e) {
return new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, Status.ERROR,
"Check repository configuration: " + e.getMessage(), e);
} catch (CoreException e) {
return e.getStatus();
} finally {
monitor.done();
}
}
@Override
public String getRepositoryUrlFromTaskUrl(String url) {
if (url == null) {
return null;
}
int index = url.indexOf(IBugzillaConstants.URL_GET_SHOW_BUG);
return index == -1 ? null : url.substring(0, index);
}
@Override
public String getTaskIdFromTaskUrl(String url) {
if (url == null) {
return null;
}
int index = url.indexOf(IBugzillaConstants.URL_GET_SHOW_BUG);
return index == -1 ? null : url.substring(index + IBugzillaConstants.URL_GET_SHOW_BUG.length());
}
@Override
public String getTaskUrl(String repositoryUrl, String taskId) {
try {
return BugzillaClient.getBugUrlWithoutLogin(repositoryUrl, taskId);
} catch (Exception ex) {
StatusHandler.fail(ex, "Error constructing task url for " + repositoryUrl + " id:" + taskId, false);
}
return null;
}
@Override
public void updateTaskFromRepository(TaskRepository repository, AbstractTask repositoryTask,
IProgressMonitor monitor) {
// ignore
}
@Override
public String getTaskIdPrefix() {
return "bug";
}
public BugzillaClientManager getClientManager() {
if (clientManager == null) {
clientManager = new BugzillaClientManager();
}
return clientManager;
}
@Override
public void updateAttributes(TaskRepository repository, IProgressMonitor monitor) throws CoreException {
if (repository != null) {
BugzillaCorePlugin.getRepositoryConfiguration(repository, true);
}
}
public boolean isRepositoryConfigurationStale(TaskRepository repository) throws CoreException {
boolean result = true;
try {
BugzillaClient client = getClientManager().getClient(repository);
if (client != null) {
String timestamp = client.getConfigurationTimestamp();
if (timestamp != null) {
String oldTimestamp = repository.getProperty(IBugzillaConstants.PROPERTY_CONFIGTIMESTAMP);
if (oldTimestamp != null) {
result = !timestamp.equals(oldTimestamp);
}
repository.setProperty(IBugzillaConstants.PROPERTY_CONFIGTIMESTAMP, timestamp);
}
}
} catch (MalformedURLException e) {
StatusHandler.fail(e, "Error retrieving configuration timestamp for " + repository.getUrl(), false);
}
return result;
}
public void updateAttributeOptions(TaskRepository taskRepository, RepositoryTaskData existingReport)
throws CoreException {
String product = existingReport.getAttributeValue(BugzillaReportElement.PRODUCT.getKeyString());
for (RepositoryTaskAttribute attribute : existingReport.getAttributes()) {
BugzillaReportElement element = BugzillaReportElement.valueOf(attribute.getId().trim().toUpperCase(
Locale.ENGLISH));
attribute.clearOptions();
List<String> optionValues = BugzillaCorePlugin.getRepositoryConfiguration(taskRepository, false)
.getOptionValues(element, product);
if (element != BugzillaReportElement.OP_SYS && element != BugzillaReportElement.BUG_SEVERITY
&& element != BugzillaReportElement.PRIORITY && element != BugzillaReportElement.BUG_STATUS) {
Collections.sort(optionValues);
}
if (element == BugzillaReportElement.TARGET_MILESTONE && optionValues.isEmpty()) {
existingReport.removeAttribute(BugzillaReportElement.TARGET_MILESTONE);
continue;
}
attribute.clearOptions();
for (String option : optionValues) {
attribute.addOption(option, option);
}
// TODO: bug#162428, bug#150680 - something along the lines of...
// but must think about the case of multiple values selected etc.
// if(attribute.hasOptions()) {
// if(!attribute.getOptionValues().containsKey(attribute.getValue()))
// {
// // updateAttributes()
// }
// }
}
}
/**
* Adds bug attributes to new bug model and sets defaults
*
* @param proxySettings
* TODO
* @param characterEncoding
* TODO
*
*/
public static void setupNewBugAttributes(TaskRepository taskRepository, RepositoryTaskData newTaskData)
throws CoreException {
String product = newTaskData.getProduct();
newTaskData.removeAllAttributes();
RepositoryConfiguration repositoryConfiguration = BugzillaCorePlugin.getRepositoryConfiguration(taskRepository,
false);
RepositoryTaskAttribute a = BugzillaClient.makeNewAttribute(BugzillaReportElement.PRODUCT);
List<String> optionValues = repositoryConfiguration.getProducts();
Collections.sort(optionValues);
// for (String option : optionValues) {
// a.addOptionValue(option, option);
// }
a.setValue(product);
a.setReadOnly(true);
newTaskData.addAttribute(BugzillaReportElement.PRODUCT.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.BUG_STATUS);
optionValues = repositoryConfiguration.getStatusValues();
for (String option : optionValues) {
a.addOption(option, option);
}
a.setValue(IBugzillaConstants.VALUE_STATUS_NEW);
newTaskData.addAttribute(BugzillaReportElement.BUG_STATUS.getKeyString(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.SHORT_DESC);
newTaskData.addAttribute(BugzillaReportElement.SHORT_DESC.getKeyString(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.VERSION);
optionValues = repositoryConfiguration.getVersions(newTaskData.getProduct());
Collections.sort(optionValues);
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() > 0) {
a.setValue(optionValues.get(optionValues.size() - 1));
}
newTaskData.addAttribute(BugzillaReportElement.VERSION.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.COMPONENT);
optionValues = repositoryConfiguration.getComponents(newTaskData.getProduct());
Collections.sort(optionValues);
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() == 1) {
a.setValue(optionValues.get(0));
}
newTaskData.addAttribute(BugzillaReportElement.COMPONENT.getKeyString(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.REP_PLATFORM);
optionValues = repositoryConfiguration.getPlatforms();
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 choose first platform: All
a.setValue(optionValues.get(0));
}
newTaskData.addAttribute(BugzillaReportElement.REP_PLATFORM.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.OP_SYS);
optionValues = repositoryConfiguration.getOSs();
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 change to choose first op_sys All
a.setValue(optionValues.get(0));
}
newTaskData.addAttribute(BugzillaReportElement.OP_SYS.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.PRIORITY);
optionValues = repositoryConfiguration.getPriorities();
for (String option : optionValues) {
a.addOption(option, option);
}
- a.setValue(optionValues.get((optionValues.size() / 2))); // choose middle priority
+ if (optionValues.size() > 0) {
+ a.setValue(optionValues.get((optionValues.size() / 2))); // choose middle priority
+ }
newTaskData.addAttribute(BugzillaReportElement.PRIORITY.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.BUG_SEVERITY);
optionValues = repositoryConfiguration.getSeverities();
for (String option : optionValues) {
a.addOption(option, option);
}
- a.setValue(optionValues.get((optionValues.size() / 2))); // choose middle severity
+ if (optionValues.size() > 0) {
+ a.setValue(optionValues.get((optionValues.size() / 2))); // choose middle severity
+ }
newTaskData.addAttribute(BugzillaReportElement.BUG_SEVERITY.getKeyString(), a);
// attributes.put(a.getName(), a);
// a = new
// RepositoryTaskAttribute(BugzillaReportElement.TARGET_MILESTONE);
// optionValues =
// BugzillaCorePlugin.getDefault().getgetProductConfiguration(serverUrl).getTargetMilestones(
// newReport.getProduct());
// for (String option : optionValues) {
// a.addOptionValue(option, option);
// }
// if(optionValues.size() > 0) {
// // new bug posts will fail if target_milestone element is
// included
// // and there are no milestones on the server
// newReport.addAttribute(BugzillaReportElement.TARGET_MILESTONE, a);
// }
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.ASSIGNED_TO);
a.setValue("");
a.setReadOnly(false);
newTaskData.addAttribute(BugzillaReportElement.ASSIGNED_TO.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.BUG_FILE_LOC);
a.setValue("http://");
a.setHidden(false);
newTaskData.addAttribute(BugzillaReportElement.BUG_FILE_LOC.getKeyString(), a);
// attributes.put(a.getName(), a);
// newReport.attributes = attributes;
}
public static int getBugId(String taskId) throws CoreException {
try {
return Integer.parseInt(taskId);
} catch (NumberFormatException e) {
throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, 0, "Invalid bug id: "
+ taskId, e));
}
}
}
| false | true | public static void setupNewBugAttributes(TaskRepository taskRepository, RepositoryTaskData newTaskData)
throws CoreException {
String product = newTaskData.getProduct();
newTaskData.removeAllAttributes();
RepositoryConfiguration repositoryConfiguration = BugzillaCorePlugin.getRepositoryConfiguration(taskRepository,
false);
RepositoryTaskAttribute a = BugzillaClient.makeNewAttribute(BugzillaReportElement.PRODUCT);
List<String> optionValues = repositoryConfiguration.getProducts();
Collections.sort(optionValues);
// for (String option : optionValues) {
// a.addOptionValue(option, option);
// }
a.setValue(product);
a.setReadOnly(true);
newTaskData.addAttribute(BugzillaReportElement.PRODUCT.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.BUG_STATUS);
optionValues = repositoryConfiguration.getStatusValues();
for (String option : optionValues) {
a.addOption(option, option);
}
a.setValue(IBugzillaConstants.VALUE_STATUS_NEW);
newTaskData.addAttribute(BugzillaReportElement.BUG_STATUS.getKeyString(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.SHORT_DESC);
newTaskData.addAttribute(BugzillaReportElement.SHORT_DESC.getKeyString(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.VERSION);
optionValues = repositoryConfiguration.getVersions(newTaskData.getProduct());
Collections.sort(optionValues);
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() > 0) {
a.setValue(optionValues.get(optionValues.size() - 1));
}
newTaskData.addAttribute(BugzillaReportElement.VERSION.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.COMPONENT);
optionValues = repositoryConfiguration.getComponents(newTaskData.getProduct());
Collections.sort(optionValues);
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() == 1) {
a.setValue(optionValues.get(0));
}
newTaskData.addAttribute(BugzillaReportElement.COMPONENT.getKeyString(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.REP_PLATFORM);
optionValues = repositoryConfiguration.getPlatforms();
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 choose first platform: All
a.setValue(optionValues.get(0));
}
newTaskData.addAttribute(BugzillaReportElement.REP_PLATFORM.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.OP_SYS);
optionValues = repositoryConfiguration.getOSs();
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 change to choose first op_sys All
a.setValue(optionValues.get(0));
}
newTaskData.addAttribute(BugzillaReportElement.OP_SYS.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.PRIORITY);
optionValues = repositoryConfiguration.getPriorities();
for (String option : optionValues) {
a.addOption(option, option);
}
a.setValue(optionValues.get((optionValues.size() / 2))); // choose middle priority
newTaskData.addAttribute(BugzillaReportElement.PRIORITY.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.BUG_SEVERITY);
optionValues = repositoryConfiguration.getSeverities();
for (String option : optionValues) {
a.addOption(option, option);
}
a.setValue(optionValues.get((optionValues.size() / 2))); // choose middle severity
newTaskData.addAttribute(BugzillaReportElement.BUG_SEVERITY.getKeyString(), a);
// attributes.put(a.getName(), a);
// a = new
// RepositoryTaskAttribute(BugzillaReportElement.TARGET_MILESTONE);
// optionValues =
// BugzillaCorePlugin.getDefault().getgetProductConfiguration(serverUrl).getTargetMilestones(
// newReport.getProduct());
// for (String option : optionValues) {
// a.addOptionValue(option, option);
// }
// if(optionValues.size() > 0) {
// // new bug posts will fail if target_milestone element is
// included
// // and there are no milestones on the server
// newReport.addAttribute(BugzillaReportElement.TARGET_MILESTONE, a);
// }
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.ASSIGNED_TO);
a.setValue("");
a.setReadOnly(false);
newTaskData.addAttribute(BugzillaReportElement.ASSIGNED_TO.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.BUG_FILE_LOC);
a.setValue("http://");
a.setHidden(false);
newTaskData.addAttribute(BugzillaReportElement.BUG_FILE_LOC.getKeyString(), a);
// attributes.put(a.getName(), a);
// newReport.attributes = attributes;
}
| public static void setupNewBugAttributes(TaskRepository taskRepository, RepositoryTaskData newTaskData)
throws CoreException {
String product = newTaskData.getProduct();
newTaskData.removeAllAttributes();
RepositoryConfiguration repositoryConfiguration = BugzillaCorePlugin.getRepositoryConfiguration(taskRepository,
false);
RepositoryTaskAttribute a = BugzillaClient.makeNewAttribute(BugzillaReportElement.PRODUCT);
List<String> optionValues = repositoryConfiguration.getProducts();
Collections.sort(optionValues);
// for (String option : optionValues) {
// a.addOptionValue(option, option);
// }
a.setValue(product);
a.setReadOnly(true);
newTaskData.addAttribute(BugzillaReportElement.PRODUCT.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.BUG_STATUS);
optionValues = repositoryConfiguration.getStatusValues();
for (String option : optionValues) {
a.addOption(option, option);
}
a.setValue(IBugzillaConstants.VALUE_STATUS_NEW);
newTaskData.addAttribute(BugzillaReportElement.BUG_STATUS.getKeyString(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.SHORT_DESC);
newTaskData.addAttribute(BugzillaReportElement.SHORT_DESC.getKeyString(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.VERSION);
optionValues = repositoryConfiguration.getVersions(newTaskData.getProduct());
Collections.sort(optionValues);
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() > 0) {
a.setValue(optionValues.get(optionValues.size() - 1));
}
newTaskData.addAttribute(BugzillaReportElement.VERSION.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.COMPONENT);
optionValues = repositoryConfiguration.getComponents(newTaskData.getProduct());
Collections.sort(optionValues);
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() == 1) {
a.setValue(optionValues.get(0));
}
newTaskData.addAttribute(BugzillaReportElement.COMPONENT.getKeyString(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.REP_PLATFORM);
optionValues = repositoryConfiguration.getPlatforms();
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 choose first platform: All
a.setValue(optionValues.get(0));
}
newTaskData.addAttribute(BugzillaReportElement.REP_PLATFORM.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.OP_SYS);
optionValues = repositoryConfiguration.getOSs();
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 change to choose first op_sys All
a.setValue(optionValues.get(0));
}
newTaskData.addAttribute(BugzillaReportElement.OP_SYS.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.PRIORITY);
optionValues = repositoryConfiguration.getPriorities();
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() > 0) {
a.setValue(optionValues.get((optionValues.size() / 2))); // choose middle priority
}
newTaskData.addAttribute(BugzillaReportElement.PRIORITY.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.BUG_SEVERITY);
optionValues = repositoryConfiguration.getSeverities();
for (String option : optionValues) {
a.addOption(option, option);
}
if (optionValues.size() > 0) {
a.setValue(optionValues.get((optionValues.size() / 2))); // choose middle severity
}
newTaskData.addAttribute(BugzillaReportElement.BUG_SEVERITY.getKeyString(), a);
// attributes.put(a.getName(), a);
// a = new
// RepositoryTaskAttribute(BugzillaReportElement.TARGET_MILESTONE);
// optionValues =
// BugzillaCorePlugin.getDefault().getgetProductConfiguration(serverUrl).getTargetMilestones(
// newReport.getProduct());
// for (String option : optionValues) {
// a.addOptionValue(option, option);
// }
// if(optionValues.size() > 0) {
// // new bug posts will fail if target_milestone element is
// included
// // and there are no milestones on the server
// newReport.addAttribute(BugzillaReportElement.TARGET_MILESTONE, a);
// }
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.ASSIGNED_TO);
a.setValue("");
a.setReadOnly(false);
newTaskData.addAttribute(BugzillaReportElement.ASSIGNED_TO.getKeyString(), a);
// attributes.put(a.getName(), a);
a = BugzillaClient.makeNewAttribute(BugzillaReportElement.BUG_FILE_LOC);
a.setValue("http://");
a.setHidden(false);
newTaskData.addAttribute(BugzillaReportElement.BUG_FILE_LOC.getKeyString(), a);
// attributes.put(a.getName(), a);
// newReport.attributes = attributes;
}
|
diff --git a/crypto/src/org/bouncycastle/cms/KeyAgreeRecipientInformation.java b/crypto/src/org/bouncycastle/cms/KeyAgreeRecipientInformation.java
index 394b2a8d..6d327298 100644
--- a/crypto/src/org/bouncycastle/cms/KeyAgreeRecipientInformation.java
+++ b/crypto/src/org/bouncycastle/cms/KeyAgreeRecipientInformation.java
@@ -1,256 +1,256 @@
package org.bouncycastle.cms;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.cms.IssuerAndSerialNumber;
import org.bouncycastle.asn1.cms.KeyAgreeRecipientIdentifier;
import org.bouncycastle.asn1.cms.KeyAgreeRecipientInfo;
import org.bouncycastle.asn1.cms.OriginatorIdentifierOrKey;
import org.bouncycastle.asn1.cms.OriginatorPublicKey;
import org.bouncycastle.asn1.cms.RecipientEncryptedKey;
import org.bouncycastle.asn1.cms.RecipientKeyIdentifier;
import org.bouncycastle.asn1.cms.ecc.MQVuserKeyingMaterial;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jce.spec.MQVPrivateKeySpec;
import org.bouncycastle.jce.spec.MQVPublicKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
/**
* the RecipientInfo class for a recipient who has been sent a message
* encrypted using key agreement.
*/
public class KeyAgreeRecipientInformation
extends RecipientInformation
{
private KeyAgreeRecipientInfo info;
private ASN1OctetString _encryptedKey;
public KeyAgreeRecipientInformation(
KeyAgreeRecipientInfo info,
AlgorithmIdentifier encAlg,
InputStream data)
{
this(info, encAlg, null, data);
}
public KeyAgreeRecipientInformation(
KeyAgreeRecipientInfo info,
AlgorithmIdentifier encAlg,
AlgorithmIdentifier macAlg,
InputStream data)
{
super(encAlg, macAlg, AlgorithmIdentifier.getInstance(info.getKeyEncryptionAlgorithm()), data);
this.info = info;
this.rid = new RecipientId();
try
{
ASN1Sequence s = this.info.getRecipientEncryptedKeys();
// TODO Handle the case of more than one encrypted key
RecipientEncryptedKey id = RecipientEncryptedKey.getInstance(
s.getObjectAt(0));
KeyAgreeRecipientIdentifier karid = id.getIdentifier();
IssuerAndSerialNumber iAndSN = karid.getIssuerAndSerialNumber();
if (iAndSN != null)
{
rid.setIssuer(iAndSN.getName().getEncoded());
rid.setSerialNumber(iAndSN.getSerialNumber().getValue());
}
else
{
RecipientKeyIdentifier rKeyID = karid.getRKeyID();
- // Note: 'date' and 'other' fieldss of RecipientKeyIdentifier appear to be only informational
+ // Note: 'date' and 'other' fields of RecipientKeyIdentifier appear to be only informational
rid.setSubjectKeyIdentifier(rKeyID.getSubjectKeyIdentifier().getOctets());
}
_encryptedKey = id.getEncryptedKey();
}
catch (IOException e)
{
throw new IllegalArgumentException("invalid rid in KeyAgreeRecipientInformation");
}
}
private PublicKey getSenderPublicKey(Key receiverPrivateKey,
OriginatorIdentifierOrKey originator, Provider prov)
throws CMSException, GeneralSecurityException, IOException
{
OriginatorPublicKey opk = originator.getOriginatorKey();
if (opk != null)
{
return getPublicKeyFromOriginatorPublicKey(receiverPrivateKey, originator.getOriginatorKey(), prov);
}
OriginatorId origID = new OriginatorId();
IssuerAndSerialNumber iAndSN = originator.getIssuerAndSerialNumber();
if (iAndSN != null)
{
origID.setIssuer(iAndSN.getName().getEncoded());
origID.setSerialNumber(iAndSN.getSerialNumber().getValue());
}
else
{
SubjectKeyIdentifier ski = originator.getSubjectKeyIdentifier();
origID.setSubjectKeyIdentifier(ski.getKeyIdentifier());
}
return getPublicKeyFromOriginatorId(origID, prov);
}
private PublicKey getPublicKeyFromOriginatorPublicKey(Key receiverPrivateKey,
OriginatorPublicKey originatorPublicKey, Provider prov)
throws CMSException, GeneralSecurityException, IOException
{
PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(
ASN1Object.fromByteArray(receiverPrivateKey.getEncoded()));
SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(
privInfo.getAlgorithmId(),
originatorPublicKey.getPublicKey().getBytes());
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubInfo.getEncoded());
KeyFactory fact = KeyFactory.getInstance(keyEncAlg.getObjectId().getId(), prov);
return fact.generatePublic(pubSpec);
}
private PublicKey getPublicKeyFromOriginatorId(OriginatorId origID, Provider prov)
throws CMSException
{
// TODO Support all alternatives for OriginatorIdentifierOrKey
// see RFC 3852 6.2.2
throw new CMSException("No support for 'originator' as IssuerAndSerialNumber or SubjectKeyIdentifier");
}
private SecretKey calculateAgreedWrapKey(String wrapAlg,
PublicKey senderPublicKey, PrivateKey receiverPrivateKey, Provider prov)
throws CMSException, GeneralSecurityException, IOException
{
String agreeAlg = keyEncAlg.getObjectId().getId();
if (agreeAlg.equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF))
{
byte[] ukmEncoding = info.getUserKeyingMaterial().getOctets();
MQVuserKeyingMaterial ukm = MQVuserKeyingMaterial.getInstance(
ASN1Object.fromByteArray(ukmEncoding));
PublicKey ephemeralKey = getPublicKeyFromOriginatorPublicKey(receiverPrivateKey,
ukm.getEphemeralPublicKey(), prov);
senderPublicKey = new MQVPublicKeySpec(senderPublicKey, ephemeralKey);
receiverPrivateKey = new MQVPrivateKeySpec(receiverPrivateKey, receiverPrivateKey);
}
KeyAgreement agreement = KeyAgreement.getInstance(agreeAlg, prov);
agreement.init(receiverPrivateKey);
agreement.doPhase(senderPublicKey, true);
return agreement.generateSecret(wrapAlg);
}
private Key unwrapSessionKey(String wrapAlg, SecretKey agreedKey,
Provider prov)
throws GeneralSecurityException
{
AlgorithmIdentifier aid = encAlg;
if (aid == null)
{
aid = macAlg;
}
String alg = aid.getObjectId().getId();
byte[] encryptedKey = _encryptedKey.getOctets();
// TODO Should we try alternate ways of unwrapping?
// (see KeyTransRecipientInformation.getSessionKey)
Cipher keyCipher = Cipher.getInstance(wrapAlg, prov);
keyCipher.init(Cipher.UNWRAP_MODE, agreedKey);
return keyCipher.unwrap(encryptedKey, alg, Cipher.SECRET_KEY);
}
protected Key getSessionKey(Key receiverPrivateKey, Provider prov)
throws CMSException
{
try
{
String wrapAlg = DERObjectIdentifier.getInstance(
ASN1Sequence.getInstance(keyEncAlg.getParameters()).getObjectAt(0)).getId();
PublicKey senderPublicKey = getSenderPublicKey(receiverPrivateKey,
info.getOriginator(), prov);
SecretKey agreedWrapKey = calculateAgreedWrapKey(wrapAlg,
senderPublicKey, (PrivateKey)receiverPrivateKey, prov);
return unwrapSessionKey(wrapAlg, agreedWrapKey, prov);
}
catch (NoSuchAlgorithmException e)
{
throw new CMSException("can't find algorithm.", e);
}
catch (InvalidKeyException e)
{
throw new CMSException("key invalid in message.", e);
}
catch (InvalidKeySpecException e)
{
throw new CMSException("originator key spec invalid.", e);
}
catch (NoSuchPaddingException e)
{
throw new CMSException("required padding not supported.", e);
}
catch (Exception e)
{
throw new CMSException("originator key invalid.", e);
}
}
/**
* decrypt the content and return it
*/
public CMSTypedStream getContentStream(
Key key,
String prov)
throws CMSException, NoSuchProviderException
{
return getContentStream(key, CMSUtils.getProvider(prov));
}
public CMSTypedStream getContentStream(
Key key,
Provider prov)
throws CMSException
{
Key sKey = getSessionKey(key, prov);
return getContentFromSessionKey(sKey, prov);
}
}
| true | true | public KeyAgreeRecipientInformation(
KeyAgreeRecipientInfo info,
AlgorithmIdentifier encAlg,
AlgorithmIdentifier macAlg,
InputStream data)
{
super(encAlg, macAlg, AlgorithmIdentifier.getInstance(info.getKeyEncryptionAlgorithm()), data);
this.info = info;
this.rid = new RecipientId();
try
{
ASN1Sequence s = this.info.getRecipientEncryptedKeys();
// TODO Handle the case of more than one encrypted key
RecipientEncryptedKey id = RecipientEncryptedKey.getInstance(
s.getObjectAt(0));
KeyAgreeRecipientIdentifier karid = id.getIdentifier();
IssuerAndSerialNumber iAndSN = karid.getIssuerAndSerialNumber();
if (iAndSN != null)
{
rid.setIssuer(iAndSN.getName().getEncoded());
rid.setSerialNumber(iAndSN.getSerialNumber().getValue());
}
else
{
RecipientKeyIdentifier rKeyID = karid.getRKeyID();
// Note: 'date' and 'other' fieldss of RecipientKeyIdentifier appear to be only informational
rid.setSubjectKeyIdentifier(rKeyID.getSubjectKeyIdentifier().getOctets());
}
_encryptedKey = id.getEncryptedKey();
}
catch (IOException e)
{
throw new IllegalArgumentException("invalid rid in KeyAgreeRecipientInformation");
}
}
| public KeyAgreeRecipientInformation(
KeyAgreeRecipientInfo info,
AlgorithmIdentifier encAlg,
AlgorithmIdentifier macAlg,
InputStream data)
{
super(encAlg, macAlg, AlgorithmIdentifier.getInstance(info.getKeyEncryptionAlgorithm()), data);
this.info = info;
this.rid = new RecipientId();
try
{
ASN1Sequence s = this.info.getRecipientEncryptedKeys();
// TODO Handle the case of more than one encrypted key
RecipientEncryptedKey id = RecipientEncryptedKey.getInstance(
s.getObjectAt(0));
KeyAgreeRecipientIdentifier karid = id.getIdentifier();
IssuerAndSerialNumber iAndSN = karid.getIssuerAndSerialNumber();
if (iAndSN != null)
{
rid.setIssuer(iAndSN.getName().getEncoded());
rid.setSerialNumber(iAndSN.getSerialNumber().getValue());
}
else
{
RecipientKeyIdentifier rKeyID = karid.getRKeyID();
// Note: 'date' and 'other' fields of RecipientKeyIdentifier appear to be only informational
rid.setSubjectKeyIdentifier(rKeyID.getSubjectKeyIdentifier().getOctets());
}
_encryptedKey = id.getEncryptedKey();
}
catch (IOException e)
{
throw new IllegalArgumentException("invalid rid in KeyAgreeRecipientInformation");
}
}
|
diff --git a/src/de/ueller/midlet/gps/Trace.java b/src/de/ueller/midlet/gps/Trace.java
index 420fe046..f96839dc 100644
--- a/src/de/ueller/midlet/gps/Trace.java
+++ b/src/de/ueller/midlet/gps/Trace.java
@@ -1,3559 +1,3567 @@
/*
* GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net
* See file COPYING.
*/
package de.ueller.midlet.gps;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
//#if polish.api.fileconnection
import javax.microedition.io.file.FileConnection;
//#endif
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.List;
//#if polish.android
import android.view.WindowManager;
//#else
import javax.microedition.lcdui.game.GameCanvas;
//#endif
import javax.microedition.midlet.MIDlet;
import de.enough.polish.util.Locale;
import de.ueller.gps.SECellID;
import de.ueller.gps.GetCompass;
import de.ueller.gps.data.Legend;
import de.ueller.gps.data.Configuration;
import de.ueller.gps.data.Position;
import de.ueller.gps.data.Satellite;
import de.ueller.gps.nmea.NmeaInput;
import de.ueller.gps.sirf.SirfInput;
import de.ueller.gps.tools.DateTimeTools;
import de.ueller.gps.tools.HelperRoutines;
import de.ueller.gps.tools.IconActionPerformer;
import de.ueller.gps.tools.LayoutElement;
import de.ueller.gps.urls.Urls;
import de.ueller.gpsMid.mapData.DictReader;
//#if polish.api.osm-editing
import de.ueller.midlet.gps.GuiOSMWayDisplay;
import de.ueller.midlet.gps.data.EditableWay;
//#endif
import de.ueller.gpsMid.CancelMonitorInterface;
import de.ueller.gpsMid.mapData.QueueDataReader;
import de.ueller.gpsMid.mapData.QueueDictReader;
import de.ueller.gpsMid.mapData.Tile;
import de.ueller.midlet.gps.data.CellIdProvider;
import de.ueller.midlet.gps.data.CompassProvider;
import de.ueller.midlet.gps.data.Compass;
import de.ueller.midlet.gps.data.GSMCell;
import de.ueller.midlet.gps.data.Proj2D;
import de.ueller.midlet.gps.data.ProjFactory;
import de.ueller.midlet.gps.data.ProjMath;
import de.ueller.midlet.gps.data.Gpx;
import de.ueller.midlet.gps.data.IntPoint;
import de.ueller.midlet.gps.data.MoreMath;
import de.ueller.midlet.gps.data.Node;
import de.ueller.midlet.gps.data.PositionMark;
import de.ueller.midlet.gps.data.Projection;
import de.ueller.midlet.gps.data.Proj3D;
import de.ueller.midlet.gps.data.RoutePositionMark;
import de.ueller.midlet.gps.data.SECellLocLogger;
import de.ueller.midlet.gps.data.Way;
import de.ueller.midlet.gps.names.Names;
import de.ueller.midlet.gps.routing.RouteNode;
import de.ueller.midlet.gps.routing.Routing;
import de.ueller.midlet.gps.GuiMapFeatures;
import de.ueller.midlet.gps.tile.Images;
import de.ueller.midlet.gps.tile.PaintContext;
import de.ueller.midlet.gps.GpsMidDisplayable;
import de.ueller.midlet.screens.GuiWaypointPredefined;
//#if polish.android
import de.enough.polish.android.midlet.MidletBridge;
//#endif
/**
* Implements the main "Map" screen which displays the map, offers track recording etc.
* @author Harald Mueller
*
*/
public class Trace extends KeyCommandCanvas implements LocationMsgReceiver,
CompassReceiver, Runnable , GpsMidDisplayable, CompletionListener, IconActionPerformer {
/** Soft button for exiting the map screen */
protected static final int EXIT_CMD = 1;
protected static final int CONNECT_GPS_CMD = 2;
protected static final int DISCONNECT_GPS_CMD = 3;
protected static final int START_RECORD_CMD = 4;
protected static final int STOP_RECORD_CMD = 5;
protected static final int MANAGE_TRACKS_CMD = 6;
protected static final int SAVE_WAYP_CMD = 7;
protected static final int ENTER_WAYP_CMD = 8;
protected static final int MAN_WAYP_CMD = 9;
protected static final int ROUTING_TOGGLE_CMD = 10;
protected static final int CAMERA_CMD = 11;
protected static final int CLEAR_DEST_CMD = 12;
protected static final int SET_DEST_CMD = 13;
protected static final int MAPFEATURES_CMD = 14;
protected static final int RECORDINGS_CMD = 16;
protected static final int ROUTINGS_CMD = 17;
protected static final int OK_CMD =18;
protected static final int BACK_CMD = 19;
protected static final int ZOOM_IN_CMD = 20;
protected static final int ZOOM_OUT_CMD = 21;
protected static final int MANUAL_ROTATION_MODE_CMD = 22;
protected static final int TOGGLE_OVERLAY_CMD = 23;
protected static final int TOGGLE_BACKLIGHT_CMD = 24;
protected static final int TOGGLE_FULLSCREEN_CMD = 25;
protected static final int TOGGLE_MAP_PROJ_CMD = 26;
protected static final int TOGGLE_KEY_LOCK_CMD = 27;
protected static final int TOGGLE_RECORDING_CMD = 28;
protected static final int TOGGLE_RECORDING_SUSP_CMD = 29;
protected static final int RECENTER_GPS_CMD = 30;
protected static final int DATASCREEN_CMD = 31;
protected static final int OVERVIEW_MAP_CMD = 32;
protected static final int RETRIEVE_XML = 33;
protected static final int PAN_LEFT25_CMD = 34;
protected static final int PAN_RIGHT25_CMD = 35;
protected static final int PAN_UP25_CMD = 36;
protected static final int PAN_DOWN25_CMD = 37;
protected static final int PAN_LEFT2_CMD = 38;
protected static final int PAN_RIGHT2_CMD = 39;
protected static final int PAN_UP2_CMD = 40;
protected static final int PAN_DOWN2_CMD = 41;
protected static final int REFRESH_CMD = 42;
protected static final int SEARCH_CMD = 43;
protected static final int TOGGLE_AUDIO_REC = 44;
protected static final int ROUTING_START_CMD = 45;
protected static final int ROUTING_STOP_CMD = 46;
protected static final int ONLINE_INFO_CMD = 47;
protected static final int ROUTING_START_WITH_MODE_SELECT_CMD = 48;
protected static final int RETRIEVE_NODE = 49;
protected static final int ICON_MENU = 50;
protected static final int ABOUT_CMD = 51;
protected static final int SETUP_CMD = 52;
protected static final int SEND_MESSAGE_CMD = 53;
protected static final int SHOW_DEST_CMD = 54;
protected static final int EDIT_ADDR_CMD = 55;
protected static final int OPEN_URL_CMD = 56;
protected static final int SHOW_PREVIOUS_POSITION_CMD = 57;
protected static final int TOGGLE_GPS_CMD = 58;
protected static final int CELLID_LOCATION_CMD = 59;
protected static final int MANUAL_LOCATION_CMD = 60;
protected static final int EDIT_ENTITY = 61;
private final Command [] CMDS = new Command[62];
public static final int DATASCREEN_NONE = 0;
public static final int DATASCREEN_TACHO = 1;
public static final int DATASCREEN_TRIP = 2;
public static final int DATASCREEN_SATS = 3;
public final static int DISTANCE_GENERIC = 1;
public final static int DISTANCE_ALTITUDE = 2;
public final static int DISTANCE_ROAD = 3;
public final static int DISTANCE_AIR = 4;
public final static int DISTANCE_UNKNOWN = 5;
// private SirfInput si;
private LocationMsgProducer locationProducer;
private LocationMsgProducer cellIDLocationProducer = null;
private CompassProducer compassProducer = null;
private volatile int compassDirection = 0;
private volatile int compassDeviation = 0;
private volatile int compassDeviated = 0;
public byte solution = LocationMsgReceiver.STATUS_OFF;
public String solutionStr = Locale.get("solution.Off");
/** Flag if the user requested to be centered to the current GPS position (true)
* or if the user moved the map away from this position (false).
*/
public boolean gpsRecenter = true;
/** Flag if the gps position is not yet valid after recenter request
*/
public volatile boolean gpsRecenterInvalid = true;
/** Flag if the gps position is stale (last known position instead of current) after recenter request
*/
public volatile boolean gpsRecenterStale = true;
/** Flag if the map is autoZoomed
*/
public boolean autoZoomed = true;
private Position pos = new Position(0.0f, 0.0f,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis());
/**
* this node contains actually RAD coordinates
* although the constructor for Node(lat, lon) requires parameters in DEC format
* - e. g. "new Node(49.328010f, 11.352556f)"
*/
public Node center = new Node(49.328010f, 11.352556f);
private Node prevPositionNode = null;
// Projection projection;
private final GpsMid parent;
public static TraceLayout tl = null;
private String lastTitleMsg;
private String currentTitleMsg;
private volatile int currentTitleMsgOpenCount = 0;
private volatile int setTitleMsgTimeout = 0;
private String lastTitleMsgClock;
private String currentAlertTitle;
private String currentAlertMessage;
private volatile int currentAlertsOpenCount = 0;
private volatile int setAlertTimeout = 0;
private long lastBackLightOnTime = 0;
private volatile static long lastUserActionTime = 0;
private long collected = 0;
public PaintContext pc;
public float scale = Configuration.getRealBaseScale();
int showAddons = 0;
/** x position display was touched last time (on pointerPressed() ) */
private static int touchX = 0;
/** y position display was touched last time (on pointerPressed() ) */
private static int touchY = 0;
/** x position display was released last time (on pointerReleased() ) */
private static int touchReleaseX = 0;
/** y position display was released last time (on pointerReleased() ) */
private static int touchReleaseY = 0;
/** center when display was touched last time (on pointerReleased() ) */
private static Node centerPointerPressedN = new Node();
private static Node pickPointStart = new Node();
private static Node pickPointEnd = new Node();
/**
* time at which a pointer press occured to determine
* single / double / long taps
*/
private long pressedPointerTime;
/**
* indicates if the next release event is valid or the corresponding pointer pressing has already been handled
*/
private volatile boolean pointerActionDone;
/** timer checking for single tap */
private volatile TimerTask singleTapTimerTask = null;
/** timer checking for long tap */
private volatile TimerTask longTapTimerTask = null;
/** timer for returning to small buttons */
private volatile TimerTask bigButtonTimerTask = null;
/**
* Indicates that there was any drag event since the last pointerPressed
*/
private static volatile boolean pointerDragged = false;
/**
* Indicates that there was a rather far drag event since the last pointerPressed
*/
private static volatile boolean pointerDraggedMuch = false;
/** indicates whether we already are checking for a single tap in the TimerTask */
private static volatile boolean checkingForSingleTap = false;
private final int DOUBLETAP_MAXDELAY = 300;
private final int LONGTAP_DELAY = 1000;
public volatile boolean routeCalc=false;
public Tile tiles[] = new Tile[6];
public volatile boolean baseTilesRead = false;
public Way actualSpeedLimitWay;
// this is only for visual debugging of the routing engine
Vector routeNodes = new Vector();
private long oldRecalculationTime;
private List recordingsMenu = null;
private List routingsMenu = null;
private GuiTacho guiTacho = null;
private GuiTrip guiTrip = null;
private GuiSatellites guiSatellites = null;
private GuiWaypointSave guiWaypointSave = null;
private final GuiWaypointPredefined guiWaypointPredefined = null;
private static TraceIconMenu traceIconMenu = null;
private final static Logger logger = Logger.getInstance(Trace.class, Logger.DEBUG);
//#mdebug info
public static final String statMsg[] = { "no Start1:", "no Start2:",
"to long :", "interrupt:", "checksum :", "no End1 :",
"no End2 :" };
//#enddebug
/**
* Quality of Bluetooth reception, 0..100.
*/
private byte btquality;
private int[] statRecord;
/**
* Current speed from GPS in km/h.
*/
public volatile int speed;
public volatile float fspeed;
/**
* variables for setting course from GPS movement
* TODO: make speed threshold (currently courseMinSpeed)
* user-settable by transfer mode in the style file
* and/or in user menu
*/
// was three until release 0.7; less than three allows
// for course setting even with slow walking, while
// the heuristics filter away erratic courses
// I've even tested with 0.5f with good results --jkpj
private final float courseMinSpeed = 1.5f;
private volatile int prevCourse = -1;
private volatile int secondPrevCourse = -1;
private volatile int thirdPrevCourse = -1;
/**
* Current altitude from GPS in m.
*/
public volatile int altitude;
/**
* Flag if we're speeding
*/
private volatile boolean speeding = false;
private long lastTimeOfSpeedingSound = 0;
private long startTimeOfSpeedingSign = 0;
private int speedingSpeedLimit = 0;
/**
* Current course from GPS in compass degrees, 0..359.
*/
private int course = 0;
private int coursegps = 0;
public boolean atDest = false;
public boolean movedAwayFromDest = true;
private Names namesThread;
private Urls urlsThread;
private ImageCollector imageCollector;
private QueueDataReader tileReader;
private QueueDictReader dictReader;
private final Runtime runtime = Runtime.getRuntime();
private RoutePositionMark dest = null;
public Vector route = null;
private RouteInstructions ri = null;
private boolean running = false;
private static final int CENTERPOS = Graphics.HCENTER | Graphics.VCENTER;
public Gpx gpx;
public AudioRecorder audioRec;
private static volatile Trace traceInstance = null;
private Routing routeEngine;
/*
private static Font smallBoldFont;
private static int smallBoldFontHeight;
*/
public boolean manualRotationMode = false;
public Vector locationUpdateListeners;
private Projection panProjection;
private Trace() throws Exception {
//#debug
logger.info("init Trace");
this.parent = GpsMid.getInstance();
Configuration.setHasPointerEvents(hasPointerEvents());
CMDS[EXIT_CMD] = new Command(Locale.get("generic.Exit")/*Exit*/, Command.EXIT, 2);
CMDS[REFRESH_CMD] = new Command(Locale.get("trace.Refresh")/*Refresh*/, Command.ITEM, 4);
CMDS[SEARCH_CMD] = new Command(Locale.get("generic.Search")/*Search*/, Command.OK, 1);
CMDS[CONNECT_GPS_CMD] = new Command(Locale.get("trace.StartGPS")/*Start GPS*/,Command.ITEM, 2);
CMDS[DISCONNECT_GPS_CMD] = new Command(Locale.get("trace.StopGPS")/*Stop GPS*/,Command.ITEM, 2);
CMDS[TOGGLE_GPS_CMD] = new Command(Locale.get("trace.ToggleGPS")/*Toggle GPS*/,Command.ITEM, 2);
CMDS[START_RECORD_CMD] = new Command(Locale.get("trace.StartRecord")/*Start record*/,Command.ITEM, 4);
CMDS[STOP_RECORD_CMD] = new Command(Locale.get("trace.StopRecord")/*Stop record*/,Command.ITEM, 4);
CMDS[MANAGE_TRACKS_CMD] = new Command(Locale.get("trace.ManageTracks")/*Manage tracks*/,Command.ITEM, 5);
CMDS[SAVE_WAYP_CMD] = new Command(Locale.get("trace.SaveWaypoint")/*Save waypoint*/,Command.ITEM, 7);
CMDS[ENTER_WAYP_CMD] = new Command(Locale.get("trace.EnterWaypoint")/*Enter waypoint*/,Command.ITEM, 7);
CMDS[MAN_WAYP_CMD] = new Command(Locale.get("trace.ManageWaypoints")/*Manage waypoints*/,Command.ITEM, 7);
CMDS[ROUTING_TOGGLE_CMD] = new Command(Locale.get("trace.ToggleRouting")/*Toggle routing*/,Command.ITEM, 3);
CMDS[CAMERA_CMD] = new Command(Locale.get("trace.Camera")/*Camera*/,Command.ITEM, 9);
CMDS[CLEAR_DEST_CMD] = new Command(Locale.get("trace.ClearDestination")/*Clear destination*/,Command.ITEM, 10);
CMDS[SET_DEST_CMD] = new Command(Locale.get("trace.AsDestination")/*As destination*/,Command.ITEM, 11);
CMDS[MAPFEATURES_CMD] = new Command(Locale.get("trace.MapFeatures")/*Map Features*/,Command.ITEM, 12);
CMDS[RECORDINGS_CMD] = new Command(Locale.get("trace.Recordings")/*Recordings...*/,Command.ITEM, 4);
CMDS[ROUTINGS_CMD] = new Command(Locale.get("trace.Routing3")/*Routing...*/,Command.ITEM, 3);
CMDS[OK_CMD] = new Command(Locale.get("generic.OK")/*OK*/,Command.OK, 14);
CMDS[BACK_CMD] = new Command(Locale.get("generic.Back")/*Back*/,Command.BACK, 15);
CMDS[ZOOM_IN_CMD] = new Command(Locale.get("trace.ZoomIn")/*Zoom in*/,Command.ITEM, 100);
CMDS[ZOOM_OUT_CMD] = new Command(Locale.get("trace.ZoomOut")/*Zoom out*/,Command.ITEM, 100);
CMDS[MANUAL_ROTATION_MODE_CMD] = new Command(Locale.get("trace.ManualRotation2")/*Manual rotation mode*/,Command.ITEM, 100);
CMDS[TOGGLE_OVERLAY_CMD] = new Command(Locale.get("trace.NextOverlay")/*Next overlay*/,Command.ITEM, 100);
CMDS[TOGGLE_BACKLIGHT_CMD] = new Command(Locale.get("trace.KeepBacklight")/*Keep backlight on/off*/,Command.ITEM, 100);
CMDS[TOGGLE_FULLSCREEN_CMD] = new Command(Locale.get("trace.SwitchToFullscreen")/*Switch to fullscreen*/,Command.ITEM, 100);
CMDS[TOGGLE_MAP_PROJ_CMD] = new Command(Locale.get("trace.NextMapProjection")/*Next map projection*/,Command.ITEM, 100);
CMDS[TOGGLE_KEY_LOCK_CMD] = new Command(Locale.get("trace.ToggleKeylock")/*(De)Activate Keylock*/,Command.ITEM, 100);
CMDS[TOGGLE_RECORDING_CMD] = new Command(Locale.get("trace.ToggleRecording")/*(De)Activate recording*/,Command.ITEM, 100);
CMDS[TOGGLE_RECORDING_SUSP_CMD] = new Command(Locale.get("trace.SuspendRecording")/*Suspend recording*/,Command.ITEM, 100);
CMDS[RECENTER_GPS_CMD] = new Command(Locale.get("trace.RecenterOnGPS")/*Recenter on GPS*/,Command.ITEM, 100);
CMDS[SHOW_DEST_CMD] = new Command(Locale.get("trace.ShowDestination")/*Show destination*/,Command.ITEM, 100);
CMDS[SHOW_PREVIOUS_POSITION_CMD] = new Command(Locale.get("trace.ShowPreviousPosition")/*Previous position*/,Command.ITEM, 100);
CMDS[DATASCREEN_CMD] = new Command(Locale.get("trace.Tacho")/*Tacho*/, Command.ITEM, 15);
CMDS[OVERVIEW_MAP_CMD] = new Command(Locale.get("trace.OverviewFilterMap")/*Overview/Filter map*/, Command.ITEM, 20);
CMDS[RETRIEVE_XML] = new Command(Locale.get("trace.RetrieveXML")/*Retrieve XML*/,Command.ITEM, 200);
CMDS[EDIT_ENTITY] = new Command(Locale.get("traceiconmenu.EditPOI")/*Edit POI*/,Command.ITEM, 200);
CMDS[PAN_LEFT25_CMD] = new Command(Locale.get("trace.left25")/*left 25%*/,Command.ITEM, 100);
CMDS[PAN_RIGHT25_CMD] = new Command(Locale.get("trace.right25")/*right 25%*/,Command.ITEM, 100);
CMDS[PAN_UP25_CMD] = new Command(Locale.get("trace.up25")/*up 25%*/,Command.ITEM, 100);
CMDS[PAN_DOWN25_CMD] = new Command(Locale.get("trace.down25")/*down 25%*/,Command.ITEM, 100);
CMDS[PAN_LEFT2_CMD] = new Command(Locale.get("trace.left2")/*left 2*/,Command.ITEM, 100);
CMDS[PAN_RIGHT2_CMD] = new Command(Locale.get("trace.right2")/*right 2*/,Command.ITEM, 100);
CMDS[PAN_UP2_CMD] = new Command(Locale.get("trace.up2")/*up 2*/,Command.ITEM, 100);
CMDS[PAN_DOWN2_CMD] = new Command(Locale.get("trace.down2")/*down 2*/,Command.ITEM, 100);
CMDS[TOGGLE_AUDIO_REC] = new Command(Locale.get("trace.AudioRecording")/*Audio recording*/,Command.ITEM, 100);
CMDS[ROUTING_START_CMD] = new Command(Locale.get("trace.CalculateRoute")/*Calculate route*/,Command.ITEM, 100);
CMDS[ROUTING_STOP_CMD] = new Command(Locale.get("trace.StopRouting")/*Stop routing*/,Command.ITEM, 100);
CMDS[ONLINE_INFO_CMD] = new Command(Locale.get("trace.OnlineInfo")/*Online info*/,Command.ITEM, 100);
CMDS[ROUTING_START_WITH_MODE_SELECT_CMD] = new Command(Locale.get("trace.CalculateRoute2")/*Calculate route...*/,Command.ITEM, 100);
CMDS[RETRIEVE_NODE] = new Command(Locale.get("trace.AddPOI")/*Add POI to OSM...*/,Command.ITEM, 100);
CMDS[ICON_MENU] = new Command(Locale.get("trace.Menu")/*Menu*/,Command.OK, 100);
CMDS[SETUP_CMD] = new Command(Locale.get("trace.Setup")/*Setup*/, Command.ITEM, 25);
CMDS[ABOUT_CMD] = new Command(Locale.get("generic.About")/*About*/, Command.ITEM, 30);
//#if polish.api.wmapi
CMDS[SEND_MESSAGE_CMD] = new Command(Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/,Command.ITEM, 20);
//#endif
CMDS[EDIT_ADDR_CMD] = new Command(Locale.get("trace.AddAddrNode")/*Add Addr node*/,Command.ITEM,100);
CMDS[CELLID_LOCATION_CMD] = new Command(Locale.get("trace.CellidLocation")/*Set location from CellID*/,Command.ITEM,100);
CMDS[MANUAL_LOCATION_CMD] = new Command(Locale.get("trace.ManualLocation")/*Set location manually*/,Command.ITEM,100);
addAllCommands();
Configuration.loadKeyShortcuts(gameKeyCommand, singleKeyPressCommand,
repeatableKeyPressCommand, doubleKeyPressCommand, longKeyPressCommand,
nonReleasableKeyPressCommand, CMDS);
if (!Configuration.getCfgBitState(Configuration.CFGBIT_CANVAS_SPECIFIC_DEFAULTS_DONE)) {
if (getWidth() > 219) {
// if the map display is wide enough, show the clock in the map screen by default
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP, true);
// if the map display is wide enough, use big tab buttons by default
Configuration.setCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_BIG_TAB_BUTTONS, true);
}
if (hasPointerEvents()) {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_LARGE_FONT, true);
}
Configuration.setCfgBitSavedState(Configuration.CFGBIT_CANVAS_SPECIFIC_DEFAULTS_DONE, true);
}
try {
startup();
} catch (Exception e) {
logger.fatal(Locale.get("trace.GotExceptionDuringStartup")/*Got an exception during startup: */ + e.getMessage());
e.printStackTrace();
return;
}
// setTitle("initTrace ready");
locationUpdateListeners = new Vector();
traceInstance = this;
}
public Command getCommand(int command) {
return CMDS[command];
}
/**
* Returns the instance of the map screen. If none exists yet,
* a new instance is generated
* @return Reference to singleton instance
*/
public static synchronized Trace getInstance() {
if (traceInstance == null) {
try {
traceInstance = new Trace();
} catch (Exception e) {
logger.exception(Locale.get("trace.FailedToInitialiseMapScreen")/*Failed to initialise Map screen*/, e);
}
}
return traceInstance;
}
public float getGpsLat() {
return pos.latitude;
}
public float getGpsLon() {
return pos.longitude;
}
public void stopCompass() {
if (compassProducer != null) {
compassProducer.close();
}
compassProducer = null;
}
public void startCompass() {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer == null) {
compassProducer = new GetCompass();
if (!compassProducer.init(this)) {
logger.info("Failed to init compass producer");
compassProducer = null;
} else if (!compassProducer.activate(this)) {
logger.info("Failed to activate compass producer");
compassProducer = null;
}
}
}
/**
* Starts the LocationProvider in the background
*/
public void run() {
try {
if (running) {
receiveMessage(Locale.get("trace.GpsStarterRunning")/*GPS starter already running*/);
return;
}
//#debug info
logger.info("start thread init locationprovider");
if (locationProducer != null) {
receiveMessage(Locale.get("trace.LocProvRunning")/*Location provider already running*/);
return;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_NONE) {
receiveMessage(Locale.get("trace.NoLocProv")/*"No location provider*/);
return;
}
running=true;
startCompass();
int locprov = Configuration.getLocationProvider();
receiveMessage(Locale.get("trace.ConnectTo")/*Connect to */ + Configuration.LOCATIONPROVIDER[locprov]);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_CELLID_STARTUP)) {
// Don't do initial lookup if we're going to start primary cellid location provider anyway
if (Configuration.getLocationProvider() != Configuration.LOCATIONPROVIDER_SECELL || !Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
commandAction(CELLID_LOCATION_CMD);
}
}
switch (locprov) {
case Configuration.LOCATIONPROVIDER_SIRF:
locationProducer = new SirfInput();
break;
case Configuration.LOCATIONPROVIDER_NMEA:
locationProducer = new NmeaInput();
break;
case Configuration.LOCATIONPROVIDER_SECELL:
if (cellIDLocationProducer != null) {
cellIDLocationProducer.close();
}
locationProducer = new SECellID();
break;
case Configuration.LOCATIONPROVIDER_JSR179:
//#if polish.api.locationapi
try {
String jsr179Version = null;
try {
jsr179Version = System.getProperty("microedition.location.version");
} catch (RuntimeException re) {
// Some phones throw exceptions if trying to access properties that don't
// exist, so we have to catch these and just ignore them.
} catch (Exception e) {
// As above
}
//#if polish.android
// FIXME current (2010-06) android j2mepolish doesn't give this info
//#else
if (jsr179Version != null && jsr179Version.length() > 0) {
//#endif
Class jsr179Class = Class.forName("de.ueller.gps.location.JSR179Input");
locationProducer = (LocationMsgProducer) jsr179Class.newInstance();
//#if polish.android
//#else
}
//#endif
} catch (ClassNotFoundException cnfe) {
locationDecoderEnd();
logger.exception(Locale.get("trace.NoJSR179Support")/*Your phone does not support JSR179, please use a different location provider*/, cnfe);
running = false;
return;
}
//#else
// keep Eclipse happy
if (true) {
logger.error(Locale.get("trace.JSR179NotCompiledIn")/*JSR179 is not compiled in this version of GpsMid*/);
running = false;
return;
}
//#endif
break;
}
//#if polish.api.fileconnection
/**
* Allow for logging the raw data coming from the gps
*/
String url = Configuration.getGpsRawLoggerUrl();
//logger.error("Raw logging url: " + url);
if (url != null) {
try {
if (Configuration.getGpsRawLoggerEnable()) {
logger.info("Raw Location logging to: " + url);
url += "rawGpsLog" + HelperRoutines.formatSimpleDateNow() + ".txt";
//#if polish.android
de.enough.polish.android.io.Connection logCon = Connector.open(url);
//#else
javax.microedition.io.Connection logCon = Connector.open(url);
//#endif
if (logCon instanceof FileConnection) {
FileConnection fileCon = (FileConnection)logCon;
if (!fileCon.exists()) {
fileCon.create();
}
locationProducer.enableRawLogging(((FileConnection)logCon).openOutputStream());
} else {
logger.info("Raw logging of NMEA is only to filesystem supported");
}
}
/**
* Help out the OpenCellId.org project by gathering and logging
* data of cell ids together with current Gps location. This information
* can then be uploaded to their web site to determine the position of the
* cell towers. It currently only works for SE phones
*/
if (Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
SECellLocLogger secl = new SECellLocLogger();
if (secl.init()) {
locationProducer.addLocationMsgReceiver(secl);
}
}
} catch (IOException ioe) {
logger.exception(Locale.get("trace.CouldntOpenFileForRawLogging")/*Could not open file for raw logging of Gps data*/,ioe);
} catch (SecurityException se) {
logger.error(Locale.get("trace.PermissionWritingDataDenied")/*Permission to write data for NMEA raw logging was denied*/);
}
}
//#endif
if (locationProducer == null) {
logger.error(Locale.get("trace.ChooseDiffLocMethod")/*Your phone does not seem to support this method of location input, please choose a different one*/);
running = false;
return;
}
if (!locationProducer.init(this)) {
logger.info("Failed to initialise location producer");
running = false;
return;
}
if (!locationProducer.activate(this)) {
logger.info("Failed to activate location producer");
running = false;
return;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_CONNECT)) {
GpsMid.mNoiseMaker.playSound("CONNECT");
}
//#debug debug
logger.debug("rm connect, add disconnect");
removeCommand(CMDS[CONNECT_GPS_CMD]);
addCommand(CMDS[DISCONNECT_GPS_CMD]);
//#debug info
logger.info("end startLocationPovider thread");
// setTitle("lp="+Configuration.getLocationProvider() + " " + Configuration.getBtUrl());
} catch (SecurityException se) {
/**
* The application was not permitted to connect to the required resources
* Not much we can do here other than gracefully shutdown the thread *
*/
} catch (OutOfMemoryError oome) {
logger.fatal(Locale.get("trace.TraceThreadCrashOOM")/*Trace thread crashed as out of memory: */ + oome.getMessage());
oome.printStackTrace();
} catch (Exception e) {
logger.fatal(Locale.get("trace.TraceThreadCrashWith")/*Trace thread crashed unexpectedly with error */ + e.getMessage());
e.printStackTrace();
} finally {
running = false;
}
running = false;
}
// add the command only if icon menus are not used
public void addCommand(Command c) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
super.addCommand(c);
}
}
public RoutePositionMark getDest() {
return dest;
}
// remove the command only if icon menus are not used
public void removeCommand(Command c) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
super.removeCommand(c);
}
}
public synchronized void pause() {
logger.debug("Pausing application");
if (imageCollector != null) {
imageCollector.suspend();
}
if (locationProducer != null) {
locationProducer.close();
} else {
return;
}
int polling = 0;
while ((locationProducer != null) && (polling < 7)) {
polling++;
try {
wait(200);
} catch (InterruptedException e) {
break;
}
}
if (locationProducer != null) {
logger.error(Locale.get("trace.LocationProducerTookTooLong")/*LocationProducer took too long to close, giving up*/);
}
}
public void resumeAfterPause() {
logger.debug("resuming application after pause");
if (imageCollector != null) {
imageCollector.resume();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS) && !running && (locationProducer == null)) {
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
}
public void resume() {
logger.debug("resuming application");
if (imageCollector != null) {
imageCollector.resume();
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
public void autoRouteRecalculate() {
if ( gpsRecenter && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_AUTO_RECALC) ) {
if (Math.abs(System.currentTimeMillis()-oldRecalculationTime) >= 7000 ) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_ROUTINGINSTRUCTIONS)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getRecalculationSound(), (byte) 5, (byte) 1 );
}
//#debug debug
logger.debug("autoRouteRecalculate");
// recalculate route
commandAction(ROUTING_START_CMD);
}
}
}
public boolean isGpsConnected() {
return (locationProducer != null && solution != LocationMsgReceiver.STATUS_OFF);
}
/**
* Adds all commands for a normal menu.
*/
public void addAllCommands() {
addCommand(CMDS[EXIT_CMD]);
addCommand(CMDS[SEARCH_CMD]);
if (isGpsConnected()) {
addCommand(CMDS[DISCONNECT_GPS_CMD]);
} else {
addCommand(CMDS[CONNECT_GPS_CMD]);
}
addCommand(CMDS[MANAGE_TRACKS_CMD]);
addCommand(CMDS[MAN_WAYP_CMD]);
addCommand(CMDS[ROUTINGS_CMD]);
addCommand(CMDS[RECORDINGS_CMD]);
addCommand(CMDS[MAPFEATURES_CMD]);
addCommand(CMDS[DATASCREEN_CMD]);
addCommand(CMDS[OVERVIEW_MAP_CMD]);
//#if polish.api.online
addCommand(CMDS[ONLINE_INFO_CMD]);
//#if polish.api.osm-editing
addCommand(CMDS[RETRIEVE_XML]);
addCommand(CMDS[EDIT_ENTITY]);
addCommand(CMDS[RETRIEVE_NODE]);
addCommand(CMDS[EDIT_ADDR_CMD]);
//#endif
//#endif
addCommand(CMDS[SETUP_CMD]);
addCommand(CMDS[ABOUT_CMD]);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
//#ifndef polish.android
super.addCommand(CMDS[ICON_MENU]);
//#endif
}
}
setCommandListener(this);
}
/**
* This method must remove all commands that were added by addAllCommands().
*/
public void removeAllCommands() {
//setCommandListener(null);
/* Although j2me documentation says removeCommand for a non-attached command is allowed
* this would crash MicroEmulator. Thus we only remove the commands attached.
*/
removeCommand(CMDS[EXIT_CMD]);
removeCommand(CMDS[SEARCH_CMD]);
if (isGpsConnected()) {
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
} else {
removeCommand(CMDS[CONNECT_GPS_CMD]);
}
removeCommand(CMDS[MANAGE_TRACKS_CMD]);
removeCommand(CMDS[MAN_WAYP_CMD]);
removeCommand(CMDS[MAPFEATURES_CMD]);
removeCommand(CMDS[RECORDINGS_CMD]);
removeCommand(CMDS[ROUTINGS_CMD]);
removeCommand(CMDS[DATASCREEN_CMD]);
removeCommand(CMDS[OVERVIEW_MAP_CMD]);
//#if polish.api.online
removeCommand(CMDS[ONLINE_INFO_CMD]);
//#if polish.api.osm-editing
removeCommand(CMDS[RETRIEVE_XML]);
removeCommand(CMDS[EDIT_ENTITY]);
removeCommand(CMDS[RETRIEVE_NODE]);
removeCommand(CMDS[EDIT_ADDR_CMD]);
//#endif
//#endif
removeCommand(CMDS[SETUP_CMD]);
removeCommand(CMDS[ABOUT_CMD]);
removeCommand(CMDS[CELLID_LOCATION_CMD]);
removeCommand(CMDS[MANUAL_LOCATION_CMD]);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
//#ifndef polish.android
super.removeCommand(CMDS[ICON_MENU]);
//#endif
}
}
}
/** Sets the Canvas to fullScreen or windowed mode
* when icon menus are active the Menu command gets removed
* so the Canvas will not unhide the menu bar first when pressing fire (e.g. on SE mobiles)
*/
public void setFullScreenMode(boolean fullScreen) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
//#ifndef polish.android
if (fullScreen) {
super.removeCommand(CMDS[ICON_MENU]);
} else
//#endif
{
//#ifndef polish.android
super.addCommand(CMDS[ICON_MENU]);
//#endif
}
}
//#if polish.android
if (fullScreen) {
MidletBridge.instance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
MidletBridge.instance.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
//#else
super.setFullScreenMode(fullScreen);
//#endif
}
public void commandAction(int actionId) {
// take care we'll update actualWay
if (actionId == RETRIEVE_XML || actionId == EDIT_ADDR_CMD) {
repaint();
}
commandAction(CMDS[actionId], null);
}
public void commandAction(Command c, Displayable d) {
updateLastUserActionTime();
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD])
|| (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD])
|| (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.slower();
} else if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.faster();
} else if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
Configuration.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else if (imageCollector != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
// set compass compassDeviation
if (compassDeviation == 360) {
compassDeviation = 0;
} else {
compassDeviation += courseDiff;
compassDeviation %= 360;
if (course < 0) {
course += 360;
}
}
} else {
// manual rotation
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
gpsRecenter = false;
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording
// would not be stopped when leaving the map.
if (Legend.isValid && gpx.isRecordingTrk()) {
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.PleaseStopRecording")/*Please stop recording before exit.*/ , 2500);
return;
}
if (Legend.isValid) {
pause();
}
parent.exit();
return;
}
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StartingToRecord")/*Starting to record*/, 1250);
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StoppingToRecord")/*Stopping to record*/, 1250);
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) {
// FIXME it's not strictly necessary to stop, after there are translation for the pause
// message, change to Locale.get("trace.YouNeedStopPauseRecording")
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.YouNeedStopRecording")/*You need to stop recording before managing tracks.*/ , 4000);
return;
}
GuiGpx guiGpx = new GuiGpx(this);
guiGpx.show();
return;
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
return;
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
if (TrackPlayer.isPlaying) {
TrackPlayer.getInstance().stop();
alert(Locale.get("trace.Trackplayer")/*Trackplayer*/, Locale.get("trace.PlayingStopped")/*Playing stopped for connecting to GPS*/, 2500);
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
return;
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null) {
locationProducer.close();
}
return;
}
if (c == CMDS[TOGGLE_GPS_CMD]) {
if (isGpsConnected()) {
commandAction(DISCONNECT_GPS_CMD);
} else {
commandAction(CONNECT_GPS_CMD);
}
return;
}
if (c == CMDS[SEARCH_CMD]) {
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_DEFAULT);
guiSearch.show();
return;
}
if (c == CMDS[ENTER_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
return;
}
if (c == CMDS[MAN_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
return;
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
return;
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
return;
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
return;
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
boolean hasJSR120 = Configuration.hasDeviceJSR120();
int noElements = 3;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
noElements++;
}
//#endif
int idx = 0;
String[] elements = new String[noElements];
if (gpx.isRecordingTrk()) {
elements[idx++] = Locale.get("trace.StopGpxTracklog")/*Stop Gpx tracklog*/;
} else {
elements[idx++] = Locale.get("trace.StartGpxTracklog")/*Start Gpx tracklog*/;
}
elements[idx++] = Locale.get("trace.SaveWaypoint")/*Save waypoint*/;
elements[idx++] = Locale.get("trace.EnterWaypoint")/*Enter waypoint*/;
//#if polish.api.mmapi
elements[idx++] = Locale.get("trace.TakePictures")/*Take pictures*/;
if (audioRec.isRecording()) {
elements[idx++] = Locale.get("trace.StopAudioRecording")/*Stop audio recording*/;
} else {
elements[idx++] = Locale.get("trace.StartAudioRecording")/*Start audio recording*/;
}
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
elements[idx++] = Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/;
}
//#endif
recordingsMenu = new List(Locale.get("trace.Recordings")/*Recordings...*/,Choice.IMPLICIT,elements,null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
return;
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = new String[4];
if (routeCalc || route != null) {
elements[0] = Locale.get("trace.StopRouting")/*Stop routing*/;
} else {
elements[0] = Locale.get("trace.CalculateRoute")/*Calculate route*/;
}
elements[1] = Locale.get("trace.SetDestination")/*Set destination*/;
elements[2] = Locale.get("trace.ShowDestination")/*Show destination*/;
elements[3] = Locale.get("trace.ClearDestination")/*Clear destination*/;
routingsMenu = new List(Locale.get("trace.Routing2")/*Routing..*/, Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
return;
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
PositionMark posMark = null;
if (gpsRecenter) {
// TODO: If we lose the fix the old position and height
// will be used silently -> we should inform the user
// here that we have no fix - he may not know what's going on.
posMark = new PositionMark(center.radlat, center.radlon,
(int)pos.altitude, pos.timeMillis,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1);
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
posMark = new PositionMark(center.radlat, center.radlon,
PositionMark.INVALID_ELEVATION,
pos.timeMillis, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1);
}
/*
if (Configuration.getCfgBitState(Configuration.CFGBIT_WAYPT_OFFER_PREDEF)) {
if (guiWaypointPredefined == null) {
guiWaypointPredefined = new GuiWaypointPredefined(this);
}
if (guiWaypointPredefined != null) {
guiWaypointPredefined.setData(posMark);
guiWaypointPredefined.show();
}
} else {
*/
showGuiWaypointSave(posMark);
//}
}
return;
}
if (c == CMDS[ONLINE_INFO_CMD]) {
//#if polish.api.online
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc);
gWeb.show();
//#else
alert(Locale.get("trace.NoOnlineCapa")/*No online capabilites*/,
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
//#endif
}
if (c == CMDS[BACK_CMD]) {
show();
return;
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
switch (recordingsMenu.getSelectedIndex()) {
case 0: {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) {
show();
}
} else {
commandAction(START_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) {
show();
}
}
break;
}
case 1: {
commandAction(SAVE_WAYP_CMD);
break;
}
case 2: {
commandAction(ENTER_WAYP_CMD);
break;
}
//#if polish.api.mmapi
case 3: {
commandAction(CAMERA_CMD);
break;
}
case 4: {
show();
commandAction(TOGGLE_AUDIO_REC);
break;
}
//#endif
//#if polish.api.mmapi && polish.api.wmapi
case 5: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#elif polish.api.wmapi
case 3: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#endif
}
}
if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
break;
}
case 1: {
commandAction(SET_DEST_CMD);
break;
}
case 2: {
commandAction(SHOW_DEST_CMD);
break;
}
case 3: {
commandAction(CLEAR_DEST_CMD);
break;
}
}
}
return;
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]) {
try {
Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception(Locale.get("trace.YourPhoneNoCamSupport")/*Your phone does not support the necessary JSRs to use the camera*/, cnfe);
}
return;
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
recordingsMenu = null; // refresh recordings menu
return;
}
//#endif
if (c == CMDS[ROUTING_TOGGLE_CMD]) {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
return;
}
if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
GuiRoute guiRoute = new GuiRoute(this, false);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) {
commandAction(ROUTING_START_CMD);
} else {
guiRoute.show();
}
return;
}
if (c == CMDS[ROUTING_START_CMD]) {
if (! routeCalc || RouteLineProducer.isRunning()) {
routeCalc = true;
if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
// center of the map is the route source
RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon);
logger.info("Routing source: " + routeSource);
routeNodes=new Vector();
routeEngine = new Routing(this);
routeEngine.solve(routeSource, dest);
// resume();
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ROUTING_STOP_CMD]) {
NoiseMaker.stopPlayer();
if (routeCalc) {
if (routeEngine != null) {
routeEngine.cancelRouting();
}
alert(Locale.get("trace.RouteCalculation")/*Route Calculation*/, Locale.get("trace.Cancelled")/*Cancelled*/, 1500);
} else {
alert(Locale.get("trace.Routing")/*Routing*/, Locale.get("generic.Off")/*Off*/, 750);
}
endRouting();
routingsMenu = null; // refresh routingsMenu
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
if (hasPointerEvents()) {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourse")/*Change course with zoom buttons*/, 3000);
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourseWithLeftRightKeys")/*Change course with left/right keys*/, 3000);
}
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("generic.Off")/*Off*/, 750);
}
return;
}
if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
return;
}
if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
return;
}
if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
return;
}
if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (manualRotationMode) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
compassDeviation = 0;
} else {
course = 0;
}
alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750);
} else {
// FIXME rename string to generic
alert(Locale.get("guidiscover.MapProjection")/*Map Projection*/, ProjFactory.nextProj(), 750);
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
return;
}
if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert(Locale.get("trace.GpsMid")/*GpsMid*/, hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked")/*Keys and touch screen unlocked*/ : Locale.get("trace.KeysUnlocked")/*Keys unlocked*/, 1000);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
} else {
commandAction(START_RECORD_CMD);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.ResumingRecording")/*Resuming recording*/, 1000);
gpx.resumeTrk();
} else {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.SuspendingRecording")/*Suspending recording*/, 1000);
gpx.suspendTrk();
}
}
return;
}
if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
autoZoomed = true;
if (pos.latitude != 0.0f) {
receivePosition(pos);
}
newDataReady();
return;
}
if (c == CMDS[SHOW_DEST_CMD]) {
if (dest != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
prevPositionNode = center.copy();
center.setLatLonRad(dest.lat, dest.lon);
movedAwayFromDest = false;
updatePosition();
}
else {
alert(Locale.get("trace.ShowDestination")/*Show destination*/, Locale.get("trace.DestinationNotSpecifiedYet")/*Destination is not specified yet*/, 3000);
}
return;
}
if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) {
if (prevPositionNode != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLon(prevPositionNode);
updatePosition();
}
}
if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
return;
}
if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
showIconMenu();
return;
}
if (c == CMDS[SETUP_CMD]) {
new GuiDiscover(parent);
return;
}
if (c == CMDS[ABOUT_CMD]) {
new Splash(parent, GpsMid.initDone);
return;
}
if (c == CMDS[CELLID_LOCATION_CMD]) {
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) {
locationProducer.triggerPositionUpdate();
newDataReady();
} else {
if (cellIDLocationProducer == null) {
// init sleeping cellid location provider if cellid is not primary
cellIDLocationProducer = new SECellID();
if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) {
logger.info("Failed to initialise CellID location producer");
}
}
if (cellIDLocationProducer != null) {
cellIDLocationProducer.triggerPositionUpdate();
newDataReady();
}
}
return;
}
if (c == CMDS[MANUAL_LOCATION_CMD]) {
Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD,
center.radlon / MoreMath.FAC_DECTORAD,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis(), Position.TYPE_MANUAL);
// implies center to gps, to give feedback as the gps rectangle
gpsRecenter = true;
// gpsRecenterInvalid = true;
// gpsRecenterStale = true;
autoZoomed = true;
receivePosition(setpos);
receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0);
newDataReady();
return;
}
if (! routeCalc) {
//#if polish.api.osm-editing
if (c == CMDS[RETRIEVE_XML]) {
if (Legend.enableEdits) {
// -1 alert ("Editing", "Urlidx: " + pc.actualWay.urlIdx, Alert.FOREVER);
if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) {
parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER);
}
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GuiOSMWayDisplay guiWay = new GuiOSMWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[EDIT_ENTITY]) {
if (Legend.enableEdits) {
// FIXME: do the following:
// * set a flag that default operation is OSM edit
// * do a search for nearby POIs, asking for type
// * when the user selects, open OSM editing
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_EDIT_ENTITY);
guiSearch.show();
return;
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[RETRIEVE_NODE]) {
// FIXME add support for accessing a node
// under cursor
if (Legend.enableEdits) {
GuiOSMPOIDisplay guiNode = new GuiOSMPOIDisplay(-1, null,
center.radlat, center.radlon, this);
guiNode.show();
guiNode.refresh();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
if (c == CMDS[EDIT_ADDR_CMD]) {
if (Legend.enableEdits) {
String streetName = "";
if ((pc != null) && (pc.actualWay != null)) {
streetName = getName(pc.actualWay.nameIdx);
}
GuiOSMAddrDisplay guiAddr = new GuiOSMAddrDisplay(-1, streetName, null,
center.radlat, center.radlon, this);
guiAddr.show();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
//#else
if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) {
alert("No online capabilites",
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
}
//#endif
if (c == CMDS[SET_DEST_CMD]) {
RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon);
setDestination(pm1);
return;
}
if (c == CMDS[CLEAR_DEST_CMD]) {
setDestination(null);
return;
}
} else {
alert(Locale.get("trace.Error")/*Error*/, Locale.get("trace.CurrentlyInRouteCalculation")/*Currently in route calculation*/, 2000);
}
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceCommandAction")/*In Trace.commandAction*/, e);
}
}
private void startImageCollector() throws Exception {
//#debug info
logger.info("Starting ImageCollector");
Images images = new Images();
pc = new PaintContext(this, images);
/* move responsibility for overscan to ImageCollector
int w = (this.getWidth() * 125) / 100;
int h = (this.getHeight() * 125) / 100;
*/
imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.copy();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
//#debug info
logger.info("Stopping ImageCollector");
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
urlsThread = new Urls();
new DictReader(this);
// wait until base tiles are read; otherwise there's apparently
// a race condition triggered on Symbian s60r3 phones, see
// https://sourceforge.net/support/tracker.php?aid=3284022
if (Legend.isValid) {
while (!baseTilesRead) {
try {
Thread.sleep(250);
} catch (InterruptedException e1) {
// nothing to do in that case
}
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
Thread thread = new Thread(this, "Trace");
thread.start();
}
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte)5);
startImageCollector();
recreateTraceLayout();
}
public void shutdown() {
if (gpx != null) {
// change to "false" to ask for track name if configure to
// currently "true" to not ask for name to ensure fast
// quit & try to avoid loss of data which might result from
// waiting for user to type the name
gpx.saveTrk(true);
}
//#debug debug
logger.debug("Shutdown: stopImageCollector");
stopImageCollector();
if (namesThread != null) {
//#debug debug
logger.debug("Shutdown: namesThread");
namesThread.stop();
namesThread = null;
}
if (urlsThread != null) {
urlsThread.stop();
urlsThread = null;
}
if (dictReader != null) {
//#debug debug
logger.debug("Shutdown: dictReader");
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
//#debug debug
logger.debug("Shutdown: tileReader");
tileReader.shutdown();
tileReader = null;
}
if (locationProducer != null) {
//#debug debug
logger.debug("Shutdown: locationProducer");
locationProducer.close();
}
if (TrackPlayer.isPlaying) {
//#debug debug
logger.debug("Shutdown: TrackPlayer");
TrackPlayer.getInstance().stop();
}
}
public void sizeChanged(int w, int h) {
updateLastUserActionTime();
if (imageCollector != null) {
logger.info("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector")/*Could not reinitialise Image Collector after size change*/, e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
tl = new TraceLayout(0, 0, w, h);
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null) {
/*
* When painting we receive a copy of the center coordinates
* where the imageCollector has drawn last
* as we need to base the routing instructions on the information
* determined during the way drawing (e.g. the current routePathConnection)
*/
Node drawnCenter = imageCollector.paint(pc);
if (route != null && ri != null && pc.lineP2 != null && pc.getP() != null/*avoids exception at route calc*/) {
pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2);
/*
* we also need to make sure the current way for the real position
* has really been detected by the imageCollector which happens when drawing the ways
* So we check if we just painted an image that did not cover
* the center of the display because it was too far painted off from
* the display center position and in this case we don't give route instructions
* Thus e.g. after leaving a long tunnel without gps fix there will not be given an
* obsolete instruction from inside the tunnel
*/
int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2);
if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs
&&
Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs
) {
/*
* we need to synchronize the route instructions on the informations determined during way painting
* so we give the route instructions right after drawing the image with the map
* and use the center of the last drawn image for the route instructions
*/
ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan);
}
}
} else {
// show the way bar even if ImageCollector is not running because it's necessary on touch screens to get to the icon menu
tl.ele[TraceLayout.WAYNAME].setText(" ");
}
/* Beginning of voice instructions started from overlay code (besides showRoute above)
*/
// Determine if we are at the destination
if (dest != null) {
float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon);
atDest = (distance < 25);
if (atDest) {
if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1);
}
} else if (!movedAwayFromDest) {
movedAwayFromDest = true;
}
}
// determine if we are currently speeding
speeding = false;
int maxSpeed = 0;
// only detect speeding when gpsRecentered and there is a current way
if (gpsRecenter && actualSpeedLimitWay != null) {
maxSpeed = actualSpeedLimitWay.getMaxSpeed();
// check for winter speed limit if configured
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
&& (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) {
maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter();
}
if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) {
speeding = true;
}
}
if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
// give speeding alert only every 10 seconds
if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) {
lastTimeOfSpeedingSound = System.currentTimeMillis();
GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound());
}
}
/*
* end of voice instructions started from overlay code
*/
/*
* the final part of the overlay should not give any voice instructions
*/
g.setColor(Legend.COLOR_MAP_TEXT);
switch (showAddons) {
case 1:
yc = showMemory(g, yc, la);
break;
case 2:
yc = showConnectStatistics(g, yc, la);
break;
default:
showAddons = 0;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) {
if (pc != null) {
tl.calcScaleBarWidth(pc);
tl.ele[TraceLayout.SCALEBAR].setText(" ");
}
}
setPointOfTheCompass();
}
showMovement(g);
// Show gpx track recording status
LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION];
LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT];
if (gpx.isRecordingTrk()) {
// we are recording tracklogs
if (gpx.isRecordingTrkSuspended()) {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); // blue
} else {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); // red
}
eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")/*r*/);
}
if (TrackPlayer.isPlaying) {
eSolution.setText(Locale.get("trace.Replay")/*Replay*/);
} else {
if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID ||
solution == LocationMsgReceiver.STATUS_MANUAL)) {
eSolution.setText(Locale.get("solution.Off")/*Off*/);
} else {
eSolution.setText(solutionStr);
}
}
LayoutElement e = tl.ele[TraceLayout.CELLID];
// show if we are logging cellIDs
if (SECellLocLogger.isCellIDLogging() > 0) {
if (SECellLocLogger.isCellIDLogging() == 2) {
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); // yellow
} else {
//Attempting to log, but currently no valid info available
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); // red
}
e.setText(Locale.get("trace.cellIDs")/*cellIDs*/);
}
// show audio recording status
e = tl.ele[TraceLayout.AUDIOREC];
if (audioRec.isRecording()) {
e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); // red
e.setText(Locale.get("trace.AudioRec")/*AudioRec*/);
}
if (pc != null) {
showDestination(pc);
}
if (speed > 0 &&
Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("guitacho.kmh")/* km/h*/);
} else {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + Locale.get("guitacho.mph"));
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP)
&& locationProducer != null
&& LocationMsgReceiverList.isPosValid(solution)
) {
tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE));
}
if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) )
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) {
e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE];
e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]);
double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon);
e.setText(Locale.get("trace.Air")/*Air:*/ + showDistance((int) distLine, DISTANCE_AIR));
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) {
e = tl.ele[TraceLayout.CURRENT_TIME]; // e is used *twice* below (also as vRelative)
e.setText(DateTimeTools.getClock(System.currentTimeMillis(), true));
/*
don't use new Date() - it is very slow on some Nokia devices
currentTime.setTime( new Date( System.currentTimeMillis() ) );
e.setText(
currentTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(currentTime.get(Calendar.MINUTE)));
*/
// if current time is visible, positioning OFFROUTE above current time will work
tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e);
}
setSpeedingSign(maxSpeed);
if (hasPointerEvents()) {
tl.ele[TraceLayout.ZOOM_IN].setText("+");
tl.ele[TraceLayout.ZOOM_OUT].setText("-");
tl.ele[TraceLayout.RECENTER_GPS].setText("|");
e = tl.ele[TraceLayout.SHOW_DEST];
if (atDest && prevPositionNode != null) {
e.setText("<");
e.setActionID(SHOW_PREVIOUS_POSITION_CMD);
} else {
e.setText(">");
e.setActionID(SHOW_DEST_CMD + (Trace.SET_DEST_CMD << 16) );
}
}
e = tl.ele[TraceLayout.TITLEBAR];
if (currentTitleMsgOpenCount != 0) {
e.setText(currentTitleMsg);
// setTitleMsgTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setTitleMsgTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentTitleMsgOpenCount--;
lastTitleMsg = currentTitleMsg;
if (currentTitleMsgOpenCount == 0) {
//#debug debug
logger.debug("clearing title");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout);
setTitleMsgTimeout = 0;
}
}
}
tl.paint(g);
if (currentAlertsOpenCount > 0) {
showCurrentAlert(g);
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
}
public void showGuiWaypointSave(PositionMark posMark) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
guiWaypointSave.setData(posMark);
guiWaypointSave.show();
}
}
/** Show an alert telling the user that waypoints are not ready yet.
*/
private void showAlertLoadingWpt() {
alert("Way points", "Way points are not ready yet.", 3000);
}
private void showCurrentAlert(Graphics g) {
Font font = g.getFont();
// request same font in bold for title
Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize());
int fontHeight = font.getHeight();
// add alert title height plus extra space of one line for calculation of alertHeight
int y = titleFont.getHeight() + 2 + fontHeight;
// extra width for alert
int extraWidth = font.charWidth('W');
// alert is at least as wide as alert title
int alertWidth = titleFont.stringWidth(currentAlertTitle);
// width each alert message line must fit in
int maxWidth = getWidth() - extraWidth;
// Two passes: 1st pass calculates placement and necessary size of alert,
// 2nd pass actually does the drawing
for (int i = 0; i <= 1; i++) {
int nextSpaceAt = 0;
int prevSpaceAt = 0;
int start = 0;
// word wrap
do {
int width = 0;
// add word by word until string part is too wide for screen
while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) {
prevSpaceAt = nextSpaceAt;
nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt);
if (nextSpaceAt == -1) {
nextSpaceAt = currentAlertMessage.length();
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
nextSpaceAt++;
}
nextSpaceAt--;
// Reduce line word by word or if not possible char by char until the
// remaining string part fits to display width
while (width > maxWidth) {
if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) {
nextSpaceAt = prevSpaceAt;
} else {
nextSpaceAt--;
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
}
// determine maximum alert width
if (alertWidth < width ) {
alertWidth = width;
}
// during the second pass draw the message text lines
if (i==1) {
g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start,
getWidth()/2, y, Graphics.TOP|Graphics.HCENTER);
}
y += fontHeight;
start = nextSpaceAt;
} while (nextSpaceAt < currentAlertMessage.length() );
// at the end of the first pass draw the alert box and the alert title
if (i == 0) {
alertWidth += extraWidth;
int alertHeight = y;
int alertTop = (getHeight() - alertHeight) /2;
//alertHeight += fontHeight/2;
int alertLeft = (getWidth() - alertWidth) / 2;
// alert background color
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, alertHeight);
// background color for alert title
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3);
// alert border
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]);
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); // title border
g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); // alert border
// draw alert title
y = alertTop + 2; // output position of alert title
g.setFont(titleFont);
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]);
g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER);
g.setFont(font);
// output alert message 1.5 lines below alert title in the next pass
y += (fontHeight * 3 / 2);
}
} // end for
// setAlertTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setAlertTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentAlertsOpenCount--;
if (currentAlertsOpenCount == 0) {
//#debug debug
logger.debug("clearing alert");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setAlertTimeout);
setAlertTimeout = 0;
}
}
}
private void setSpeedingSign(int maxSpeed) {
// speeding = true;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL)
&&
(
speeding
||
(System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000
)
) {
if (speeding) {
speedingSpeedLimit = maxSpeed;
startTimeOfSpeedingSign = System.currentTimeMillis();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit));
} else {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f + 0.5f)));
}
} else {
startTimeOfSpeedingSign = 0;
}
}
/**
*
*/
private void getPC() {
pc.course = course;
pc.scale = scale;
pc.center = center.copy();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.dest = dest;
}
public void cleanup() {
namesThread.cleanup();
urlsThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
// public void searchElement(PositionMark pm) throws Exception {
// PaintContext pc = new PaintContext(this, null);
// // take a bigger angle for lon because of positions near to the poles.
// Node nld = new Node(pm.lat - 0.0001f, pm.lon - 0.0005f, true);
// Node nru = new Node(pm.lat + 0.0001f, pm.lon + 0.0005f, true);
// pc.searchLD = nld;
// pc.searchRU = nru;
// pc.dest = pm;
// pc.setP(new Proj2D(new Node(pm.lat, pm.lon, true), 5000, 100, 100));
// for (int i = 0; i < 4; i++) {
// tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
// }
// }
public void searchNextRoutableWay(RoutePositionMark pm) throws Exception {
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
// Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
// Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
// pc.searchLD=nld;
// pc.searchRU=nru;
pc.squareDstWithPenToActualRoutableWay = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
// retry searching an expanding region at the position mark
Projection p;
do {
p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize);
pc.setP(p);
for (int i=0; i<4; i++) {
tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT);
}
// stop the search when a routable way is found
if (pc.actualRoutableWay != null) {
break;
}
// expand the region that gets searched for a routable way
pc.xSize += 100;
pc.ySize += 100;
// System.out.println(pc.xSize);
} while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); // until we searched at least 500 m edge length
Way w = pc.actualRoutableWay;
pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon);
}
private void setPointOfTheCompass() {
String c = "";
if (ProjFactory.getProj() != ProjFactory.NORTH_UP
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) {
c = Configuration.getCompassDirection(course);
}
// if tl shows big onscreen buttons add spaces to compass directions consisting of only one char or not shown
if (tl.bigOnScreenButtons && c.length() <= 1) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP) {
c = "(" + Configuration.getCompassDirection(0) + ")";
} else {
c = " " + c + " ";
}
}
tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c);
}
private int showConnectStatistics(Graphics g, int yc, int la) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]);
// only try to show compass id and cell id if user has somehow switched them on
GSMCell cell = null;
if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL || Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
cell = CellIdProvider.getInstance().obtainCachedCellID();
}
Compass compass = null;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) {
compass = CompassProvider.getInstance().obtainCachedCompass();
}
if (cell == null) {
g.drawString("No Cell ID available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (compass == null) {
g.drawString("No compass direction available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public void showDestination(PaintContext pc) {
// Avoid exception after route calculation
if ( pc.getP() == null || imageCollector == null )
return;
try {
if (dest != null) {
pc.getP().forward(dest.lat, dest.lon, pc.lineP2);
// System.out.println(dest.toString());
int x = pc.lineP2.x - imageCollector.xScreenOverscan;
int y = pc.lineP2.y - imageCollector.yScreenOverscan;
pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS);
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]);
if (dest.displayName != null) {
pc.g.drawString(dest.displayName, x, y+8,
Graphics.TOP | Graphics.HCENTER);
}
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_LINE]);
pc.g.setStrokeStyle(Graphics.SOLID);
pc.g.drawLine( pc.getP().getImageCenter().x - imageCollector.xScreenOverscan,
pc.getP().getImageCenter().y - imageCollector.yScreenOverscan,x, y);
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
e.printStackTrace();
}
}
/**
* Draws the position square, the movement line and the center cross.
*
* @param g Graphics context for drawing
*/
public void showMovement(Graphics g) {
// Avoid exception after route calculation
if ( pc.getP() == null )
return;
IntPoint centerP = null;
try {
if (imageCollector != null) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]);
centerP = pc.getP().getImageCenter();
int centerX = centerP.x - imageCollector.xScreenOverscan;
int centerY = centerP.y - imageCollector.yScreenOverscan;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0, 0);
pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD),
(pos.longitude * MoreMath.FAC_DECTORAD), p1);
posX = p1.getX()-imageCollector.xScreenOverscan;
posY = p1.getY()-imageCollector.yScreenOverscan;
} else {
posX = centerX;
posY = centerY;
}
g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]);
float radc = course * MoreMath.FAC_DECTORAD;
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
// crosshair center cursor
if (!gpsRecenter || gpsRecenterInvalid) {
g.drawLine(centerX, centerY - 12, centerX, centerY + 12);
g.drawLine(centerX - 12, centerY, centerX + 12, centerY);
g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360);
}
if (! gpsRecenterInvalid) {
// gps position spot
pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS);
// gps position rectangle
g.drawRect(posX - 4, posY - 4, 8, 8);
g.drawLine(posX, posY, px, py);
}
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
if (centerP == null) {
logger.silentexception("No centerP", e);
}
e.printStackTrace();
}
}
/**
* Show next screen in the sequence of data screens
* (tacho, trip, satellites).
* @param currentScreen Data screen currently shown, use the DATASCREEN_XXX
* constants from this class. Use DATASCREEN_NONE if none of them
* is on screen i.e. the first one should be shown.
*/
public void showNextDataScreen(int currentScreen) {
switch (currentScreen)
{
case DATASCREEN_TACHO:
// Tacho is followed by Trip.
if (guiTrip == null) {
guiTrip = new GuiTrip(this);
}
if (guiTrip != null) {
guiTrip.show();
}
break;
case DATASCREEN_TRIP:
// Trip is followed by Satellites.
if (guiSatellites == null) {
guiSatellites = new GuiSatellites(this, locationProducer);
}
if (guiSatellites != null) {
guiSatellites.show();
}
break;
case DATASCREEN_SATS:
// After Satellites, go back to map.
this.show();
break;
case DATASCREEN_NONE:
default:
// Tacho is first data screen
if (guiTacho == null) {
guiTacho = new GuiTacho(this);
}
if (guiTacho != null) {
guiTacho.show();
}
break;
}
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0);
g.drawString(Locale.get("trace.Freemem")/*Freemem: */ + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Totmem")/*Totmem: */ + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Percent")/*Percent: */
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.ThreadsRunning")/*Threads running: */
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Names")/*Names: */ + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.SingleT")/*Single T: */ + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.FileT")/*File T: */ + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.LastMsg")/*LastMsg: */ + lastTitleMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( Locale.get("trace.at")/*at */ + lastTitleMsgClock, 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
private void updatePosition() {
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course=course;
repaint();
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosition(float lat, float lon, float scale) {
//#debug debug
logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " +
(lon * MoreMath.FAC_RADTODEC));
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLonRad(lat, lon);
this.scale = scale;
updatePosition();
}
public synchronized void receiveCompassStatus(int status) {
}
public synchronized void receiveCompass(float direction) {
//#debug debug
logger.debug("Got compass reading: " + direction);
compassDirection = (int) direction;
compassDeviated = ((int) direction + compassDeviation + 360) % 360;
// TODO: allow for user to use compass for turning the map in panning mode
// (gpsRenter test below switchable by user setting)
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && gpsRecenter) {
updateCourse(compassDeviated);
//repaint();
}
// course = compassDeviated;
//}
}
public static void updateLastUserActionTime() {
lastUserActionTime = System.currentTimeMillis();
}
public static long getDurationSinceLastUserActionTime() {
return System.currentTimeMillis() - lastUserActionTime;
}
public void updateCourse(int newcourse) {
coursegps = newcourse;
/* don't rotate too fast
*/
if ((newcourse - course)> 180) {
course = course + 360;
}
if ((course-newcourse)> 180) {
newcourse = newcourse + 360;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
course = newcourse;
} else {
// FIXME I think this is too slow a turn at least when course is
// of good quality, turning should be faster. This probably alleviates
// the trouble caused by unreliable gps course. However,
// some kind of heuristic, averaging course or evaluating the
// quality of course and fast or instant rotation with a known good GPS fix
// should be implemented instead of assuming course is always unreliable.
// The course fluctuations are lesser in faster speeds, so if we're constantly
// (for three consecutive locations) above say 5 km/h, a reasonable approach
// could be to use direct course change in that case, and for speed below
// 5 km/h use the slow turning below.
// jkpj 2010-01-17
// on 2011-04-11: jkpj switched from 1/4 rotation back to 3/4 rotation,
// returning to what it was supposed to do before 2010-11-30.
course = course + ((newcourse - course)*3)/4 + 360;
}
while (course > 360) {
course -= 360;
}
}
public synchronized void receivePosition(Position pos) {
// FIXME signal on location gained
//#debug info
logger.info("New position: " + pos);
collected++;
if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 &&
getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs()
&& isShown()
) {
gpsRecenter = true;
//autoZoomed = true;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) {
if (pos.type == Position.TYPE_GPS_LASTKNOWN) {
// if we have a current cell id fix from cellid location,
// don't overwrite it with a stale GPS location, but ignore the position
// FIXME perhaps compare timestamps here in case the last known gps is later
if (this.pos.type == Position.TYPE_CELLID) {
return;
}
gpsRecenterInvalid = false;
gpsRecenterStale = true;
}
}
this.pos = pos;
if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) {
gpsRecenterInvalid = false;
gpsRecenterStale = false;
}
if (gpsRecenter) {
center.setLatLonDeg(pos.latitude, pos.longitude);
speed = (int) (pos.speed * 3.6f);
fspeed = pos.speed * 3.6f;
// FIXME add auto-fallback mode where course is from GPS at high speeds and from compass
// at low speeds
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
updateCourse(compassDeviated);
} else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) {
// Problem: resolve issue erratic course due to GPS fluctuation
// when GPS reception is poor (maybe 3..7S),
// causes unnecessary and disturbing map rotation when device is in one location
// Heuristic for solving: After being still, require
// three consecutive over-the-limit speed readings with roughly the
// same course
if (thirdPrevCourse != -1) {
// first check for normal flow of things, we've had three valid courses after movement start
updateCourse((int) pos.course);
} else if (prevCourse == -1) {
// previous course was invalid,
// don't set course yet, but set the first tentatively good course
prevCourse = (int) pos.course;
} else if (secondPrevCourse == -1) {
// the previous course was the first good one.
// If this course is in the same 60-degree
// sector as the first course, we have two valid courses
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
secondPrevCourse = prevCourse;
}
prevCourse = (int) pos.course;
} else {
// we have received two previous valid curses, check for this one
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
thirdPrevCourse = secondPrevCourse;
//No need to set these as we'll now trust courses until speed goes below limit
// - unless we'll later add averaging of recent courses for poor GPS reception
//secondPrevCourse = prevCourse;
//prevCourse = (int) pos.course;
updateCourse((int) pos.course);
} else {
prevCourse = (int) pos.course;
secondPrevCourse = -1;
}
}
} else {
// speed under the minimum, invalidate all prev courses
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
}
if (gpx.isRecordingTrk()) {
try {
// don't tracklog manual cellid position or gps start/stop last known position
if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179
&& pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) {
} else {
gpx.addTrkPt(pos);
}
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
altitude = (int) (pos.altitude);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM)
&& gpsRecenter
&& (isGpsConnected() || TrackPlayer.isPlaying)
&& autoZoomed
&& pc.getP() != null
&& pos.speed != Float.NaN // if speed is unknown do not autozoom
&& pos.speed != 0 // if speed is 0 do not autozoom
) {
// the minimumScale at 20km/h and below is equivalent to having zoomed in manually once from the startup zoom level
final float minimumScale = Configuration.getRealBaseScale() / 1.5f;
final int minimumSpeed = 20;
// the maximumScale at 160km/h and above is equivalent to having zoomed out manually once from the startup zoom level
final float maximumScale = Configuration.getRealBaseScale() * 1.5f;
final int maximumSpeed = 160;
int speedForScale = speed;
float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed);
// make sure the new scale is within the minimum / maximum scale values
if (newScale < minimumScale) {
newScale = minimumScale;
} else if (newScale > maximumScale) {
newScale = maximumScale;
}
// autozoom in more at the last 200 m of the route
if (route != null && RouteInstructions.getDstRouteToDestination() <= 200) {
float newScale2 = newScale;
newScale2 = newScale / (1f + (200f - RouteInstructions.getDstRouteToDestination())/ 200f);
// fixed increased zoom for the last 100 m
newScale = Math.max(newScale2, newScale / 1.5f);
}
scale = newScale;
// // calculate meters to top of screen
// float topLat = pc.getP().getMaxLat();
// float topLon = (pc.getP().getMinLon() + pc.getP().getMaxLon()) / 2f;
// float distance = MoreMath.dist(center.radlat, center.radlon, topLat, topLon );
// System.out.println("current distance to top of screen: " + distance);
//
// // avoid zooming in or out too far
// int speedForScale = course;
// if (speedForScale < 30) {
// speedForScale = 30;
// } else if (speedForScale > 160) {
// speedForScale = 160;
// }
//
// final float SECONDS_TO_PREVIEW = 45f;
// float metersToPreview = (float) speedForScale / 3.6f * SECONDS_TO_PREVIEW;
// System.out.println(metersToPreview + "meters to preview at " + speedForScale + "km/h");
//
// if (metersToPreview < 2000) {
// // calculate top position that needs to be visible to preview the metersToPreview
// topLat = center.radlat + (topLat - center.radlat) * metersToPreview / distance;
// topLon = center.radlon + (topLon - center.radlon) * metersToPreview / distance;
// System.out.println("new distance to top:" + MoreMath.dist(center.radlat, center.radlon, topLat, topLon ));
//
// /*
// * calculate scale factor, we multiply this again with 2 * 1.2 = 2.4 to take into account we calculated half the screen height
// * and 1.2f is probably the factor the PaintContext is larger than the display size
// * (new scale is calculated similiar to GuiWaypoint)
// */
// IntPoint intPoint1 = new IntPoint(0, 0);
// IntPoint intPoint2 = new IntPoint(getWidth(), getHeight());
// Node n1 = new Node(center.radlat, center.radlon, true);
// Node n2 = new Node(topLat, topLon, true);
// scale = pc.getP().getScale(n1, n2, intPoint1, intPoint2) * 2.4f;
// }
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentTitleMsg = s;
synchronized (this) {
/*
* only increase the number of current title messages
* if the timer already has been set in the display code
*/
if (setTitleMsgTimeout == 0) {
currentTitleMsgOpenCount++;
}
setTitleMsgTimeout = 3000;
}
lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false);
repaint();
}
public void receiveSatellites(Satellite[] sats) {
// Not interested
}
/** Shows an alert message
*
* @param title The title of the alert
* @param message The message text
* @param timeout Timeout in ms. Please reserve enough time so the user can
* actually read the message. Use Alert.FOREVER if you want no timeout.
*/
public synchronized void alert(String title, String message, int timeout) {
// #debug info
logger.info("Showing trace alert: " + title + ": " + message);
if (timeout == Alert.FOREVER) {
timeout = 10000;
}
currentAlertTitle = title;
currentAlertMessage = message;
synchronized (this) {
/*
* only increase the number of current open alerts
* if the timer already has been set in the display code
*/
if (setAlertTimeout == 0) {
currentAlertsOpenCount++;
}
setAlertTimeout = timeout;
}
repaint();
}
public MIDlet getParent() {
return parent;
}
protected void pointerPressed(int x, int y) {
updateLastUserActionTime();
long currTime = System.currentTimeMillis();
pointerDragged = false;
pointerDraggedMuch = false;
pointerActionDone = false;
// remember center when the pointer was pressed for dragging
centerPointerPressedN = center.copy();
if (imageCollector != null) {
panProjection=imageCollector.getCurrentProjection();
pickPointStart=panProjection.inverse(x,y, pickPointStart);
} else {
panProjection = null;
}
// remember the LayoutElement the pointer is pressed down at, this will also highlight it on the display
int touchedElementId = tl.getElementIdAtPointer(x, y);
if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU)
&&
tl.isAnyActionIdAtPointer(x, y)
) {
tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId));
repaint();
}
// check for double press
if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) {
doubleTap(x, y);
return;
}
// Remember the time and position the pointer was pressed after the check for double tap,
// so the double tap code will check for the position of the first of the two taps
pressedPointerTime = currTime;
Trace.touchX = x;
Trace.touchY = y;
// Give a message if keyboard/user interface is locked.
// This must be done after remembering the touchX/Y positions as they are needed to unlock
if (keyboardLocked) {
keyPressed(0);
return;
}
// // when these statements are reached, no double tap action has been executed,
// // so check here if there's currently already a TimerTask waiting for a single tap.
// // If yes, perform the current single tap action immediately before starting the next TimerTask
// if (checkingForSingleTap && !pointerDraggedMuch) {
// singleTap();
// pointerActionDone = false;
// }
//
longTapTimerTask = new TimerTask() {
public void run() {
// if no action (e.g. from double tap) is already done
// and the pointer did not move or if it was pressed on a control and not moved much
if (!pointerActionDone) {
if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){
longTap();
}
}
}
};
try {
// set timer to continue check if this is a long tap
GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoLongTapTimerTask")/*No LongTap TimerTask: */ + e.toString());
}
}
protected void pointerReleased(int x, int y) {
// releasing the pointer cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
// releasing the pointer will clear the highlighting of the touched element
if (tl.getTouchedElement() != null) {
tl.clearTouchedElement();
repaint();
}
if (!pointerActionDone && !keyboardLocked) {
touchReleaseX = x;
touchReleaseY = y;
// check for a single tap in a timer started after the maximum double tap delay
// if the timer will not be cancelled by a double tap, the timer will execute the single tap command
singleTapTimerTask = new TimerTask() {
public void run() {
if (!keyboardLocked) {
singleTap(touchReleaseX, touchReleaseY);
}
}
};
try {
// set timer to check if this is a single tap
GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoSingleTapTimerTask")/*No SingleTap TimerTask: */ + e.toString());
}
if (pointerDragged) {
pointerDragged(x , y);
return;
}
}
}
protected void pointerDragged (int x, int y) {
updateLastUserActionTime();
LayoutElement e = tl.getElementAtPointer(x, y);
if (tl.getTouchedElement() != e) {
// leaving the touched element cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
tl.clearTouchedElement();
repaint();
}
// If the initially touched element is reached again during dragging, highlight it
if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) {
tl.setTouchedElement(e);
repaint();
}
if (pointerActionDone) {
return;
}
// check if there's been much movement, do this before the slide lock/unlock
// to avoid a single tap action when not sliding enough
if (Math.abs(x - Trace.touchX) > 8
||
Math.abs(y - Trace.touchY) > 8
) {
pointerDraggedMuch = true;
// avoid double tap triggering on fast consecutive drag actions starting at almost the same position
pressedPointerTime = 0;
}
// slide at least 1/4 display width to lock / unlock GpsMid
if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) {
if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU
&&
x - touchX > getWidth() / 4
) {
commandAction(TOGGLE_KEY_LOCK_CMD);
pointerActionDone = true;
}
return;
}
if (keyboardLocked) {
return;
}
pointerDragged = true;
// do not start map dragging on a touch control if only dragged slightly
if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) {
return;
}
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) {
// difference between where the pointer was pressed and is currently dragged
// int diffX = Trace.touchX - x;
// int diffY = Trace.touchY - y;
//
// IntPoint centerPointerPressedP = new IntPoint();
pickPointEnd=panProjection.inverse(x,y, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
// System.out.println("diff " + diffX + "/" + diffY + " " + (pickPointEnd.radlat-pickPointStart.radlat) + "/" + (pickPointEnd.radlon-pickPointStart.radlon) );
imageCollector.newDataReady();
gpsRecenter = false;
}
}
private void singleTap(int x, int y) {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we set the touchable button sizes
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) {
// if pointer was dragged much, do not recognize a single tap on the map
if (pointerDraggedMuch) {
return;
}
// #debug debug
logger.debug("single tap map");
if (!tl.bigOnScreenButtons) {
tl.setOnScreenButtonSize(true);
// set timer to continuously check if the last user interaction is old enough to make the buttons small again
final long BIGBUTTON_DURATION = 5000;
bigButtonTimerTask = new TimerTask() {
public void run() {
if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) {
// make the on screen touch buttons small again
tl.setOnScreenButtonSize(false);
requestRedraw();
bigButtonTimerTask.cancel();
}
}
};
try {
GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500);
} catch (Exception e) {
logger.error("Error scheduling bigButtonTimerTask: " + e.toString());
}
}
}
repaint();
} else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) {
tl.clearTouchedElement();
int actionId = tl.getActionIdAtPointer(x, y);
if (actionId > 0) {
// #debug debug
logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY);
if (System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
} else if (manualRotationMode) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_LEFT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_RIGHT2_CMD;
}
} else if (TrackPlayer.isPlaying) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
}
commandAction(actionId);
repaint();
}
}
}
private void doubleTap(int x, int y) {
// if not double tapping a control, then the map area must be double tapped and we zoom in
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) {
// if this is a double press on the map, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
// if pointer was dragged much, do not recognize a double tap on the map
if (pointerDraggedMuch) {
return;
}
//#debug debug
logger.debug("double tap map");
pointerActionDone = true;
commandAction(ZOOM_IN_CMD);
}
repaint();
return;
} else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){
// double tapping a control
int actionId = tl.getActionIdDoubleAtPointer(x, y);
//#debug debug
logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x);
if (actionId > 0) {
// if this is a double press on a control, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
pointerActionDone = true;
commandAction(actionId);
tl.clearTouchedElement();
repaint();
return;
} else {
singleTap(x, y);
}
}
}
private void longTap() {
// if not tapping a control, then the map area must be tapped so we do the long tap action for the map area
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) {
if (!pointerDraggedMuch && Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) {
pointerActionDone = true;
//#debug debug
logger.debug("long tap map");
//#if polish.api.online
// long tap map to open a place-related menu
// use the place of touch instead of old center as position,
// set as new center
pickPointEnd=panProjection.inverse(touchX,touchY, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
imageCollector.newDataReady();
gpsRecenter = false;
commandAction(ONLINE_INFO_CMD);
//#endif
}
return;
// long tapping a control
} else {
int actionId = tl.getActionIdLongAtPointer(touchX, touchY);
if (actionId > 0 && tl.getElementAtPointer(touchX, touchY) == tl.getTouchedElement()) {
tl.clearTouchedElement();
repaint();
pointerActionDone = true;
//#debug debug
logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY);
commandAction(actionId);
}
}
}
/**
* Returns the command used to go to the data screens.
* Needed by the data screens so they can find the key codes used for this
* as they have to use them too.
* @return Command
*/
public Command getDataScreenCommand() {
return CMDS[DATASCREEN_CMD];
}
public Tile getDict(byte zl) {
return tiles[zl];
}
public void setDict(Tile dict, byte zl) {
tiles[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from Configuration
Configuration.getStartupPos(center);
if (center.radlat == 0.0f && center.radlon == 0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
// read saved destination position from Configuration
if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) {
Node destNode = new Node();
Configuration.getDestPos(destNode);
setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon));
}
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void setBaseTilesRead(boolean read) {
baseTilesRead = read;
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint();
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
// some fault tolerance - will crash without a map
if (Legend.isValid) {
GpsMid.mNoiseMaker.playSound("DISCONNECT");
}
}
//if (gpx != null) {
// /**
// * Close and Save the gpx recording, to ensure we don't loose data
// */
// gpx.saveTrk(false);
//}
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
if (locationProducer == null) {
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
notify();
addCommand(CMDS[CONNECT_GPS_CMD]);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveStatus(byte status, int satsReceived) {
if (status != LocationMsgReceiver.STATUS_ON
&& status != LocationMsgReceiver.STATUS_2D
&& status != LocationMsgReceiver.STATUS_3D
&& status != LocationMsgReceiver.STATUS_DGPS) {
// no fix, invalidate speed heuristic
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
// FIXME signal a sound on location gained or lost
solution = status;
solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived);
repaint();
+ // to update e.g. tacho
+ if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
+ synchronized (locationUpdateListeners) {
+ for (int i = 0; i < locationUpdateListeners.size(); i++) {
+ ((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
+ }
+ }
+ }
}
public String getName(int idx) {
if (idx < 0) {
return null;
}
return namesThread.getName(idx);
}
public String getUrl(int idx) {
if (idx < 0) {
return null;
}
return urlsThread.getUrl(idx);
}
public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) {
return namesThread.fulltextSearch(snippet, cmi);
}
// this is called by ImageCollector
public void requestRedraw() {
repaint();
}
public void newDataReady() {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
Legend.freeDrawnWayAndAreaSearchImages();
GpsMid.getInstance().show(this);
setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
updateLastUserActionTime();
repaint();
}
public void recreateTraceLayout() {
tl = new TraceLayout(0, 0, getWidth(), getHeight());
}
public void resetSize() {
sizeChanged(getWidth(), getHeight());
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getDestination() {
return dest;
}
public void setDestination(RoutePositionMark dest) {
endRouting();
this.dest = dest;
pc.dest = dest;
if (dest != null) {
//#debug info
logger.info("Setting destination to " + dest.toString());
// move map only to the destination, if GUI is not optimized for routing
if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) {
commandAction(SHOW_DEST_CMD);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) {
Configuration.setDestPos(new Node(dest.lat, dest.lon, true));
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true);
}
movedAwayFromDest = false;
} else {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false);
//#debug info
logger.info("Setting destination to null");
}
}
public void endRouting() {
RouteInstructions.initialRecalcDone = false;
RouteInstructions.icCountOffRouteDetected = 0;
RouteInstructions.routeInstructionsHeight = 0;
RouteInstructions.abortRouteLineProduction();
setRoute(null);
setRouteNodes(null);
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
}
if (this.route != null) {
// reset off-route as soon as first route connection is known
RouteInstructions.resetOffRoute(this.route, center);
if (ri == null) {
ri = new RouteInstructions(this);
}
// show map during route line production
if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) {
resumeImageCollectorAfterRouteCalc();
}
ri.newRoute(this.route);
oldRecalculationTime = System.currentTimeMillis();
}
// show map always after route calculation
resumeImageCollectorAfterRouteCalc();
routeCalc=false;
routeEngine=null;
}
private void resumeImageCollectorAfterRouteCalc() {
try {
if (imageCollector == null) {
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
} else if (imageCollector != null) {
imageCollector.newDataReady();
}
repaint();
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceResumeImageCollector")/*In Trace.resumeImageCollector*/, e);
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
urlsThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
public Vector getRouteNodes() {
return routeNodes;
}
public void setRouteNodes(Vector routeNodes) {
this.routeNodes = routeNodes;
}
protected void hideNotify() {
//#debug debug
logger.debug("Hide notify has been called, screen will no longer be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
//#debug debug
logger.debug("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
public Vector getRoute() {
return route;
}
public void actionCompleted() {
boolean reAddCommands = true;
if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
addAllCommands();
}
}
public void showIconMenu() {
if (traceIconMenu == null) {
traceIconMenu = new TraceIconMenu(this, this);
}
traceIconMenu.show();
}
/** uncache the icon menu to reflect changes in the setup or save memory */
public static void uncacheIconMenu() {
//#mdebug trace
if (traceIconMenu != null) {
logger.trace("uncaching TraceIconMenu");
}
//#enddebug
traceIconMenu = null;
}
/** interface for IconMenuWithPages: recreate the icon menu from scratch and show it (introduced for reflecting size change of the Canvas) */
public void recreateAndShowIconMenu() {
uncacheIconMenu();
showIconMenu();
}
/** interface for received actions from the IconMenu GUI */
public void performIconAction(int actionId) {
//#if not polish.android
show();
//#endif
updateLastUserActionTime();
// when we are low on memory or during route calculation do not cache the icon menu (including scaled images)
if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) {
//#debug info
logger.info("low mem: Uncaching traceIconMenu");
uncacheIconMenu();
}
if (actionId != IconActionPerformer.BACK_ACTIONID) {
commandAction(actionId);
}
}
/** convert distance to string based on user preferences */
// The default way to show a distance is "10km" for
// distances 10km or more, "2,6km" for distances under 10, and
// "600m" for distances under 1km.
public static String showDistance(int meters) {
return showDistance(meters, DISTANCE_GENERIC);
}
public static String showDistance(int meters, int type) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.m");
}
int MajorUnit = meters / 1000;
int MinorUnit = meters % 1000;
// km.mm
//String MinorShort = (MinorUnit / 10 < 10 ? "0" : "") + (MinorUnit / 10);
// km.m
String MinorShort = Integer.toString((int)MinorUnit / 100);
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.km");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.m");
} else {
// FIXME use e.g. getDecimalSeparator() for decimal comma/point selection
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.km");
}
} else {
return Integer.toString(meters) + Locale.get("guitacho.m");
}
} else {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.yd");
}
int MajorUnit = (int)(meters / 1609.344f);
int MinorUnit = (int)(meters % 1609.344f + 0.5f);
// mi.dd
//String MinorShort = (MinorUnit / 16.09344f < 10.0f ? "0" : "") + (int)(MinorUnit / 16.09344f);
// mi.d
String MinorShort = Integer.toString((int)(MinorUnit / 160.9344f));
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.mi");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.yd");
} else {
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.mi");
}
} else {
return Integer.toString((int)(meters / 0.9144 + 0.5f)) + Locale.get("guitacho.yd");
}
}
}
}
| true | true | public void commandAction(Command c, Displayable d) {
updateLastUserActionTime();
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD])
|| (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD])
|| (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.slower();
} else if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.faster();
} else if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
Configuration.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else if (imageCollector != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
// set compass compassDeviation
if (compassDeviation == 360) {
compassDeviation = 0;
} else {
compassDeviation += courseDiff;
compassDeviation %= 360;
if (course < 0) {
course += 360;
}
}
} else {
// manual rotation
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
gpsRecenter = false;
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording
// would not be stopped when leaving the map.
if (Legend.isValid && gpx.isRecordingTrk()) {
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.PleaseStopRecording")/*Please stop recording before exit.*/ , 2500);
return;
}
if (Legend.isValid) {
pause();
}
parent.exit();
return;
}
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StartingToRecord")/*Starting to record*/, 1250);
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StoppingToRecord")/*Stopping to record*/, 1250);
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) {
// FIXME it's not strictly necessary to stop, after there are translation for the pause
// message, change to Locale.get("trace.YouNeedStopPauseRecording")
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.YouNeedStopRecording")/*You need to stop recording before managing tracks.*/ , 4000);
return;
}
GuiGpx guiGpx = new GuiGpx(this);
guiGpx.show();
return;
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
return;
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
if (TrackPlayer.isPlaying) {
TrackPlayer.getInstance().stop();
alert(Locale.get("trace.Trackplayer")/*Trackplayer*/, Locale.get("trace.PlayingStopped")/*Playing stopped for connecting to GPS*/, 2500);
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
return;
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null) {
locationProducer.close();
}
return;
}
if (c == CMDS[TOGGLE_GPS_CMD]) {
if (isGpsConnected()) {
commandAction(DISCONNECT_GPS_CMD);
} else {
commandAction(CONNECT_GPS_CMD);
}
return;
}
if (c == CMDS[SEARCH_CMD]) {
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_DEFAULT);
guiSearch.show();
return;
}
if (c == CMDS[ENTER_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
return;
}
if (c == CMDS[MAN_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
return;
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
return;
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
return;
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
return;
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
boolean hasJSR120 = Configuration.hasDeviceJSR120();
int noElements = 3;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
noElements++;
}
//#endif
int idx = 0;
String[] elements = new String[noElements];
if (gpx.isRecordingTrk()) {
elements[idx++] = Locale.get("trace.StopGpxTracklog")/*Stop Gpx tracklog*/;
} else {
elements[idx++] = Locale.get("trace.StartGpxTracklog")/*Start Gpx tracklog*/;
}
elements[idx++] = Locale.get("trace.SaveWaypoint")/*Save waypoint*/;
elements[idx++] = Locale.get("trace.EnterWaypoint")/*Enter waypoint*/;
//#if polish.api.mmapi
elements[idx++] = Locale.get("trace.TakePictures")/*Take pictures*/;
if (audioRec.isRecording()) {
elements[idx++] = Locale.get("trace.StopAudioRecording")/*Stop audio recording*/;
} else {
elements[idx++] = Locale.get("trace.StartAudioRecording")/*Start audio recording*/;
}
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
elements[idx++] = Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/;
}
//#endif
recordingsMenu = new List(Locale.get("trace.Recordings")/*Recordings...*/,Choice.IMPLICIT,elements,null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
return;
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = new String[4];
if (routeCalc || route != null) {
elements[0] = Locale.get("trace.StopRouting")/*Stop routing*/;
} else {
elements[0] = Locale.get("trace.CalculateRoute")/*Calculate route*/;
}
elements[1] = Locale.get("trace.SetDestination")/*Set destination*/;
elements[2] = Locale.get("trace.ShowDestination")/*Show destination*/;
elements[3] = Locale.get("trace.ClearDestination")/*Clear destination*/;
routingsMenu = new List(Locale.get("trace.Routing2")/*Routing..*/, Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
return;
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
PositionMark posMark = null;
if (gpsRecenter) {
// TODO: If we lose the fix the old position and height
// will be used silently -> we should inform the user
// here that we have no fix - he may not know what's going on.
posMark = new PositionMark(center.radlat, center.radlon,
(int)pos.altitude, pos.timeMillis,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1);
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
posMark = new PositionMark(center.radlat, center.radlon,
PositionMark.INVALID_ELEVATION,
pos.timeMillis, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1);
}
/*
if (Configuration.getCfgBitState(Configuration.CFGBIT_WAYPT_OFFER_PREDEF)) {
if (guiWaypointPredefined == null) {
guiWaypointPredefined = new GuiWaypointPredefined(this);
}
if (guiWaypointPredefined != null) {
guiWaypointPredefined.setData(posMark);
guiWaypointPredefined.show();
}
} else {
*/
showGuiWaypointSave(posMark);
//}
}
return;
}
if (c == CMDS[ONLINE_INFO_CMD]) {
//#if polish.api.online
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc);
gWeb.show();
//#else
alert(Locale.get("trace.NoOnlineCapa")/*No online capabilites*/,
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
//#endif
}
if (c == CMDS[BACK_CMD]) {
show();
return;
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
switch (recordingsMenu.getSelectedIndex()) {
case 0: {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) {
show();
}
} else {
commandAction(START_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) {
show();
}
}
break;
}
case 1: {
commandAction(SAVE_WAYP_CMD);
break;
}
case 2: {
commandAction(ENTER_WAYP_CMD);
break;
}
//#if polish.api.mmapi
case 3: {
commandAction(CAMERA_CMD);
break;
}
case 4: {
show();
commandAction(TOGGLE_AUDIO_REC);
break;
}
//#endif
//#if polish.api.mmapi && polish.api.wmapi
case 5: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#elif polish.api.wmapi
case 3: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#endif
}
}
if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
break;
}
case 1: {
commandAction(SET_DEST_CMD);
break;
}
case 2: {
commandAction(SHOW_DEST_CMD);
break;
}
case 3: {
commandAction(CLEAR_DEST_CMD);
break;
}
}
}
return;
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]) {
try {
Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception(Locale.get("trace.YourPhoneNoCamSupport")/*Your phone does not support the necessary JSRs to use the camera*/, cnfe);
}
return;
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
recordingsMenu = null; // refresh recordings menu
return;
}
//#endif
if (c == CMDS[ROUTING_TOGGLE_CMD]) {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
return;
}
if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
GuiRoute guiRoute = new GuiRoute(this, false);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) {
commandAction(ROUTING_START_CMD);
} else {
guiRoute.show();
}
return;
}
if (c == CMDS[ROUTING_START_CMD]) {
if (! routeCalc || RouteLineProducer.isRunning()) {
routeCalc = true;
if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
// center of the map is the route source
RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon);
logger.info("Routing source: " + routeSource);
routeNodes=new Vector();
routeEngine = new Routing(this);
routeEngine.solve(routeSource, dest);
// resume();
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ROUTING_STOP_CMD]) {
NoiseMaker.stopPlayer();
if (routeCalc) {
if (routeEngine != null) {
routeEngine.cancelRouting();
}
alert(Locale.get("trace.RouteCalculation")/*Route Calculation*/, Locale.get("trace.Cancelled")/*Cancelled*/, 1500);
} else {
alert(Locale.get("trace.Routing")/*Routing*/, Locale.get("generic.Off")/*Off*/, 750);
}
endRouting();
routingsMenu = null; // refresh routingsMenu
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
if (hasPointerEvents()) {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourse")/*Change course with zoom buttons*/, 3000);
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourseWithLeftRightKeys")/*Change course with left/right keys*/, 3000);
}
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("generic.Off")/*Off*/, 750);
}
return;
}
if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
return;
}
if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
return;
}
if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
return;
}
if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (manualRotationMode) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
compassDeviation = 0;
} else {
course = 0;
}
alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750);
} else {
// FIXME rename string to generic
alert(Locale.get("guidiscover.MapProjection")/*Map Projection*/, ProjFactory.nextProj(), 750);
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
return;
}
if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert(Locale.get("trace.GpsMid")/*GpsMid*/, hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked")/*Keys and touch screen unlocked*/ : Locale.get("trace.KeysUnlocked")/*Keys unlocked*/, 1000);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
} else {
commandAction(START_RECORD_CMD);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.ResumingRecording")/*Resuming recording*/, 1000);
gpx.resumeTrk();
} else {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.SuspendingRecording")/*Suspending recording*/, 1000);
gpx.suspendTrk();
}
}
return;
}
if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
autoZoomed = true;
if (pos.latitude != 0.0f) {
receivePosition(pos);
}
newDataReady();
return;
}
if (c == CMDS[SHOW_DEST_CMD]) {
if (dest != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
prevPositionNode = center.copy();
center.setLatLonRad(dest.lat, dest.lon);
movedAwayFromDest = false;
updatePosition();
}
else {
alert(Locale.get("trace.ShowDestination")/*Show destination*/, Locale.get("trace.DestinationNotSpecifiedYet")/*Destination is not specified yet*/, 3000);
}
return;
}
if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) {
if (prevPositionNode != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLon(prevPositionNode);
updatePosition();
}
}
if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
return;
}
if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
showIconMenu();
return;
}
if (c == CMDS[SETUP_CMD]) {
new GuiDiscover(parent);
return;
}
if (c == CMDS[ABOUT_CMD]) {
new Splash(parent, GpsMid.initDone);
return;
}
if (c == CMDS[CELLID_LOCATION_CMD]) {
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) {
locationProducer.triggerPositionUpdate();
newDataReady();
} else {
if (cellIDLocationProducer == null) {
// init sleeping cellid location provider if cellid is not primary
cellIDLocationProducer = new SECellID();
if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) {
logger.info("Failed to initialise CellID location producer");
}
}
if (cellIDLocationProducer != null) {
cellIDLocationProducer.triggerPositionUpdate();
newDataReady();
}
}
return;
}
if (c == CMDS[MANUAL_LOCATION_CMD]) {
Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD,
center.radlon / MoreMath.FAC_DECTORAD,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis(), Position.TYPE_MANUAL);
// implies center to gps, to give feedback as the gps rectangle
gpsRecenter = true;
// gpsRecenterInvalid = true;
// gpsRecenterStale = true;
autoZoomed = true;
receivePosition(setpos);
receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0);
newDataReady();
return;
}
if (! routeCalc) {
//#if polish.api.osm-editing
if (c == CMDS[RETRIEVE_XML]) {
if (Legend.enableEdits) {
// -1 alert ("Editing", "Urlidx: " + pc.actualWay.urlIdx, Alert.FOREVER);
if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) {
parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER);
}
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GuiOSMWayDisplay guiWay = new GuiOSMWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[EDIT_ENTITY]) {
if (Legend.enableEdits) {
// FIXME: do the following:
// * set a flag that default operation is OSM edit
// * do a search for nearby POIs, asking for type
// * when the user selects, open OSM editing
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_EDIT_ENTITY);
guiSearch.show();
return;
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[RETRIEVE_NODE]) {
// FIXME add support for accessing a node
// under cursor
if (Legend.enableEdits) {
GuiOSMPOIDisplay guiNode = new GuiOSMPOIDisplay(-1, null,
center.radlat, center.radlon, this);
guiNode.show();
guiNode.refresh();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
if (c == CMDS[EDIT_ADDR_CMD]) {
if (Legend.enableEdits) {
String streetName = "";
if ((pc != null) && (pc.actualWay != null)) {
streetName = getName(pc.actualWay.nameIdx);
}
GuiOSMAddrDisplay guiAddr = new GuiOSMAddrDisplay(-1, streetName, null,
center.radlat, center.radlon, this);
guiAddr.show();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
//#else
if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) {
alert("No online capabilites",
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
}
//#endif
if (c == CMDS[SET_DEST_CMD]) {
RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon);
setDestination(pm1);
return;
}
if (c == CMDS[CLEAR_DEST_CMD]) {
setDestination(null);
return;
}
} else {
alert(Locale.get("trace.Error")/*Error*/, Locale.get("trace.CurrentlyInRouteCalculation")/*Currently in route calculation*/, 2000);
}
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceCommandAction")/*In Trace.commandAction*/, e);
}
}
private void startImageCollector() throws Exception {
//#debug info
logger.info("Starting ImageCollector");
Images images = new Images();
pc = new PaintContext(this, images);
/* move responsibility for overscan to ImageCollector
int w = (this.getWidth() * 125) / 100;
int h = (this.getHeight() * 125) / 100;
*/
imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.copy();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
//#debug info
logger.info("Stopping ImageCollector");
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
urlsThread = new Urls();
new DictReader(this);
// wait until base tiles are read; otherwise there's apparently
// a race condition triggered on Symbian s60r3 phones, see
// https://sourceforge.net/support/tracker.php?aid=3284022
if (Legend.isValid) {
while (!baseTilesRead) {
try {
Thread.sleep(250);
} catch (InterruptedException e1) {
// nothing to do in that case
}
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
Thread thread = new Thread(this, "Trace");
thread.start();
}
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte)5);
startImageCollector();
recreateTraceLayout();
}
public void shutdown() {
if (gpx != null) {
// change to "false" to ask for track name if configure to
// currently "true" to not ask for name to ensure fast
// quit & try to avoid loss of data which might result from
// waiting for user to type the name
gpx.saveTrk(true);
}
//#debug debug
logger.debug("Shutdown: stopImageCollector");
stopImageCollector();
if (namesThread != null) {
//#debug debug
logger.debug("Shutdown: namesThread");
namesThread.stop();
namesThread = null;
}
if (urlsThread != null) {
urlsThread.stop();
urlsThread = null;
}
if (dictReader != null) {
//#debug debug
logger.debug("Shutdown: dictReader");
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
//#debug debug
logger.debug("Shutdown: tileReader");
tileReader.shutdown();
tileReader = null;
}
if (locationProducer != null) {
//#debug debug
logger.debug("Shutdown: locationProducer");
locationProducer.close();
}
if (TrackPlayer.isPlaying) {
//#debug debug
logger.debug("Shutdown: TrackPlayer");
TrackPlayer.getInstance().stop();
}
}
public void sizeChanged(int w, int h) {
updateLastUserActionTime();
if (imageCollector != null) {
logger.info("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector")/*Could not reinitialise Image Collector after size change*/, e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
tl = new TraceLayout(0, 0, w, h);
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null) {
/*
* When painting we receive a copy of the center coordinates
* where the imageCollector has drawn last
* as we need to base the routing instructions on the information
* determined during the way drawing (e.g. the current routePathConnection)
*/
Node drawnCenter = imageCollector.paint(pc);
if (route != null && ri != null && pc.lineP2 != null && pc.getP() != null/*avoids exception at route calc*/) {
pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2);
/*
* we also need to make sure the current way for the real position
* has really been detected by the imageCollector which happens when drawing the ways
* So we check if we just painted an image that did not cover
* the center of the display because it was too far painted off from
* the display center position and in this case we don't give route instructions
* Thus e.g. after leaving a long tunnel without gps fix there will not be given an
* obsolete instruction from inside the tunnel
*/
int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2);
if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs
&&
Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs
) {
/*
* we need to synchronize the route instructions on the informations determined during way painting
* so we give the route instructions right after drawing the image with the map
* and use the center of the last drawn image for the route instructions
*/
ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan);
}
}
} else {
// show the way bar even if ImageCollector is not running because it's necessary on touch screens to get to the icon menu
tl.ele[TraceLayout.WAYNAME].setText(" ");
}
/* Beginning of voice instructions started from overlay code (besides showRoute above)
*/
// Determine if we are at the destination
if (dest != null) {
float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon);
atDest = (distance < 25);
if (atDest) {
if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1);
}
} else if (!movedAwayFromDest) {
movedAwayFromDest = true;
}
}
// determine if we are currently speeding
speeding = false;
int maxSpeed = 0;
// only detect speeding when gpsRecentered and there is a current way
if (gpsRecenter && actualSpeedLimitWay != null) {
maxSpeed = actualSpeedLimitWay.getMaxSpeed();
// check for winter speed limit if configured
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
&& (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) {
maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter();
}
if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) {
speeding = true;
}
}
if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
// give speeding alert only every 10 seconds
if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) {
lastTimeOfSpeedingSound = System.currentTimeMillis();
GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound());
}
}
/*
* end of voice instructions started from overlay code
*/
/*
* the final part of the overlay should not give any voice instructions
*/
g.setColor(Legend.COLOR_MAP_TEXT);
switch (showAddons) {
case 1:
yc = showMemory(g, yc, la);
break;
case 2:
yc = showConnectStatistics(g, yc, la);
break;
default:
showAddons = 0;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) {
if (pc != null) {
tl.calcScaleBarWidth(pc);
tl.ele[TraceLayout.SCALEBAR].setText(" ");
}
}
setPointOfTheCompass();
}
showMovement(g);
// Show gpx track recording status
LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION];
LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT];
if (gpx.isRecordingTrk()) {
// we are recording tracklogs
if (gpx.isRecordingTrkSuspended()) {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); // blue
} else {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); // red
}
eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")/*r*/);
}
if (TrackPlayer.isPlaying) {
eSolution.setText(Locale.get("trace.Replay")/*Replay*/);
} else {
if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID ||
solution == LocationMsgReceiver.STATUS_MANUAL)) {
eSolution.setText(Locale.get("solution.Off")/*Off*/);
} else {
eSolution.setText(solutionStr);
}
}
LayoutElement e = tl.ele[TraceLayout.CELLID];
// show if we are logging cellIDs
if (SECellLocLogger.isCellIDLogging() > 0) {
if (SECellLocLogger.isCellIDLogging() == 2) {
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); // yellow
} else {
//Attempting to log, but currently no valid info available
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); // red
}
e.setText(Locale.get("trace.cellIDs")/*cellIDs*/);
}
// show audio recording status
e = tl.ele[TraceLayout.AUDIOREC];
if (audioRec.isRecording()) {
e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); // red
e.setText(Locale.get("trace.AudioRec")/*AudioRec*/);
}
if (pc != null) {
showDestination(pc);
}
if (speed > 0 &&
Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("guitacho.kmh")/* km/h*/);
} else {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + Locale.get("guitacho.mph"));
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP)
&& locationProducer != null
&& LocationMsgReceiverList.isPosValid(solution)
) {
tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE));
}
if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) )
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) {
e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE];
e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]);
double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon);
e.setText(Locale.get("trace.Air")/*Air:*/ + showDistance((int) distLine, DISTANCE_AIR));
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) {
e = tl.ele[TraceLayout.CURRENT_TIME]; // e is used *twice* below (also as vRelative)
e.setText(DateTimeTools.getClock(System.currentTimeMillis(), true));
/*
don't use new Date() - it is very slow on some Nokia devices
currentTime.setTime( new Date( System.currentTimeMillis() ) );
e.setText(
currentTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(currentTime.get(Calendar.MINUTE)));
*/
// if current time is visible, positioning OFFROUTE above current time will work
tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e);
}
setSpeedingSign(maxSpeed);
if (hasPointerEvents()) {
tl.ele[TraceLayout.ZOOM_IN].setText("+");
tl.ele[TraceLayout.ZOOM_OUT].setText("-");
tl.ele[TraceLayout.RECENTER_GPS].setText("|");
e = tl.ele[TraceLayout.SHOW_DEST];
if (atDest && prevPositionNode != null) {
e.setText("<");
e.setActionID(SHOW_PREVIOUS_POSITION_CMD);
} else {
e.setText(">");
e.setActionID(SHOW_DEST_CMD + (Trace.SET_DEST_CMD << 16) );
}
}
e = tl.ele[TraceLayout.TITLEBAR];
if (currentTitleMsgOpenCount != 0) {
e.setText(currentTitleMsg);
// setTitleMsgTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setTitleMsgTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentTitleMsgOpenCount--;
lastTitleMsg = currentTitleMsg;
if (currentTitleMsgOpenCount == 0) {
//#debug debug
logger.debug("clearing title");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout);
setTitleMsgTimeout = 0;
}
}
}
tl.paint(g);
if (currentAlertsOpenCount > 0) {
showCurrentAlert(g);
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
}
public void showGuiWaypointSave(PositionMark posMark) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
guiWaypointSave.setData(posMark);
guiWaypointSave.show();
}
}
/** Show an alert telling the user that waypoints are not ready yet.
*/
private void showAlertLoadingWpt() {
alert("Way points", "Way points are not ready yet.", 3000);
}
private void showCurrentAlert(Graphics g) {
Font font = g.getFont();
// request same font in bold for title
Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize());
int fontHeight = font.getHeight();
// add alert title height plus extra space of one line for calculation of alertHeight
int y = titleFont.getHeight() + 2 + fontHeight;
// extra width for alert
int extraWidth = font.charWidth('W');
// alert is at least as wide as alert title
int alertWidth = titleFont.stringWidth(currentAlertTitle);
// width each alert message line must fit in
int maxWidth = getWidth() - extraWidth;
// Two passes: 1st pass calculates placement and necessary size of alert,
// 2nd pass actually does the drawing
for (int i = 0; i <= 1; i++) {
int nextSpaceAt = 0;
int prevSpaceAt = 0;
int start = 0;
// word wrap
do {
int width = 0;
// add word by word until string part is too wide for screen
while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) {
prevSpaceAt = nextSpaceAt;
nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt);
if (nextSpaceAt == -1) {
nextSpaceAt = currentAlertMessage.length();
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
nextSpaceAt++;
}
nextSpaceAt--;
// Reduce line word by word or if not possible char by char until the
// remaining string part fits to display width
while (width > maxWidth) {
if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) {
nextSpaceAt = prevSpaceAt;
} else {
nextSpaceAt--;
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
}
// determine maximum alert width
if (alertWidth < width ) {
alertWidth = width;
}
// during the second pass draw the message text lines
if (i==1) {
g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start,
getWidth()/2, y, Graphics.TOP|Graphics.HCENTER);
}
y += fontHeight;
start = nextSpaceAt;
} while (nextSpaceAt < currentAlertMessage.length() );
// at the end of the first pass draw the alert box and the alert title
if (i == 0) {
alertWidth += extraWidth;
int alertHeight = y;
int alertTop = (getHeight() - alertHeight) /2;
//alertHeight += fontHeight/2;
int alertLeft = (getWidth() - alertWidth) / 2;
// alert background color
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, alertHeight);
// background color for alert title
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3);
// alert border
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]);
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); // title border
g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); // alert border
// draw alert title
y = alertTop + 2; // output position of alert title
g.setFont(titleFont);
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]);
g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER);
g.setFont(font);
// output alert message 1.5 lines below alert title in the next pass
y += (fontHeight * 3 / 2);
}
} // end for
// setAlertTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setAlertTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentAlertsOpenCount--;
if (currentAlertsOpenCount == 0) {
//#debug debug
logger.debug("clearing alert");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setAlertTimeout);
setAlertTimeout = 0;
}
}
}
private void setSpeedingSign(int maxSpeed) {
// speeding = true;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL)
&&
(
speeding
||
(System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000
)
) {
if (speeding) {
speedingSpeedLimit = maxSpeed;
startTimeOfSpeedingSign = System.currentTimeMillis();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit));
} else {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f + 0.5f)));
}
} else {
startTimeOfSpeedingSign = 0;
}
}
/**
*
*/
private void getPC() {
pc.course = course;
pc.scale = scale;
pc.center = center.copy();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.dest = dest;
}
public void cleanup() {
namesThread.cleanup();
urlsThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
// public void searchElement(PositionMark pm) throws Exception {
// PaintContext pc = new PaintContext(this, null);
// // take a bigger angle for lon because of positions near to the poles.
// Node nld = new Node(pm.lat - 0.0001f, pm.lon - 0.0005f, true);
// Node nru = new Node(pm.lat + 0.0001f, pm.lon + 0.0005f, true);
// pc.searchLD = nld;
// pc.searchRU = nru;
// pc.dest = pm;
// pc.setP(new Proj2D(new Node(pm.lat, pm.lon, true), 5000, 100, 100));
// for (int i = 0; i < 4; i++) {
// tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
// }
// }
public void searchNextRoutableWay(RoutePositionMark pm) throws Exception {
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
// Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
// Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
// pc.searchLD=nld;
// pc.searchRU=nru;
pc.squareDstWithPenToActualRoutableWay = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
// retry searching an expanding region at the position mark
Projection p;
do {
p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize);
pc.setP(p);
for (int i=0; i<4; i++) {
tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT);
}
// stop the search when a routable way is found
if (pc.actualRoutableWay != null) {
break;
}
// expand the region that gets searched for a routable way
pc.xSize += 100;
pc.ySize += 100;
// System.out.println(pc.xSize);
} while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); // until we searched at least 500 m edge length
Way w = pc.actualRoutableWay;
pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon);
}
private void setPointOfTheCompass() {
String c = "";
if (ProjFactory.getProj() != ProjFactory.NORTH_UP
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) {
c = Configuration.getCompassDirection(course);
}
// if tl shows big onscreen buttons add spaces to compass directions consisting of only one char or not shown
if (tl.bigOnScreenButtons && c.length() <= 1) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP) {
c = "(" + Configuration.getCompassDirection(0) + ")";
} else {
c = " " + c + " ";
}
}
tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c);
}
private int showConnectStatistics(Graphics g, int yc, int la) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]);
// only try to show compass id and cell id if user has somehow switched them on
GSMCell cell = null;
if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL || Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
cell = CellIdProvider.getInstance().obtainCachedCellID();
}
Compass compass = null;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) {
compass = CompassProvider.getInstance().obtainCachedCompass();
}
if (cell == null) {
g.drawString("No Cell ID available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (compass == null) {
g.drawString("No compass direction available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public void showDestination(PaintContext pc) {
// Avoid exception after route calculation
if ( pc.getP() == null || imageCollector == null )
return;
try {
if (dest != null) {
pc.getP().forward(dest.lat, dest.lon, pc.lineP2);
// System.out.println(dest.toString());
int x = pc.lineP2.x - imageCollector.xScreenOverscan;
int y = pc.lineP2.y - imageCollector.yScreenOverscan;
pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS);
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]);
if (dest.displayName != null) {
pc.g.drawString(dest.displayName, x, y+8,
Graphics.TOP | Graphics.HCENTER);
}
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_LINE]);
pc.g.setStrokeStyle(Graphics.SOLID);
pc.g.drawLine( pc.getP().getImageCenter().x - imageCollector.xScreenOverscan,
pc.getP().getImageCenter().y - imageCollector.yScreenOverscan,x, y);
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
e.printStackTrace();
}
}
/**
* Draws the position square, the movement line and the center cross.
*
* @param g Graphics context for drawing
*/
public void showMovement(Graphics g) {
// Avoid exception after route calculation
if ( pc.getP() == null )
return;
IntPoint centerP = null;
try {
if (imageCollector != null) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]);
centerP = pc.getP().getImageCenter();
int centerX = centerP.x - imageCollector.xScreenOverscan;
int centerY = centerP.y - imageCollector.yScreenOverscan;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0, 0);
pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD),
(pos.longitude * MoreMath.FAC_DECTORAD), p1);
posX = p1.getX()-imageCollector.xScreenOverscan;
posY = p1.getY()-imageCollector.yScreenOverscan;
} else {
posX = centerX;
posY = centerY;
}
g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]);
float radc = course * MoreMath.FAC_DECTORAD;
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
// crosshair center cursor
if (!gpsRecenter || gpsRecenterInvalid) {
g.drawLine(centerX, centerY - 12, centerX, centerY + 12);
g.drawLine(centerX - 12, centerY, centerX + 12, centerY);
g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360);
}
if (! gpsRecenterInvalid) {
// gps position spot
pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS);
// gps position rectangle
g.drawRect(posX - 4, posY - 4, 8, 8);
g.drawLine(posX, posY, px, py);
}
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
if (centerP == null) {
logger.silentexception("No centerP", e);
}
e.printStackTrace();
}
}
/**
* Show next screen in the sequence of data screens
* (tacho, trip, satellites).
* @param currentScreen Data screen currently shown, use the DATASCREEN_XXX
* constants from this class. Use DATASCREEN_NONE if none of them
* is on screen i.e. the first one should be shown.
*/
public void showNextDataScreen(int currentScreen) {
switch (currentScreen)
{
case DATASCREEN_TACHO:
// Tacho is followed by Trip.
if (guiTrip == null) {
guiTrip = new GuiTrip(this);
}
if (guiTrip != null) {
guiTrip.show();
}
break;
case DATASCREEN_TRIP:
// Trip is followed by Satellites.
if (guiSatellites == null) {
guiSatellites = new GuiSatellites(this, locationProducer);
}
if (guiSatellites != null) {
guiSatellites.show();
}
break;
case DATASCREEN_SATS:
// After Satellites, go back to map.
this.show();
break;
case DATASCREEN_NONE:
default:
// Tacho is first data screen
if (guiTacho == null) {
guiTacho = new GuiTacho(this);
}
if (guiTacho != null) {
guiTacho.show();
}
break;
}
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0);
g.drawString(Locale.get("trace.Freemem")/*Freemem: */ + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Totmem")/*Totmem: */ + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Percent")/*Percent: */
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.ThreadsRunning")/*Threads running: */
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Names")/*Names: */ + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.SingleT")/*Single T: */ + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.FileT")/*File T: */ + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.LastMsg")/*LastMsg: */ + lastTitleMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( Locale.get("trace.at")/*at */ + lastTitleMsgClock, 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
private void updatePosition() {
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course=course;
repaint();
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosition(float lat, float lon, float scale) {
//#debug debug
logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " +
(lon * MoreMath.FAC_RADTODEC));
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLonRad(lat, lon);
this.scale = scale;
updatePosition();
}
public synchronized void receiveCompassStatus(int status) {
}
public synchronized void receiveCompass(float direction) {
//#debug debug
logger.debug("Got compass reading: " + direction);
compassDirection = (int) direction;
compassDeviated = ((int) direction + compassDeviation + 360) % 360;
// TODO: allow for user to use compass for turning the map in panning mode
// (gpsRenter test below switchable by user setting)
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && gpsRecenter) {
updateCourse(compassDeviated);
//repaint();
}
// course = compassDeviated;
//}
}
public static void updateLastUserActionTime() {
lastUserActionTime = System.currentTimeMillis();
}
public static long getDurationSinceLastUserActionTime() {
return System.currentTimeMillis() - lastUserActionTime;
}
public void updateCourse(int newcourse) {
coursegps = newcourse;
/* don't rotate too fast
*/
if ((newcourse - course)> 180) {
course = course + 360;
}
if ((course-newcourse)> 180) {
newcourse = newcourse + 360;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
course = newcourse;
} else {
// FIXME I think this is too slow a turn at least when course is
// of good quality, turning should be faster. This probably alleviates
// the trouble caused by unreliable gps course. However,
// some kind of heuristic, averaging course or evaluating the
// quality of course and fast or instant rotation with a known good GPS fix
// should be implemented instead of assuming course is always unreliable.
// The course fluctuations are lesser in faster speeds, so if we're constantly
// (for three consecutive locations) above say 5 km/h, a reasonable approach
// could be to use direct course change in that case, and for speed below
// 5 km/h use the slow turning below.
// jkpj 2010-01-17
// on 2011-04-11: jkpj switched from 1/4 rotation back to 3/4 rotation,
// returning to what it was supposed to do before 2010-11-30.
course = course + ((newcourse - course)*3)/4 + 360;
}
while (course > 360) {
course -= 360;
}
}
public synchronized void receivePosition(Position pos) {
// FIXME signal on location gained
//#debug info
logger.info("New position: " + pos);
collected++;
if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 &&
getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs()
&& isShown()
) {
gpsRecenter = true;
//autoZoomed = true;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) {
if (pos.type == Position.TYPE_GPS_LASTKNOWN) {
// if we have a current cell id fix from cellid location,
// don't overwrite it with a stale GPS location, but ignore the position
// FIXME perhaps compare timestamps here in case the last known gps is later
if (this.pos.type == Position.TYPE_CELLID) {
return;
}
gpsRecenterInvalid = false;
gpsRecenterStale = true;
}
}
this.pos = pos;
if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) {
gpsRecenterInvalid = false;
gpsRecenterStale = false;
}
if (gpsRecenter) {
center.setLatLonDeg(pos.latitude, pos.longitude);
speed = (int) (pos.speed * 3.6f);
fspeed = pos.speed * 3.6f;
// FIXME add auto-fallback mode where course is from GPS at high speeds and from compass
// at low speeds
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
updateCourse(compassDeviated);
} else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) {
// Problem: resolve issue erratic course due to GPS fluctuation
// when GPS reception is poor (maybe 3..7S),
// causes unnecessary and disturbing map rotation when device is in one location
// Heuristic for solving: After being still, require
// three consecutive over-the-limit speed readings with roughly the
// same course
if (thirdPrevCourse != -1) {
// first check for normal flow of things, we've had three valid courses after movement start
updateCourse((int) pos.course);
} else if (prevCourse == -1) {
// previous course was invalid,
// don't set course yet, but set the first tentatively good course
prevCourse = (int) pos.course;
} else if (secondPrevCourse == -1) {
// the previous course was the first good one.
// If this course is in the same 60-degree
// sector as the first course, we have two valid courses
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
secondPrevCourse = prevCourse;
}
prevCourse = (int) pos.course;
} else {
// we have received two previous valid curses, check for this one
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
thirdPrevCourse = secondPrevCourse;
//No need to set these as we'll now trust courses until speed goes below limit
// - unless we'll later add averaging of recent courses for poor GPS reception
//secondPrevCourse = prevCourse;
//prevCourse = (int) pos.course;
updateCourse((int) pos.course);
} else {
prevCourse = (int) pos.course;
secondPrevCourse = -1;
}
}
} else {
// speed under the minimum, invalidate all prev courses
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
}
if (gpx.isRecordingTrk()) {
try {
// don't tracklog manual cellid position or gps start/stop last known position
if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179
&& pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) {
} else {
gpx.addTrkPt(pos);
}
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
altitude = (int) (pos.altitude);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM)
&& gpsRecenter
&& (isGpsConnected() || TrackPlayer.isPlaying)
&& autoZoomed
&& pc.getP() != null
&& pos.speed != Float.NaN // if speed is unknown do not autozoom
&& pos.speed != 0 // if speed is 0 do not autozoom
) {
// the minimumScale at 20km/h and below is equivalent to having zoomed in manually once from the startup zoom level
final float minimumScale = Configuration.getRealBaseScale() / 1.5f;
final int minimumSpeed = 20;
// the maximumScale at 160km/h and above is equivalent to having zoomed out manually once from the startup zoom level
final float maximumScale = Configuration.getRealBaseScale() * 1.5f;
final int maximumSpeed = 160;
int speedForScale = speed;
float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed);
// make sure the new scale is within the minimum / maximum scale values
if (newScale < minimumScale) {
newScale = minimumScale;
} else if (newScale > maximumScale) {
newScale = maximumScale;
}
// autozoom in more at the last 200 m of the route
if (route != null && RouteInstructions.getDstRouteToDestination() <= 200) {
float newScale2 = newScale;
newScale2 = newScale / (1f + (200f - RouteInstructions.getDstRouteToDestination())/ 200f);
// fixed increased zoom for the last 100 m
newScale = Math.max(newScale2, newScale / 1.5f);
}
scale = newScale;
// // calculate meters to top of screen
// float topLat = pc.getP().getMaxLat();
// float topLon = (pc.getP().getMinLon() + pc.getP().getMaxLon()) / 2f;
// float distance = MoreMath.dist(center.radlat, center.radlon, topLat, topLon );
// System.out.println("current distance to top of screen: " + distance);
//
// // avoid zooming in or out too far
// int speedForScale = course;
// if (speedForScale < 30) {
// speedForScale = 30;
// } else if (speedForScale > 160) {
// speedForScale = 160;
// }
//
// final float SECONDS_TO_PREVIEW = 45f;
// float metersToPreview = (float) speedForScale / 3.6f * SECONDS_TO_PREVIEW;
// System.out.println(metersToPreview + "meters to preview at " + speedForScale + "km/h");
//
// if (metersToPreview < 2000) {
// // calculate top position that needs to be visible to preview the metersToPreview
// topLat = center.radlat + (topLat - center.radlat) * metersToPreview / distance;
// topLon = center.radlon + (topLon - center.radlon) * metersToPreview / distance;
// System.out.println("new distance to top:" + MoreMath.dist(center.radlat, center.radlon, topLat, topLon ));
//
// /*
// * calculate scale factor, we multiply this again with 2 * 1.2 = 2.4 to take into account we calculated half the screen height
// * and 1.2f is probably the factor the PaintContext is larger than the display size
// * (new scale is calculated similiar to GuiWaypoint)
// */
// IntPoint intPoint1 = new IntPoint(0, 0);
// IntPoint intPoint2 = new IntPoint(getWidth(), getHeight());
// Node n1 = new Node(center.radlat, center.radlon, true);
// Node n2 = new Node(topLat, topLon, true);
// scale = pc.getP().getScale(n1, n2, intPoint1, intPoint2) * 2.4f;
// }
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentTitleMsg = s;
synchronized (this) {
/*
* only increase the number of current title messages
* if the timer already has been set in the display code
*/
if (setTitleMsgTimeout == 0) {
currentTitleMsgOpenCount++;
}
setTitleMsgTimeout = 3000;
}
lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false);
repaint();
}
public void receiveSatellites(Satellite[] sats) {
// Not interested
}
/** Shows an alert message
*
* @param title The title of the alert
* @param message The message text
* @param timeout Timeout in ms. Please reserve enough time so the user can
* actually read the message. Use Alert.FOREVER if you want no timeout.
*/
public synchronized void alert(String title, String message, int timeout) {
// #debug info
logger.info("Showing trace alert: " + title + ": " + message);
if (timeout == Alert.FOREVER) {
timeout = 10000;
}
currentAlertTitle = title;
currentAlertMessage = message;
synchronized (this) {
/*
* only increase the number of current open alerts
* if the timer already has been set in the display code
*/
if (setAlertTimeout == 0) {
currentAlertsOpenCount++;
}
setAlertTimeout = timeout;
}
repaint();
}
public MIDlet getParent() {
return parent;
}
protected void pointerPressed(int x, int y) {
updateLastUserActionTime();
long currTime = System.currentTimeMillis();
pointerDragged = false;
pointerDraggedMuch = false;
pointerActionDone = false;
// remember center when the pointer was pressed for dragging
centerPointerPressedN = center.copy();
if (imageCollector != null) {
panProjection=imageCollector.getCurrentProjection();
pickPointStart=panProjection.inverse(x,y, pickPointStart);
} else {
panProjection = null;
}
// remember the LayoutElement the pointer is pressed down at, this will also highlight it on the display
int touchedElementId = tl.getElementIdAtPointer(x, y);
if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU)
&&
tl.isAnyActionIdAtPointer(x, y)
) {
tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId));
repaint();
}
// check for double press
if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) {
doubleTap(x, y);
return;
}
// Remember the time and position the pointer was pressed after the check for double tap,
// so the double tap code will check for the position of the first of the two taps
pressedPointerTime = currTime;
Trace.touchX = x;
Trace.touchY = y;
// Give a message if keyboard/user interface is locked.
// This must be done after remembering the touchX/Y positions as they are needed to unlock
if (keyboardLocked) {
keyPressed(0);
return;
}
// // when these statements are reached, no double tap action has been executed,
// // so check here if there's currently already a TimerTask waiting for a single tap.
// // If yes, perform the current single tap action immediately before starting the next TimerTask
// if (checkingForSingleTap && !pointerDraggedMuch) {
// singleTap();
// pointerActionDone = false;
// }
//
longTapTimerTask = new TimerTask() {
public void run() {
// if no action (e.g. from double tap) is already done
// and the pointer did not move or if it was pressed on a control and not moved much
if (!pointerActionDone) {
if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){
longTap();
}
}
}
};
try {
// set timer to continue check if this is a long tap
GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoLongTapTimerTask")/*No LongTap TimerTask: */ + e.toString());
}
}
protected void pointerReleased(int x, int y) {
// releasing the pointer cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
// releasing the pointer will clear the highlighting of the touched element
if (tl.getTouchedElement() != null) {
tl.clearTouchedElement();
repaint();
}
if (!pointerActionDone && !keyboardLocked) {
touchReleaseX = x;
touchReleaseY = y;
// check for a single tap in a timer started after the maximum double tap delay
// if the timer will not be cancelled by a double tap, the timer will execute the single tap command
singleTapTimerTask = new TimerTask() {
public void run() {
if (!keyboardLocked) {
singleTap(touchReleaseX, touchReleaseY);
}
}
};
try {
// set timer to check if this is a single tap
GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoSingleTapTimerTask")/*No SingleTap TimerTask: */ + e.toString());
}
if (pointerDragged) {
pointerDragged(x , y);
return;
}
}
}
protected void pointerDragged (int x, int y) {
updateLastUserActionTime();
LayoutElement e = tl.getElementAtPointer(x, y);
if (tl.getTouchedElement() != e) {
// leaving the touched element cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
tl.clearTouchedElement();
repaint();
}
// If the initially touched element is reached again during dragging, highlight it
if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) {
tl.setTouchedElement(e);
repaint();
}
if (pointerActionDone) {
return;
}
// check if there's been much movement, do this before the slide lock/unlock
// to avoid a single tap action when not sliding enough
if (Math.abs(x - Trace.touchX) > 8
||
Math.abs(y - Trace.touchY) > 8
) {
pointerDraggedMuch = true;
// avoid double tap triggering on fast consecutive drag actions starting at almost the same position
pressedPointerTime = 0;
}
// slide at least 1/4 display width to lock / unlock GpsMid
if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) {
if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU
&&
x - touchX > getWidth() / 4
) {
commandAction(TOGGLE_KEY_LOCK_CMD);
pointerActionDone = true;
}
return;
}
if (keyboardLocked) {
return;
}
pointerDragged = true;
// do not start map dragging on a touch control if only dragged slightly
if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) {
return;
}
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) {
// difference between where the pointer was pressed and is currently dragged
// int diffX = Trace.touchX - x;
// int diffY = Trace.touchY - y;
//
// IntPoint centerPointerPressedP = new IntPoint();
pickPointEnd=panProjection.inverse(x,y, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
// System.out.println("diff " + diffX + "/" + diffY + " " + (pickPointEnd.radlat-pickPointStart.radlat) + "/" + (pickPointEnd.radlon-pickPointStart.radlon) );
imageCollector.newDataReady();
gpsRecenter = false;
}
}
private void singleTap(int x, int y) {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we set the touchable button sizes
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) {
// if pointer was dragged much, do not recognize a single tap on the map
if (pointerDraggedMuch) {
return;
}
// #debug debug
logger.debug("single tap map");
if (!tl.bigOnScreenButtons) {
tl.setOnScreenButtonSize(true);
// set timer to continuously check if the last user interaction is old enough to make the buttons small again
final long BIGBUTTON_DURATION = 5000;
bigButtonTimerTask = new TimerTask() {
public void run() {
if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) {
// make the on screen touch buttons small again
tl.setOnScreenButtonSize(false);
requestRedraw();
bigButtonTimerTask.cancel();
}
}
};
try {
GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500);
} catch (Exception e) {
logger.error("Error scheduling bigButtonTimerTask: " + e.toString());
}
}
}
repaint();
} else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) {
tl.clearTouchedElement();
int actionId = tl.getActionIdAtPointer(x, y);
if (actionId > 0) {
// #debug debug
logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY);
if (System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
} else if (manualRotationMode) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_LEFT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_RIGHT2_CMD;
}
} else if (TrackPlayer.isPlaying) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
}
commandAction(actionId);
repaint();
}
}
}
private void doubleTap(int x, int y) {
// if not double tapping a control, then the map area must be double tapped and we zoom in
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) {
// if this is a double press on the map, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
// if pointer was dragged much, do not recognize a double tap on the map
if (pointerDraggedMuch) {
return;
}
//#debug debug
logger.debug("double tap map");
pointerActionDone = true;
commandAction(ZOOM_IN_CMD);
}
repaint();
return;
} else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){
// double tapping a control
int actionId = tl.getActionIdDoubleAtPointer(x, y);
//#debug debug
logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x);
if (actionId > 0) {
// if this is a double press on a control, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
pointerActionDone = true;
commandAction(actionId);
tl.clearTouchedElement();
repaint();
return;
} else {
singleTap(x, y);
}
}
}
private void longTap() {
// if not tapping a control, then the map area must be tapped so we do the long tap action for the map area
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) {
if (!pointerDraggedMuch && Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) {
pointerActionDone = true;
//#debug debug
logger.debug("long tap map");
//#if polish.api.online
// long tap map to open a place-related menu
// use the place of touch instead of old center as position,
// set as new center
pickPointEnd=panProjection.inverse(touchX,touchY, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
imageCollector.newDataReady();
gpsRecenter = false;
commandAction(ONLINE_INFO_CMD);
//#endif
}
return;
// long tapping a control
} else {
int actionId = tl.getActionIdLongAtPointer(touchX, touchY);
if (actionId > 0 && tl.getElementAtPointer(touchX, touchY) == tl.getTouchedElement()) {
tl.clearTouchedElement();
repaint();
pointerActionDone = true;
//#debug debug
logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY);
commandAction(actionId);
}
}
}
/**
* Returns the command used to go to the data screens.
* Needed by the data screens so they can find the key codes used for this
* as they have to use them too.
* @return Command
*/
public Command getDataScreenCommand() {
return CMDS[DATASCREEN_CMD];
}
public Tile getDict(byte zl) {
return tiles[zl];
}
public void setDict(Tile dict, byte zl) {
tiles[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from Configuration
Configuration.getStartupPos(center);
if (center.radlat == 0.0f && center.radlon == 0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
// read saved destination position from Configuration
if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) {
Node destNode = new Node();
Configuration.getDestPos(destNode);
setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon));
}
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void setBaseTilesRead(boolean read) {
baseTilesRead = read;
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint();
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
// some fault tolerance - will crash without a map
if (Legend.isValid) {
GpsMid.mNoiseMaker.playSound("DISCONNECT");
}
}
//if (gpx != null) {
// /**
// * Close and Save the gpx recording, to ensure we don't loose data
// */
// gpx.saveTrk(false);
//}
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
if (locationProducer == null) {
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
notify();
addCommand(CMDS[CONNECT_GPS_CMD]);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveStatus(byte status, int satsReceived) {
if (status != LocationMsgReceiver.STATUS_ON
&& status != LocationMsgReceiver.STATUS_2D
&& status != LocationMsgReceiver.STATUS_3D
&& status != LocationMsgReceiver.STATUS_DGPS) {
// no fix, invalidate speed heuristic
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
// FIXME signal a sound on location gained or lost
solution = status;
solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived);
repaint();
}
public String getName(int idx) {
if (idx < 0) {
return null;
}
return namesThread.getName(idx);
}
public String getUrl(int idx) {
if (idx < 0) {
return null;
}
return urlsThread.getUrl(idx);
}
public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) {
return namesThread.fulltextSearch(snippet, cmi);
}
// this is called by ImageCollector
public void requestRedraw() {
repaint();
}
public void newDataReady() {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
Legend.freeDrawnWayAndAreaSearchImages();
GpsMid.getInstance().show(this);
setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
updateLastUserActionTime();
repaint();
}
public void recreateTraceLayout() {
tl = new TraceLayout(0, 0, getWidth(), getHeight());
}
public void resetSize() {
sizeChanged(getWidth(), getHeight());
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getDestination() {
return dest;
}
public void setDestination(RoutePositionMark dest) {
endRouting();
this.dest = dest;
pc.dest = dest;
if (dest != null) {
//#debug info
logger.info("Setting destination to " + dest.toString());
// move map only to the destination, if GUI is not optimized for routing
if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) {
commandAction(SHOW_DEST_CMD);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) {
Configuration.setDestPos(new Node(dest.lat, dest.lon, true));
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true);
}
movedAwayFromDest = false;
} else {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false);
//#debug info
logger.info("Setting destination to null");
}
}
public void endRouting() {
RouteInstructions.initialRecalcDone = false;
RouteInstructions.icCountOffRouteDetected = 0;
RouteInstructions.routeInstructionsHeight = 0;
RouteInstructions.abortRouteLineProduction();
setRoute(null);
setRouteNodes(null);
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
}
if (this.route != null) {
// reset off-route as soon as first route connection is known
RouteInstructions.resetOffRoute(this.route, center);
if (ri == null) {
ri = new RouteInstructions(this);
}
// show map during route line production
if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) {
resumeImageCollectorAfterRouteCalc();
}
ri.newRoute(this.route);
oldRecalculationTime = System.currentTimeMillis();
}
// show map always after route calculation
resumeImageCollectorAfterRouteCalc();
routeCalc=false;
routeEngine=null;
}
private void resumeImageCollectorAfterRouteCalc() {
try {
if (imageCollector == null) {
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
} else if (imageCollector != null) {
imageCollector.newDataReady();
}
repaint();
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceResumeImageCollector")/*In Trace.resumeImageCollector*/, e);
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
urlsThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
public Vector getRouteNodes() {
return routeNodes;
}
public void setRouteNodes(Vector routeNodes) {
this.routeNodes = routeNodes;
}
protected void hideNotify() {
//#debug debug
logger.debug("Hide notify has been called, screen will no longer be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
//#debug debug
logger.debug("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
public Vector getRoute() {
return route;
}
public void actionCompleted() {
boolean reAddCommands = true;
if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
addAllCommands();
}
}
public void showIconMenu() {
if (traceIconMenu == null) {
traceIconMenu = new TraceIconMenu(this, this);
}
traceIconMenu.show();
}
/** uncache the icon menu to reflect changes in the setup or save memory */
public static void uncacheIconMenu() {
//#mdebug trace
if (traceIconMenu != null) {
logger.trace("uncaching TraceIconMenu");
}
//#enddebug
traceIconMenu = null;
}
/** interface for IconMenuWithPages: recreate the icon menu from scratch and show it (introduced for reflecting size change of the Canvas) */
public void recreateAndShowIconMenu() {
uncacheIconMenu();
showIconMenu();
}
/** interface for received actions from the IconMenu GUI */
public void performIconAction(int actionId) {
//#if not polish.android
show();
//#endif
updateLastUserActionTime();
// when we are low on memory or during route calculation do not cache the icon menu (including scaled images)
if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) {
//#debug info
logger.info("low mem: Uncaching traceIconMenu");
uncacheIconMenu();
}
if (actionId != IconActionPerformer.BACK_ACTIONID) {
commandAction(actionId);
}
}
/** convert distance to string based on user preferences */
// The default way to show a distance is "10km" for
// distances 10km or more, "2,6km" for distances under 10, and
// "600m" for distances under 1km.
public static String showDistance(int meters) {
return showDistance(meters, DISTANCE_GENERIC);
}
public static String showDistance(int meters, int type) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.m");
}
int MajorUnit = meters / 1000;
int MinorUnit = meters % 1000;
// km.mm
//String MinorShort = (MinorUnit / 10 < 10 ? "0" : "") + (MinorUnit / 10);
// km.m
String MinorShort = Integer.toString((int)MinorUnit / 100);
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.km");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.m");
} else {
// FIXME use e.g. getDecimalSeparator() for decimal comma/point selection
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.km");
}
} else {
return Integer.toString(meters) + Locale.get("guitacho.m");
}
} else {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.yd");
}
int MajorUnit = (int)(meters / 1609.344f);
int MinorUnit = (int)(meters % 1609.344f + 0.5f);
// mi.dd
//String MinorShort = (MinorUnit / 16.09344f < 10.0f ? "0" : "") + (int)(MinorUnit / 16.09344f);
// mi.d
String MinorShort = Integer.toString((int)(MinorUnit / 160.9344f));
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.mi");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.yd");
} else {
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.mi");
}
} else {
return Integer.toString((int)(meters / 0.9144 + 0.5f)) + Locale.get("guitacho.yd");
}
}
}
}
| public void commandAction(Command c, Displayable d) {
updateLastUserActionTime();
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD])
|| (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD])
|| (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.slower();
} else if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.faster();
} else if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
Configuration.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else if (imageCollector != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
// set compass compassDeviation
if (compassDeviation == 360) {
compassDeviation = 0;
} else {
compassDeviation += courseDiff;
compassDeviation %= 360;
if (course < 0) {
course += 360;
}
}
} else {
// manual rotation
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
gpsRecenter = false;
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording
// would not be stopped when leaving the map.
if (Legend.isValid && gpx.isRecordingTrk()) {
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.PleaseStopRecording")/*Please stop recording before exit.*/ , 2500);
return;
}
if (Legend.isValid) {
pause();
}
parent.exit();
return;
}
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StartingToRecord")/*Starting to record*/, 1250);
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StoppingToRecord")/*Stopping to record*/, 1250);
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) {
// FIXME it's not strictly necessary to stop, after there are translation for the pause
// message, change to Locale.get("trace.YouNeedStopPauseRecording")
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.YouNeedStopRecording")/*You need to stop recording before managing tracks.*/ , 4000);
return;
}
GuiGpx guiGpx = new GuiGpx(this);
guiGpx.show();
return;
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
return;
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
if (TrackPlayer.isPlaying) {
TrackPlayer.getInstance().stop();
alert(Locale.get("trace.Trackplayer")/*Trackplayer*/, Locale.get("trace.PlayingStopped")/*Playing stopped for connecting to GPS*/, 2500);
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
return;
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null) {
locationProducer.close();
}
return;
}
if (c == CMDS[TOGGLE_GPS_CMD]) {
if (isGpsConnected()) {
commandAction(DISCONNECT_GPS_CMD);
} else {
commandAction(CONNECT_GPS_CMD);
}
return;
}
if (c == CMDS[SEARCH_CMD]) {
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_DEFAULT);
guiSearch.show();
return;
}
if (c == CMDS[ENTER_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
return;
}
if (c == CMDS[MAN_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
return;
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
return;
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
return;
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
return;
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
boolean hasJSR120 = Configuration.hasDeviceJSR120();
int noElements = 3;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
noElements++;
}
//#endif
int idx = 0;
String[] elements = new String[noElements];
if (gpx.isRecordingTrk()) {
elements[idx++] = Locale.get("trace.StopGpxTracklog")/*Stop Gpx tracklog*/;
} else {
elements[idx++] = Locale.get("trace.StartGpxTracklog")/*Start Gpx tracklog*/;
}
elements[idx++] = Locale.get("trace.SaveWaypoint")/*Save waypoint*/;
elements[idx++] = Locale.get("trace.EnterWaypoint")/*Enter waypoint*/;
//#if polish.api.mmapi
elements[idx++] = Locale.get("trace.TakePictures")/*Take pictures*/;
if (audioRec.isRecording()) {
elements[idx++] = Locale.get("trace.StopAudioRecording")/*Stop audio recording*/;
} else {
elements[idx++] = Locale.get("trace.StartAudioRecording")/*Start audio recording*/;
}
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
elements[idx++] = Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/;
}
//#endif
recordingsMenu = new List(Locale.get("trace.Recordings")/*Recordings...*/,Choice.IMPLICIT,elements,null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
return;
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = new String[4];
if (routeCalc || route != null) {
elements[0] = Locale.get("trace.StopRouting")/*Stop routing*/;
} else {
elements[0] = Locale.get("trace.CalculateRoute")/*Calculate route*/;
}
elements[1] = Locale.get("trace.SetDestination")/*Set destination*/;
elements[2] = Locale.get("trace.ShowDestination")/*Show destination*/;
elements[3] = Locale.get("trace.ClearDestination")/*Clear destination*/;
routingsMenu = new List(Locale.get("trace.Routing2")/*Routing..*/, Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
return;
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
PositionMark posMark = null;
if (gpsRecenter) {
// TODO: If we lose the fix the old position and height
// will be used silently -> we should inform the user
// here that we have no fix - he may not know what's going on.
posMark = new PositionMark(center.radlat, center.radlon,
(int)pos.altitude, pos.timeMillis,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1);
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
posMark = new PositionMark(center.radlat, center.radlon,
PositionMark.INVALID_ELEVATION,
pos.timeMillis, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1);
}
/*
if (Configuration.getCfgBitState(Configuration.CFGBIT_WAYPT_OFFER_PREDEF)) {
if (guiWaypointPredefined == null) {
guiWaypointPredefined = new GuiWaypointPredefined(this);
}
if (guiWaypointPredefined != null) {
guiWaypointPredefined.setData(posMark);
guiWaypointPredefined.show();
}
} else {
*/
showGuiWaypointSave(posMark);
//}
}
return;
}
if (c == CMDS[ONLINE_INFO_CMD]) {
//#if polish.api.online
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc);
gWeb.show();
//#else
alert(Locale.get("trace.NoOnlineCapa")/*No online capabilites*/,
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
//#endif
}
if (c == CMDS[BACK_CMD]) {
show();
return;
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
switch (recordingsMenu.getSelectedIndex()) {
case 0: {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) {
show();
}
} else {
commandAction(START_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) {
show();
}
}
break;
}
case 1: {
commandAction(SAVE_WAYP_CMD);
break;
}
case 2: {
commandAction(ENTER_WAYP_CMD);
break;
}
//#if polish.api.mmapi
case 3: {
commandAction(CAMERA_CMD);
break;
}
case 4: {
show();
commandAction(TOGGLE_AUDIO_REC);
break;
}
//#endif
//#if polish.api.mmapi && polish.api.wmapi
case 5: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#elif polish.api.wmapi
case 3: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#endif
}
}
if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
break;
}
case 1: {
commandAction(SET_DEST_CMD);
break;
}
case 2: {
commandAction(SHOW_DEST_CMD);
break;
}
case 3: {
commandAction(CLEAR_DEST_CMD);
break;
}
}
}
return;
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]) {
try {
Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception(Locale.get("trace.YourPhoneNoCamSupport")/*Your phone does not support the necessary JSRs to use the camera*/, cnfe);
}
return;
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
recordingsMenu = null; // refresh recordings menu
return;
}
//#endif
if (c == CMDS[ROUTING_TOGGLE_CMD]) {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
return;
}
if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
GuiRoute guiRoute = new GuiRoute(this, false);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) {
commandAction(ROUTING_START_CMD);
} else {
guiRoute.show();
}
return;
}
if (c == CMDS[ROUTING_START_CMD]) {
if (! routeCalc || RouteLineProducer.isRunning()) {
routeCalc = true;
if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
// center of the map is the route source
RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon);
logger.info("Routing source: " + routeSource);
routeNodes=new Vector();
routeEngine = new Routing(this);
routeEngine.solve(routeSource, dest);
// resume();
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ROUTING_STOP_CMD]) {
NoiseMaker.stopPlayer();
if (routeCalc) {
if (routeEngine != null) {
routeEngine.cancelRouting();
}
alert(Locale.get("trace.RouteCalculation")/*Route Calculation*/, Locale.get("trace.Cancelled")/*Cancelled*/, 1500);
} else {
alert(Locale.get("trace.Routing")/*Routing*/, Locale.get("generic.Off")/*Off*/, 750);
}
endRouting();
routingsMenu = null; // refresh routingsMenu
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
if (hasPointerEvents()) {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourse")/*Change course with zoom buttons*/, 3000);
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourseWithLeftRightKeys")/*Change course with left/right keys*/, 3000);
}
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("generic.Off")/*Off*/, 750);
}
return;
}
if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
return;
}
if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
return;
}
if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
return;
}
if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (manualRotationMode) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
compassDeviation = 0;
} else {
course = 0;
}
alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750);
} else {
// FIXME rename string to generic
alert(Locale.get("guidiscover.MapProjection")/*Map Projection*/, ProjFactory.nextProj(), 750);
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
return;
}
if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert(Locale.get("trace.GpsMid")/*GpsMid*/, hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked")/*Keys and touch screen unlocked*/ : Locale.get("trace.KeysUnlocked")/*Keys unlocked*/, 1000);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
} else {
commandAction(START_RECORD_CMD);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.ResumingRecording")/*Resuming recording*/, 1000);
gpx.resumeTrk();
} else {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.SuspendingRecording")/*Suspending recording*/, 1000);
gpx.suspendTrk();
}
}
return;
}
if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
autoZoomed = true;
if (pos.latitude != 0.0f) {
receivePosition(pos);
}
newDataReady();
return;
}
if (c == CMDS[SHOW_DEST_CMD]) {
if (dest != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
prevPositionNode = center.copy();
center.setLatLonRad(dest.lat, dest.lon);
movedAwayFromDest = false;
updatePosition();
}
else {
alert(Locale.get("trace.ShowDestination")/*Show destination*/, Locale.get("trace.DestinationNotSpecifiedYet")/*Destination is not specified yet*/, 3000);
}
return;
}
if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) {
if (prevPositionNode != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLon(prevPositionNode);
updatePosition();
}
}
if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
return;
}
if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
showIconMenu();
return;
}
if (c == CMDS[SETUP_CMD]) {
new GuiDiscover(parent);
return;
}
if (c == CMDS[ABOUT_CMD]) {
new Splash(parent, GpsMid.initDone);
return;
}
if (c == CMDS[CELLID_LOCATION_CMD]) {
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) {
locationProducer.triggerPositionUpdate();
newDataReady();
} else {
if (cellIDLocationProducer == null) {
// init sleeping cellid location provider if cellid is not primary
cellIDLocationProducer = new SECellID();
if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) {
logger.info("Failed to initialise CellID location producer");
}
}
if (cellIDLocationProducer != null) {
cellIDLocationProducer.triggerPositionUpdate();
newDataReady();
}
}
return;
}
if (c == CMDS[MANUAL_LOCATION_CMD]) {
Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD,
center.radlon / MoreMath.FAC_DECTORAD,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis(), Position.TYPE_MANUAL);
// implies center to gps, to give feedback as the gps rectangle
gpsRecenter = true;
// gpsRecenterInvalid = true;
// gpsRecenterStale = true;
autoZoomed = true;
receivePosition(setpos);
receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0);
newDataReady();
return;
}
if (! routeCalc) {
//#if polish.api.osm-editing
if (c == CMDS[RETRIEVE_XML]) {
if (Legend.enableEdits) {
// -1 alert ("Editing", "Urlidx: " + pc.actualWay.urlIdx, Alert.FOREVER);
if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) {
parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER);
}
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GuiOSMWayDisplay guiWay = new GuiOSMWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[EDIT_ENTITY]) {
if (Legend.enableEdits) {
// FIXME: do the following:
// * set a flag that default operation is OSM edit
// * do a search for nearby POIs, asking for type
// * when the user selects, open OSM editing
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_EDIT_ENTITY);
guiSearch.show();
return;
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[RETRIEVE_NODE]) {
// FIXME add support for accessing a node
// under cursor
if (Legend.enableEdits) {
GuiOSMPOIDisplay guiNode = new GuiOSMPOIDisplay(-1, null,
center.radlat, center.radlon, this);
guiNode.show();
guiNode.refresh();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
if (c == CMDS[EDIT_ADDR_CMD]) {
if (Legend.enableEdits) {
String streetName = "";
if ((pc != null) && (pc.actualWay != null)) {
streetName = getName(pc.actualWay.nameIdx);
}
GuiOSMAddrDisplay guiAddr = new GuiOSMAddrDisplay(-1, streetName, null,
center.radlat, center.radlon, this);
guiAddr.show();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
//#else
if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) {
alert("No online capabilites",
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
}
//#endif
if (c == CMDS[SET_DEST_CMD]) {
RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon);
setDestination(pm1);
return;
}
if (c == CMDS[CLEAR_DEST_CMD]) {
setDestination(null);
return;
}
} else {
alert(Locale.get("trace.Error")/*Error*/, Locale.get("trace.CurrentlyInRouteCalculation")/*Currently in route calculation*/, 2000);
}
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceCommandAction")/*In Trace.commandAction*/, e);
}
}
private void startImageCollector() throws Exception {
//#debug info
logger.info("Starting ImageCollector");
Images images = new Images();
pc = new PaintContext(this, images);
/* move responsibility for overscan to ImageCollector
int w = (this.getWidth() * 125) / 100;
int h = (this.getHeight() * 125) / 100;
*/
imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.copy();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
//#debug info
logger.info("Stopping ImageCollector");
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
urlsThread = new Urls();
new DictReader(this);
// wait until base tiles are read; otherwise there's apparently
// a race condition triggered on Symbian s60r3 phones, see
// https://sourceforge.net/support/tracker.php?aid=3284022
if (Legend.isValid) {
while (!baseTilesRead) {
try {
Thread.sleep(250);
} catch (InterruptedException e1) {
// nothing to do in that case
}
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
Thread thread = new Thread(this, "Trace");
thread.start();
}
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte)5);
startImageCollector();
recreateTraceLayout();
}
public void shutdown() {
if (gpx != null) {
// change to "false" to ask for track name if configure to
// currently "true" to not ask for name to ensure fast
// quit & try to avoid loss of data which might result from
// waiting for user to type the name
gpx.saveTrk(true);
}
//#debug debug
logger.debug("Shutdown: stopImageCollector");
stopImageCollector();
if (namesThread != null) {
//#debug debug
logger.debug("Shutdown: namesThread");
namesThread.stop();
namesThread = null;
}
if (urlsThread != null) {
urlsThread.stop();
urlsThread = null;
}
if (dictReader != null) {
//#debug debug
logger.debug("Shutdown: dictReader");
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
//#debug debug
logger.debug("Shutdown: tileReader");
tileReader.shutdown();
tileReader = null;
}
if (locationProducer != null) {
//#debug debug
logger.debug("Shutdown: locationProducer");
locationProducer.close();
}
if (TrackPlayer.isPlaying) {
//#debug debug
logger.debug("Shutdown: TrackPlayer");
TrackPlayer.getInstance().stop();
}
}
public void sizeChanged(int w, int h) {
updateLastUserActionTime();
if (imageCollector != null) {
logger.info("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector")/*Could not reinitialise Image Collector after size change*/, e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
tl = new TraceLayout(0, 0, w, h);
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null) {
/*
* When painting we receive a copy of the center coordinates
* where the imageCollector has drawn last
* as we need to base the routing instructions on the information
* determined during the way drawing (e.g. the current routePathConnection)
*/
Node drawnCenter = imageCollector.paint(pc);
if (route != null && ri != null && pc.lineP2 != null && pc.getP() != null/*avoids exception at route calc*/) {
pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2);
/*
* we also need to make sure the current way for the real position
* has really been detected by the imageCollector which happens when drawing the ways
* So we check if we just painted an image that did not cover
* the center of the display because it was too far painted off from
* the display center position and in this case we don't give route instructions
* Thus e.g. after leaving a long tunnel without gps fix there will not be given an
* obsolete instruction from inside the tunnel
*/
int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2);
if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs
&&
Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs
) {
/*
* we need to synchronize the route instructions on the informations determined during way painting
* so we give the route instructions right after drawing the image with the map
* and use the center of the last drawn image for the route instructions
*/
ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan);
}
}
} else {
// show the way bar even if ImageCollector is not running because it's necessary on touch screens to get to the icon menu
tl.ele[TraceLayout.WAYNAME].setText(" ");
}
/* Beginning of voice instructions started from overlay code (besides showRoute above)
*/
// Determine if we are at the destination
if (dest != null) {
float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon);
atDest = (distance < 25);
if (atDest) {
if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1);
}
} else if (!movedAwayFromDest) {
movedAwayFromDest = true;
}
}
// determine if we are currently speeding
speeding = false;
int maxSpeed = 0;
// only detect speeding when gpsRecentered and there is a current way
if (gpsRecenter && actualSpeedLimitWay != null) {
maxSpeed = actualSpeedLimitWay.getMaxSpeed();
// check for winter speed limit if configured
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
&& (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) {
maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter();
}
if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) {
speeding = true;
}
}
if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
// give speeding alert only every 10 seconds
if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) {
lastTimeOfSpeedingSound = System.currentTimeMillis();
GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound());
}
}
/*
* end of voice instructions started from overlay code
*/
/*
* the final part of the overlay should not give any voice instructions
*/
g.setColor(Legend.COLOR_MAP_TEXT);
switch (showAddons) {
case 1:
yc = showMemory(g, yc, la);
break;
case 2:
yc = showConnectStatistics(g, yc, la);
break;
default:
showAddons = 0;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) {
if (pc != null) {
tl.calcScaleBarWidth(pc);
tl.ele[TraceLayout.SCALEBAR].setText(" ");
}
}
setPointOfTheCompass();
}
showMovement(g);
// Show gpx track recording status
LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION];
LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT];
if (gpx.isRecordingTrk()) {
// we are recording tracklogs
if (gpx.isRecordingTrkSuspended()) {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); // blue
} else {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); // red
}
eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")/*r*/);
}
if (TrackPlayer.isPlaying) {
eSolution.setText(Locale.get("trace.Replay")/*Replay*/);
} else {
if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID ||
solution == LocationMsgReceiver.STATUS_MANUAL)) {
eSolution.setText(Locale.get("solution.Off")/*Off*/);
} else {
eSolution.setText(solutionStr);
}
}
LayoutElement e = tl.ele[TraceLayout.CELLID];
// show if we are logging cellIDs
if (SECellLocLogger.isCellIDLogging() > 0) {
if (SECellLocLogger.isCellIDLogging() == 2) {
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); // yellow
} else {
//Attempting to log, but currently no valid info available
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); // red
}
e.setText(Locale.get("trace.cellIDs")/*cellIDs*/);
}
// show audio recording status
e = tl.ele[TraceLayout.AUDIOREC];
if (audioRec.isRecording()) {
e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); // red
e.setText(Locale.get("trace.AudioRec")/*AudioRec*/);
}
if (pc != null) {
showDestination(pc);
}
if (speed > 0 &&
Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("guitacho.kmh")/* km/h*/);
} else {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + Locale.get("guitacho.mph"));
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP)
&& locationProducer != null
&& LocationMsgReceiverList.isPosValid(solution)
) {
tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE));
}
if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) )
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) {
e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE];
e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]);
double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon);
e.setText(Locale.get("trace.Air")/*Air:*/ + showDistance((int) distLine, DISTANCE_AIR));
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) {
e = tl.ele[TraceLayout.CURRENT_TIME]; // e is used *twice* below (also as vRelative)
e.setText(DateTimeTools.getClock(System.currentTimeMillis(), true));
/*
don't use new Date() - it is very slow on some Nokia devices
currentTime.setTime( new Date( System.currentTimeMillis() ) );
e.setText(
currentTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(currentTime.get(Calendar.MINUTE)));
*/
// if current time is visible, positioning OFFROUTE above current time will work
tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e);
}
setSpeedingSign(maxSpeed);
if (hasPointerEvents()) {
tl.ele[TraceLayout.ZOOM_IN].setText("+");
tl.ele[TraceLayout.ZOOM_OUT].setText("-");
tl.ele[TraceLayout.RECENTER_GPS].setText("|");
e = tl.ele[TraceLayout.SHOW_DEST];
if (atDest && prevPositionNode != null) {
e.setText("<");
e.setActionID(SHOW_PREVIOUS_POSITION_CMD);
} else {
e.setText(">");
e.setActionID(SHOW_DEST_CMD + (Trace.SET_DEST_CMD << 16) );
}
}
e = tl.ele[TraceLayout.TITLEBAR];
if (currentTitleMsgOpenCount != 0) {
e.setText(currentTitleMsg);
// setTitleMsgTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setTitleMsgTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentTitleMsgOpenCount--;
lastTitleMsg = currentTitleMsg;
if (currentTitleMsgOpenCount == 0) {
//#debug debug
logger.debug("clearing title");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout);
setTitleMsgTimeout = 0;
}
}
}
tl.paint(g);
if (currentAlertsOpenCount > 0) {
showCurrentAlert(g);
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
}
public void showGuiWaypointSave(PositionMark posMark) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
guiWaypointSave.setData(posMark);
guiWaypointSave.show();
}
}
/** Show an alert telling the user that waypoints are not ready yet.
*/
private void showAlertLoadingWpt() {
alert("Way points", "Way points are not ready yet.", 3000);
}
private void showCurrentAlert(Graphics g) {
Font font = g.getFont();
// request same font in bold for title
Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize());
int fontHeight = font.getHeight();
// add alert title height plus extra space of one line for calculation of alertHeight
int y = titleFont.getHeight() + 2 + fontHeight;
// extra width for alert
int extraWidth = font.charWidth('W');
// alert is at least as wide as alert title
int alertWidth = titleFont.stringWidth(currentAlertTitle);
// width each alert message line must fit in
int maxWidth = getWidth() - extraWidth;
// Two passes: 1st pass calculates placement and necessary size of alert,
// 2nd pass actually does the drawing
for (int i = 0; i <= 1; i++) {
int nextSpaceAt = 0;
int prevSpaceAt = 0;
int start = 0;
// word wrap
do {
int width = 0;
// add word by word until string part is too wide for screen
while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) {
prevSpaceAt = nextSpaceAt;
nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt);
if (nextSpaceAt == -1) {
nextSpaceAt = currentAlertMessage.length();
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
nextSpaceAt++;
}
nextSpaceAt--;
// Reduce line word by word or if not possible char by char until the
// remaining string part fits to display width
while (width > maxWidth) {
if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) {
nextSpaceAt = prevSpaceAt;
} else {
nextSpaceAt--;
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
}
// determine maximum alert width
if (alertWidth < width ) {
alertWidth = width;
}
// during the second pass draw the message text lines
if (i==1) {
g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start,
getWidth()/2, y, Graphics.TOP|Graphics.HCENTER);
}
y += fontHeight;
start = nextSpaceAt;
} while (nextSpaceAt < currentAlertMessage.length() );
// at the end of the first pass draw the alert box and the alert title
if (i == 0) {
alertWidth += extraWidth;
int alertHeight = y;
int alertTop = (getHeight() - alertHeight) /2;
//alertHeight += fontHeight/2;
int alertLeft = (getWidth() - alertWidth) / 2;
// alert background color
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, alertHeight);
// background color for alert title
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3);
// alert border
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]);
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); // title border
g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); // alert border
// draw alert title
y = alertTop + 2; // output position of alert title
g.setFont(titleFont);
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]);
g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER);
g.setFont(font);
// output alert message 1.5 lines below alert title in the next pass
y += (fontHeight * 3 / 2);
}
} // end for
// setAlertTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setAlertTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentAlertsOpenCount--;
if (currentAlertsOpenCount == 0) {
//#debug debug
logger.debug("clearing alert");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setAlertTimeout);
setAlertTimeout = 0;
}
}
}
private void setSpeedingSign(int maxSpeed) {
// speeding = true;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL)
&&
(
speeding
||
(System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000
)
) {
if (speeding) {
speedingSpeedLimit = maxSpeed;
startTimeOfSpeedingSign = System.currentTimeMillis();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit));
} else {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f + 0.5f)));
}
} else {
startTimeOfSpeedingSign = 0;
}
}
/**
*
*/
private void getPC() {
pc.course = course;
pc.scale = scale;
pc.center = center.copy();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.dest = dest;
}
public void cleanup() {
namesThread.cleanup();
urlsThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
// public void searchElement(PositionMark pm) throws Exception {
// PaintContext pc = new PaintContext(this, null);
// // take a bigger angle for lon because of positions near to the poles.
// Node nld = new Node(pm.lat - 0.0001f, pm.lon - 0.0005f, true);
// Node nru = new Node(pm.lat + 0.0001f, pm.lon + 0.0005f, true);
// pc.searchLD = nld;
// pc.searchRU = nru;
// pc.dest = pm;
// pc.setP(new Proj2D(new Node(pm.lat, pm.lon, true), 5000, 100, 100));
// for (int i = 0; i < 4; i++) {
// tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
// }
// }
public void searchNextRoutableWay(RoutePositionMark pm) throws Exception {
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
// Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
// Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
// pc.searchLD=nld;
// pc.searchRU=nru;
pc.squareDstWithPenToActualRoutableWay = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
// retry searching an expanding region at the position mark
Projection p;
do {
p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize);
pc.setP(p);
for (int i=0; i<4; i++) {
tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT);
}
// stop the search when a routable way is found
if (pc.actualRoutableWay != null) {
break;
}
// expand the region that gets searched for a routable way
pc.xSize += 100;
pc.ySize += 100;
// System.out.println(pc.xSize);
} while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); // until we searched at least 500 m edge length
Way w = pc.actualRoutableWay;
pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon);
}
private void setPointOfTheCompass() {
String c = "";
if (ProjFactory.getProj() != ProjFactory.NORTH_UP
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) {
c = Configuration.getCompassDirection(course);
}
// if tl shows big onscreen buttons add spaces to compass directions consisting of only one char or not shown
if (tl.bigOnScreenButtons && c.length() <= 1) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP) {
c = "(" + Configuration.getCompassDirection(0) + ")";
} else {
c = " " + c + " ";
}
}
tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c);
}
private int showConnectStatistics(Graphics g, int yc, int la) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]);
// only try to show compass id and cell id if user has somehow switched them on
GSMCell cell = null;
if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL || Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
cell = CellIdProvider.getInstance().obtainCachedCellID();
}
Compass compass = null;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) {
compass = CompassProvider.getInstance().obtainCachedCompass();
}
if (cell == null) {
g.drawString("No Cell ID available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (compass == null) {
g.drawString("No compass direction available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public void showDestination(PaintContext pc) {
// Avoid exception after route calculation
if ( pc.getP() == null || imageCollector == null )
return;
try {
if (dest != null) {
pc.getP().forward(dest.lat, dest.lon, pc.lineP2);
// System.out.println(dest.toString());
int x = pc.lineP2.x - imageCollector.xScreenOverscan;
int y = pc.lineP2.y - imageCollector.yScreenOverscan;
pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS);
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]);
if (dest.displayName != null) {
pc.g.drawString(dest.displayName, x, y+8,
Graphics.TOP | Graphics.HCENTER);
}
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_LINE]);
pc.g.setStrokeStyle(Graphics.SOLID);
pc.g.drawLine( pc.getP().getImageCenter().x - imageCollector.xScreenOverscan,
pc.getP().getImageCenter().y - imageCollector.yScreenOverscan,x, y);
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
e.printStackTrace();
}
}
/**
* Draws the position square, the movement line and the center cross.
*
* @param g Graphics context for drawing
*/
public void showMovement(Graphics g) {
// Avoid exception after route calculation
if ( pc.getP() == null )
return;
IntPoint centerP = null;
try {
if (imageCollector != null) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]);
centerP = pc.getP().getImageCenter();
int centerX = centerP.x - imageCollector.xScreenOverscan;
int centerY = centerP.y - imageCollector.yScreenOverscan;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0, 0);
pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD),
(pos.longitude * MoreMath.FAC_DECTORAD), p1);
posX = p1.getX()-imageCollector.xScreenOverscan;
posY = p1.getY()-imageCollector.yScreenOverscan;
} else {
posX = centerX;
posY = centerY;
}
g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]);
float radc = course * MoreMath.FAC_DECTORAD;
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
// crosshair center cursor
if (!gpsRecenter || gpsRecenterInvalid) {
g.drawLine(centerX, centerY - 12, centerX, centerY + 12);
g.drawLine(centerX - 12, centerY, centerX + 12, centerY);
g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360);
}
if (! gpsRecenterInvalid) {
// gps position spot
pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS);
// gps position rectangle
g.drawRect(posX - 4, posY - 4, 8, 8);
g.drawLine(posX, posY, px, py);
}
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
if (centerP == null) {
logger.silentexception("No centerP", e);
}
e.printStackTrace();
}
}
/**
* Show next screen in the sequence of data screens
* (tacho, trip, satellites).
* @param currentScreen Data screen currently shown, use the DATASCREEN_XXX
* constants from this class. Use DATASCREEN_NONE if none of them
* is on screen i.e. the first one should be shown.
*/
public void showNextDataScreen(int currentScreen) {
switch (currentScreen)
{
case DATASCREEN_TACHO:
// Tacho is followed by Trip.
if (guiTrip == null) {
guiTrip = new GuiTrip(this);
}
if (guiTrip != null) {
guiTrip.show();
}
break;
case DATASCREEN_TRIP:
// Trip is followed by Satellites.
if (guiSatellites == null) {
guiSatellites = new GuiSatellites(this, locationProducer);
}
if (guiSatellites != null) {
guiSatellites.show();
}
break;
case DATASCREEN_SATS:
// After Satellites, go back to map.
this.show();
break;
case DATASCREEN_NONE:
default:
// Tacho is first data screen
if (guiTacho == null) {
guiTacho = new GuiTacho(this);
}
if (guiTacho != null) {
guiTacho.show();
}
break;
}
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0);
g.drawString(Locale.get("trace.Freemem")/*Freemem: */ + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Totmem")/*Totmem: */ + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Percent")/*Percent: */
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.ThreadsRunning")/*Threads running: */
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Names")/*Names: */ + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.SingleT")/*Single T: */ + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.FileT")/*File T: */ + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.LastMsg")/*LastMsg: */ + lastTitleMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( Locale.get("trace.at")/*at */ + lastTitleMsgClock, 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
private void updatePosition() {
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course=course;
repaint();
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosition(float lat, float lon, float scale) {
//#debug debug
logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " +
(lon * MoreMath.FAC_RADTODEC));
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLonRad(lat, lon);
this.scale = scale;
updatePosition();
}
public synchronized void receiveCompassStatus(int status) {
}
public synchronized void receiveCompass(float direction) {
//#debug debug
logger.debug("Got compass reading: " + direction);
compassDirection = (int) direction;
compassDeviated = ((int) direction + compassDeviation + 360) % 360;
// TODO: allow for user to use compass for turning the map in panning mode
// (gpsRenter test below switchable by user setting)
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && gpsRecenter) {
updateCourse(compassDeviated);
//repaint();
}
// course = compassDeviated;
//}
}
public static void updateLastUserActionTime() {
lastUserActionTime = System.currentTimeMillis();
}
public static long getDurationSinceLastUserActionTime() {
return System.currentTimeMillis() - lastUserActionTime;
}
public void updateCourse(int newcourse) {
coursegps = newcourse;
/* don't rotate too fast
*/
if ((newcourse - course)> 180) {
course = course + 360;
}
if ((course-newcourse)> 180) {
newcourse = newcourse + 360;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
course = newcourse;
} else {
// FIXME I think this is too slow a turn at least when course is
// of good quality, turning should be faster. This probably alleviates
// the trouble caused by unreliable gps course. However,
// some kind of heuristic, averaging course or evaluating the
// quality of course and fast or instant rotation with a known good GPS fix
// should be implemented instead of assuming course is always unreliable.
// The course fluctuations are lesser in faster speeds, so if we're constantly
// (for three consecutive locations) above say 5 km/h, a reasonable approach
// could be to use direct course change in that case, and for speed below
// 5 km/h use the slow turning below.
// jkpj 2010-01-17
// on 2011-04-11: jkpj switched from 1/4 rotation back to 3/4 rotation,
// returning to what it was supposed to do before 2010-11-30.
course = course + ((newcourse - course)*3)/4 + 360;
}
while (course > 360) {
course -= 360;
}
}
public synchronized void receivePosition(Position pos) {
// FIXME signal on location gained
//#debug info
logger.info("New position: " + pos);
collected++;
if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 &&
getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs()
&& isShown()
) {
gpsRecenter = true;
//autoZoomed = true;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) {
if (pos.type == Position.TYPE_GPS_LASTKNOWN) {
// if we have a current cell id fix from cellid location,
// don't overwrite it with a stale GPS location, but ignore the position
// FIXME perhaps compare timestamps here in case the last known gps is later
if (this.pos.type == Position.TYPE_CELLID) {
return;
}
gpsRecenterInvalid = false;
gpsRecenterStale = true;
}
}
this.pos = pos;
if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) {
gpsRecenterInvalid = false;
gpsRecenterStale = false;
}
if (gpsRecenter) {
center.setLatLonDeg(pos.latitude, pos.longitude);
speed = (int) (pos.speed * 3.6f);
fspeed = pos.speed * 3.6f;
// FIXME add auto-fallback mode where course is from GPS at high speeds and from compass
// at low speeds
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
updateCourse(compassDeviated);
} else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) {
// Problem: resolve issue erratic course due to GPS fluctuation
// when GPS reception is poor (maybe 3..7S),
// causes unnecessary and disturbing map rotation when device is in one location
// Heuristic for solving: After being still, require
// three consecutive over-the-limit speed readings with roughly the
// same course
if (thirdPrevCourse != -1) {
// first check for normal flow of things, we've had three valid courses after movement start
updateCourse((int) pos.course);
} else if (prevCourse == -1) {
// previous course was invalid,
// don't set course yet, but set the first tentatively good course
prevCourse = (int) pos.course;
} else if (secondPrevCourse == -1) {
// the previous course was the first good one.
// If this course is in the same 60-degree
// sector as the first course, we have two valid courses
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
secondPrevCourse = prevCourse;
}
prevCourse = (int) pos.course;
} else {
// we have received two previous valid curses, check for this one
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
thirdPrevCourse = secondPrevCourse;
//No need to set these as we'll now trust courses until speed goes below limit
// - unless we'll later add averaging of recent courses for poor GPS reception
//secondPrevCourse = prevCourse;
//prevCourse = (int) pos.course;
updateCourse((int) pos.course);
} else {
prevCourse = (int) pos.course;
secondPrevCourse = -1;
}
}
} else {
// speed under the minimum, invalidate all prev courses
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
}
if (gpx.isRecordingTrk()) {
try {
// don't tracklog manual cellid position or gps start/stop last known position
if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179
&& pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) {
} else {
gpx.addTrkPt(pos);
}
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
altitude = (int) (pos.altitude);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM)
&& gpsRecenter
&& (isGpsConnected() || TrackPlayer.isPlaying)
&& autoZoomed
&& pc.getP() != null
&& pos.speed != Float.NaN // if speed is unknown do not autozoom
&& pos.speed != 0 // if speed is 0 do not autozoom
) {
// the minimumScale at 20km/h and below is equivalent to having zoomed in manually once from the startup zoom level
final float minimumScale = Configuration.getRealBaseScale() / 1.5f;
final int minimumSpeed = 20;
// the maximumScale at 160km/h and above is equivalent to having zoomed out manually once from the startup zoom level
final float maximumScale = Configuration.getRealBaseScale() * 1.5f;
final int maximumSpeed = 160;
int speedForScale = speed;
float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed);
// make sure the new scale is within the minimum / maximum scale values
if (newScale < minimumScale) {
newScale = minimumScale;
} else if (newScale > maximumScale) {
newScale = maximumScale;
}
// autozoom in more at the last 200 m of the route
if (route != null && RouteInstructions.getDstRouteToDestination() <= 200) {
float newScale2 = newScale;
newScale2 = newScale / (1f + (200f - RouteInstructions.getDstRouteToDestination())/ 200f);
// fixed increased zoom for the last 100 m
newScale = Math.max(newScale2, newScale / 1.5f);
}
scale = newScale;
// // calculate meters to top of screen
// float topLat = pc.getP().getMaxLat();
// float topLon = (pc.getP().getMinLon() + pc.getP().getMaxLon()) / 2f;
// float distance = MoreMath.dist(center.radlat, center.radlon, topLat, topLon );
// System.out.println("current distance to top of screen: " + distance);
//
// // avoid zooming in or out too far
// int speedForScale = course;
// if (speedForScale < 30) {
// speedForScale = 30;
// } else if (speedForScale > 160) {
// speedForScale = 160;
// }
//
// final float SECONDS_TO_PREVIEW = 45f;
// float metersToPreview = (float) speedForScale / 3.6f * SECONDS_TO_PREVIEW;
// System.out.println(metersToPreview + "meters to preview at " + speedForScale + "km/h");
//
// if (metersToPreview < 2000) {
// // calculate top position that needs to be visible to preview the metersToPreview
// topLat = center.radlat + (topLat - center.radlat) * metersToPreview / distance;
// topLon = center.radlon + (topLon - center.radlon) * metersToPreview / distance;
// System.out.println("new distance to top:" + MoreMath.dist(center.radlat, center.radlon, topLat, topLon ));
//
// /*
// * calculate scale factor, we multiply this again with 2 * 1.2 = 2.4 to take into account we calculated half the screen height
// * and 1.2f is probably the factor the PaintContext is larger than the display size
// * (new scale is calculated similiar to GuiWaypoint)
// */
// IntPoint intPoint1 = new IntPoint(0, 0);
// IntPoint intPoint2 = new IntPoint(getWidth(), getHeight());
// Node n1 = new Node(center.radlat, center.radlon, true);
// Node n2 = new Node(topLat, topLon, true);
// scale = pc.getP().getScale(n1, n2, intPoint1, intPoint2) * 2.4f;
// }
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentTitleMsg = s;
synchronized (this) {
/*
* only increase the number of current title messages
* if the timer already has been set in the display code
*/
if (setTitleMsgTimeout == 0) {
currentTitleMsgOpenCount++;
}
setTitleMsgTimeout = 3000;
}
lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false);
repaint();
}
public void receiveSatellites(Satellite[] sats) {
// Not interested
}
/** Shows an alert message
*
* @param title The title of the alert
* @param message The message text
* @param timeout Timeout in ms. Please reserve enough time so the user can
* actually read the message. Use Alert.FOREVER if you want no timeout.
*/
public synchronized void alert(String title, String message, int timeout) {
// #debug info
logger.info("Showing trace alert: " + title + ": " + message);
if (timeout == Alert.FOREVER) {
timeout = 10000;
}
currentAlertTitle = title;
currentAlertMessage = message;
synchronized (this) {
/*
* only increase the number of current open alerts
* if the timer already has been set in the display code
*/
if (setAlertTimeout == 0) {
currentAlertsOpenCount++;
}
setAlertTimeout = timeout;
}
repaint();
}
public MIDlet getParent() {
return parent;
}
protected void pointerPressed(int x, int y) {
updateLastUserActionTime();
long currTime = System.currentTimeMillis();
pointerDragged = false;
pointerDraggedMuch = false;
pointerActionDone = false;
// remember center when the pointer was pressed for dragging
centerPointerPressedN = center.copy();
if (imageCollector != null) {
panProjection=imageCollector.getCurrentProjection();
pickPointStart=panProjection.inverse(x,y, pickPointStart);
} else {
panProjection = null;
}
// remember the LayoutElement the pointer is pressed down at, this will also highlight it on the display
int touchedElementId = tl.getElementIdAtPointer(x, y);
if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU)
&&
tl.isAnyActionIdAtPointer(x, y)
) {
tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId));
repaint();
}
// check for double press
if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) {
doubleTap(x, y);
return;
}
// Remember the time and position the pointer was pressed after the check for double tap,
// so the double tap code will check for the position of the first of the two taps
pressedPointerTime = currTime;
Trace.touchX = x;
Trace.touchY = y;
// Give a message if keyboard/user interface is locked.
// This must be done after remembering the touchX/Y positions as they are needed to unlock
if (keyboardLocked) {
keyPressed(0);
return;
}
// // when these statements are reached, no double tap action has been executed,
// // so check here if there's currently already a TimerTask waiting for a single tap.
// // If yes, perform the current single tap action immediately before starting the next TimerTask
// if (checkingForSingleTap && !pointerDraggedMuch) {
// singleTap();
// pointerActionDone = false;
// }
//
longTapTimerTask = new TimerTask() {
public void run() {
// if no action (e.g. from double tap) is already done
// and the pointer did not move or if it was pressed on a control and not moved much
if (!pointerActionDone) {
if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){
longTap();
}
}
}
};
try {
// set timer to continue check if this is a long tap
GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoLongTapTimerTask")/*No LongTap TimerTask: */ + e.toString());
}
}
protected void pointerReleased(int x, int y) {
// releasing the pointer cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
// releasing the pointer will clear the highlighting of the touched element
if (tl.getTouchedElement() != null) {
tl.clearTouchedElement();
repaint();
}
if (!pointerActionDone && !keyboardLocked) {
touchReleaseX = x;
touchReleaseY = y;
// check for a single tap in a timer started after the maximum double tap delay
// if the timer will not be cancelled by a double tap, the timer will execute the single tap command
singleTapTimerTask = new TimerTask() {
public void run() {
if (!keyboardLocked) {
singleTap(touchReleaseX, touchReleaseY);
}
}
};
try {
// set timer to check if this is a single tap
GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoSingleTapTimerTask")/*No SingleTap TimerTask: */ + e.toString());
}
if (pointerDragged) {
pointerDragged(x , y);
return;
}
}
}
protected void pointerDragged (int x, int y) {
updateLastUserActionTime();
LayoutElement e = tl.getElementAtPointer(x, y);
if (tl.getTouchedElement() != e) {
// leaving the touched element cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
tl.clearTouchedElement();
repaint();
}
// If the initially touched element is reached again during dragging, highlight it
if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) {
tl.setTouchedElement(e);
repaint();
}
if (pointerActionDone) {
return;
}
// check if there's been much movement, do this before the slide lock/unlock
// to avoid a single tap action when not sliding enough
if (Math.abs(x - Trace.touchX) > 8
||
Math.abs(y - Trace.touchY) > 8
) {
pointerDraggedMuch = true;
// avoid double tap triggering on fast consecutive drag actions starting at almost the same position
pressedPointerTime = 0;
}
// slide at least 1/4 display width to lock / unlock GpsMid
if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) {
if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU
&&
x - touchX > getWidth() / 4
) {
commandAction(TOGGLE_KEY_LOCK_CMD);
pointerActionDone = true;
}
return;
}
if (keyboardLocked) {
return;
}
pointerDragged = true;
// do not start map dragging on a touch control if only dragged slightly
if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) {
return;
}
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) {
// difference between where the pointer was pressed and is currently dragged
// int diffX = Trace.touchX - x;
// int diffY = Trace.touchY - y;
//
// IntPoint centerPointerPressedP = new IntPoint();
pickPointEnd=panProjection.inverse(x,y, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
// System.out.println("diff " + diffX + "/" + diffY + " " + (pickPointEnd.radlat-pickPointStart.radlat) + "/" + (pickPointEnd.radlon-pickPointStart.radlon) );
imageCollector.newDataReady();
gpsRecenter = false;
}
}
private void singleTap(int x, int y) {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we set the touchable button sizes
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) {
// if pointer was dragged much, do not recognize a single tap on the map
if (pointerDraggedMuch) {
return;
}
// #debug debug
logger.debug("single tap map");
if (!tl.bigOnScreenButtons) {
tl.setOnScreenButtonSize(true);
// set timer to continuously check if the last user interaction is old enough to make the buttons small again
final long BIGBUTTON_DURATION = 5000;
bigButtonTimerTask = new TimerTask() {
public void run() {
if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) {
// make the on screen touch buttons small again
tl.setOnScreenButtonSize(false);
requestRedraw();
bigButtonTimerTask.cancel();
}
}
};
try {
GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500);
} catch (Exception e) {
logger.error("Error scheduling bigButtonTimerTask: " + e.toString());
}
}
}
repaint();
} else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) {
tl.clearTouchedElement();
int actionId = tl.getActionIdAtPointer(x, y);
if (actionId > 0) {
// #debug debug
logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY);
if (System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
} else if (manualRotationMode) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_LEFT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_RIGHT2_CMD;
}
} else if (TrackPlayer.isPlaying) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
}
commandAction(actionId);
repaint();
}
}
}
private void doubleTap(int x, int y) {
// if not double tapping a control, then the map area must be double tapped and we zoom in
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) {
// if this is a double press on the map, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
// if pointer was dragged much, do not recognize a double tap on the map
if (pointerDraggedMuch) {
return;
}
//#debug debug
logger.debug("double tap map");
pointerActionDone = true;
commandAction(ZOOM_IN_CMD);
}
repaint();
return;
} else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){
// double tapping a control
int actionId = tl.getActionIdDoubleAtPointer(x, y);
//#debug debug
logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x);
if (actionId > 0) {
// if this is a double press on a control, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
pointerActionDone = true;
commandAction(actionId);
tl.clearTouchedElement();
repaint();
return;
} else {
singleTap(x, y);
}
}
}
private void longTap() {
// if not tapping a control, then the map area must be tapped so we do the long tap action for the map area
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) {
if (!pointerDraggedMuch && Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) {
pointerActionDone = true;
//#debug debug
logger.debug("long tap map");
//#if polish.api.online
// long tap map to open a place-related menu
// use the place of touch instead of old center as position,
// set as new center
pickPointEnd=panProjection.inverse(touchX,touchY, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
imageCollector.newDataReady();
gpsRecenter = false;
commandAction(ONLINE_INFO_CMD);
//#endif
}
return;
// long tapping a control
} else {
int actionId = tl.getActionIdLongAtPointer(touchX, touchY);
if (actionId > 0 && tl.getElementAtPointer(touchX, touchY) == tl.getTouchedElement()) {
tl.clearTouchedElement();
repaint();
pointerActionDone = true;
//#debug debug
logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY);
commandAction(actionId);
}
}
}
/**
* Returns the command used to go to the data screens.
* Needed by the data screens so they can find the key codes used for this
* as they have to use them too.
* @return Command
*/
public Command getDataScreenCommand() {
return CMDS[DATASCREEN_CMD];
}
public Tile getDict(byte zl) {
return tiles[zl];
}
public void setDict(Tile dict, byte zl) {
tiles[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from Configuration
Configuration.getStartupPos(center);
if (center.radlat == 0.0f && center.radlon == 0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
// read saved destination position from Configuration
if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) {
Node destNode = new Node();
Configuration.getDestPos(destNode);
setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon));
}
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void setBaseTilesRead(boolean read) {
baseTilesRead = read;
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint();
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
// some fault tolerance - will crash without a map
if (Legend.isValid) {
GpsMid.mNoiseMaker.playSound("DISCONNECT");
}
}
//if (gpx != null) {
// /**
// * Close and Save the gpx recording, to ensure we don't loose data
// */
// gpx.saveTrk(false);
//}
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
if (locationProducer == null) {
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
notify();
addCommand(CMDS[CONNECT_GPS_CMD]);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveStatus(byte status, int satsReceived) {
if (status != LocationMsgReceiver.STATUS_ON
&& status != LocationMsgReceiver.STATUS_2D
&& status != LocationMsgReceiver.STATUS_3D
&& status != LocationMsgReceiver.STATUS_DGPS) {
// no fix, invalidate speed heuristic
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
// FIXME signal a sound on location gained or lost
solution = status;
solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived);
repaint();
// to update e.g. tacho
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
public String getName(int idx) {
if (idx < 0) {
return null;
}
return namesThread.getName(idx);
}
public String getUrl(int idx) {
if (idx < 0) {
return null;
}
return urlsThread.getUrl(idx);
}
public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) {
return namesThread.fulltextSearch(snippet, cmi);
}
// this is called by ImageCollector
public void requestRedraw() {
repaint();
}
public void newDataReady() {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
Legend.freeDrawnWayAndAreaSearchImages();
GpsMid.getInstance().show(this);
setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
updateLastUserActionTime();
repaint();
}
public void recreateTraceLayout() {
tl = new TraceLayout(0, 0, getWidth(), getHeight());
}
public void resetSize() {
sizeChanged(getWidth(), getHeight());
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getDestination() {
return dest;
}
public void setDestination(RoutePositionMark dest) {
endRouting();
this.dest = dest;
pc.dest = dest;
if (dest != null) {
//#debug info
logger.info("Setting destination to " + dest.toString());
// move map only to the destination, if GUI is not optimized for routing
if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) {
commandAction(SHOW_DEST_CMD);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) {
Configuration.setDestPos(new Node(dest.lat, dest.lon, true));
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true);
}
movedAwayFromDest = false;
} else {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false);
//#debug info
logger.info("Setting destination to null");
}
}
public void endRouting() {
RouteInstructions.initialRecalcDone = false;
RouteInstructions.icCountOffRouteDetected = 0;
RouteInstructions.routeInstructionsHeight = 0;
RouteInstructions.abortRouteLineProduction();
setRoute(null);
setRouteNodes(null);
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
}
if (this.route != null) {
// reset off-route as soon as first route connection is known
RouteInstructions.resetOffRoute(this.route, center);
if (ri == null) {
ri = new RouteInstructions(this);
}
// show map during route line production
if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) {
resumeImageCollectorAfterRouteCalc();
}
ri.newRoute(this.route);
oldRecalculationTime = System.currentTimeMillis();
}
// show map always after route calculation
resumeImageCollectorAfterRouteCalc();
routeCalc=false;
routeEngine=null;
}
private void resumeImageCollectorAfterRouteCalc() {
try {
if (imageCollector == null) {
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
} else if (imageCollector != null) {
imageCollector.newDataReady();
}
repaint();
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceResumeImageCollector")/*In Trace.resumeImageCollector*/, e);
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
urlsThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
public Vector getRouteNodes() {
return routeNodes;
}
public void setRouteNodes(Vector routeNodes) {
this.routeNodes = routeNodes;
}
protected void hideNotify() {
//#debug debug
logger.debug("Hide notify has been called, screen will no longer be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
//#debug debug
logger.debug("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
public Vector getRoute() {
return route;
}
public void actionCompleted() {
boolean reAddCommands = true;
if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
addAllCommands();
}
}
public void showIconMenu() {
if (traceIconMenu == null) {
traceIconMenu = new TraceIconMenu(this, this);
}
traceIconMenu.show();
}
/** uncache the icon menu to reflect changes in the setup or save memory */
public static void uncacheIconMenu() {
//#mdebug trace
if (traceIconMenu != null) {
logger.trace("uncaching TraceIconMenu");
}
//#enddebug
traceIconMenu = null;
}
/** interface for IconMenuWithPages: recreate the icon menu from scratch and show it (introduced for reflecting size change of the Canvas) */
public void recreateAndShowIconMenu() {
uncacheIconMenu();
showIconMenu();
}
/** interface for received actions from the IconMenu GUI */
public void performIconAction(int actionId) {
//#if not polish.android
show();
//#endif
updateLastUserActionTime();
// when we are low on memory or during route calculation do not cache the icon menu (including scaled images)
if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) {
//#debug info
logger.info("low mem: Uncaching traceIconMenu");
uncacheIconMenu();
}
if (actionId != IconActionPerformer.BACK_ACTIONID) {
commandAction(actionId);
}
}
/** convert distance to string based on user preferences */
// The default way to show a distance is "10km" for
// distances 10km or more, "2,6km" for distances under 10, and
// "600m" for distances under 1km.
public static String showDistance(int meters) {
return showDistance(meters, DISTANCE_GENERIC);
}
public static String showDistance(int meters, int type) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.m");
}
int MajorUnit = meters / 1000;
int MinorUnit = meters % 1000;
// km.mm
//String MinorShort = (MinorUnit / 10 < 10 ? "0" : "") + (MinorUnit / 10);
// km.m
String MinorShort = Integer.toString((int)MinorUnit / 100);
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.km");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.m");
} else {
// FIXME use e.g. getDecimalSeparator() for decimal comma/point selection
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.km");
}
} else {
return Integer.toString(meters) + Locale.get("guitacho.m");
}
} else {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.yd");
}
int MajorUnit = (int)(meters / 1609.344f);
int MinorUnit = (int)(meters % 1609.344f + 0.5f);
// mi.dd
//String MinorShort = (MinorUnit / 16.09344f < 10.0f ? "0" : "") + (int)(MinorUnit / 16.09344f);
// mi.d
String MinorShort = Integer.toString((int)(MinorUnit / 160.9344f));
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.mi");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.yd");
} else {
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.mi");
}
} else {
return Integer.toString((int)(meters / 0.9144 + 0.5f)) + Locale.get("guitacho.yd");
}
}
}
}
|
diff --git a/contentconnector-core/src/main/java/com/gentics/cr/CRConfigFileLoader.java b/contentconnector-core/src/main/java/com/gentics/cr/CRConfigFileLoader.java
index e82eb19b..83a44730 100644
--- a/contentconnector-core/src/main/java/com/gentics/cr/CRConfigFileLoader.java
+++ b/contentconnector-core/src/main/java/com/gentics/cr/CRConfigFileLoader.java
@@ -1,196 +1,195 @@
package com.gentics.cr;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import com.gentics.cr.configuration.ConfigurationSettings;
import com.gentics.cr.configuration.EnvironmentConfiguration;
import com.gentics.cr.configuration.GenericConfiguration;
import com.gentics.cr.util.CRUtil;
import com.gentics.cr.util.RegexFileFilter;
/**
* Loads a configuration from a given file.
* Last changed: $Date: 2010-04-01 15:24:02 +0200 (Do, 01 Apr 2010) $
* @version $Revision: 541 $
* @author $Author: [email protected] $
*
*/
public class CRConfigFileLoader extends CRConfigUtil {
/**
* Config directory. (${com.gentics.portalnode.confpath}/rest/)
*/
private static final String CONFIG_DIR = EnvironmentConfiguration.CONFPATH
+ "/rest/";
/**
* Generated unique serial version id.
*/
private static final long serialVersionUID = -87744244157623456L;
/**
* Log4j logger for error and debug messages.
*/
private static Logger log = Logger.getLogger(CRConfigFileLoader.class);
/**
* webapproot for resolving in property values.
*/
private String webapproot;
/**
* Create new instance of CRConfigFileLoader.
* @param name of config
* @param givenWebapproot root directory of application
* (config read fallback)
*/
public CRConfigFileLoader(final String name, final String givenWebapproot) {
this(name, givenWebapproot, "");
}
/**
* Load config from String with subdir.
* @param name configuration name
* @param givenWebapproot root directory of application
* (config read fallback)
* @param subdir sub directory of .../conf/gentics/rest/ to use in this
* configuration.
*/
public CRConfigFileLoader(final String name, final String givenWebapproot,
final String subdir) {
super();
webapproot = givenWebapproot;
//Load Environment Properties
EnvironmentConfiguration.loadEnvironmentProperties();
checkForSanity();
setName(name);
//load default configuration
loadConfigFile(CONFIG_DIR + subdir
+ name + ".properties");
//load environment specific configuration
String modePath = ConfigurationSettings.getConfigurationPath();
if (modePath != null && !"".equals(modePath)) {
loadConfigFile(CONFIG_DIR + subdir
+ modePath + name + ".properties");
}
// initialize datasource with handle_props and dsprops
initDS();
}
/**
* Checks for common configuration mistakes.
*/
private void checkForSanity() {
String dir = CRUtil.resolveSystemProperties(CONFIG_DIR);
File confDir = new File(dir);
if (confDir.exists() && confDir.isDirectory()) {
log.debug("Loading configuration from " + dir);
} else {
String errMsg = "CONFIGURATION ERROR: Configuration directory does"
+ " not seem to contain a"
+ " valid configuration. The directory " + dir
+ " must exist and contain valid configuration files.";
log.error(errMsg);
System.err.println(errMsg);
}
}
/**
* Load the config file(s) for this instance.
* @param path file system path to the configuration
*/
private void loadConfigFile(final String path) {
String errorMessage = "Could not load configuration file at: "
- + CRUtil.resolveSystemProperties("${" + CRUtil.PORTALNODE_CONFPATH
- + "}/rest/" + this.getName() + ".properties") + "!";
+ + CRUtil.resolveSystemProperties(path) + "!";
try {
//LOAD SERVLET CONFIGURATION
String confpath = CRUtil.resolveSystemProperties(path);
java.io.File defaultConfigfile = new java.io.File(confpath);
String basename = defaultConfigfile.getName();
String dirname = defaultConfigfile.getParent();
Vector<String> configfiles = new Vector<String>(1);
if (defaultConfigfile.canRead()) {
configfiles.add(confpath);
}
//add all files matching the regex "name.*.properties"
java.io.File directory = new java.io.File(dirname);
FileFilter regexFilter = new RegexFileFilter(basename
.replaceAll("\\..*", "") + "\\.[^\\.]+\\.properties");
for (java.io.File file : directory.listFiles(regexFilter)) {
configfiles.add(file.getPath());
}
//load all found files into config
for (String file : configfiles) {
loadConfiguration(this, file, webapproot);
}
if (configfiles.size() == 0) {
throw new FileNotFoundException(
"Cannot find any valid configfile.");
}
} catch (FileNotFoundException e) {
log.error(errorMessage, e);
} catch (IOException e) {
log.error(errorMessage, e);
} catch (NullPointerException e) {
log.error(errorMessage, e);
}
}
/**
* Loads a configuration file into a GenericConfig instance and resolves
* system variables.
* @param emptyConfig - configuration to load the file into.
* @param path - path of the file to load
* @param webapproot - root directory of the web application for resolving
* ${webapproot} in property values.
* @throws IOException - if configuration file cannot be read.
*/
public static void loadConfiguration(final GenericConfiguration emptyConfig,
final String path, final String webapproot) throws IOException {
Properties props = new Properties();
props.load(new FileInputStream(CRUtil.resolveSystemProperties(path)));
for (Entry<Object, Object> entry : props.entrySet()) {
Object value = entry.getValue();
Object key = entry.getKey();
setProperty(emptyConfig, (String) key, (String) value, webapproot);
}
}
/**
* Set a property for this configuration. Resolves system properties in
* values.
* @param config - configuration to set the property for
* @param key - property to set
* @param value - value to set for the property
* @param webapproot - root directory of the webapplication. this is used to
* resolve ${webapproot} in the property values.
*/
private static void setProperty(final GenericConfiguration config,
final String key, final String value, final String webapproot) {
//Resolve system properties, so that they can be used in config values
String resolvedValue = CRUtil.resolveSystemProperties((String) value);
//Replace webapproot in the properties values, so that this variable can
//be used
if (webapproot != null) {
resolvedValue = resolvedValue.replaceAll("\\$\\{webapproot\\}",
webapproot.replace('\\', '/'));
}
//Set the property
config.set(key, resolvedValue);
log.debug("CONFIG: " + key + " has been set to " + resolvedValue);
}
}
| true | true | private void loadConfigFile(final String path) {
String errorMessage = "Could not load configuration file at: "
+ CRUtil.resolveSystemProperties("${" + CRUtil.PORTALNODE_CONFPATH
+ "}/rest/" + this.getName() + ".properties") + "!";
try {
//LOAD SERVLET CONFIGURATION
String confpath = CRUtil.resolveSystemProperties(path);
java.io.File defaultConfigfile = new java.io.File(confpath);
String basename = defaultConfigfile.getName();
String dirname = defaultConfigfile.getParent();
Vector<String> configfiles = new Vector<String>(1);
if (defaultConfigfile.canRead()) {
configfiles.add(confpath);
}
//add all files matching the regex "name.*.properties"
java.io.File directory = new java.io.File(dirname);
FileFilter regexFilter = new RegexFileFilter(basename
.replaceAll("\\..*", "") + "\\.[^\\.]+\\.properties");
for (java.io.File file : directory.listFiles(regexFilter)) {
configfiles.add(file.getPath());
}
//load all found files into config
for (String file : configfiles) {
loadConfiguration(this, file, webapproot);
}
if (configfiles.size() == 0) {
throw new FileNotFoundException(
"Cannot find any valid configfile.");
}
} catch (FileNotFoundException e) {
log.error(errorMessage, e);
} catch (IOException e) {
log.error(errorMessage, e);
} catch (NullPointerException e) {
log.error(errorMessage, e);
}
}
| private void loadConfigFile(final String path) {
String errorMessage = "Could not load configuration file at: "
+ CRUtil.resolveSystemProperties(path) + "!";
try {
//LOAD SERVLET CONFIGURATION
String confpath = CRUtil.resolveSystemProperties(path);
java.io.File defaultConfigfile = new java.io.File(confpath);
String basename = defaultConfigfile.getName();
String dirname = defaultConfigfile.getParent();
Vector<String> configfiles = new Vector<String>(1);
if (defaultConfigfile.canRead()) {
configfiles.add(confpath);
}
//add all files matching the regex "name.*.properties"
java.io.File directory = new java.io.File(dirname);
FileFilter regexFilter = new RegexFileFilter(basename
.replaceAll("\\..*", "") + "\\.[^\\.]+\\.properties");
for (java.io.File file : directory.listFiles(regexFilter)) {
configfiles.add(file.getPath());
}
//load all found files into config
for (String file : configfiles) {
loadConfiguration(this, file, webapproot);
}
if (configfiles.size() == 0) {
throw new FileNotFoundException(
"Cannot find any valid configfile.");
}
} catch (FileNotFoundException e) {
log.error(errorMessage, e);
} catch (IOException e) {
log.error(errorMessage, e);
} catch (NullPointerException e) {
log.error(errorMessage, e);
}
}
|
diff --git a/src/main/java/jenkins/plugins/shiningpanda/utils/BuilderUtil.java b/src/main/java/jenkins/plugins/shiningpanda/utils/BuilderUtil.java
index 7f3377e..07abd55 100644
--- a/src/main/java/jenkins/plugins/shiningpanda/utils/BuilderUtil.java
+++ b/src/main/java/jenkins/plugins/shiningpanda/utils/BuilderUtil.java
@@ -1,297 +1,297 @@
/*
* ShiningPanda plug-in for Jenkins
* Copyright (C) 2011-2012 ShiningPanda S.A.S.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of its license which incorporates the terms and
* conditions of version 3 of the GNU Affero General Public License,
* supplemented by the additional permissions under the GNU Affero GPL
* version 3 section 7: if you modify this program, or any covered work,
* by linking or combining it with other code, such other code is not
* for that reason alone subject to any of the requirements of the GNU
* Affero GPL version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* license for more details.
*
* You should have received a copy of the license along with this program.
* If not, see <https://raw.github.com/jenkinsci/shiningpanda-plugin/master/LICENSE.txt>.
*/
package jenkins.plugins.shiningpanda.utils;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.matrix.MatrixRun;
import hudson.model.BuildListener;
import hudson.model.AbstractBuild;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jenkins.plugins.shiningpanda.Messages;
import jenkins.plugins.shiningpanda.command.Command;
import jenkins.plugins.shiningpanda.command.CommandNature;
import jenkins.plugins.shiningpanda.interpreters.Python;
import jenkins.plugins.shiningpanda.interpreters.Virtualenv;
import jenkins.plugins.shiningpanda.matrix.PythonAxis;
import jenkins.plugins.shiningpanda.tools.PythonInstallation;
public class BuilderUtil
{
/**
* Get the consolidated environment for the provided build.
*
* @param build
* The build
* @param listener
* The build listener
* @return The consolidated environment
* @throws IOException
* @throws InterruptedException
*/
public static EnvVars getEnvironment(AbstractBuild<?, ?> build, BuildListener listener) throws IOException,
InterruptedException
{
// Get the base environment
EnvVars environment = build.getEnvironment(listener);
// Add build variables, for instance if user defined a text axis
environment.overrideAll(build.getBuildVariables());
// Check if define some nasty variables
for (String key : EnvVarsUtil.getPythonHomeKeys())
// Check if key is contained
if (environment.containsKey(key))
{
// Log the error
listener.fatalError(Messages.BuilderUtil_PythonHomeKeyFound(key));
// Notify to do not continue the build
return null;
}
// Return the consolidated environment
return environment;
}
/**
* Get the PYTHON installation.
*
* @param build
* The build
* @param listener
* The listener
* @param environment
* The environment
* @param name
* The name
* @return The PYTHON installation for this build
* @throws IOException
* @throws InterruptedException
*/
public static PythonInstallation getInstallation(AbstractBuild<?, ?> build, BuildListener listener, EnvVars environment,
String name) throws IOException, InterruptedException
{
// Check if this is a matrix build
- if (build instanceof MatrixRun)
+ if ((Object) build instanceof MatrixRun)
{
// Check if the environment contains a PYTHON axis key
if (!environment.containsKey(PythonAxis.KEY))
{
// If not, log
listener.fatalError(Messages.BuilderUtil_PythonAxis_Required());
// Return null to stop the build
return null;
}
// Get the name from the environment
name = environment.get(PythonAxis.KEY);
}
// Check if the name exists
if (name == null)
{
// Log the error
listener.fatalError(Messages.BuilderUtil_Installation_NameNotFound());
// Do not continue the build
return null;
}
// Expand the HOME folder with these variables
PythonInstallation installation = PythonInstallation.fromName(name);
// Check if found an installation
if (installation == null)
{
// Log
listener.fatalError(Messages.BuilderUtil_Installation_NotFound(name));
// Failed to find the installation, do not continue
return null;
}
// Get the installation for this build
return installation.forBuild(listener, environment);
}
/**
* Get an interpreter.
*
* @param launcher
* The launcher
* @param listener
* The listener
* @param home
* The home of the interpreter
* @return The interpreter if exists, else null
* @throws IOException
* @throws InterruptedException
*/
public static Python getInterpreter(Launcher launcher, BuildListener listener, String home) throws IOException,
InterruptedException
{
// Get an interpreter given its home
Python interpreter = Python.fromHome(new FilePath(launcher.getChannel(), home));
// Check if found an interpreter and if this interpreter is valid
if (interpreter == null || !interpreter.isValid())
{
// Log
listener.fatalError(Messages.BuilderUtil_Interpreter_Invalid(interpreter == null ? home : interpreter.getHome()
.getRemote()));
// Invalid
return null;
}
// Check if has white space in its home path
if (StringUtil.hasWhitespace(interpreter.getHome().getRemote()))
{
// Log
listener.fatalError(Messages.BuilderUtil_Interpreter_WhitespaceNotAllowed(interpreter == null ? home : interpreter
.getHome().getRemote()));
// Invalid
return null;
}
// This is a valid interpreter
return interpreter;
}
/**
* Get a VIRTUALENV from its home folder.
*
* @param listener
* The listener
* @param home
* The home folder
* @return The VIRTUALENV
* @throws IOException
* @throws InterruptedException
*/
public static Virtualenv getVirtualenv(BuildListener listener, FilePath home) throws IOException, InterruptedException
{
// Create the VIRTUAL environment
Virtualenv virtualenv = new Virtualenv(home);
// Check if has white space in its home path
if (StringUtil.hasWhitespace(virtualenv.getHome().getRemote()))
{
// Log
listener.fatalError(Messages.BuilderUtil_Interpreter_WhitespaceNotAllowed(virtualenv.getHome().getRemote()));
// Invalid
return null;
}
// Return the VIRTUALENV
return virtualenv;
}
/**
* Launch a command.
*
* @param launcher
* The launcher
* @param listener
* The build listener
* @param pwd
* The working directory
* @param environment
* The environment
* @param interpreter
* The interpreter
* @param nature
* The nature of the command: PYTHON, shell, X shell
* @param command
* The command to execute
* @param ignoreExitCode
* Is the exit code ignored?
* @return true if was successful, else false
* @throws IOException
* @throws InterruptedException
*/
public static boolean launch(Launcher launcher, BuildListener listener, FilePath pwd, EnvVars environment,
Python interpreter, String nature, String command, boolean ignoreExitCode) throws IOException, InterruptedException
{
// Get PYTHON executable
String executable = interpreter.getExecutable().getRemote();
// Set the interpreter environment
environment.overrideAll(interpreter.getEnvironment());
// Add PYTHON_EXE environment variable
environment.override("PYTHON_EXE", executable);
// Launch the script
return Command.get(FilePathUtil.isUnix(pwd), executable, CommandNature.get(nature), command, ignoreExitCode).launch(
launcher, listener, environment, pwd);
}
/**
* Get the first available interpreter on the executor.
*
* @param launcher
* The launcher
* @param listener
* The build listener
* @param environment
* The environment
* @return The first available interpreter
* @throws IOException
* @throws InterruptedException
*/
public static Python getInterpreter(Launcher launcher, BuildListener listener, EnvVars environment) throws IOException,
InterruptedException
{
// Get the list of existing interpreter
List<Python> interpreters = getInterpreters(launcher, listener, environment);
// Check if at least one found
if (!interpreters.isEmpty())
// Return the first one
return interpreters.get(0);
// Failed to found one
listener.fatalError(Messages.BuilderUtil_NoInterpreterFound());
// Return null
return null;
}
/**
* Get the list of the valid interpreter on an executor.
*
* @param launcher
* The launcher
* @param listener
* The build listener
* @param environment
* The environment
* @return The list of available interpreter
* @throws IOException
* @throws InterruptedException
*/
public static List<Python> getInterpreters(Launcher launcher, BuildListener listener, EnvVars environment)
throws IOException, InterruptedException
{
// Create the interpreter list
List<Python> interpreters = new ArrayList<Python>();
// Go threw all PYTHON installations
for (PythonInstallation installation : PythonInstallation.list())
{
// Convert for the build
installation = installation.forBuild(listener, environment);
// Get an interpreter given its home
Python interpreter = Python.fromHome(new FilePath(launcher.getChannel(), installation.getHome()));
// Check if exists, is valid and has no whitespace in its home
if (interpreter != null && interpreter.isValid() && !StringUtil.hasWhitespace(interpreter.getHome().getRemote()))
// Add the interpreter
interpreters.add(interpreter);
}
// Return the list of interpreters
return interpreters;
}
}
| true | true | public static PythonInstallation getInstallation(AbstractBuild<?, ?> build, BuildListener listener, EnvVars environment,
String name) throws IOException, InterruptedException
{
// Check if this is a matrix build
if (build instanceof MatrixRun)
{
// Check if the environment contains a PYTHON axis key
if (!environment.containsKey(PythonAxis.KEY))
{
// If not, log
listener.fatalError(Messages.BuilderUtil_PythonAxis_Required());
// Return null to stop the build
return null;
}
// Get the name from the environment
name = environment.get(PythonAxis.KEY);
}
// Check if the name exists
if (name == null)
{
// Log the error
listener.fatalError(Messages.BuilderUtil_Installation_NameNotFound());
// Do not continue the build
return null;
}
// Expand the HOME folder with these variables
PythonInstallation installation = PythonInstallation.fromName(name);
// Check if found an installation
if (installation == null)
{
// Log
listener.fatalError(Messages.BuilderUtil_Installation_NotFound(name));
// Failed to find the installation, do not continue
return null;
}
// Get the installation for this build
return installation.forBuild(listener, environment);
}
| public static PythonInstallation getInstallation(AbstractBuild<?, ?> build, BuildListener listener, EnvVars environment,
String name) throws IOException, InterruptedException
{
// Check if this is a matrix build
if ((Object) build instanceof MatrixRun)
{
// Check if the environment contains a PYTHON axis key
if (!environment.containsKey(PythonAxis.KEY))
{
// If not, log
listener.fatalError(Messages.BuilderUtil_PythonAxis_Required());
// Return null to stop the build
return null;
}
// Get the name from the environment
name = environment.get(PythonAxis.KEY);
}
// Check if the name exists
if (name == null)
{
// Log the error
listener.fatalError(Messages.BuilderUtil_Installation_NameNotFound());
// Do not continue the build
return null;
}
// Expand the HOME folder with these variables
PythonInstallation installation = PythonInstallation.fromName(name);
// Check if found an installation
if (installation == null)
{
// Log
listener.fatalError(Messages.BuilderUtil_Installation_NotFound(name));
// Failed to find the installation, do not continue
return null;
}
// Get the installation for this build
return installation.forBuild(listener, environment);
}
|
diff --git a/work-swing-impl/impl/src/main/java/org/cytoscape/work/internal/task/JDialogTaskManager.java b/work-swing-impl/impl/src/main/java/org/cytoscape/work/internal/task/JDialogTaskManager.java
index eb693da0c..52b601353 100644
--- a/work-swing-impl/impl/src/main/java/org/cytoscape/work/internal/task/JDialogTaskManager.java
+++ b/work-swing-impl/impl/src/main/java/org/cytoscape/work/internal/task/JDialogTaskManager.java
@@ -1,276 +1,279 @@
package org.cytoscape.work.internal.task;
import java.awt.Window;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;
import org.cytoscape.work.AbstractTaskManager;
import org.cytoscape.work.Task;
import org.cytoscape.work.TaskFactory;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TunableRecorder;
import org.cytoscape.work.internal.tunables.JDialogTunableMutator;
import org.cytoscape.work.swing.DialogTaskManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Uses Swing components to create a user interface for the <code>Task</code>.
*
* This will not work if the application is running in headless mode.
*/
public class JDialogTaskManager extends AbstractTaskManager<JDialog,Window> implements DialogTaskManager {
private static final Logger logger = LoggerFactory.getLogger(JDialogTaskManager.class);
/**
* The delay between the execution of the <code>Task</code> and
* showing its task dialog.
*
* When a <code>Task</code> is executed, <code>JDialogTaskManager</code>
* will not show its task dialog immediately. It will delay for a
* period of time before showing the dialog. This way, short lived
* <code>Task</code>s won't have a dialog box.
*/
static final long DELAY_BEFORE_SHOWING_DIALOG = 1;
/**
* The time unit of <code>DELAY_BEFORE_SHOWING_DIALOG</code>.
*/
static final TimeUnit DELAY_TIMEUNIT = TimeUnit.SECONDS;
/**
* Used for calling <code>Task.run()</code>.
*/
private ExecutorService taskExecutorService;
/**
* Used for opening dialogs after a specific amount of delay.
*/
private ScheduledExecutorService timedDialogExecutorService;
/**
* Used for calling <code>Task.cancel()</code>.
* <code>Task.cancel()</code> must be called in a different
* thread from the thread running Swing. This is done to
* prevent Swing from freezing if <code>Task.cancel()</code>
* takes too long to finish.
*
* This can be the same as <code>taskExecutorService</code>.
*/
private ExecutorService cancelExecutorService;
// Parent component of Task Monitor GUI.
private Window parent;
private final JDialogTunableMutator dialogTunableMutator;
/**
* Construct with default behavior.
* <ul>
* <li><code>owner</code> is set to null.</li>
* <li><code>taskExecutorService</code> is a cached thread pool.</li>
* <li><code>timedExecutorService</code> is a single thread executor.</li>
* <li><code>cancelExecutorService</code> is the same as <code>taskExecutorService</code>.</li>
* </ul>
*/
public JDialogTaskManager(final JDialogTunableMutator tunableMutator) {
super(tunableMutator);
this.dialogTunableMutator = tunableMutator;
parent = null;
taskExecutorService = Executors.newCachedThreadPool();
addShutdownHook(taskExecutorService);
timedDialogExecutorService = Executors.newSingleThreadScheduledExecutor();
addShutdownHook(timedDialogExecutorService);
cancelExecutorService = taskExecutorService;
}
/**
* Adds a shutdown hook to the JVM that shuts down an
* <code>ExecutorService</code>. <code>ExecutorService</code>s
* need to be told to shut down, otherwise the JVM won't
* cleanly terminate.
*/
void addShutdownHook(final ExecutorService serviceToShutdown) {
// Used to create a thread that is executed by the shutdown hook
ThreadFactory threadFactory = Executors.defaultThreadFactory();
Runnable shutdownHook = new Runnable() {
public void run() {
serviceToShutdown.shutdownNow();
}
};
Runtime.getRuntime().addShutdownHook(threadFactory.newThread(shutdownHook));
}
/**
* @param parent JDialogs created by this TaskManager will use this
* to set the parent of the dialog.
*/
@Override
public void setExecutionContext(final Window parent) {
this.parent = parent;
}
@Override
public JDialog getConfiguration(TaskFactory factory, Object tunableContext) {
throw new UnsupportedOperationException("There is no configuration available for a DialogTaskManager");
}
@Override
public void execute(final TaskIterator iterator) {
execute(iterator, null);
}
/**
* For users of this class.
*/
public void execute(final TaskIterator taskIterator, Object tunableContext) {
final SwingTaskMonitor taskMonitor = new SwingTaskMonitor(cancelExecutorService, parent);
final Task first;
try {
dialogTunableMutator.setConfigurationContext(parent);
if ( tunableContext != null && !displayTunables(tunableContext) ) {
taskMonitor.cancel();
return;
}
taskMonitor.setExpectedNumTasks( taskIterator.getNumTasks() );
// Get the first task and display its tunables. This is a bit of a hack.
// We do this outside of the thread so that the task monitor only gets
// displayed AFTER the first tunables dialog gets displayed.
first = taskIterator.next();
if (!displayTunables(first)) {
taskMonitor.cancel();
return;
}
} catch (Exception exception) {
logger.warn("Caught exception getting and validating task. ", exception);
taskMonitor.showException(exception);
return;
}
// create the task thread
final Runnable tasks = new TaskThread(first, taskMonitor, taskIterator);
// submit the task thread for execution
final Future<?> executorFuture = taskExecutorService.submit(tasks);
openTaskMonitorOnDelay(taskMonitor, executorFuture);
}
// This creates a thread on delay that conditionally displays the task monitor gui
// if the task thread has not yet finished.
private void openTaskMonitorOnDelay(final SwingTaskMonitor taskMonitor,
final Future<?> executorFuture) {
final Runnable timedOpen = new Runnable() {
public void run() {
if (!(executorFuture.isDone() || executorFuture.isCancelled())) {
taskMonitor.setFuture(executorFuture);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (!taskMonitor.isClosed()) {
taskMonitor.open();
}
}
});
}
}
};
timedDialogExecutorService.schedule(timedOpen, DELAY_BEFORE_SHOWING_DIALOG, DELAY_TIMEUNIT);
}
private class TaskThread implements Runnable {
private final SwingTaskMonitor taskMonitor;
private final TaskIterator taskIterator;
private final Task first;
TaskThread(final Task first, final SwingTaskMonitor tm, final TaskIterator ti) {
this.first = first;
this.taskMonitor = tm;
this.taskIterator = ti;
}
public void run() {
try {
// actually run the first task
// don't dispaly the tunables here - they were handled above.
taskMonitor.setTask(first);
first.run(taskMonitor);
if (taskMonitor.cancelled())
return;
// now execute all subsequent tasks
while (taskIterator.hasNext()) {
final Task task = taskIterator.next();
taskMonitor.setTask(task);
// hide the dialog to avoid swing threading issues
// while displaying tunables
taskMonitor.showDialog(false);
if (!displayTunables(task)) {
taskMonitor.cancel();
return;
}
taskMonitor.showDialog(true);
task.run(taskMonitor);
if (taskMonitor.cancelled())
break;
}
} catch (Throwable exception) {
logger.warn("Caught exception executing task. ", exception);
taskMonitor.showException(new Exception(exception));
+ } finally {
+ parent = null;
+ dialogTunableMutator.setConfigurationContext(null);
}
// clean up the task monitor
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (taskMonitor.isOpened() && !taskMonitor.isShowingException())
taskMonitor.close();
}
});
}
}
private boolean displayTunables(final Object task) throws Exception {
if (task == null) {
return true;
}
boolean ret = dialogTunableMutator.validateAndWriteBack(task);
for ( TunableRecorder ti : tunableRecorders )
ti.recordTunableState(task);
return ret;
}
}
| true | true | public void run() {
try {
// actually run the first task
// don't dispaly the tunables here - they were handled above.
taskMonitor.setTask(first);
first.run(taskMonitor);
if (taskMonitor.cancelled())
return;
// now execute all subsequent tasks
while (taskIterator.hasNext()) {
final Task task = taskIterator.next();
taskMonitor.setTask(task);
// hide the dialog to avoid swing threading issues
// while displaying tunables
taskMonitor.showDialog(false);
if (!displayTunables(task)) {
taskMonitor.cancel();
return;
}
taskMonitor.showDialog(true);
task.run(taskMonitor);
if (taskMonitor.cancelled())
break;
}
} catch (Throwable exception) {
logger.warn("Caught exception executing task. ", exception);
taskMonitor.showException(new Exception(exception));
}
// clean up the task monitor
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (taskMonitor.isOpened() && !taskMonitor.isShowingException())
taskMonitor.close();
}
});
}
| public void run() {
try {
// actually run the first task
// don't dispaly the tunables here - they were handled above.
taskMonitor.setTask(first);
first.run(taskMonitor);
if (taskMonitor.cancelled())
return;
// now execute all subsequent tasks
while (taskIterator.hasNext()) {
final Task task = taskIterator.next();
taskMonitor.setTask(task);
// hide the dialog to avoid swing threading issues
// while displaying tunables
taskMonitor.showDialog(false);
if (!displayTunables(task)) {
taskMonitor.cancel();
return;
}
taskMonitor.showDialog(true);
task.run(taskMonitor);
if (taskMonitor.cancelled())
break;
}
} catch (Throwable exception) {
logger.warn("Caught exception executing task. ", exception);
taskMonitor.showException(new Exception(exception));
} finally {
parent = null;
dialogTunableMutator.setConfigurationContext(null);
}
// clean up the task monitor
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (taskMonitor.isOpened() && !taskMonitor.isShowingException())
taskMonitor.close();
}
});
}
|
diff --git a/SpagoBIWhatIfEngine/src/it/eng/spagobi/engines/whatif/model/PivotJsonHTMLSerializer.java b/SpagoBIWhatIfEngine/src/it/eng/spagobi/engines/whatif/model/PivotJsonHTMLSerializer.java
index 87b86f8cf..07f5a874e 100644
--- a/SpagoBIWhatIfEngine/src/it/eng/spagobi/engines/whatif/model/PivotJsonHTMLSerializer.java
+++ b/SpagoBIWhatIfEngine/src/it/eng/spagobi/engines/whatif/model/PivotJsonHTMLSerializer.java
@@ -1,319 +1,318 @@
/* SpagoBI, the Open Source Business Intelligence suite
* Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice.
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
*
* Renderer of the model...
* It uses the WhatIfHTMLRenderer to render the table in a HTML format
*
* @author Alberto Ghedin ([email protected])
*/
package it.eng.spagobi.engines.whatif.model;
import it.eng.spagobi.commons.utilities.StringUtilities;
import it.eng.spagobi.engines.whatif.cube.CubeUtilities;
import it.eng.spagobi.engines.whatif.dimension.SbiDimension;
import it.eng.spagobi.engines.whatif.hierarchy.SbiHierarchy;
import it.eng.spagobi.pivot4j.ui.WhatIfHTMLRenderer;
import it.eng.spagobi.utilities.engines.SpagoBIEngineRuntimeException;
import it.eng.spagobi.utilities.exceptions.SpagoBIRuntimeException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.hibernate.jdbc.util.BasicFormatterImpl;
import org.json.JSONException;
import org.olap4j.Axis;
import org.olap4j.CellSet;
import org.olap4j.CellSetAxis;
import org.olap4j.OlapConnection;
import org.olap4j.metadata.Dimension;
import org.olap4j.metadata.Hierarchy;
import org.olap4j.metadata.Member;
import com.eyeq.pivot4j.PivotModel;
import com.eyeq.pivot4j.query.QueryAdapter;
import com.eyeq.pivot4j.transform.ChangeSlicer;
import com.eyeq.pivot4j.transform.impl.ChangeSlicerImpl;
import com.eyeq.pivot4j.ui.command.DrillCollapseMemberCommand;
import com.eyeq.pivot4j.ui.command.DrillCollapsePositionCommand;
import com.eyeq.pivot4j.ui.command.DrillDownCommand;
import com.eyeq.pivot4j.ui.command.DrillDownReplaceCommand;
import com.eyeq.pivot4j.ui.command.DrillExpandMemberCommand;
import com.eyeq.pivot4j.ui.command.DrillExpandPositionCommand;
import com.eyeq.pivot4j.ui.command.DrillUpReplaceCommand;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class PivotJsonHTMLSerializer extends JsonSerializer<PivotModel> {
public static transient Logger logger = Logger.getLogger(PivotJsonHTMLSerializer.class);
private static final int FILTERS_AXIS_POS= -1;
private static final String NAME= "name";
private static final String UNIQUE_NAME= "uniqueName";
private static final String COLUMNS= "columns";
private static final String ROWS= "rows";
private static final String FILTERS= "filters";
private static final String TABLE= "table";
private static final String ROWSAXISORDINAL = "rowsAxisOrdinal";
private static final String COLUMNSAXISORDINAL = "columnsAxisOrdinal";
private static final String MDXFORMATTED = "mdxFormatted";
private static final String MODELCONFIG = "modelConfig";
private OlapConnection connection;
private ModelConfig modelConfig;
public PivotJsonHTMLSerializer(OlapConnection connection, ModelConfig modelConfig){
this.connection = connection;
this.modelConfig = modelConfig;
}
public void serialize(PivotModel value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException{
logger.debug("IN");
String table="";
logger.debug("Creating the renderer");
StringWriter writer = new StringWriter();
WhatIfHTMLRenderer renderer = new WhatIfHTMLRenderer(writer);
logger.debug("Setting the properties of the renderer");
renderer.setShowParentMembers(false); // Optionally make the parent members visible.
renderer.setShowDimensionTitle(false); // Optionally hide the dimension title headers.
renderer.setCellSpacing(0);
renderer.setRowHeaderStyleClass("x-column-header-inner x-column-header x-column-header-align-left x-box-item x-column-header-default x-unselectable x-grid-header-ct x-docked x-grid-header-ct-default x-docked-top x-grid-header-ct-docked-top x-grid-header-ct-default-docked-top x-box-layout-ct x-docked-noborder-top x-docked-noborder-right x-docked-noborder-left x-pivot-header");
renderer.setColumnHeaderStyleClass("x-column-header-inner x-column-header x-column-header-align-left x-box-item x-column-header-default x-unselectable x-grid-header-ct x-docked x-grid-header-ct-default x-docked-top x-grid-header-ct-docked-top x-grid-header-ct-default-docked-top x-box-layout-ct x-docked-noborder-top x-docked-noborder-right x-docked-noborder-left x-pivot-header");
renderer.setCornerStyleClass("x-column-header-inner x-column-header x-column-header-align-left x-box-item x-column-header-default x-unselectable x-grid-header-ct x-docked x-grid-header-ct-default x-docked-top x-grid-header-ct-docked-top x-grid-header-ct-default-docked-top x-box-layout-ct x-docked-noborder-top x-docked-noborder-right x-docked-noborder-left x-pivot-header");
renderer.setCellStyleClass("x-grid-cell x-grid-td x-grid-cell-gridcolumn-1014 x-unselectable x-grid-cell-inner x-grid-row-alt x-grid-data-row x-grid-with-col-lines x-grid-cell x-pivot-cell");
renderer.setTableStyleClass("x-panel-body x-grid-body x-panel-body-default x-box-layout-ct x-panel-body-default x-pivot-table");
renderer.setRowStyleClass(" generic-row-style ");
renderer.setEvenRowStyleClass(" even-row ");
renderer.setOddRowStyleClass(" odd-row ");
String drillDownModeValue = modelConfig.getDrillType();
renderer.removeCommand(new DrillUpReplaceCommand(renderer).getName());
renderer.removeCommand(new DrillDownReplaceCommand(renderer).getName());
renderer.removeCommand(new DrillExpandMemberCommand(renderer).getName());
renderer.removeCommand(new DrillCollapseMemberCommand(renderer).getName());
renderer.removeCommand(new DrillCollapsePositionCommand(renderer).getName());
renderer.removeCommand(new DrillExpandPositionCommand(renderer).getName());
if(drillDownModeValue.equals(DrillDownCommand.MODE_POSITION)){
renderer.addCommand(new DrillExpandPositionCommand(renderer));
renderer.addCommand(new DrillCollapsePositionCommand(renderer));
}else if(drillDownModeValue.equals(DrillDownCommand.MODE_MEMBER)){
renderer.addCommand(new DrillCollapseMemberCommand(renderer));
renderer.addCommand(new DrillExpandMemberCommand(renderer));
}else if(drillDownModeValue.equals(DrillDownCommand.MODE_REPLACE)){
renderer.addCommand(new DrillDownReplaceCommand(renderer));
renderer.addCommand(new DrillUpReplaceCommand(renderer));
/*NOT TO BE CHANGED ---> used for drill-up in replace mode*/
renderer.setShowDimensionTitle(true); // Optionally hide the dimension title headers.
/*--------------------------------------------------------*/
}
renderer.setDrillDownMode(drillDownModeValue);
renderer.setEnableColumnDrillDown(true);
renderer.setEnableRowDrillDown(true);
renderer.setEnableSort(true);
logger.debug("Rendering the model");
renderer.render(value);
try {
writer.flush();
writer.close();
table = writer.getBuffer().toString();
} catch (IOException e) {
logger.error("Error serializing the table",e);
throw new SpagoBIEngineRuntimeException("Error serializing the table",e);
}
CellSet cellSet = value.getCellSet();
List<CellSetAxis> axis = cellSet.getAxes();
try {
List<Hierarchy> axisHierarchies = axis.get(0).getAxisMetaData().getHierarchies();
axisHierarchies.addAll(axis.get(1).getAxisMetaData().getHierarchies());
List<Dimension> axisDimensions = CubeUtilities.getDimensions(axisHierarchies);
List<Dimension> otherHDimensions = CubeUtilities.getDimensions(value.getCube().getHierarchies());
otherHDimensions.removeAll(axisDimensions);
jgen.writeStartObject();
jgen.writeStringField(TABLE, table);
serializeAxis(ROWS, jgen,axis, Axis.ROWS);
serializeAxis(COLUMNS, jgen,axis, Axis.COLUMNS);
serializeDimensions(jgen, otherHDimensions, FILTERS_AXIS_POS, FILTERS, true, value);
jgen.writeNumberField(COLUMNSAXISORDINAL, Axis.COLUMNS.axisOrdinal());
jgen.writeNumberField(ROWSAXISORDINAL, Axis.ROWS.axisOrdinal());
jgen.writeObjectField(MODELCONFIG, modelConfig);
//build the query mdx
- String mdxQuery = value.getMdx();
- mdxQuery = formatQueryString(mdxQuery);
+ String mdxQuery = formatQueryString( value.getCurrentMdx());
jgen.writeStringField(MDXFORMATTED, mdxQuery);
jgen.writeEndObject();
} catch (Exception e) {
logger.error("Error serializing the pivot table", e);
throw new SpagoBIRuntimeException("Error serializing the pivot table", e);
}
logger.debug("OUT");
}
private void serializeAxis(String field,JsonGenerator jgen, List<CellSetAxis> axis, Axis type) throws JSONException, JsonGenerationException, IOException{
CellSetAxis aAxis= axis.get(0);
int axisPos = 0;
if(!aAxis.getAxisOrdinal().equals(type)){
aAxis = axis.get(1);
axisPos = 1;
}
List<Hierarchy> hierarchies = aAxis.getAxisMetaData().getHierarchies();
List<Dimension> dimensions = CubeUtilities.getDimensions(hierarchies);
serializeDimensions(jgen, dimensions, axisPos, field, false, null);
}
private void serializeDimensions(JsonGenerator jgen, List<Dimension> dimensions, int axis, String field, boolean withSlicers, PivotModel model) throws JSONException, JsonGenerationException, IOException{
QueryAdapter qa = null;
ChangeSlicer ph = null;
if(withSlicers){
qa = new QueryAdapter(model);
qa.initialize();
ph = new ChangeSlicerImpl(qa, connection);
}
jgen.writeArrayFieldStart(field);
for (int i=0; i<dimensions.size(); i++) {
Dimension aDimension = dimensions.get(i);
SbiDimension myDimension = new SbiDimension(aDimension, axis, i);
List<Hierarchy> dimensionHierarchies = aDimension.getHierarchies();
String selectedHierarchyName = modelConfig.getDimensionHierarchyMap().get(myDimension.getUniqueName());
if(selectedHierarchyName==null){
selectedHierarchyName = aDimension.getDefaultHierarchy().getUniqueName();
}
myDimension.setSelectedHierarchyUniqueName(selectedHierarchyName);
for (int j=0; j<dimensionHierarchies.size(); j++) {
Hierarchy hierarchy = dimensionHierarchies.get(j);
SbiHierarchy hierarchyObject = new SbiHierarchy(hierarchy, i);
if(withSlicers){
List<Member> slicers = ph.getSlicer(hierarchy);
if(slicers!= null && slicers.size()>0){
List<Map<String,String>> slicerMap = new ArrayList<Map<String,String>>();
for(int k=0; k<slicers.size(); k++){
Map<String,String> slicer = new HashMap<String,String>();
slicer.put(UNIQUE_NAME, slicers.get(k).getUniqueName());
slicer.put(NAME, slicers.get(k).getName());
slicerMap.add(slicer);
}
hierarchyObject.setSlicers( slicerMap);
}
}
myDimension.getHierarchies().add(hierarchyObject);
//set the position of the selected hierarchy
if(selectedHierarchyName.equals(hierarchy.getUniqueName())){
myDimension.setSelectedHierarchyPosition(j);
}
}
jgen.writeObject(myDimension);
}
jgen.writeEndArray();
}
//
// private void serializeFilters(String field, JsonGenerator jgen,List<Hierarchy> hierarchies, PivotModel model) throws JSONException, JsonGenerationException, IOException{
//
// QueryAdapter qa = new QueryAdapter(model);
// qa.initialize();
//
// ChangeSlicer ph = new ChangeSlicerImpl(qa, connection);
//
//
// jgen.writeArrayFieldStart(field);
// if(hierarchies!=null){
// for (int i=0; i<hierarchies.size(); i++) {
// Hierarchy hierarchy = hierarchies.get(i);
// Map<String,Object> hierarchyObject = new HashMap<String,Object>();
// hierarchyObject.put(NAME, hierarchy.getName());
// hierarchyObject.put(UNIQUE_NAME, hierarchy.getUniqueName());
// hierarchyObject.put(POSITION, ""+i);
// hierarchyObject.put(AXIS, ""+FILTERS_AXIS_POS);
//
//
// List<Member> slicers = ph.getSlicer(hierarchy);
// if(slicers!= null && slicers.size()>0){
// List<Map<String,String>> slicerMap = new ArrayList<Map<String,String>>();
// for(int j=0; j<slicers.size(); j++){
// Map<String,String> slicer = new HashMap<String,String>();
// slicer.put(UNIQUE_NAME, slicers.get(j).getUniqueName());
// slicer.put(NAME, slicers.get(j).getName());
// slicerMap.add(slicer);
// }
// hierarchyObject.put(SLICERS, slicerMap);
// }
// jgen.writeObject(hierarchyObject);
//
// }
// }
// jgen.writeEndArray();
// }
public String formatQueryString(String queryString) {
String formattedQuery;
BasicFormatterImpl fromatter;
if(queryString == null || queryString.equals("")){
logger.error("Impossible to get the query string because the query is null");
return "";
}
fromatter = new BasicFormatterImpl() ;
formattedQuery = fromatter.format(queryString);
return StringUtilities.fromStringToHTML(formattedQuery);
}
}
| true | true | public void serialize(PivotModel value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException{
logger.debug("IN");
String table="";
logger.debug("Creating the renderer");
StringWriter writer = new StringWriter();
WhatIfHTMLRenderer renderer = new WhatIfHTMLRenderer(writer);
logger.debug("Setting the properties of the renderer");
renderer.setShowParentMembers(false); // Optionally make the parent members visible.
renderer.setShowDimensionTitle(false); // Optionally hide the dimension title headers.
renderer.setCellSpacing(0);
renderer.setRowHeaderStyleClass("x-column-header-inner x-column-header x-column-header-align-left x-box-item x-column-header-default x-unselectable x-grid-header-ct x-docked x-grid-header-ct-default x-docked-top x-grid-header-ct-docked-top x-grid-header-ct-default-docked-top x-box-layout-ct x-docked-noborder-top x-docked-noborder-right x-docked-noborder-left x-pivot-header");
renderer.setColumnHeaderStyleClass("x-column-header-inner x-column-header x-column-header-align-left x-box-item x-column-header-default x-unselectable x-grid-header-ct x-docked x-grid-header-ct-default x-docked-top x-grid-header-ct-docked-top x-grid-header-ct-default-docked-top x-box-layout-ct x-docked-noborder-top x-docked-noborder-right x-docked-noborder-left x-pivot-header");
renderer.setCornerStyleClass("x-column-header-inner x-column-header x-column-header-align-left x-box-item x-column-header-default x-unselectable x-grid-header-ct x-docked x-grid-header-ct-default x-docked-top x-grid-header-ct-docked-top x-grid-header-ct-default-docked-top x-box-layout-ct x-docked-noborder-top x-docked-noborder-right x-docked-noborder-left x-pivot-header");
renderer.setCellStyleClass("x-grid-cell x-grid-td x-grid-cell-gridcolumn-1014 x-unselectable x-grid-cell-inner x-grid-row-alt x-grid-data-row x-grid-with-col-lines x-grid-cell x-pivot-cell");
renderer.setTableStyleClass("x-panel-body x-grid-body x-panel-body-default x-box-layout-ct x-panel-body-default x-pivot-table");
renderer.setRowStyleClass(" generic-row-style ");
renderer.setEvenRowStyleClass(" even-row ");
renderer.setOddRowStyleClass(" odd-row ");
String drillDownModeValue = modelConfig.getDrillType();
renderer.removeCommand(new DrillUpReplaceCommand(renderer).getName());
renderer.removeCommand(new DrillDownReplaceCommand(renderer).getName());
renderer.removeCommand(new DrillExpandMemberCommand(renderer).getName());
renderer.removeCommand(new DrillCollapseMemberCommand(renderer).getName());
renderer.removeCommand(new DrillCollapsePositionCommand(renderer).getName());
renderer.removeCommand(new DrillExpandPositionCommand(renderer).getName());
if(drillDownModeValue.equals(DrillDownCommand.MODE_POSITION)){
renderer.addCommand(new DrillExpandPositionCommand(renderer));
renderer.addCommand(new DrillCollapsePositionCommand(renderer));
}else if(drillDownModeValue.equals(DrillDownCommand.MODE_MEMBER)){
renderer.addCommand(new DrillCollapseMemberCommand(renderer));
renderer.addCommand(new DrillExpandMemberCommand(renderer));
}else if(drillDownModeValue.equals(DrillDownCommand.MODE_REPLACE)){
renderer.addCommand(new DrillDownReplaceCommand(renderer));
renderer.addCommand(new DrillUpReplaceCommand(renderer));
/*NOT TO BE CHANGED ---> used for drill-up in replace mode*/
renderer.setShowDimensionTitle(true); // Optionally hide the dimension title headers.
/*--------------------------------------------------------*/
}
renderer.setDrillDownMode(drillDownModeValue);
renderer.setEnableColumnDrillDown(true);
renderer.setEnableRowDrillDown(true);
renderer.setEnableSort(true);
logger.debug("Rendering the model");
renderer.render(value);
try {
writer.flush();
writer.close();
table = writer.getBuffer().toString();
} catch (IOException e) {
logger.error("Error serializing the table",e);
throw new SpagoBIEngineRuntimeException("Error serializing the table",e);
}
CellSet cellSet = value.getCellSet();
List<CellSetAxis> axis = cellSet.getAxes();
try {
List<Hierarchy> axisHierarchies = axis.get(0).getAxisMetaData().getHierarchies();
axisHierarchies.addAll(axis.get(1).getAxisMetaData().getHierarchies());
List<Dimension> axisDimensions = CubeUtilities.getDimensions(axisHierarchies);
List<Dimension> otherHDimensions = CubeUtilities.getDimensions(value.getCube().getHierarchies());
otherHDimensions.removeAll(axisDimensions);
jgen.writeStartObject();
jgen.writeStringField(TABLE, table);
serializeAxis(ROWS, jgen,axis, Axis.ROWS);
serializeAxis(COLUMNS, jgen,axis, Axis.COLUMNS);
serializeDimensions(jgen, otherHDimensions, FILTERS_AXIS_POS, FILTERS, true, value);
jgen.writeNumberField(COLUMNSAXISORDINAL, Axis.COLUMNS.axisOrdinal());
jgen.writeNumberField(ROWSAXISORDINAL, Axis.ROWS.axisOrdinal());
jgen.writeObjectField(MODELCONFIG, modelConfig);
//build the query mdx
String mdxQuery = value.getMdx();
mdxQuery = formatQueryString(mdxQuery);
jgen.writeStringField(MDXFORMATTED, mdxQuery);
jgen.writeEndObject();
} catch (Exception e) {
logger.error("Error serializing the pivot table", e);
throw new SpagoBIRuntimeException("Error serializing the pivot table", e);
}
logger.debug("OUT");
}
| public void serialize(PivotModel value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException{
logger.debug("IN");
String table="";
logger.debug("Creating the renderer");
StringWriter writer = new StringWriter();
WhatIfHTMLRenderer renderer = new WhatIfHTMLRenderer(writer);
logger.debug("Setting the properties of the renderer");
renderer.setShowParentMembers(false); // Optionally make the parent members visible.
renderer.setShowDimensionTitle(false); // Optionally hide the dimension title headers.
renderer.setCellSpacing(0);
renderer.setRowHeaderStyleClass("x-column-header-inner x-column-header x-column-header-align-left x-box-item x-column-header-default x-unselectable x-grid-header-ct x-docked x-grid-header-ct-default x-docked-top x-grid-header-ct-docked-top x-grid-header-ct-default-docked-top x-box-layout-ct x-docked-noborder-top x-docked-noborder-right x-docked-noborder-left x-pivot-header");
renderer.setColumnHeaderStyleClass("x-column-header-inner x-column-header x-column-header-align-left x-box-item x-column-header-default x-unselectable x-grid-header-ct x-docked x-grid-header-ct-default x-docked-top x-grid-header-ct-docked-top x-grid-header-ct-default-docked-top x-box-layout-ct x-docked-noborder-top x-docked-noborder-right x-docked-noborder-left x-pivot-header");
renderer.setCornerStyleClass("x-column-header-inner x-column-header x-column-header-align-left x-box-item x-column-header-default x-unselectable x-grid-header-ct x-docked x-grid-header-ct-default x-docked-top x-grid-header-ct-docked-top x-grid-header-ct-default-docked-top x-box-layout-ct x-docked-noborder-top x-docked-noborder-right x-docked-noborder-left x-pivot-header");
renderer.setCellStyleClass("x-grid-cell x-grid-td x-grid-cell-gridcolumn-1014 x-unselectable x-grid-cell-inner x-grid-row-alt x-grid-data-row x-grid-with-col-lines x-grid-cell x-pivot-cell");
renderer.setTableStyleClass("x-panel-body x-grid-body x-panel-body-default x-box-layout-ct x-panel-body-default x-pivot-table");
renderer.setRowStyleClass(" generic-row-style ");
renderer.setEvenRowStyleClass(" even-row ");
renderer.setOddRowStyleClass(" odd-row ");
String drillDownModeValue = modelConfig.getDrillType();
renderer.removeCommand(new DrillUpReplaceCommand(renderer).getName());
renderer.removeCommand(new DrillDownReplaceCommand(renderer).getName());
renderer.removeCommand(new DrillExpandMemberCommand(renderer).getName());
renderer.removeCommand(new DrillCollapseMemberCommand(renderer).getName());
renderer.removeCommand(new DrillCollapsePositionCommand(renderer).getName());
renderer.removeCommand(new DrillExpandPositionCommand(renderer).getName());
if(drillDownModeValue.equals(DrillDownCommand.MODE_POSITION)){
renderer.addCommand(new DrillExpandPositionCommand(renderer));
renderer.addCommand(new DrillCollapsePositionCommand(renderer));
}else if(drillDownModeValue.equals(DrillDownCommand.MODE_MEMBER)){
renderer.addCommand(new DrillCollapseMemberCommand(renderer));
renderer.addCommand(new DrillExpandMemberCommand(renderer));
}else if(drillDownModeValue.equals(DrillDownCommand.MODE_REPLACE)){
renderer.addCommand(new DrillDownReplaceCommand(renderer));
renderer.addCommand(new DrillUpReplaceCommand(renderer));
/*NOT TO BE CHANGED ---> used for drill-up in replace mode*/
renderer.setShowDimensionTitle(true); // Optionally hide the dimension title headers.
/*--------------------------------------------------------*/
}
renderer.setDrillDownMode(drillDownModeValue);
renderer.setEnableColumnDrillDown(true);
renderer.setEnableRowDrillDown(true);
renderer.setEnableSort(true);
logger.debug("Rendering the model");
renderer.render(value);
try {
writer.flush();
writer.close();
table = writer.getBuffer().toString();
} catch (IOException e) {
logger.error("Error serializing the table",e);
throw new SpagoBIEngineRuntimeException("Error serializing the table",e);
}
CellSet cellSet = value.getCellSet();
List<CellSetAxis> axis = cellSet.getAxes();
try {
List<Hierarchy> axisHierarchies = axis.get(0).getAxisMetaData().getHierarchies();
axisHierarchies.addAll(axis.get(1).getAxisMetaData().getHierarchies());
List<Dimension> axisDimensions = CubeUtilities.getDimensions(axisHierarchies);
List<Dimension> otherHDimensions = CubeUtilities.getDimensions(value.getCube().getHierarchies());
otherHDimensions.removeAll(axisDimensions);
jgen.writeStartObject();
jgen.writeStringField(TABLE, table);
serializeAxis(ROWS, jgen,axis, Axis.ROWS);
serializeAxis(COLUMNS, jgen,axis, Axis.COLUMNS);
serializeDimensions(jgen, otherHDimensions, FILTERS_AXIS_POS, FILTERS, true, value);
jgen.writeNumberField(COLUMNSAXISORDINAL, Axis.COLUMNS.axisOrdinal());
jgen.writeNumberField(ROWSAXISORDINAL, Axis.ROWS.axisOrdinal());
jgen.writeObjectField(MODELCONFIG, modelConfig);
//build the query mdx
String mdxQuery = formatQueryString( value.getCurrentMdx());
jgen.writeStringField(MDXFORMATTED, mdxQuery);
jgen.writeEndObject();
} catch (Exception e) {
logger.error("Error serializing the pivot table", e);
throw new SpagoBIRuntimeException("Error serializing the pivot table", e);
}
logger.debug("OUT");
}
|
diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/ResourceHelper.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/ResourceHelper.java
index 59d3984ab..1b76b5833 100644
--- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/ResourceHelper.java
+++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/ResourceHelper.java
@@ -1,147 +1,147 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.filebuffers.tests;
import java.io.File;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import org.eclipse.core.internal.filebuffers.ContainerGenerator;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Plugin;
/**
* @since 3.0
*/
public class ResourceHelper {
private final static IProgressMonitor NULL_MONITOR= new NullProgressMonitor();
private static final int MAX_RETRY= 5;
public static IProject createProject(String projectName) throws CoreException {
IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
IProject project= root.getProject(projectName);
if (!project.exists())
project.create(NULL_MONITOR);
else
project.refreshLocal(IResource.DEPTH_INFINITE, null);
if (!project.isOpen())
project.open(NULL_MONITOR);
return project;
}
public static void deleteProject(String projectName) throws CoreException {
IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
IProject project= root.getProject(projectName);
if (project.exists())
delete(project);
}
public static void delete(final IProject project) throws CoreException {
delete(project, true);
}
public static void delete(final IProject project, boolean deleteContent) throws CoreException {
for (int i= 0; i < MAX_RETRY; i++) {
try {
project.delete(deleteContent, true, NULL_MONITOR);
i= MAX_RETRY;
} catch (CoreException x) {
if (i == MAX_RETRY - 1) {
FileBuffersTestPlugin.getDefault().getLog().log(x.getStatus());
- throw x;
+// throw x;
}
try {
Thread.sleep(1000); // sleep a second
} catch (InterruptedException e) {
}
}
}
}
public static IFolder createFolder(String folderPath) throws CoreException {
ContainerGenerator generator= new ContainerGenerator(ResourcesPlugin.getWorkspace(), new Path(folderPath));
IContainer container= generator.generateContainer(NULL_MONITOR);
if (container instanceof IFolder)
return (IFolder) container;
return null;
}
public static IFile createFile(IFolder folder, String name, String contents) throws CoreException {
IFile file= folder.getFile(name);
if (contents == null)
contents= "";
InputStream inputStream= new StringBufferInputStream(contents);
file.create(inputStream, true, NULL_MONITOR);
return file;
}
public static IFile createLinkedFile(IContainer container, IPath linkPath, File linkedFileTarget) throws CoreException {
IFile iFile= container.getFile(linkPath);
iFile.createLink(new Path(linkedFileTarget.getAbsolutePath()), IResource.ALLOW_MISSING_LOCAL, NULL_MONITOR);
return iFile;
}
public static IFile createLinkedFile(IContainer container, IPath linkPath, Plugin plugin, IPath linkedFileTargetPath) throws CoreException {
File file= FileTool.getFileInPlugin(plugin, linkedFileTargetPath);
IFile iFile= container.getFile(linkPath);
iFile.createLink(new Path(file.getAbsolutePath()), IResource.ALLOW_MISSING_LOCAL, NULL_MONITOR);
return iFile;
}
public static IFolder createLinkedFolder(IContainer container, IPath linkPath, File linkedFolderTarget) throws CoreException {
IFolder folder= container.getFolder(linkPath);
folder.createLink(new Path(linkedFolderTarget.getAbsolutePath()), IResource.ALLOW_MISSING_LOCAL, NULL_MONITOR);
return folder;
}
public static IFolder createLinkedFolder(IContainer container, IPath linkPath, Plugin plugin, IPath linkedFolderTargetPath) throws CoreException {
File file= FileTool.getFileInPlugin(plugin, linkedFolderTargetPath);
IFolder iFolder= container.getFolder(linkPath);
iFolder.createLink(new Path(file.getAbsolutePath()), IResource.ALLOW_MISSING_LOCAL, NULL_MONITOR);
return iFolder;
}
public static IProject createLinkedProject(String projectName, Plugin plugin, IPath linkPath) throws CoreException {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IProject project= workspace.getRoot().getProject(projectName);
IProjectDescription desc= workspace.newProjectDescription(projectName);
File file= FileTool.getFileInPlugin(plugin, linkPath);
IPath projectLocation= new Path(file.getAbsolutePath());
if (Platform.getLocation().equals(projectLocation))
projectLocation= null;
desc.setLocation(projectLocation);
project.create(desc, NULL_MONITOR);
if (!project.isOpen())
project.open(NULL_MONITOR);
return project;
}
}
| true | true | public static void delete(final IProject project, boolean deleteContent) throws CoreException {
for (int i= 0; i < MAX_RETRY; i++) {
try {
project.delete(deleteContent, true, NULL_MONITOR);
i= MAX_RETRY;
} catch (CoreException x) {
if (i == MAX_RETRY - 1) {
FileBuffersTestPlugin.getDefault().getLog().log(x.getStatus());
throw x;
}
try {
Thread.sleep(1000); // sleep a second
} catch (InterruptedException e) {
}
}
}
}
| public static void delete(final IProject project, boolean deleteContent) throws CoreException {
for (int i= 0; i < MAX_RETRY; i++) {
try {
project.delete(deleteContent, true, NULL_MONITOR);
i= MAX_RETRY;
} catch (CoreException x) {
if (i == MAX_RETRY - 1) {
FileBuffersTestPlugin.getDefault().getLog().log(x.getStatus());
// throw x;
}
try {
Thread.sleep(1000); // sleep a second
} catch (InterruptedException e) {
}
}
}
}
|
diff --git a/pmd/src/net/sourceforge/pmd/rules/OverrideBothEqualsAndHashcode.java b/pmd/src/net/sourceforge/pmd/rules/OverrideBothEqualsAndHashcode.java
index f7c817416..82e11ffac 100644
--- a/pmd/src/net/sourceforge/pmd/rules/OverrideBothEqualsAndHashcode.java
+++ b/pmd/src/net/sourceforge/pmd/rules/OverrideBothEqualsAndHashcode.java
@@ -1,83 +1,83 @@
package net.sourceforge.pmd.rules;
import net.sourceforge.pmd.AbstractRule;
import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
import net.sourceforge.pmd.ast.ASTFormalParameter;
import net.sourceforge.pmd.ast.ASTFormalParameters;
import net.sourceforge.pmd.ast.ASTImplementsList;
import net.sourceforge.pmd.ast.ASTMethodDeclarator;
import net.sourceforge.pmd.ast.SimpleNode;
import java.util.List;
public class OverrideBothEqualsAndHashcode extends AbstractRule {
private boolean implementsComparable = false;
private boolean containsEquals = false;
private boolean containsHashCode = false;
private SimpleNode nodeFound = null;
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
if (node.isInterface()) {
return data;
}
super.visit(node, data);
if (!implementsComparable && (containsEquals ^ containsHashCode)) {
if(nodeFound == null){
nodeFound = node;
}
addViolation(data, nodeFound);
}
implementsComparable = containsEquals = containsHashCode = false;
nodeFound = null;
return data;
}
public Object visit(ASTImplementsList node, Object data) {
for (int ix = 0; ix < node.jjtGetNumChildren(); ix++) {
if (node.jjtGetChild(ix).getClass().equals(ASTClassOrInterfaceType.class)
&& ((SimpleNode) node.jjtGetChild(ix)).hasImageEqualTo("Comparable")) {
implementsComparable = true;
return data;
}
}
return super.visit(node, data);
}
public Object visit(ASTMethodDeclarator node, Object data) {
if (implementsComparable) {
return data;
}
int iFormalParams = 0;
String paramName = null;
for (int ix = 0; ix < node.jjtGetNumChildren(); ix++) {
SimpleNode sn = (SimpleNode) node.jjtGetChild(ix);
if (sn.getClass().equals(ASTFormalParameters.class)) {
List allParams = ((ASTFormalParameters) sn).findChildrenOfType(ASTFormalParameter.class);
for (int i = 0; i < allParams.size(); i++) {
iFormalParams++;
ASTFormalParameter formalParam = (ASTFormalParameter) allParams.get(i);
ASTClassOrInterfaceType param = (ASTClassOrInterfaceType) formalParam.getFirstChildOfType(ASTClassOrInterfaceType.class);
if (param != null) {
paramName = param.getImage();
}
}
}
}
if (iFormalParams == 0 && node.hasImageEqualTo("hashCode")) {
containsHashCode = true;
nodeFound = node;
- } else if (iFormalParams == 1 && node.hasImageEqualTo("equals") && (paramName.equals("Object") || paramName.equals("java.lang.Object"))) {
+ } else if (iFormalParams == 1 && node.hasImageEqualTo("equals") && ("Object".equals(paramName) || "java.lang.Object".equals(paramName))) {
containsEquals = true;
nodeFound = node;
}
return super.visit(node, data);
}
}
| true | true | public Object visit(ASTMethodDeclarator node, Object data) {
if (implementsComparable) {
return data;
}
int iFormalParams = 0;
String paramName = null;
for (int ix = 0; ix < node.jjtGetNumChildren(); ix++) {
SimpleNode sn = (SimpleNode) node.jjtGetChild(ix);
if (sn.getClass().equals(ASTFormalParameters.class)) {
List allParams = ((ASTFormalParameters) sn).findChildrenOfType(ASTFormalParameter.class);
for (int i = 0; i < allParams.size(); i++) {
iFormalParams++;
ASTFormalParameter formalParam = (ASTFormalParameter) allParams.get(i);
ASTClassOrInterfaceType param = (ASTClassOrInterfaceType) formalParam.getFirstChildOfType(ASTClassOrInterfaceType.class);
if (param != null) {
paramName = param.getImage();
}
}
}
}
if (iFormalParams == 0 && node.hasImageEqualTo("hashCode")) {
containsHashCode = true;
nodeFound = node;
} else if (iFormalParams == 1 && node.hasImageEqualTo("equals") && (paramName.equals("Object") || paramName.equals("java.lang.Object"))) {
containsEquals = true;
nodeFound = node;
}
return super.visit(node, data);
}
| public Object visit(ASTMethodDeclarator node, Object data) {
if (implementsComparable) {
return data;
}
int iFormalParams = 0;
String paramName = null;
for (int ix = 0; ix < node.jjtGetNumChildren(); ix++) {
SimpleNode sn = (SimpleNode) node.jjtGetChild(ix);
if (sn.getClass().equals(ASTFormalParameters.class)) {
List allParams = ((ASTFormalParameters) sn).findChildrenOfType(ASTFormalParameter.class);
for (int i = 0; i < allParams.size(); i++) {
iFormalParams++;
ASTFormalParameter formalParam = (ASTFormalParameter) allParams.get(i);
ASTClassOrInterfaceType param = (ASTClassOrInterfaceType) formalParam.getFirstChildOfType(ASTClassOrInterfaceType.class);
if (param != null) {
paramName = param.getImage();
}
}
}
}
if (iFormalParams == 0 && node.hasImageEqualTo("hashCode")) {
containsHashCode = true;
nodeFound = node;
} else if (iFormalParams == 1 && node.hasImageEqualTo("equals") && ("Object".equals(paramName) || "java.lang.Object".equals(paramName))) {
containsEquals = true;
nodeFound = node;
}
return super.visit(node, data);
}
|
diff --git a/src/api/org/openmrs/arden/Call.java b/src/api/org/openmrs/arden/Call.java
index a34273b9..d3cfd227 100644
--- a/src/api/org/openmrs/arden/Call.java
+++ b/src/api/org/openmrs/arden/Call.java
@@ -1,106 +1,106 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.arden;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
*
*/
public class Call {
private String callVar = null;
private String callMethod = null;
private ArrayList<String> parameters = null;
public Call(String callVar, String callMethod) {
this.callVar = callVar;
this.callMethod = callMethod;
this.parameters = new ArrayList<String>();
}
public String getCallVar() {
return callVar;
}
public void setCallVar(String callVar) {
this.callVar = callVar;
}
public String getCallMethod() {
return callMethod;
}
public void setCallMethod(String callMethod) {
this.callMethod = callMethod;
}
public void write(Writer w) {
try {
w.append("\t\t\t\tString value = null;\n");
w.append("\t\t\t\tString variable = null;\n");
w.append("\t\t\t\tint varLen = 0;\n");
for (int i = 0; i < parameters.size(); i++) {
String currParam = parameters.get(i);
w.append("\t\t\t\tvarLen = " + "\"" + currParam + "\"" + ".length();\n");
w.append("\t\t\t\tvalue=userVarMap.get("+ "\"" + currParam + "\"" + ");\n");
w.append("\t\t\t\tif(value != null){\n");
w.append("\t\t\t\t\tparameters.put(\"param" + (i+1) + "\"," + "value);\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\t// It must be a result value or date\n");
w.append("\t\t\t\telse if(" + "\"" + currParam + "\"" + ".endsWith(\"_value\"))\n");
w.append("\t\t\t\t{\n");
w.append("\t\t\t\t\tvariable = "+ "\"" + currParam + "\"" + ".substring(0, varLen-6); // -6 for _value\n");
w.append("\t\t\t\t\tvalue = resultLookup.get(variable).toString();\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\telse if(variable.endsWith(\"_date\"))\n");
w.append("\t\t\t\t{\n");
w.append("\t\t\t\t\tvariable = " + "\"" + currParam + "\"" + ".substring(0, varLen-5); // -5 for _date\n");
w.append("\t\t\t\t\tvalue = resultLookup.get(variable).getResultDate().toString();\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\telse\n");
w.append("\t\t\t\t{\n");
- w.append("\t\t\t\t\tvalue = resultLookup.get(variable).toString();\n");
+ w.append("\t\t\t\t\tvalue = resultLookup.get(" +"\"" + currParam + "\"" + ").toString();\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\tif(value != null){\n");
w.append("\t\t\t\t\tparameters.put(\"param" + (i+1) + "\"," + "value);\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\telse\n");
w.append("\t\t\t\t{\n");
w.append("\t\t\t\t\tparameters.put(\"param" + (i+1) + "\",\"" + currParam + "\");\n");
w.append("\t\t\t\t}\n");
}
w.append("\t\t\t\t");
if (getCallVar() != null && getCallVar().length() > 0) {
w.append("Result " + getCallVar() + " = ");
}
w.append("logicService.eval(patient, \"" + getCallMethod()
+ "\",parameters);\n");
} catch (Exception e) {
}
}
public void addParameter(String parameter) {
this.parameters.add(parameter);
}
}
| true | true | public void write(Writer w) {
try {
w.append("\t\t\t\tString value = null;\n");
w.append("\t\t\t\tString variable = null;\n");
w.append("\t\t\t\tint varLen = 0;\n");
for (int i = 0; i < parameters.size(); i++) {
String currParam = parameters.get(i);
w.append("\t\t\t\tvarLen = " + "\"" + currParam + "\"" + ".length();\n");
w.append("\t\t\t\tvalue=userVarMap.get("+ "\"" + currParam + "\"" + ");\n");
w.append("\t\t\t\tif(value != null){\n");
w.append("\t\t\t\t\tparameters.put(\"param" + (i+1) + "\"," + "value);\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\t// It must be a result value or date\n");
w.append("\t\t\t\telse if(" + "\"" + currParam + "\"" + ".endsWith(\"_value\"))\n");
w.append("\t\t\t\t{\n");
w.append("\t\t\t\t\tvariable = "+ "\"" + currParam + "\"" + ".substring(0, varLen-6); // -6 for _value\n");
w.append("\t\t\t\t\tvalue = resultLookup.get(variable).toString();\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\telse if(variable.endsWith(\"_date\"))\n");
w.append("\t\t\t\t{\n");
w.append("\t\t\t\t\tvariable = " + "\"" + currParam + "\"" + ".substring(0, varLen-5); // -5 for _date\n");
w.append("\t\t\t\t\tvalue = resultLookup.get(variable).getResultDate().toString();\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\telse\n");
w.append("\t\t\t\t{\n");
w.append("\t\t\t\t\tvalue = resultLookup.get(variable).toString();\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\tif(value != null){\n");
w.append("\t\t\t\t\tparameters.put(\"param" + (i+1) + "\"," + "value);\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\telse\n");
w.append("\t\t\t\t{\n");
w.append("\t\t\t\t\tparameters.put(\"param" + (i+1) + "\",\"" + currParam + "\");\n");
w.append("\t\t\t\t}\n");
}
w.append("\t\t\t\t");
if (getCallVar() != null && getCallVar().length() > 0) {
w.append("Result " + getCallVar() + " = ");
}
w.append("logicService.eval(patient, \"" + getCallMethod()
+ "\",parameters);\n");
} catch (Exception e) {
}
}
| public void write(Writer w) {
try {
w.append("\t\t\t\tString value = null;\n");
w.append("\t\t\t\tString variable = null;\n");
w.append("\t\t\t\tint varLen = 0;\n");
for (int i = 0; i < parameters.size(); i++) {
String currParam = parameters.get(i);
w.append("\t\t\t\tvarLen = " + "\"" + currParam + "\"" + ".length();\n");
w.append("\t\t\t\tvalue=userVarMap.get("+ "\"" + currParam + "\"" + ");\n");
w.append("\t\t\t\tif(value != null){\n");
w.append("\t\t\t\t\tparameters.put(\"param" + (i+1) + "\"," + "value);\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\t// It must be a result value or date\n");
w.append("\t\t\t\telse if(" + "\"" + currParam + "\"" + ".endsWith(\"_value\"))\n");
w.append("\t\t\t\t{\n");
w.append("\t\t\t\t\tvariable = "+ "\"" + currParam + "\"" + ".substring(0, varLen-6); // -6 for _value\n");
w.append("\t\t\t\t\tvalue = resultLookup.get(variable).toString();\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\telse if(variable.endsWith(\"_date\"))\n");
w.append("\t\t\t\t{\n");
w.append("\t\t\t\t\tvariable = " + "\"" + currParam + "\"" + ".substring(0, varLen-5); // -5 for _date\n");
w.append("\t\t\t\t\tvalue = resultLookup.get(variable).getResultDate().toString();\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\telse\n");
w.append("\t\t\t\t{\n");
w.append("\t\t\t\t\tvalue = resultLookup.get(" +"\"" + currParam + "\"" + ").toString();\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\tif(value != null){\n");
w.append("\t\t\t\t\tparameters.put(\"param" + (i+1) + "\"," + "value);\n");
w.append("\t\t\t\t}\n");
w.append("\t\t\t\telse\n");
w.append("\t\t\t\t{\n");
w.append("\t\t\t\t\tparameters.put(\"param" + (i+1) + "\",\"" + currParam + "\");\n");
w.append("\t\t\t\t}\n");
}
w.append("\t\t\t\t");
if (getCallVar() != null && getCallVar().length() > 0) {
w.append("Result " + getCallVar() + " = ");
}
w.append("logicService.eval(patient, \"" + getCallMethod()
+ "\",parameters);\n");
} catch (Exception e) {
}
}
|
diff --git a/spock-maven/src/main/java/org/spockframework/buildsupport/maven/FindSpecksMojo.java b/spock-maven/src/main/java/org/spockframework/buildsupport/maven/FindSpecksMojo.java
index ac4839dd..f5901eda 100644
--- a/spock-maven/src/main/java/org/spockframework/buildsupport/maven/FindSpecksMojo.java
+++ b/spock-maven/src/main/java/org/spockframework/buildsupport/maven/FindSpecksMojo.java
@@ -1,93 +1,94 @@
package org.spockframework.buildsupport.maven;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.model.Plugin;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.spockframework.buildsupport.JUnit4TestClassFinder;
/**
* Finds all test classes that can be run with JUnit 4 (including but not
* limited to Spock specifications), and configures Surefire accordingly.
*
* @author Peter Niederwieser
* @goal find-specks
* @phase process-test-classes
*/
public class FindSpecksMojo extends AbstractMojo {
/**
* @parameter expression="${project}"
*/
MavenProject project;
/**
* @parameter expression="${project.build.testOutputDirectory}"
*/
File testOutputDirectory;
public void execute() throws MojoExecutionException {
List<File> tests;
try {
tests = new JUnit4TestClassFinder().findTestClasses(testOutputDirectory);
} catch (IOException e) {
- throw new MojoExecutionException("IO error while searching for test classes", e);
+ // chaining the exception would result in a cluttered error message
+ throw new MojoExecutionException(e.toString());
}
getLog().info(String.format("Found %d test classes", tests.size()));
Plugin plugin = getSurefirePlugin();
Xpp3Dom config = (Xpp3Dom)plugin.getConfiguration();
if (config == null) {
config = new Xpp3Dom("configuration");
plugin.setConfiguration(config);
}
Xpp3Dom includes = config.getChild("includes");
if (includes == null) {
includes = new Xpp3Dom("includes");
config.addChild(includes);
}
for (File test : tests) {
String relativePath = test.getAbsolutePath().substring(testOutputDirectory.getAbsolutePath().length() + 1);
String relativePathJavaExt = relativePath.substring(0, relativePath.length() - ".class".length()) + ".java";
Xpp3Dom includeNode = new Xpp3Dom("include");
includeNode.setValue(relativePathJavaExt);
includes.addChild(includeNode);
}
}
private Plugin getSurefirePlugin() throws MojoExecutionException {
@SuppressWarnings("unchecked")
List<Plugin> plugins = project.getBuildPlugins();
for (Plugin plugin : plugins)
if (plugin.getGroupId().equals("org.apache.maven.plugins")
&& plugin.getArtifactId().equals("maven-surefire-plugin"))
return plugin;
throw new MojoExecutionException("Surefire plugin not found");
}
}
| true | true | public void execute() throws MojoExecutionException {
List<File> tests;
try {
tests = new JUnit4TestClassFinder().findTestClasses(testOutputDirectory);
} catch (IOException e) {
throw new MojoExecutionException("IO error while searching for test classes", e);
}
getLog().info(String.format("Found %d test classes", tests.size()));
Plugin plugin = getSurefirePlugin();
Xpp3Dom config = (Xpp3Dom)plugin.getConfiguration();
if (config == null) {
config = new Xpp3Dom("configuration");
plugin.setConfiguration(config);
}
Xpp3Dom includes = config.getChild("includes");
if (includes == null) {
includes = new Xpp3Dom("includes");
config.addChild(includes);
}
for (File test : tests) {
String relativePath = test.getAbsolutePath().substring(testOutputDirectory.getAbsolutePath().length() + 1);
String relativePathJavaExt = relativePath.substring(0, relativePath.length() - ".class".length()) + ".java";
Xpp3Dom includeNode = new Xpp3Dom("include");
includeNode.setValue(relativePathJavaExt);
includes.addChild(includeNode);
}
}
| public void execute() throws MojoExecutionException {
List<File> tests;
try {
tests = new JUnit4TestClassFinder().findTestClasses(testOutputDirectory);
} catch (IOException e) {
// chaining the exception would result in a cluttered error message
throw new MojoExecutionException(e.toString());
}
getLog().info(String.format("Found %d test classes", tests.size()));
Plugin plugin = getSurefirePlugin();
Xpp3Dom config = (Xpp3Dom)plugin.getConfiguration();
if (config == null) {
config = new Xpp3Dom("configuration");
plugin.setConfiguration(config);
}
Xpp3Dom includes = config.getChild("includes");
if (includes == null) {
includes = new Xpp3Dom("includes");
config.addChild(includes);
}
for (File test : tests) {
String relativePath = test.getAbsolutePath().substring(testOutputDirectory.getAbsolutePath().length() + 1);
String relativePathJavaExt = relativePath.substring(0, relativePath.length() - ".class".length()) + ".java";
Xpp3Dom includeNode = new Xpp3Dom("include");
includeNode.setValue(relativePathJavaExt);
includes.addChild(includeNode);
}
}
|
diff --git a/src/edu/unc/genomics/wigmath/ValueDistribution.java b/src/edu/unc/genomics/wigmath/ValueDistribution.java
index 18640f6..48a4d8d 100644
--- a/src/edu/unc/genomics/wigmath/ValueDistribution.java
+++ b/src/edu/unc/genomics/wigmath/ValueDistribution.java
@@ -1,124 +1,125 @@
package edu.unc.genomics.wigmath;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.broad.igv.bbfile.WigItem;
import com.beust.jcommander.Parameter;
import edu.unc.genomics.CommandLineTool;
import edu.unc.genomics.io.WigFile;
import edu.unc.genomics.io.WigFileException;
import edu.unc.genomics.ngs.Autocorrelation;
import edu.unc.utils.FloatHistogram;
public class ValueDistribution extends CommandLineTool {
private static final Logger log = Logger.getLogger(Autocorrelation.class);
@Parameter(names = {"-i", "--input"}, description = "Input file", required = true)
public WigFile inputFile;
@Parameter(names = {"-l", "--min"}, description = "Minimum bin value")
public Float min;
@Parameter(names = {"-h", "--max"}, description = "Maximum bin value")
public Float max;
@Parameter(names = {"-n", "--bins"}, description = "Number of bins")
public int numBins = 40;
@Parameter(names = {"-o", "--output"}, description = "Output file")
public Path outputFile;
private double mean;
private double stdev;
private long N;
public void run() throws IOException {
log.debug("Generating histogram of Wig values");
if (min == null) {
min = (float) inputFile.min();
}
if (max == null) {
max = (float) inputFile.max();
}
FloatHistogram hist = new FloatHistogram(numBins, min, max);
N = inputFile.numBases();
mean = inputFile.mean();
stdev = inputFile.stdev();
// Also compute the skewness and kurtosis while going through the values
double sumOfCubeOfDeviances = 0;
double sumOfFourthOfDeviances = 0;
for (String chr : inputFile.chromosomes()) {
int start = inputFile.getChrStart(chr);
int stop = inputFile.getChrStop(chr);
log.debug("Processing chromosome " + chr + " region " + start + "-" + stop);
// Process the chromosome in chunks
int bp = start;
while (bp < stop) {
int chunkStart = bp;
int chunkStop = Math.min(bp+DEFAULT_CHUNK_SIZE-1, stop);
log.debug("Processing chunk "+chr+":"+chunkStart+"-"+chunkStop);
Iterator<WigItem> iter;
try {
iter = inputFile.query(chr, chunkStart, chunkStop);
} catch (WigFileException e) {
e.printStackTrace();
throw new RuntimeException("Error getting data from Wig file!");
}
while (iter.hasNext()) {
WigItem item = iter.next();
for (int i = item.getStartBase(); i <= item.getEndBase(); i++) {
- if (i >= chunkStart && i <= chunkStop) {
- hist.addValue(item.getWigValue());
+ float value = item.getWigValue();
+ if (i >= chunkStart && i <= chunkStop && !Float.isNaN(value) && !Float.isInfinite(value)) {
+ hist.addValue(value);
double deviance = item.getWigValue() - mean;
double cubeOfDeviance = Math.pow(deviance, 3);
sumOfCubeOfDeviances += cubeOfDeviance;
sumOfFourthOfDeviances += deviance*cubeOfDeviance;
}
}
}
bp = chunkStop + 1;
}
}
double skewness = (sumOfCubeOfDeviances/N) / Math.pow(stdev,3);
double kurtosis = (sumOfFourthOfDeviances/N) / Math.pow(stdev,4);
if (outputFile != null) {
log.debug("Writing to output file");
try (BufferedWriter writer = Files.newBufferedWriter(outputFile, Charset.defaultCharset())) {
// Output the moments of the distribution
writer.write("Moments:\t<w> = " + inputFile.mean());
writer.newLine();
- writer.write("\tvar(w) = " + inputFile.stdev()*inputFile.stdev());
+ writer.write("\t\tvar(w) = " + inputFile.stdev()*inputFile.stdev());
writer.newLine();
- writer.write("\tskew(w) = " + skewness);
+ writer.write("\t\tskew(w) = " + skewness);
writer.newLine();
- writer.write("\tkur(w) = " + kurtosis);
+ writer.write("\t\tkur(w) = " + kurtosis);
writer.newLine();
writer.write("Histogram:");
writer.newLine();
writer.write(hist.toString());
}
} else {
System.out.println(hist.toString());
}
inputFile.close();
}
public static void main(String[] args) throws IOException, WigFileException {
new ValueDistribution().instanceMain(args);
}
}
| false | true | public void run() throws IOException {
log.debug("Generating histogram of Wig values");
if (min == null) {
min = (float) inputFile.min();
}
if (max == null) {
max = (float) inputFile.max();
}
FloatHistogram hist = new FloatHistogram(numBins, min, max);
N = inputFile.numBases();
mean = inputFile.mean();
stdev = inputFile.stdev();
// Also compute the skewness and kurtosis while going through the values
double sumOfCubeOfDeviances = 0;
double sumOfFourthOfDeviances = 0;
for (String chr : inputFile.chromosomes()) {
int start = inputFile.getChrStart(chr);
int stop = inputFile.getChrStop(chr);
log.debug("Processing chromosome " + chr + " region " + start + "-" + stop);
// Process the chromosome in chunks
int bp = start;
while (bp < stop) {
int chunkStart = bp;
int chunkStop = Math.min(bp+DEFAULT_CHUNK_SIZE-1, stop);
log.debug("Processing chunk "+chr+":"+chunkStart+"-"+chunkStop);
Iterator<WigItem> iter;
try {
iter = inputFile.query(chr, chunkStart, chunkStop);
} catch (WigFileException e) {
e.printStackTrace();
throw new RuntimeException("Error getting data from Wig file!");
}
while (iter.hasNext()) {
WigItem item = iter.next();
for (int i = item.getStartBase(); i <= item.getEndBase(); i++) {
if (i >= chunkStart && i <= chunkStop) {
hist.addValue(item.getWigValue());
double deviance = item.getWigValue() - mean;
double cubeOfDeviance = Math.pow(deviance, 3);
sumOfCubeOfDeviances += cubeOfDeviance;
sumOfFourthOfDeviances += deviance*cubeOfDeviance;
}
}
}
bp = chunkStop + 1;
}
}
double skewness = (sumOfCubeOfDeviances/N) / Math.pow(stdev,3);
double kurtosis = (sumOfFourthOfDeviances/N) / Math.pow(stdev,4);
if (outputFile != null) {
log.debug("Writing to output file");
try (BufferedWriter writer = Files.newBufferedWriter(outputFile, Charset.defaultCharset())) {
// Output the moments of the distribution
writer.write("Moments:\t<w> = " + inputFile.mean());
writer.newLine();
writer.write("\tvar(w) = " + inputFile.stdev()*inputFile.stdev());
writer.newLine();
writer.write("\tskew(w) = " + skewness);
writer.newLine();
writer.write("\tkur(w) = " + kurtosis);
writer.newLine();
writer.write("Histogram:");
writer.newLine();
writer.write(hist.toString());
}
} else {
System.out.println(hist.toString());
}
inputFile.close();
}
| public void run() throws IOException {
log.debug("Generating histogram of Wig values");
if (min == null) {
min = (float) inputFile.min();
}
if (max == null) {
max = (float) inputFile.max();
}
FloatHistogram hist = new FloatHistogram(numBins, min, max);
N = inputFile.numBases();
mean = inputFile.mean();
stdev = inputFile.stdev();
// Also compute the skewness and kurtosis while going through the values
double sumOfCubeOfDeviances = 0;
double sumOfFourthOfDeviances = 0;
for (String chr : inputFile.chromosomes()) {
int start = inputFile.getChrStart(chr);
int stop = inputFile.getChrStop(chr);
log.debug("Processing chromosome " + chr + " region " + start + "-" + stop);
// Process the chromosome in chunks
int bp = start;
while (bp < stop) {
int chunkStart = bp;
int chunkStop = Math.min(bp+DEFAULT_CHUNK_SIZE-1, stop);
log.debug("Processing chunk "+chr+":"+chunkStart+"-"+chunkStop);
Iterator<WigItem> iter;
try {
iter = inputFile.query(chr, chunkStart, chunkStop);
} catch (WigFileException e) {
e.printStackTrace();
throw new RuntimeException("Error getting data from Wig file!");
}
while (iter.hasNext()) {
WigItem item = iter.next();
for (int i = item.getStartBase(); i <= item.getEndBase(); i++) {
float value = item.getWigValue();
if (i >= chunkStart && i <= chunkStop && !Float.isNaN(value) && !Float.isInfinite(value)) {
hist.addValue(value);
double deviance = item.getWigValue() - mean;
double cubeOfDeviance = Math.pow(deviance, 3);
sumOfCubeOfDeviances += cubeOfDeviance;
sumOfFourthOfDeviances += deviance*cubeOfDeviance;
}
}
}
bp = chunkStop + 1;
}
}
double skewness = (sumOfCubeOfDeviances/N) / Math.pow(stdev,3);
double kurtosis = (sumOfFourthOfDeviances/N) / Math.pow(stdev,4);
if (outputFile != null) {
log.debug("Writing to output file");
try (BufferedWriter writer = Files.newBufferedWriter(outputFile, Charset.defaultCharset())) {
// Output the moments of the distribution
writer.write("Moments:\t<w> = " + inputFile.mean());
writer.newLine();
writer.write("\t\tvar(w) = " + inputFile.stdev()*inputFile.stdev());
writer.newLine();
writer.write("\t\tskew(w) = " + skewness);
writer.newLine();
writer.write("\t\tkur(w) = " + kurtosis);
writer.newLine();
writer.write("Histogram:");
writer.newLine();
writer.write(hist.toString());
}
} else {
System.out.println(hist.toString());
}
inputFile.close();
}
|
diff --git a/src/main/ed/js/engine/Convert.java b/src/main/ed/js/engine/Convert.java
index 30a660c20..31366e66e 100644
--- a/src/main/ed/js/engine/Convert.java
+++ b/src/main/ed/js/engine/Convert.java
@@ -1,1308 +1,1314 @@
// Convert.java
package ed.js.engine;
import java.io.*;
import java.util.*;
import org.mozilla.javascript.*;
import ed.js.*;
import ed.io.*;
import ed.util.*;
public class Convert {
static boolean D = Boolean.getBoolean( "DEBUG.JS" );
public Convert( File sourceFile )
throws IOException {
this( sourceFile.toString() , StreamUtil.readFully( sourceFile , "UTF-8" ) );
}
public Convert( String name , String source )
throws IOException {
_name = name;
_source = source;
_className = _name.replaceAll(".*/(.*?)","").replaceAll( "[^\\w]+" , "_" );
CompilerEnvirons ce = new CompilerEnvirons();
Parser p = new Parser( ce , ce.getErrorReporter() );
ScriptOrFnNode theNode = p.parse( _source , _name , 0 );
_encodedSource = p.getEncodedSource();
init( theNode );
}
private void init( ScriptOrFnNode sn ){
if ( _it != null )
throw new RuntimeException( "too late" );
NodeTransformer nf = new NodeTransformer();
nf.transform( sn );
if ( D ){
Debug.print( sn , 0 );
}
State state = new State();
_setLineNumbers( sn , sn );
_addFunctionNodes( sn , state );
if ( D ) System.out.println( "***************" );
Node n = sn.getFirstChild();
while ( n != null ){
if ( n.getType() != Token.FUNCTION ){
if ( n.getNext() == null &&
n.getType() == Token.EXPR_RESULT ){
_append( "return " , n );
_hasReturn = true;
}
_add( n , sn , state );
_append( "\n" , n );
}
n = n.getNext();
}
if ( ! _hasReturn ) {
_append( "return null;" , sn );
}
else {
int end = _mainJavaCode.length() - 1;
boolean alreadyHaveOne = false;
for ( ; end >= 0; end-- ){
char c = _mainJavaCode.charAt( end );
if ( Character.isWhitespace( c ) )
continue;
if ( c == ';' ){
if ( ! alreadyHaveOne ){
alreadyHaveOne = true;
continue;
}
_mainJavaCode.setLength( end + 1 );
}
break;
}
}
}
private void _add( Node n , State s ){
_add( n , null , s );
}
private void _add( Node n , ScriptOrFnNode sn , State state ){
switch ( n.getType() ){
case Token.TYPEOF:
_append( "JS_typeof( " , n );
_assertOne( n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.TYPEOFNAME:
_append( "JS_typeof( " , n );
if ( state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
_append( " ) " , n );
break;
case Token.REGEXP:
int myId = _regex.size();
ScriptOrFnNode parent = _nodeToSOR.get( n );
int rId = n.getIntProp( Node.REGEXP_PROP , -1 );
_regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) );
_append( " _regex[" + myId + "] " , n );
break;
case Token.ARRAYLIT:
{
_append( "( JSArray.create( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) ) " , n );
}
break;
case Token.OBJECTLIT:
{
_append( "JS_buildLiteralObject( new String[]{ " , n );
boolean first = true;
for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){
if ( first )
first = false;
else
_append( " , " , n );
_append( "\"" + id.toString() + "\"" , n );
}
_append( " } " , n );
Node c = n.getFirstChild();
while ( c != null ){
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) " , n );
}
break;
case Token.NEW:
_append( "scope.clearThisNew( " , n );
_addCall( n , state , true );
_append( " ) " , n );
break;
case Token.THIS:
_append( "passedIn.getThis()" , n );
break;
case Token.INC:
case Token.DEC:
_assertOne( n );
Node tempChild = n.getFirstChild();
if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) &&
state.useLocalVariable( tempChild.getString() ) )
throw new RuntimeException( "can't increment local variables" );
_append( "JS_inc( " , n );
_createRef( n.getFirstChild() , state );
_append( " , " , n );
_append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n );
_append( " , " , n );
_append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n );
_append( ")" , n );
break;
case Token.USE_STACK:
_append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n );
break;
case Token.SETPROP_OP:
case Token.SETELEM_OP:
Node theOp = n.getFirstChild().getNext().getNext();
if ( theOp.getType() == Token.ADD &&
( theOp.getFirstChild().getType() == Token.USE_STACK ||
theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){
_append( "\n" , n );
_append( "JS_setDefferedPlus( (JSObject) " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( theOp.getFirstChild().getType() == Token.USE_STACK ?
theOp.getFirstChild().getNext() :
theOp.getFirstChild() ,
state );
_append( " \n ) \n" , n );
break;
}
_append( "\n { \n" , n );
_append( "JSObject __tempObject = (JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
String tempName = "__temp" + (int)(Math.random() * 10000);
state._tempOpNames.push( tempName );
_append( "Object " + tempName + " = " , n );
_add( n.getFirstChild().getNext() , state );
_append( ";\n" , n );
_append( " __tempObject.set(" , n );
_append( tempName , n );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ); \n" , n );
_append( " } \n" , n );
break;
case Token.SETPROP:
case Token.SETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").set( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ); " , n );
break;
case Token.GETPROPNOWARN:
case Token.GETPROP:
case Token.GETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").get( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )" , n );
break;
case Token.EXPR_RESULT:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.CALL:
_addCall( n , state );
break;
case Token.NUMBER:
String temp = String.valueOf( n.getDouble() );
if ( temp.endsWith( ".0" ) )
temp = "Integer.valueOf( " + temp.substring( 0 , temp.length() - 2 ) + " ) ";
else
temp = "Double.valueOf( " + temp + " ) ";
_append( temp , n );
break;
case Token.STRING:
int stringId = _strings.size();
_strings.add( n.getString() );
_append( "_strings[" + stringId + "]" ,n );
break;
case Token.TRUE:
_append( " true " , n );
break;
case Token.FALSE:
_append( " false " , n );
break;
case Token.NULL:
_append( " null " , n );
break;
case Token.VAR:
_addVar( n , state );
break;
case Token.GETVAR:
if ( state.useLocalVariable( n.getString() ) ){
_append( n.getString() , n );
break;
}
case Token.NAME:
if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
break;
case Token.SETVAR:
final String foo = n.getFirstChild().getString();
if ( state.useLocalVariable( foo ) ){
if ( ! state.hasSymbol( foo ) )
throw new RuntimeException( "something is wrong" );
_append( foo + " = " , n );
_add( n.getFirstChild().getNext() , state );
_append( "\n" , n );
}
else {
_setVar( foo ,
n.getFirstChild().getNext() ,
state , true );
}
break;
case Token.SETNAME:
_addSet( n , state );
break;
case Token.FUNCTION:
_addFunction( n , state );
break;
case Token.BLOCK:
_addBlock( n , state );
break;
case Token.EXPR_VOID:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.RETURN:
+ boolean last = n.getNext() == null;
+ if ( ! last )
+ _append( "if ( true ) { " , n );
_append( "return " , n );
if ( n.getFirstChild() != null ){
_assertOne( n );
_add( n.getFirstChild() , state );
}
else {
_append( " null " , n );
}
- _append( ";\n" , n );
+ _append( ";" , n );
+ if ( ! last )
+ _append( "}" , n );
+ _append( "\n" , n );
break;
case Token.BITNOT:
_assertOne( n );
_append( "JS_bitnot( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.HOOK:
_append( " ( JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ? ( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) : ( " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ) ) " , n );
break;
case Token.NE:
_append( " ! " , n );
case Token.MUL:
case Token.DIV:
case Token.ADD:
case Token.SUB:
case Token.EQ:
case Token.SHEQ:
case Token.GE:
case Token.LE:
case Token.LT:
case Token.GT:
case Token.BITOR:
case Token.BITAND:
case Token.BITXOR:
case Token.URSH:
case Token.RSH:
case Token.LSH:
case Token.MOD:
_append( "JS_" , n );
String fooooo = _2ThingThings.get( n.getType() );
if ( fooooo == null )
throw new RuntimeException( "noting for : " + n );
_append( fooooo , n );
_append( "\n( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )\n " , n );
break;
case Token.IFNE:
_addIFNE( n , state );
break;
case Token.LOOP:
_addLoop( n , state );
break;
case Token.EMPTY:
if ( n.getFirstChild() != null ){
Debug.printTree( n , 0 );
throw new RuntimeException( "not really empty" );
}
break;
case Token.LABEL:
_append( n.getString() + ":" , n );
break;
case Token.BREAK:
_append( "break " + n.getString() + ";\n" , n );
break;
case Token.CONTINUE:
_append( "continue " + n.getString() + ";\n" , n );
break;
case Token.WHILE:
_append( "while( JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ) " , n );
_add( n.getFirstChild().getNext() , state );
break;
case Token.FOR:
_addFor( n , state );
break;
case Token.TARGET:
break;
case Token.NOT:
_assertOne( n );
_append( " ! JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.AND:
_append( " ( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " && " , n );
_append( " JS_evalToBool( " , n );
_add( c , state );
_append( " ) " , n );
c = c.getNext();
}
_append( " ) " , n );
break;
case Token.OR:
Node cc = n.getFirstChild();
if ( cc.getNext() == null )
throw new RuntimeException( "what?" );
if ( cc.getNext().getNext() != null )
throw new RuntimeException( "what?" );
_append( "( scope.orSave( " , n );
_add( cc , state );
_append( " ) ? scope.getOrSave() : ( " , n );
_add( cc.getNext() , state );
_append( " ) ) " , n );
break;
case Token.LOCAL_BLOCK:
_assertOne( n );
if ( n.getFirstChild().getType() != Token.TRY )
throw new RuntimeException("only know about LOCAL_BLOCK with try" );
_addTry( n.getFirstChild() , state );
break;
case Token.THROW:
_append( "throw new JSException( " , n );
_add( n.getFirstChild() , state );
_append( " ); " , n );
break;
case Token.INSTANCEOF:
_append( "JS_instanceof( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
if ( n.getFirstChild().getNext().getNext() != null )
throw new RuntimeException( "something is wrong" );
break;
case Token.DELPROP:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( " ).removeField( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
break;
default:
Debug.printTree( n , 0 );
throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() );
}
}
private void _createRef( Node n , State state ){
if ( n.getType() == Token.NAME || n.getType() == Token.GETVAR ){
if ( state.useLocalVariable( n.getString() ) )
throw new RuntimeException( "can't create a JSRef from a local variable : " + n.getString() );
_append( " new JSRef( scope , null , " , n );
_append( "\"" + n.getString() + "\"" , n );
_append( " ) " , n );
return;
}
if ( n.getType() == Token.GETPROP ||
n.getType() == Token.GETELEM ){
_append( " new JSRef( scope , (JSObject)" , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
return;
}
throw new RuntimeException( "can't handle" );
}
private void _addTry( Node n , State state ){
_assertType( n , Token.TRY );
Node mainBlock = n.getFirstChild();
_assertType( mainBlock , Token.BLOCK );
_append( "try { \n " , n );
_add( mainBlock , state );
_append( " \n } \n " , n );
n = mainBlock.getNext();
while ( n != null ){
if ( n.getType() == Token.FINALLY ){
_assertType( n.getFirstChild() , Token.BLOCK );
_append( "finally { \n" , n );
_add( n.getFirstChild() , state );
_append( " \n } \n " , n );
n = n.getNext();
continue;
}
if ( n.getType() == Token.LOCAL_BLOCK &&
n.getFirstChild().getType() == Token.CATCH_SCOPE ){
Node c = n.getFirstChild();
Node b = c.getNext();
_assertType( b , Token.BLOCK );
_assertType( b.getFirstChild() , Token.ENTERWITH );
_assertType( b.getFirstChild().getNext() , Token.WITH );
b = b.getFirstChild().getNext().getFirstChild();
_assertType( b , Token.BLOCK );
//Debug.printTree( b , 0 );
String jsName = c.getFirstChild().getString();
String javaName = "javaEEE" + jsName;
_append( " catch ( Throwable " + javaName + " ){ \n " , c );
_append( " if ( " + javaName + " instanceof JSException ) " , c );
_append( " scope.put( \"" + jsName + "\" , ((JSException)" + javaName + ").getObject() , true ); " , c );
_append( " else \n " , c );
_append( " scope.put( \"" + jsName + "\" , " + javaName + " , true ); " , c );
b = b.getFirstChild();
while ( b != null ){
if ( b.getType() == Token.LEAVEWITH )
break;
_add( b , state );
b = b.getNext();
}
_append( " } \n " , c );
n = n.getNext();
continue;
}
if ( n.getType() == Token.GOTO ||
n.getType() == Token.TARGET ||
n.getType() == Token.JSR ){
n = n.getNext();
continue;
}
throw new RuntimeException( "what : " + n.getType() );
}
}
private void _addFor( Node n , State state ){
_assertType( n , Token.FOR );
final int numChildren = countChildren( n );
if ( numChildren == 4 ){
_append( "\n for ( " , n );
if ( n.getFirstChild().getType() == Token.BLOCK )
_add( n.getFirstChild().getFirstChild() , state );
else {
_add( n.getFirstChild() , state );
_append( " ; " , n );
}
_append( " \n JS_evalToBool( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) ; \n" , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " )\n " , n );
_add( n.getFirstChild().getNext().getNext().getNext() , state );
}
else if ( numChildren == 3 ){
String name = n.getFirstChild().getString();
String tempName = name + "TEMP";
_append( "\n for ( String " , n );
_append( tempName , n );
_append( " : ((JSObject)" , n );
_add( n.getFirstChild().getNext() , state );
_append( " ).keySet() ){\n " , n );
if ( state.useLocalVariable( name ) )
_append( name + " = new JSString( " + tempName + ") ; " , n );
else
_append( "scope.put( \"" + name + "\" , new JSString( " + tempName + " ) , true );\n" , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( "\n}\n" , n );
}
else {
throw new RuntimeException( "wtf?" );
}
}
private void _addLoop( Node n , State state ){
_assertType( n , Token.LOOP );
final Node theLoop = n;
n = n.getFirstChild();
Node nodes[] = null;
if ( ( nodes = _matches( n , _while1 ) ) != null ){
Node main = nodes[1];
Node predicate = nodes[5];
_append( "while ( JS_evalToBool( " , theLoop );
_add( predicate.getFirstChild() , state );
_append( " ) ) " , theLoop );
_add( main , state );
}
else if ( ( nodes = _matches( n , _doWhile1 ) ) != null ){
Node main = nodes[1];
Node predicate = nodes[3];
_assertType( predicate , Token.IFEQ );
_append( "do \n " , theLoop );
_add( main , state );
_append( " \n while ( JS_evalToBool( " , n );
_add( predicate.getFirstChild() , state );
_append( " ) );\n " , n );
}
else {
throw new RuntimeException( "what?" );
}
}
private void _addIFNE( Node n , State state ){
_assertType( n , Token.IFNE );
final Node.Jump theIf = (Node.Jump)n;
_assertOne( n ); // this is the predicate
Node ifBlock = n.getNext();
_append( "if ( JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ){\n" , n );
_add( ifBlock , state );
_append( "}\n" , n );
n = n.getNext().getNext();
if ( n.getType() == Token.TARGET ){
if ( n.getNext() != null )
throw new RuntimeException( "something is wrong" );
return;
}
_assertType( n , Token.GOTO );
_assertType( n.getNext() , Token.TARGET );
if ( theIf.target.hashCode() != n.getNext().hashCode() )
throw new RuntimeException( "hashes don't match" );
n = n.getNext().getNext();
_append( " else { " , n );
_add( n , state );
_append( " } \n" , n );
_assertType( n.getNext() , Token.TARGET );
if ( n.getNext().getNext() != null )
throw new RuntimeException( "something is wrong" );
}
private void _addFunctionNodes( ScriptOrFnNode sn , State state ){
for ( int i=0; i<sn.getFunctionCount(); i++ ){
FunctionNode fn = sn.getFunctionNode( i );
_setLineNumbers( fn , fn );
String name = fn.getFunctionName();
if ( name.length() == 0 )
name = "tempFunc_" + _id + "_" + i + "_" + _methodId++;
state._functionIdToName.put( i , name );
if ( D ){
System.out.println( "***************" );
System.out.println( i + " : " + name );
}
_setVar( name , fn , state );
_append( "; \n scope.getFunction( \"" + name + "\" ).setName( \"" + name + "\" );\n\n" , fn );
}
}
private void _addFunction( Node n , State state ){
if ( ! ( n instanceof FunctionNode ) ){
_append( getFunc( n , state ) , n );
return;
}
FunctionNode fn = (FunctionNode)n;
_assertOne( n );
state = state.child();
state._hasLambdaExpressions = fn.getFunctionCount() > 0;
boolean hasArguments = false;
{
List<Node> toSearch = new ArrayList<Node>();
toSearch.add( n );
while ( toSearch.size() > 0 ){
Node cur = toSearch.remove( toSearch.size() - 1 );
if ( cur.getType() == Token.NAME ||
cur.getType() == Token.GETVAR )
if ( cur.getString().equals( "arguments" ) )
hasArguments = true;
if ( cur.getType() == Token.INC )
if ( cur.getFirstChild().getType() == Token.GETVAR ||
cur.getFirstChild().getType() == Token.NAME )
state.addBadLocal( cur.getFirstChild().getString() );
if ( cur.getNext() != null )
toSearch.add( cur.getNext() );
if ( cur.getFirstChild() != null )
toSearch.add( cur.getFirstChild() );
}
}
//state.debug();
_append( "new JSFunctionCalls" + fn.getParamCount() + "( scope , null ){ \n" , n );
String callLine = "public Object call( final Scope passedIn ";
String varSetup = "";
for ( int i=0; i<fn.getParamCount(); i++ ){
final String foo = fn.getParamOrVarName( i );
callLine += " , ";
callLine += " Object " + foo;
if ( ! state.useLocalVariable( foo ) ){
callLine += "INNNNN";
varSetup += " \nscope.put(\"" + foo + "\"," + foo + "INNNNN , true );\n ";
if ( hasArguments )
varSetup += "arguments.add( " + foo + "INNNNN );\n";
}
else {
state.addSymbol( foo );
if ( hasArguments )
varSetup += "arguments.add( " + foo + " );\n";
}
callLine += " ";
}
callLine += " , Object extra[] ){\n" ;
_append( callLine + " final Scope scope = new Scope( \"temp scope for: \" + _name , _scope , passedIn ); " , n );
if ( hasArguments ){
_append( "JSArray arguments = new JSArray();\n" , n );
_append( "scope.put( \"arguments\" , arguments , true );\n" , n );
}
_append( varSetup , n );
if ( hasArguments )
_append( "if ( extra != null ) for ( Object TTTT : extra ) arguments.add( TTTT );\n" , n );
for ( int i=fn.getParamCount(); i<fn.getParamAndVarCount(); i++ ){
final String foo = fn.getParamOrVarName( i );
if ( state.useLocalVariable( foo ) ){
state.addSymbol( foo );
_append( "Object " + foo + " = null;\n" , n );
}
}
_addFunctionNodes( fn , state );
_add( n.getFirstChild() , state );
_append( "}\n" , n );
int myStringId = _strings.size();
_strings.add( getSource( fn ) );
_append( "\t public String toString(){ return _strings[" + myStringId + "].toString(); }" , fn );
_append( "}\n" , n );
}
private void _addBlock( Node n , State state ){
_assertType( n , Token.BLOCK );
if ( n.getFirstChild() == null )
return;
// this is weird. look at bracing0.js
boolean bogusBrace = true;
Node c = n.getFirstChild();
while ( c != null ){
if ( c.getType() != Token.EXPR_VOID ){
bogusBrace = false;
break;
}
if ( c.getFirstChild().getNext() != null ){
bogusBrace = false;
break;
}
if ( c.getFirstChild().getType() != Token.SETVAR ){
bogusBrace = false;
break;
}
c = c.getNext();
}
bogusBrace = bogusBrace ||
( n.getFirstChild().getNext() == null &&
n.getFirstChild().getType() == Token.EXPR_VOID &&
n.getFirstChild().getFirstChild() == null );
if ( bogusBrace ){
c = n.getFirstChild();
while ( c != null ){
_add( c , state );
c = c.getNext();
}
return;
}
_append( "{" , n );
Node child = n.getFirstChild();
while ( child != null ){
_add( child , state );
if ( child.getType() == Token.IFNE )
break;
child = child.getNext();
}
_append( "}" , n );
}
private void _addSet( Node n , State state ){
_assertType( n , Token.SETNAME );
Node name = n.getFirstChild();
_setVar( name.getString() , name.getNext() , state );
}
private void _addVar( Node n , State state ){
_assertType( n , Token.VAR );
_assertOne( n );
Node name = n.getFirstChild();
_assertOne( name );
_setVar( name.getString() , name.getFirstChild() , state );
}
private void _addCall( Node n , State state ){
_addCall( n , state , false );
}
private void _addCall( Node n , State state , boolean isClass ){
Node name = n.getFirstChild();
boolean useThis = name.getType() == Token.GETPROP && ! isClass;
if ( useThis )
_append( "scope.clearThisNormal( " , n );
Boolean inc[] = new Boolean[]{ true };
String f = getFunc( name , state , isClass , inc );
_append( ( inc[0] ? f : "" ) + ".call( scope" + ( isClass ? ".newThis( " + f + " )" : "" ) + " " , n );
Node param = name.getNext();
while ( param != null ){
_append( " , " , param );
_add( param , state );
param = param.getNext();
}
_append( " ) " , n );
if ( useThis )
_append( " ) " , n );
}
private void _setVar( String name , Node val , State state ){
_setVar( name , val , state , false );
}
private void _setVar( String name , Node val , State state , boolean local ){
if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ){
_append( name + " = " , val );
_add( val , state );
_append( ";\n" , val );
return;
}
_append( "scope.put( \"" + name + "\" , " , val);
_add( val , state );
_append( " , " + local + " ) " , val );
}
private int countChildren( Node n ){
int num = 0;
Node c = n.getFirstChild();
while ( c != null ){
num++;
c = c.getNext();
}
return num;
}
public static void _assertOne( Node n ){
if ( n.getFirstChild() == null ){
Debug.printTree( n , 0 );
throw new RuntimeException( "no child" );
}
if ( n.getFirstChild().getNext() != null ){
Debug.printTree( n , 0 );
throw new RuntimeException( "more than 1 child" );
}
}
public static void _assertType( Node n , int type ){
if ( type != n.getType() )
throw new RuntimeException( "wrong type" );
}
private void _setLineNumbers( Node n , final ScriptOrFnNode sof ){
final int line = n.getLineno();
if ( line < 0 )
throw new RuntimeException( "something is wrong" );
List<Node> todo = new LinkedList<Node>();
_nodeToSourceLine.put( n , line );
_nodeToSOR.put( n , sof );
if ( n.getFirstChild() != null )
todo.add( n.getFirstChild() );
if ( n.getNext() != null )
todo.add( n.getNext() );
while ( todo.size() > 0 ){
n = todo.remove(0);
if ( n.getLineno() > 0 ){
_setLineNumbers( n , n instanceof ScriptOrFnNode ? (ScriptOrFnNode)n : sof );
continue;
}
_nodeToSourceLine.put( n , line );
_nodeToSOR.put( n , sof );
if ( n.getFirstChild() != null )
todo.add( n.getFirstChild() );
if ( n.getNext() != null )
todo.add( n.getNext() );
}
}
private void _append( String s , Node n ){
_mainJavaCode.append( s );
int numLines = 0;
for ( int i=0; i<s.length(); i++ )
if ( s.charAt( i ) == '\n' )
numLines++;
final int start = _currentLineNumber;
final int end = _currentLineNumber + numLines;
for ( int i=start; i<end; i++ ){
List<Node> l = _javaCodeToLines.get( i );
if ( l == null ){
l = new ArrayList<Node>();
_javaCodeToLines.put( i , l );
}
l.add( n );
}
_currentLineNumber = end;
}
private String getFunc( Node n , State state ){
return getFunc( n , state , false , null );
}
private String getFunc( Node n , State state , boolean isClass , Boolean inc[] ){
if ( n.getClass().getName().indexOf( "StringNode" ) < 0 ){
if ( n.getType() == Token.GETPROP && ! isClass ){
_append( "scope.getFunctionAndSetThis( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( ".toString() ) " , n );
return "";
}
int start = _mainJavaCode.length();
_append( "((JSFunction )" , n);
_add( n , state );
_append( ")" , n );
int end = _mainJavaCode.length();
if( isClass ){
if ( inc == null )
throw new RuntimeException( "inc is null and can't be here" );
inc[0] = false;
return "(" + _mainJavaCode.substring( start , end ) + ")";
}
return "";
}
String name = n.getString();
if ( name == null || name.length() == 0 ){
int id = n.getIntProp( Node.FUNCTION_PROP , -1 );
if ( id == -1 )
throw new RuntimeException( "no name or id for this thing" );
name = state._functionIdToName.get( id );
if ( name == null || name.length() == 0 )
throw new RuntimeException( "no name for this id " );
}
if ( state.hasSymbol( name ) )
return "(( JSFunction)" + name + ")";
return "scope.getFunction( \"" + name + "\" )";
}
public String getClassName(){
return _className;
}
String getClassString(){
StringBuilder buf = new StringBuilder();
buf.append( "package " + _package + ";\n" );
buf.append( "import ed.js.*;\n" );
buf.append( "import ed.js.func.*;\n" );
buf.append( "import ed.js.engine.Scope;\n" );
buf.append( "import ed.js.engine.JSCompiledScript;\n" );
buf.append( "public class " ).append( _className ).append( " extends JSCompiledScript {\n" );
buf.append( "\tpublic Object _call( Scope scope , Object extra[] ){\n" );
buf.append( "\t\t final Scope passedIn = scope; \n" );
buf.append( "\t\t scope = new Scope( \"compiled script for:" + _name.replaceAll( "/tmp/jxp/s?/?0\\.\\d+/" , "" ) + "\" , scope ); \n" );
buf.append( "\t\t JSArray arguments = new JSArray(); scope.put( \"arguments\" , arguments , true );\n " );
buf.append( "\t\t if ( extra != null ) for ( Object TTTT : extra ) arguments.add( TTTT );\n" );
_preMainLines = StringUtil.count( buf.toString() , "\n" );
buf.append( _mainJavaCode );
buf.append( "\n\n\t}\n\n" );
buf.append( "\n}\n\n" );
return buf.toString();
}
public JSFunction get(){
if ( _it != null )
return _it;
try {
Class c = CompileUtil.compile( _package , getClassName() , getClassString() );
JSCompiledScript it = (JSCompiledScript)c.newInstance();
it._convert = this;
it._regex = new JSRegex[ _regex.size() ];
for ( int i=0; i<_regex.size(); i++ ){
Pair<String,String> p = _regex.get( i );
JSRegex foo = new JSRegex( p.first , p.second );
it._regex[i] = foo;
}
it._strings = new JSString[ _strings.size() ];
for ( int i=0; i<_strings.size(); i++ )
it._strings[i] = new JSString( _strings.get( i ) );
it.setName( _name );
_it = it;
return _it;
}
catch ( RuntimeException re ){
re.printStackTrace();
fixStack( re );
throw re;
}
catch ( Exception e ){
e.printStackTrace();
fixStack( e );
throw new RuntimeException( e );
}
}
public void fixStack( Throwable e ){
boolean removeThings = false;
StackTraceElement stack[] = e.getStackTrace();
boolean changed = false;
for ( int i=0; i<stack.length; i++ ){
StackTraceElement element = stack[i];
if ( element == null )
continue;
if ( element.toString().contains( ".call(JSFunctionCalls" ) ||
element.toString().contains( "ed.js.JSFunctionBase.call(" ) ||
element.toString().contains( "ed.js.engine.JSCompiledScript.call" ) ){
removeThings = true;
changed = true;
stack[i] = null;
continue;
}
final String file = getClassName() + ".java";
String es = element.toString();
if ( ! es.contains( file ) )
continue;
int line = StringParseUtil.parseInt( es.substring( es.lastIndexOf( ":" ) + 1 ) , -1 ) - _preMainLines;
List<Node> nodes = _javaCodeToLines.get( line );
if ( nodes == null )
continue;
// the +1 is for the way rhino stuff
line = _nodeToSourceLine.get( nodes.get(0) ) + 1;
ScriptOrFnNode sof = _nodeToSOR.get( nodes.get(0) );
String method = "___";
if ( sof instanceof FunctionNode )
method = ((FunctionNode)sof).getFunctionName();
stack[i] = new StackTraceElement( _name , method , _name , line );
changed = true;
}
if ( removeThings ){
List<StackTraceElement> lst = new ArrayList<StackTraceElement>();
for ( StackTraceElement s : stack ){
if ( s == null )
continue;
lst.add( s );
}
stack = new StackTraceElement[lst.size()];
for ( int i=0; i<stack.length; i++ )
stack[i] = lst.get(i);
}
if ( changed )
e.setStackTrace( stack );
}
String getSource( FunctionNode fn ){
final int start = fn.getEncodedSourceStart();
final int end = fn.getEncodedSourceEnd();
final String encoded = _encodedSource.substring( start , end );
final String realSource = Decompiler.decompile( encoded , 0 , new UintMap() );
return realSource;
}
public boolean hasReturn(){
return _hasReturn;
}
//final File _file;
final String _name;
final String _source;
final String _encodedSource;
final String _className;
final String _package = "ed.js.gen";
final int _id = ID++;
// these 3 variables should only be use by _append
private int _currentLineNumber = 0;
final Map<Integer,List<Node>> _javaCodeToLines = new TreeMap<Integer,List<Node>>();
final Map<Node,Integer> _nodeToSourceLine = new HashMap<Node,Integer>();
final Map<Node,ScriptOrFnNode> _nodeToSOR = new HashMap<Node,ScriptOrFnNode>();
final List<Pair<String,String>> _regex = new ArrayList<Pair<String,String>>();
final List<String> _strings = new ArrayList<String>();
int _preMainLines = -1;
private final StringBuilder _mainJavaCode = new StringBuilder();
private boolean _hasReturn = false;
private JSFunction _it;
private int _methodId = 0;
private static int ID = 1;
private final static Map<Integer,String> _2ThingThings = new HashMap<Integer,String>();
static {
_2ThingThings.put( Token.ADD , "add" );
_2ThingThings.put( Token.MUL , "mul" );
_2ThingThings.put( Token.SUB , "sub" );
_2ThingThings.put( Token.DIV , "div" );
_2ThingThings.put( Token.SHEQ , "sheq" );
_2ThingThings.put( Token.EQ , "eq" );
_2ThingThings.put( Token.NE , "eq" );
_2ThingThings.put( Token.GE , "ge" );
_2ThingThings.put( Token.LE , "le" );
_2ThingThings.put( Token.LT , "lt" );
_2ThingThings.put( Token.GT , "gt" );
_2ThingThings.put( Token.BITOR , "bitor" );
_2ThingThings.put( Token.BITAND , "bitand" );
_2ThingThings.put( Token.BITXOR , "bitxor" );
_2ThingThings.put( Token.URSH , "ursh" );
_2ThingThings.put( Token.RSH , "rsh" );
_2ThingThings.put( Token.LSH , "lsh" );
_2ThingThings.put( Token.MOD , "mod" );
}
private static final int _while1[] = new int[]{ Token.GOTO , Token.TARGET , 0 , 0 , Token.TARGET , Token.IFEQ , Token.TARGET };
private static final int _doWhile1[] = new int[]{ Token.TARGET , 0 , Token.TARGET , Token.IFEQ , Token.TARGET };
private static Node[] _matches( Node n , int types[] ){
Node foo[] = new Node[types.length];
for ( int i=0; i<types.length; i++ ){
foo[i] = n;
if ( types[i] > 0 && n.getType() != types[i] )
return null;
n = n.getNext();
}
return n == null ? foo : null;
}
}
| false | true | private void _add( Node n , ScriptOrFnNode sn , State state ){
switch ( n.getType() ){
case Token.TYPEOF:
_append( "JS_typeof( " , n );
_assertOne( n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.TYPEOFNAME:
_append( "JS_typeof( " , n );
if ( state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
_append( " ) " , n );
break;
case Token.REGEXP:
int myId = _regex.size();
ScriptOrFnNode parent = _nodeToSOR.get( n );
int rId = n.getIntProp( Node.REGEXP_PROP , -1 );
_regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) );
_append( " _regex[" + myId + "] " , n );
break;
case Token.ARRAYLIT:
{
_append( "( JSArray.create( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) ) " , n );
}
break;
case Token.OBJECTLIT:
{
_append( "JS_buildLiteralObject( new String[]{ " , n );
boolean first = true;
for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){
if ( first )
first = false;
else
_append( " , " , n );
_append( "\"" + id.toString() + "\"" , n );
}
_append( " } " , n );
Node c = n.getFirstChild();
while ( c != null ){
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) " , n );
}
break;
case Token.NEW:
_append( "scope.clearThisNew( " , n );
_addCall( n , state , true );
_append( " ) " , n );
break;
case Token.THIS:
_append( "passedIn.getThis()" , n );
break;
case Token.INC:
case Token.DEC:
_assertOne( n );
Node tempChild = n.getFirstChild();
if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) &&
state.useLocalVariable( tempChild.getString() ) )
throw new RuntimeException( "can't increment local variables" );
_append( "JS_inc( " , n );
_createRef( n.getFirstChild() , state );
_append( " , " , n );
_append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n );
_append( " , " , n );
_append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n );
_append( ")" , n );
break;
case Token.USE_STACK:
_append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n );
break;
case Token.SETPROP_OP:
case Token.SETELEM_OP:
Node theOp = n.getFirstChild().getNext().getNext();
if ( theOp.getType() == Token.ADD &&
( theOp.getFirstChild().getType() == Token.USE_STACK ||
theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){
_append( "\n" , n );
_append( "JS_setDefferedPlus( (JSObject) " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( theOp.getFirstChild().getType() == Token.USE_STACK ?
theOp.getFirstChild().getNext() :
theOp.getFirstChild() ,
state );
_append( " \n ) \n" , n );
break;
}
_append( "\n { \n" , n );
_append( "JSObject __tempObject = (JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
String tempName = "__temp" + (int)(Math.random() * 10000);
state._tempOpNames.push( tempName );
_append( "Object " + tempName + " = " , n );
_add( n.getFirstChild().getNext() , state );
_append( ";\n" , n );
_append( " __tempObject.set(" , n );
_append( tempName , n );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ); \n" , n );
_append( " } \n" , n );
break;
case Token.SETPROP:
case Token.SETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").set( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ); " , n );
break;
case Token.GETPROPNOWARN:
case Token.GETPROP:
case Token.GETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").get( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )" , n );
break;
case Token.EXPR_RESULT:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.CALL:
_addCall( n , state );
break;
case Token.NUMBER:
String temp = String.valueOf( n.getDouble() );
if ( temp.endsWith( ".0" ) )
temp = "Integer.valueOf( " + temp.substring( 0 , temp.length() - 2 ) + " ) ";
else
temp = "Double.valueOf( " + temp + " ) ";
_append( temp , n );
break;
case Token.STRING:
int stringId = _strings.size();
_strings.add( n.getString() );
_append( "_strings[" + stringId + "]" ,n );
break;
case Token.TRUE:
_append( " true " , n );
break;
case Token.FALSE:
_append( " false " , n );
break;
case Token.NULL:
_append( " null " , n );
break;
case Token.VAR:
_addVar( n , state );
break;
case Token.GETVAR:
if ( state.useLocalVariable( n.getString() ) ){
_append( n.getString() , n );
break;
}
case Token.NAME:
if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
break;
case Token.SETVAR:
final String foo = n.getFirstChild().getString();
if ( state.useLocalVariable( foo ) ){
if ( ! state.hasSymbol( foo ) )
throw new RuntimeException( "something is wrong" );
_append( foo + " = " , n );
_add( n.getFirstChild().getNext() , state );
_append( "\n" , n );
}
else {
_setVar( foo ,
n.getFirstChild().getNext() ,
state , true );
}
break;
case Token.SETNAME:
_addSet( n , state );
break;
case Token.FUNCTION:
_addFunction( n , state );
break;
case Token.BLOCK:
_addBlock( n , state );
break;
case Token.EXPR_VOID:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.RETURN:
_append( "return " , n );
if ( n.getFirstChild() != null ){
_assertOne( n );
_add( n.getFirstChild() , state );
}
else {
_append( " null " , n );
}
_append( ";\n" , n );
break;
case Token.BITNOT:
_assertOne( n );
_append( "JS_bitnot( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.HOOK:
_append( " ( JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ? ( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) : ( " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ) ) " , n );
break;
case Token.NE:
_append( " ! " , n );
case Token.MUL:
case Token.DIV:
case Token.ADD:
case Token.SUB:
case Token.EQ:
case Token.SHEQ:
case Token.GE:
case Token.LE:
case Token.LT:
case Token.GT:
case Token.BITOR:
case Token.BITAND:
case Token.BITXOR:
case Token.URSH:
case Token.RSH:
case Token.LSH:
case Token.MOD:
_append( "JS_" , n );
String fooooo = _2ThingThings.get( n.getType() );
if ( fooooo == null )
throw new RuntimeException( "noting for : " + n );
_append( fooooo , n );
_append( "\n( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )\n " , n );
break;
case Token.IFNE:
_addIFNE( n , state );
break;
case Token.LOOP:
_addLoop( n , state );
break;
case Token.EMPTY:
if ( n.getFirstChild() != null ){
Debug.printTree( n , 0 );
throw new RuntimeException( "not really empty" );
}
break;
case Token.LABEL:
_append( n.getString() + ":" , n );
break;
case Token.BREAK:
_append( "break " + n.getString() + ";\n" , n );
break;
case Token.CONTINUE:
_append( "continue " + n.getString() + ";\n" , n );
break;
case Token.WHILE:
_append( "while( JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ) " , n );
_add( n.getFirstChild().getNext() , state );
break;
case Token.FOR:
_addFor( n , state );
break;
case Token.TARGET:
break;
case Token.NOT:
_assertOne( n );
_append( " ! JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.AND:
_append( " ( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " && " , n );
_append( " JS_evalToBool( " , n );
_add( c , state );
_append( " ) " , n );
c = c.getNext();
}
_append( " ) " , n );
break;
case Token.OR:
Node cc = n.getFirstChild();
if ( cc.getNext() == null )
throw new RuntimeException( "what?" );
if ( cc.getNext().getNext() != null )
throw new RuntimeException( "what?" );
_append( "( scope.orSave( " , n );
_add( cc , state );
_append( " ) ? scope.getOrSave() : ( " , n );
_add( cc.getNext() , state );
_append( " ) ) " , n );
break;
case Token.LOCAL_BLOCK:
_assertOne( n );
if ( n.getFirstChild().getType() != Token.TRY )
throw new RuntimeException("only know about LOCAL_BLOCK with try" );
_addTry( n.getFirstChild() , state );
break;
case Token.THROW:
_append( "throw new JSException( " , n );
_add( n.getFirstChild() , state );
_append( " ); " , n );
break;
case Token.INSTANCEOF:
_append( "JS_instanceof( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
if ( n.getFirstChild().getNext().getNext() != null )
throw new RuntimeException( "something is wrong" );
break;
case Token.DELPROP:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( " ).removeField( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
break;
default:
Debug.printTree( n , 0 );
throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() );
}
}
| private void _add( Node n , ScriptOrFnNode sn , State state ){
switch ( n.getType() ){
case Token.TYPEOF:
_append( "JS_typeof( " , n );
_assertOne( n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.TYPEOFNAME:
_append( "JS_typeof( " , n );
if ( state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
_append( " ) " , n );
break;
case Token.REGEXP:
int myId = _regex.size();
ScriptOrFnNode parent = _nodeToSOR.get( n );
int rId = n.getIntProp( Node.REGEXP_PROP , -1 );
_regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) );
_append( " _regex[" + myId + "] " , n );
break;
case Token.ARRAYLIT:
{
_append( "( JSArray.create( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) ) " , n );
}
break;
case Token.OBJECTLIT:
{
_append( "JS_buildLiteralObject( new String[]{ " , n );
boolean first = true;
for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){
if ( first )
first = false;
else
_append( " , " , n );
_append( "\"" + id.toString() + "\"" , n );
}
_append( " } " , n );
Node c = n.getFirstChild();
while ( c != null ){
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) " , n );
}
break;
case Token.NEW:
_append( "scope.clearThisNew( " , n );
_addCall( n , state , true );
_append( " ) " , n );
break;
case Token.THIS:
_append( "passedIn.getThis()" , n );
break;
case Token.INC:
case Token.DEC:
_assertOne( n );
Node tempChild = n.getFirstChild();
if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) &&
state.useLocalVariable( tempChild.getString() ) )
throw new RuntimeException( "can't increment local variables" );
_append( "JS_inc( " , n );
_createRef( n.getFirstChild() , state );
_append( " , " , n );
_append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n );
_append( " , " , n );
_append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n );
_append( ")" , n );
break;
case Token.USE_STACK:
_append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n );
break;
case Token.SETPROP_OP:
case Token.SETELEM_OP:
Node theOp = n.getFirstChild().getNext().getNext();
if ( theOp.getType() == Token.ADD &&
( theOp.getFirstChild().getType() == Token.USE_STACK ||
theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){
_append( "\n" , n );
_append( "JS_setDefferedPlus( (JSObject) " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( theOp.getFirstChild().getType() == Token.USE_STACK ?
theOp.getFirstChild().getNext() :
theOp.getFirstChild() ,
state );
_append( " \n ) \n" , n );
break;
}
_append( "\n { \n" , n );
_append( "JSObject __tempObject = (JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
String tempName = "__temp" + (int)(Math.random() * 10000);
state._tempOpNames.push( tempName );
_append( "Object " + tempName + " = " , n );
_add( n.getFirstChild().getNext() , state );
_append( ";\n" , n );
_append( " __tempObject.set(" , n );
_append( tempName , n );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ); \n" , n );
_append( " } \n" , n );
break;
case Token.SETPROP:
case Token.SETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").set( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ); " , n );
break;
case Token.GETPROPNOWARN:
case Token.GETPROP:
case Token.GETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").get( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )" , n );
break;
case Token.EXPR_RESULT:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.CALL:
_addCall( n , state );
break;
case Token.NUMBER:
String temp = String.valueOf( n.getDouble() );
if ( temp.endsWith( ".0" ) )
temp = "Integer.valueOf( " + temp.substring( 0 , temp.length() - 2 ) + " ) ";
else
temp = "Double.valueOf( " + temp + " ) ";
_append( temp , n );
break;
case Token.STRING:
int stringId = _strings.size();
_strings.add( n.getString() );
_append( "_strings[" + stringId + "]" ,n );
break;
case Token.TRUE:
_append( " true " , n );
break;
case Token.FALSE:
_append( " false " , n );
break;
case Token.NULL:
_append( " null " , n );
break;
case Token.VAR:
_addVar( n , state );
break;
case Token.GETVAR:
if ( state.useLocalVariable( n.getString() ) ){
_append( n.getString() , n );
break;
}
case Token.NAME:
if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
break;
case Token.SETVAR:
final String foo = n.getFirstChild().getString();
if ( state.useLocalVariable( foo ) ){
if ( ! state.hasSymbol( foo ) )
throw new RuntimeException( "something is wrong" );
_append( foo + " = " , n );
_add( n.getFirstChild().getNext() , state );
_append( "\n" , n );
}
else {
_setVar( foo ,
n.getFirstChild().getNext() ,
state , true );
}
break;
case Token.SETNAME:
_addSet( n , state );
break;
case Token.FUNCTION:
_addFunction( n , state );
break;
case Token.BLOCK:
_addBlock( n , state );
break;
case Token.EXPR_VOID:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.RETURN:
boolean last = n.getNext() == null;
if ( ! last )
_append( "if ( true ) { " , n );
_append( "return " , n );
if ( n.getFirstChild() != null ){
_assertOne( n );
_add( n.getFirstChild() , state );
}
else {
_append( " null " , n );
}
_append( ";" , n );
if ( ! last )
_append( "}" , n );
_append( "\n" , n );
break;
case Token.BITNOT:
_assertOne( n );
_append( "JS_bitnot( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.HOOK:
_append( " ( JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ? ( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) : ( " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ) ) " , n );
break;
case Token.NE:
_append( " ! " , n );
case Token.MUL:
case Token.DIV:
case Token.ADD:
case Token.SUB:
case Token.EQ:
case Token.SHEQ:
case Token.GE:
case Token.LE:
case Token.LT:
case Token.GT:
case Token.BITOR:
case Token.BITAND:
case Token.BITXOR:
case Token.URSH:
case Token.RSH:
case Token.LSH:
case Token.MOD:
_append( "JS_" , n );
String fooooo = _2ThingThings.get( n.getType() );
if ( fooooo == null )
throw new RuntimeException( "noting for : " + n );
_append( fooooo , n );
_append( "\n( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )\n " , n );
break;
case Token.IFNE:
_addIFNE( n , state );
break;
case Token.LOOP:
_addLoop( n , state );
break;
case Token.EMPTY:
if ( n.getFirstChild() != null ){
Debug.printTree( n , 0 );
throw new RuntimeException( "not really empty" );
}
break;
case Token.LABEL:
_append( n.getString() + ":" , n );
break;
case Token.BREAK:
_append( "break " + n.getString() + ";\n" , n );
break;
case Token.CONTINUE:
_append( "continue " + n.getString() + ";\n" , n );
break;
case Token.WHILE:
_append( "while( JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ) " , n );
_add( n.getFirstChild().getNext() , state );
break;
case Token.FOR:
_addFor( n , state );
break;
case Token.TARGET:
break;
case Token.NOT:
_assertOne( n );
_append( " ! JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.AND:
_append( " ( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " && " , n );
_append( " JS_evalToBool( " , n );
_add( c , state );
_append( " ) " , n );
c = c.getNext();
}
_append( " ) " , n );
break;
case Token.OR:
Node cc = n.getFirstChild();
if ( cc.getNext() == null )
throw new RuntimeException( "what?" );
if ( cc.getNext().getNext() != null )
throw new RuntimeException( "what?" );
_append( "( scope.orSave( " , n );
_add( cc , state );
_append( " ) ? scope.getOrSave() : ( " , n );
_add( cc.getNext() , state );
_append( " ) ) " , n );
break;
case Token.LOCAL_BLOCK:
_assertOne( n );
if ( n.getFirstChild().getType() != Token.TRY )
throw new RuntimeException("only know about LOCAL_BLOCK with try" );
_addTry( n.getFirstChild() , state );
break;
case Token.THROW:
_append( "throw new JSException( " , n );
_add( n.getFirstChild() , state );
_append( " ); " , n );
break;
case Token.INSTANCEOF:
_append( "JS_instanceof( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
if ( n.getFirstChild().getNext().getNext() != null )
throw new RuntimeException( "something is wrong" );
break;
case Token.DELPROP:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( " ).removeField( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
break;
default:
Debug.printTree( n , 0 );
throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() );
}
}
|
diff --git a/flexodesktop/modules/flexoworkfloweditor/src/main/java/org/openflexo/wkf/swleditor/gr/RoleContainerGR.java b/flexodesktop/modules/flexoworkfloweditor/src/main/java/org/openflexo/wkf/swleditor/gr/RoleContainerGR.java
index 4354783d4..4822fb09c 100644
--- a/flexodesktop/modules/flexoworkfloweditor/src/main/java/org/openflexo/wkf/swleditor/gr/RoleContainerGR.java
+++ b/flexodesktop/modules/flexoworkfloweditor/src/main/java/org/openflexo/wkf/swleditor/gr/RoleContainerGR.java
@@ -1,368 +1,369 @@
/*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenFlexo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.wkf.swleditor.gr;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import org.openflexo.fge.FGEUtils;
import org.openflexo.fge.GraphicalRepresentation;
import org.openflexo.fge.ShapeGraphicalRepresentation;
import org.openflexo.fge.controller.DrawingController;
import org.openflexo.fge.cp.ControlArea;
import org.openflexo.fge.geom.FGEDimension;
import org.openflexo.fge.geom.FGEGeometricObject.SimplifiedCardinalDirection;
import org.openflexo.fge.geom.FGEPoint;
import org.openflexo.fge.geom.FGERectangle;
import org.openflexo.fge.geom.area.FGEHalfLine;
import org.openflexo.fge.graphics.BackgroundStyle;
import org.openflexo.fge.graphics.BackgroundStyle.BackgroundImage;
import org.openflexo.fge.graphics.BackgroundStyle.BackgroundImage.ImageBackgroundType;
import org.openflexo.fge.graphics.BackgroundStyle.ColorGradient.ColorGradientDirection;
import org.openflexo.fge.graphics.DecorationPainter;
import org.openflexo.fge.graphics.ForegroundStyle;
import org.openflexo.fge.graphics.TextStyle;
import org.openflexo.fge.shapes.Shape.ShapeType;
import org.openflexo.fge.view.ShapeView;
import org.openflexo.foundation.ConvertedIntoLocalObject;
import org.openflexo.foundation.DataModification;
import org.openflexo.foundation.FlexoObservable;
import org.openflexo.foundation.wkf.Role;
import org.openflexo.foundation.wkf.dm.NodeInserted;
import org.openflexo.foundation.wkf.dm.NodeRemoved;
import org.openflexo.foundation.wkf.dm.ObjectLocationChanged;
import org.openflexo.foundation.wkf.dm.ObjectSizeChanged;
import org.openflexo.foundation.wkf.dm.RoleColorChange;
import org.openflexo.foundation.wkf.dm.RoleNameChange;
import org.openflexo.foundation.wkf.dm.RoleRemoved;
import org.openflexo.foundation.wkf.dm.WKFAttributeDataModification;
import org.openflexo.toolbox.FileResource;
import org.openflexo.wkf.swleditor.SWLEditorConstants;
import org.openflexo.wkf.swleditor.SwimmingLaneRepresentation;
public class RoleContainerGR extends SWLObjectGR<Role> implements SWLContainerGR {
static final Logger logger = Logger.getLogger(OperationNodeGR.class.getPackage().getName());
protected BackgroundStyle background;
protected ForegroundStyle decorationForeground;
protected BackgroundImage decorationBackground;
private static final FileResource USER_ROLE_ICON = new FileResource("Resources/WKF/SmallRole.gif");
private static final FileResource SYSTEM_ROLE_ICON = new FileResource("Resources/WKF/SmallSystemRole.gif");
protected Color mainColor, backColor, emphasizedMainColor, emphasizedBackColor;
private SWLContainerResizeAreas controlAreas;
public RoleContainerGR(Role role, SwimmingLaneRepresentation aDrawing) {
super(role, ShapeType.RECTANGLE, aDrawing);
((org.openflexo.fge.shapes.Rectangle) getShape()).setIsRounded(false);
setLayer(SWLEditorConstants.ROLE_LAYER);
setMinimalWidth(180);
setMinimalHeight(80);
setBorder(new ShapeBorder(0, 0, 0, 0));
// setDimensionConstraints(DimensionConstraints.CONTAINER);
/*mainColor = role.getColor();
backColor = new Color ((255*3+mainColor.getRed())/4,(255*3+mainColor.getGreen())/4,(255*3+mainColor.getBlue())/4);
setIsFloatingLabel(true);
setTextStyle(TextStyle.makeTextStyle(mainColor,new Font("SansSerif", Font.BOLD, 12)));
updatePropertiesFromWKFPreferences();*/
setIsLabelEditable(!role.isImported());
updateColors();
setDecorationPainter(new DecorationPainter() {
@Override
public void paintDecoration(org.openflexo.fge.graphics.FGEShapeDecorationGraphics g) {
g.useBackgroundStyle(background);
g.fillRect(0, 0, g.getWidth() - 1, g.getHeight() - 1);
g.useForegroundStyle(decorationForeground);
g.drawRect(0, 0, g.getWidth() - 1, g.getHeight() - 1);
g.drawLine(20, 0, 20, getHeight());
- g.getGraphics().rotate(-Math.PI / 2, 10, getHeight() / 2);
- g.drawString(getDrawable().getName(), new FGEPoint(10, getHeight() / 2), HorizontalTextAlignment.CENTER);
+ double x = 10 + g.getCurrentTextStyle().getFont().getSize() * 2;
+ double y = getHeight() / 2;
+ System.err.println(g.drawString(getDrawable().getName(), x, y, -90, HorizontalTextAlignment.CENTER));
};
@Override
public boolean paintBeforeShape() {
return false;
}
});
setForeground(ForegroundStyle.makeNone());
setBackground(BackgroundStyle.makeEmptyBackground());
role.addObserver(this);
setDimensionConstraints(DimensionConstraints.FREELY_RESIZABLE);
setLocationConstraints(LocationConstraints.AREA_CONSTRAINED);
setLocationConstrainedArea(FGEHalfLine.makeHalfLine(new FGEPoint(SWIMMING_LANE_BORDER, SWIMMING_LANE_BORDER),
SimplifiedCardinalDirection.SOUTH));
setMinimalHeight(120);
anchorLocation();
controlAreas = new SWLContainerResizeAreas(this);
}
@Override
public List<? extends ControlArea<?>> getControlAreas() {
return controlAreas.getControlAreas();
}
/*@Override
public ShapeView<Role> makeShapeView(DrawingController<?> controller)
{
return new RoleContainerView(this,controller);
}
public class RoleContainerView extends ShapeView<Role>
{
public RoleContainerView(RoleContainerGR aGraphicalRepresentation,DrawingController<?> controller)
{
super(aGraphicalRepresentation,controller);
JButton plus = new JButton(IconLibrary.PLUS);
plus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Prout le plus");
}
});
add(plus);
plus.setBounds(10,10,20,20);
validate();
}
}*/
protected static boolean isInsideRectangle(GraphicalRepresentation<?> graphicalRepresentation, DrawingController<?> controller,
MouseEvent event, FGERectangle rect) {
ShapeView view = (ShapeView) controller.getDrawingView().viewForObject(graphicalRepresentation);
Rectangle boxRect = new Rectangle((int) (rect.getX() * controller.getScale()), (int) (rect.getY() * controller.getScale()),
(int) (rect.getWidth() * controller.getScale()), (int) (rect.getHeight() * controller.getScale()));
Point clickLocation = SwingUtilities.convertPoint((Component) event.getSource(), event.getPoint(), view);
return boxRect.contains(clickLocation);
}
public Role getRole() {
return getDrawable();
}
@Override
protected boolean supportShadow() {
return false;
}
@Override
public void updatePropertiesFromWKFPreferences() {
super.updatePropertiesFromWKFPreferences();
setIsFloatingLabel(true);
setTextStyle(TextStyle.makeTextStyle(emphasizedMainColor, new Font("SansSerif", Font.BOLD, 12)));
// Those are the styles used by border painter (not the one used for shape itself, which are empty)
if (backColor == null) {
backColor = Color.BLACK;
}
background = BackgroundStyle.makeColorGradientBackground(backColor, new Color(backColor.getRed() / 2 + 128,
backColor.getGreen() / 2 + 128, backColor.getBlue() / 2 + 128), ColorGradientDirection.SOUTH_EAST_NORTH_WEST);
decorationForeground = ForegroundStyle.makeStyle(mainColor);
decorationForeground.setLineWidth(0.4);
if (getRole().getIsSystemRole()) {
decorationBackground = BackgroundStyle.makeImageBackground(SYSTEM_ROLE_ICON);
} else {
decorationBackground = BackgroundStyle.makeImageBackground(USER_ROLE_ICON);
}
decorationBackground.setImageBackgroundType(ImageBackgroundType.OPAQUE);
decorationBackground.setImageBackgroundColor(Color.WHITE);
decorationBackground.setDeltaX(16);
decorationBackground.setDeltaY(6);
decorationBackground.setUseTransparency(true);
decorationBackground.setTransparencyLevel(0.9f);
}
/*@Override
public double getX()
{
return SWIMMING_LANE_BORDER;
}
@Override
public void setXNoNotification(double posX)
{
// not applicable
}
@Override
public double getY()
{
double returned = SWIMMING_LANE_BORDER+PORT_REGISTERY_HEIGHT;
for (Role r : getRole().getRoleList().getRoles()) {
if (r == getRole()) {
return returned;
}
GraphicalRepresentation<?> gr = getGraphicalRepresentation(r);
if (gr instanceof RoleContainerGR) { // What else could it be ???
RoleContainerGR roleGR = (RoleContainerGR)gr;
returned += roleGR.getHeight()+2*SWIMMING_LANE_BORDER;
}
}
logger.warning("Unexpected situation here");
return returned;
}
@Override
public void setYNoNotification(double posY)
{
// not applicable
}
*/
@Override
public void anchorLocation() {
setX(SWIMMING_LANE_BORDER);
setY(getDrawing().yForObject(getRole()));
}
@Override
public double getWidth() {
return getDrawingGraphicalRepresentation().getWidth() - 2 * SWIMMING_LANE_BORDER;
}
@Override
public double getHeight() {
return getDrawing().getHeight(getRole());
}
@Override
public void setHeightNoNotification(double height) {
getDrawing().setHeight(getRole(), height);
}
@Override
public void setWidthNoNotification(double aValue) {
getDrawingGraphicalRepresentation().setWidth(aValue + 2 * SWIMMING_LANE_BORDER);
}
@Override
public void update(FlexoObservable observable, DataModification dataModification) {
// logger.info(">>>>>>>>>>> Notified "+dataModification+" for "+observable);
if (observable == getModel()) {
if (dataModification instanceof NodeInserted) {
getDrawing().updateGraphicalObjectsHierarchy();
notifyShapeNeedsToBeRedrawn();
notifyObjectMoved();
notifyObjectResized();
} else if (dataModification instanceof NodeRemoved) {
getDrawing().updateGraphicalObjectsHierarchy();
notifyShapeNeedsToBeRedrawn();
} else if (dataModification instanceof RoleColorChange || "color".equals(dataModification.propertyName())) {
updateColors();
notifyShapeNeedsToBeRedrawn();
} else if (dataModification instanceof RoleNameChange || "name".equals(dataModification.propertyName())) {
notifyAttributeChange(org.openflexo.fge.GraphicalRepresentation.Parameters.text);
} else if (dataModification instanceof ObjectLocationChanged) {
notifyObjectMoved();
} else if (dataModification instanceof ObjectSizeChanged) {
notifyObjectResized();
} else if (dataModification instanceof WKFAttributeDataModification) {
if (((WKFAttributeDataModification) dataModification).getAttributeName().equals(
getDrawing().SWIMMING_LANE_INDEX_KEY(getRole()))) {
getDrawing().reindexForNewObjectIndex(getRole());
} else if ("isSystemRole".equals(((WKFAttributeDataModification) dataModification).getAttributeName())) {
updatePropertiesFromWKFPreferences();
notifyShapeNeedsToBeRedrawn();
} else {
notifyShapeNeedsToBeRedrawn();
}
} else if (dataModification instanceof ConvertedIntoLocalObject) {
setIsLabelEditable(!getRole().isImported());
} else if (dataModification instanceof RoleRemoved) {
getDrawing().requestRebuildCompleteHierarchy();
}
}
}
private void updateColors() {
if (getRole() != null) {
mainColor = getRole().getColor();
if (mainColor == null) {
mainColor = Color.RED; // See also org.openflexo.wkf.roleeditor.RoleGR.getRoleColor() and
}
// org.openflexo.components.browser.wkf.RoleElement.buildCustomIcon(Color)
// org.openflexo.wkf.processeditor.gr.AbstractActivityNodeGR.getMainBgColor()
backColor = new Color((255 * 3 + mainColor.getRed()) / 4, (255 * 3 + mainColor.getGreen()) / 4,
(255 * 3 + mainColor.getBlue()) / 4);
emphasizedMainColor = FGEUtils.chooseBestColor(Color.WHITE, FGEUtils.emphasizedColor(mainColor), mainColor);
emphasizedBackColor = FGEUtils.emphasizedColor(backColor);
updatePropertiesFromWKFPreferences();
}
}
private boolean objectIsBeeingDragged = false;
@Override
public void notifyObjectWillMove() {
super.notifyObjectWillMove();
objectIsBeeingDragged = true;
}
@Override
public void notifyObjectHasMoved() {
if (objectIsBeeingDragged) {
getDrawing().reindexObjectForNewVerticalLocation(getRole(), getY());
anchorLocation();
for (GraphicalRepresentation<?> gr : getDrawingGraphicalRepresentation().getContainedGraphicalRepresentations()) {
if (gr instanceof ShapeGraphicalRepresentation && gr != this) {
((ShapeGraphicalRepresentation<?>) gr).notifyObjectHasMoved();
}
}
}
objectIsBeeingDragged = false;
super.notifyObjectHasMoved();
anchorLocation();
}
@Override
public void notifyObjectResized(FGEDimension oldSize) {
super.notifyObjectResized(oldSize);
if (isRegistered()) {
getDrawing().relayoutRoleContainers();
}
}
@Override
public void notifyObjectHasResized() {
super.notifyObjectHasResized();
getDrawing().relayoutRoleContainers();
}
}
| true | true | public RoleContainerGR(Role role, SwimmingLaneRepresentation aDrawing) {
super(role, ShapeType.RECTANGLE, aDrawing);
((org.openflexo.fge.shapes.Rectangle) getShape()).setIsRounded(false);
setLayer(SWLEditorConstants.ROLE_LAYER);
setMinimalWidth(180);
setMinimalHeight(80);
setBorder(new ShapeBorder(0, 0, 0, 0));
// setDimensionConstraints(DimensionConstraints.CONTAINER);
/*mainColor = role.getColor();
backColor = new Color ((255*3+mainColor.getRed())/4,(255*3+mainColor.getGreen())/4,(255*3+mainColor.getBlue())/4);
setIsFloatingLabel(true);
setTextStyle(TextStyle.makeTextStyle(mainColor,new Font("SansSerif", Font.BOLD, 12)));
updatePropertiesFromWKFPreferences();*/
setIsLabelEditable(!role.isImported());
updateColors();
setDecorationPainter(new DecorationPainter() {
@Override
public void paintDecoration(org.openflexo.fge.graphics.FGEShapeDecorationGraphics g) {
g.useBackgroundStyle(background);
g.fillRect(0, 0, g.getWidth() - 1, g.getHeight() - 1);
g.useForegroundStyle(decorationForeground);
g.drawRect(0, 0, g.getWidth() - 1, g.getHeight() - 1);
g.drawLine(20, 0, 20, getHeight());
g.getGraphics().rotate(-Math.PI / 2, 10, getHeight() / 2);
g.drawString(getDrawable().getName(), new FGEPoint(10, getHeight() / 2), HorizontalTextAlignment.CENTER);
};
@Override
public boolean paintBeforeShape() {
return false;
}
});
setForeground(ForegroundStyle.makeNone());
setBackground(BackgroundStyle.makeEmptyBackground());
role.addObserver(this);
setDimensionConstraints(DimensionConstraints.FREELY_RESIZABLE);
setLocationConstraints(LocationConstraints.AREA_CONSTRAINED);
setLocationConstrainedArea(FGEHalfLine.makeHalfLine(new FGEPoint(SWIMMING_LANE_BORDER, SWIMMING_LANE_BORDER),
SimplifiedCardinalDirection.SOUTH));
setMinimalHeight(120);
anchorLocation();
controlAreas = new SWLContainerResizeAreas(this);
}
| public RoleContainerGR(Role role, SwimmingLaneRepresentation aDrawing) {
super(role, ShapeType.RECTANGLE, aDrawing);
((org.openflexo.fge.shapes.Rectangle) getShape()).setIsRounded(false);
setLayer(SWLEditorConstants.ROLE_LAYER);
setMinimalWidth(180);
setMinimalHeight(80);
setBorder(new ShapeBorder(0, 0, 0, 0));
// setDimensionConstraints(DimensionConstraints.CONTAINER);
/*mainColor = role.getColor();
backColor = new Color ((255*3+mainColor.getRed())/4,(255*3+mainColor.getGreen())/4,(255*3+mainColor.getBlue())/4);
setIsFloatingLabel(true);
setTextStyle(TextStyle.makeTextStyle(mainColor,new Font("SansSerif", Font.BOLD, 12)));
updatePropertiesFromWKFPreferences();*/
setIsLabelEditable(!role.isImported());
updateColors();
setDecorationPainter(new DecorationPainter() {
@Override
public void paintDecoration(org.openflexo.fge.graphics.FGEShapeDecorationGraphics g) {
g.useBackgroundStyle(background);
g.fillRect(0, 0, g.getWidth() - 1, g.getHeight() - 1);
g.useForegroundStyle(decorationForeground);
g.drawRect(0, 0, g.getWidth() - 1, g.getHeight() - 1);
g.drawLine(20, 0, 20, getHeight());
double x = 10 + g.getCurrentTextStyle().getFont().getSize() * 2;
double y = getHeight() / 2;
System.err.println(g.drawString(getDrawable().getName(), x, y, -90, HorizontalTextAlignment.CENTER));
};
@Override
public boolean paintBeforeShape() {
return false;
}
});
setForeground(ForegroundStyle.makeNone());
setBackground(BackgroundStyle.makeEmptyBackground());
role.addObserver(this);
setDimensionConstraints(DimensionConstraints.FREELY_RESIZABLE);
setLocationConstraints(LocationConstraints.AREA_CONSTRAINED);
setLocationConstrainedArea(FGEHalfLine.makeHalfLine(new FGEPoint(SWIMMING_LANE_BORDER, SWIMMING_LANE_BORDER),
SimplifiedCardinalDirection.SOUTH));
setMinimalHeight(120);
anchorLocation();
controlAreas = new SWLContainerResizeAreas(this);
}
|
diff --git a/src/com/jidesoft/swing/CheckBoxTree.java b/src/com/jidesoft/swing/CheckBoxTree.java
index 711aa310..583c8c6d 100644
--- a/src/com/jidesoft/swing/CheckBoxTree.java
+++ b/src/com/jidesoft/swing/CheckBoxTree.java
@@ -1,519 +1,522 @@
/*
* @(#)CheckBoxTree.java 8/11/2005
*
* Copyright 2002 - 2005 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.swing;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.Position;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Hashtable;
import java.util.Vector;
import java.util.List;
import java.util.ArrayList;
/**
* CheckBoxTree is a special JTree which uses JCheckBox as the tree renderer. In addition to regular JTree's features,
* it also allows you select any number of tree nodes in the tree by selecting the check boxes. <p>To select an element,
* user can mouse click on the check box, or select one or several tree nodes and press SPACE key to toggle the check
* box selection for all selected tree nodes.
* <p/>
* In order to retrieve which tree paths are selected, you need to call {@link #getCheckBoxTreeSelectionModel()}. It
* will return the selection model that keeps track of which tree paths have been checked. For example {@link
* CheckBoxTreeSelectionModel#getSelectionPaths()} will give the list of paths which have been checked.
*/
public class CheckBoxTree extends JTree {
public static final String PROPERTY_CHECKBOX_ENABLED = "checkBoxEnabled";
public static final String PROPERTY_CLICK_IN_CHECKBOX_ONLY = "clickInCheckBoxOnly";
public static final String PROPERTY_DIG_IN = "digIn";
protected CheckBoxTreeCellRenderer _treeCellRenderer;
private CheckBoxTreeSelectionModel _checkBoxTreeSelectionModel;
private boolean _checkBoxEnabled = true;
private boolean _clickInCheckBoxOnly = true;
private PropertyChangeListener _modelChangeListener;
private TristateCheckBox _checkBox;
public CheckBoxTree() {
init();
}
public CheckBoxTree(Object[] value) {
super(value);
init();
}
public CheckBoxTree(Vector<?> value) {
super(value);
init();
}
public CheckBoxTree(Hashtable<?, ?> value) {
super(value);
init();
}
public CheckBoxTree(TreeNode root) {
super(root);
init();
}
public CheckBoxTree(TreeNode root, boolean asksAllowsChildren) {
super(root, asksAllowsChildren);
init();
}
public CheckBoxTree(TreeModel newModel) {
super(newModel);
init();
}
/**
* Initialize the CheckBoxTree.
*/
protected void init() {
_checkBoxTreeSelectionModel = createCheckBoxTreeSelectionModel(getModel());
_checkBoxTreeSelectionModel.setTree(this);
Handler handler = createHandler();
JideSwingUtilities.insertMouseListener(this, handler, 0);
addKeyListener(handler);
_checkBoxTreeSelectionModel.addTreeSelectionListener(handler);
if (_modelChangeListener == null) {
_modelChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JTree.SELECTION_MODEL_PROPERTY.equals(evt.getPropertyName())) {
updateRowMapper();
}
if ("model".equals(evt.getPropertyName()) && evt.getNewValue() instanceof TreeModel) {
_checkBoxTreeSelectionModel.setModel((TreeModel) evt.getNewValue());
}
}
};
}
addPropertyChangeListener(JTree.SELECTION_MODEL_PROPERTY, _modelChangeListener);
addPropertyChangeListener("model", _modelChangeListener);
updateRowMapper();
}
/**
* Creates the CheckBoxTreeSelectionModel.
*
* @param model the tree model.
* @return the CheckBoxTreeSelectionModel.
*/
protected CheckBoxTreeSelectionModel createCheckBoxTreeSelectionModel(TreeModel model) {
return new CheckBoxTreeSelectionModel(model);
}
/**
* RowMapper is necessary for contiguous selection.
*/
private void updateRowMapper() {
_checkBoxTreeSelectionModel.setRowMapper(getSelectionModel().getRowMapper());
}
private TreeCellRenderer _defaultRenderer;
/**
* Gets the cell renderer with check box.
*
* @return CheckBoxTree's own cell renderer which has the check box. The actual cell renderer you set by
* setCellRenderer() can be accessed by using {@link #getActualCellRenderer()}.
*/
@Override
public TreeCellRenderer getCellRenderer() {
TreeCellRenderer cellRenderer = getActualCellRenderer();
if (cellRenderer == null) {
cellRenderer = getDefaultRenderer();
}
if (_treeCellRenderer == null) {
_treeCellRenderer = createCellRenderer(cellRenderer);
}
else {
_treeCellRenderer.setActualTreeRenderer(cellRenderer);
}
return _treeCellRenderer;
}
private TreeCellRenderer getDefaultRenderer() {
if (_defaultRenderer == null)
_defaultRenderer = new DefaultTreeCellRenderer();
return _defaultRenderer;
}
/**
* Gets the actual cell renderer. Since CheckBoxTree has its own check box cell renderer, this method will give you
* access to the actual cell renderer which is either the default tree cell renderer or the cell renderer you set
* using {@link #setCellRenderer(javax.swing.tree.TreeCellRenderer)}.
*
* @return the actual cell renderer
*/
public TreeCellRenderer getActualCellRenderer() {
if (_treeCellRenderer != null) {
return _treeCellRenderer.getActualTreeRenderer();
}
else {
return super.getCellRenderer();
}
}
@Override
public void setCellRenderer(TreeCellRenderer x) {
if (x == null) {
x = getDefaultRenderer();
}
super.setCellRenderer(x);
if (_treeCellRenderer != null) {
_treeCellRenderer.setActualTreeRenderer(x);
}
}
/**
* Creates the cell renderer.
*
* @param renderer the actual renderer for the tree node. This method will return a cell renderer that use a check
* box and put the actual renderer inside it.
* @return the cell renderer.
*/
protected CheckBoxTreeCellRenderer createCellRenderer(TreeCellRenderer renderer) {
final CheckBoxTreeCellRenderer checkBoxTreeCellRenderer = new CheckBoxTreeCellRenderer(renderer, getCheckBox());
addPropertyChangeListener(CELL_RENDERER_PROPERTY, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
TreeCellRenderer treeCellRenderer = (TreeCellRenderer) evt.getNewValue();
if (treeCellRenderer != checkBoxTreeCellRenderer) {
checkBoxTreeCellRenderer.setActualTreeRenderer(treeCellRenderer);
}
else {
checkBoxTreeCellRenderer.setActualTreeRenderer(null);
}
}
});
return checkBoxTreeCellRenderer;
}
/**
* Creates the mouse listener and key listener used by CheckBoxTree.
*
* @return the Handler.
*/
protected Handler createHandler() {
return new Handler(this);
}
/**
* Get the CheckBox used for CheckBoxTreeCellRenderer.
*
* @see #setCheckBox(TristateCheckBox)
* @return the check box.
*/
public TristateCheckBox getCheckBox() {
return _checkBox;
}
/**
* Set the CheckBox used for CheckBoxTreeCellRenderer.
* <p>
* By default, it's null. CheckBoxTreeCellRenderer then will create a default TristateCheckBox.
*
* @param checkBox the check box
*/
public void setCheckBox(TristateCheckBox checkBox) {
if (_checkBox != checkBox) {
_checkBox = checkBox;
_treeCellRenderer = null;
revalidate();
repaint();
}
}
protected static class Handler implements MouseListener, KeyListener, TreeSelectionListener {
protected CheckBoxTree _tree;
int _hotspot = new JCheckBox().getPreferredSize().width;
private int _toggleCount = -1;
public Handler(CheckBoxTree tree) {
_tree = tree;
}
protected TreePath getTreePathForMouseEvent(MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e)) {
return null;
}
if (!_tree.isCheckBoxEnabled()) {
return null;
}
TreePath path = _tree.getPathForLocation(e.getX(), e.getY());
if (path == null)
return null;
if (clicksInCheckBox(e, path) || !_tree.isClickInCheckBoxOnly()) {
return path;
}
else {
return null;
}
}
protected boolean clicksInCheckBox(MouseEvent e, TreePath path) {
if (!_tree.isCheckBoxVisible(path)) {
return false;
}
else {
Rectangle bounds = _tree.getPathBounds(path);
if (_tree.getComponentOrientation().isLeftToRight()) {
return e.getX() < bounds.x + _hotspot;
}
else {
return e.getX() > bounds.x + bounds.width - _hotspot;
}
}
}
private TreePath preventToggleEvent(MouseEvent e) {
TreePath pathForMouseEvent = getTreePathForMouseEvent(e);
if (pathForMouseEvent != null) {
int toggleCount = _tree.getToggleClickCount();
if (toggleCount != -1) {
_toggleCount = toggleCount;
_tree.setToggleClickCount(-1);
}
}
return pathForMouseEvent;
}
public void mouseClicked(MouseEvent e) {
if (e.isConsumed()) {
return;
}
preventToggleEvent(e);
}
public void mousePressed(MouseEvent e) {
if (e.isConsumed()) {
return;
}
TreePath path = preventToggleEvent(e);
if (path != null) {
toggleSelections(new TreePath[] {path});
e.consume();
}
}
public void mouseReleased(MouseEvent e) {
if (e.isConsumed()) {
return;
}
TreePath path = preventToggleEvent(e);
if (path != null) {
e.consume();
}
if (_toggleCount != -1) {
_tree.setToggleClickCount(_toggleCount);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.isConsumed()) {
return;
}
if (!_tree.isCheckBoxEnabled()) {
return;
}
if (e.getModifiers() == 0 && e.getKeyChar() == KeyEvent.VK_SPACE)
toggleSelections();
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void valueChanged(TreeSelectionEvent e) {
_tree.treeDidChange();
}
protected void toggleSelections() {
TreePath[] treePaths = _tree.getSelectionPaths();
toggleSelections(treePaths);
}
private void toggleSelections(TreePath[] treePaths) {
if (treePaths == null || treePaths.length == 0 || !_tree.isEnabled()) {
return;
}
+ if (treePaths.length == 1 && !_tree.isCheckBoxEnabled(treePaths[0])) {
+ return;
+ }
CheckBoxTreeSelectionModel selectionModel = _tree.getCheckBoxTreeSelectionModel();
List<TreePath> pathToAdded = new ArrayList<TreePath>();
List<TreePath> pathToRemoved = new ArrayList<TreePath>();
for (TreePath treePath : treePaths) {
boolean selected = selectionModel.isPathSelected(treePath, selectionModel.isDigIn());
if (selected) {
pathToRemoved.add(treePath);
}
else {
pathToAdded.add(treePath);
}
}
selectionModel.removeTreeSelectionListener(this);
try {
if (pathToAdded.size() > 0) {
selectionModel.addSelectionPaths(pathToAdded.toArray(new TreePath[pathToAdded.size()]));
}
if (pathToRemoved.size() > 0) {
selectionModel.removeSelectionPaths(pathToRemoved.toArray(new TreePath[pathToRemoved.size()]));
}
}
finally {
selectionModel.addTreeSelectionListener(this);
_tree.treeDidChange();
}
}
}
@Override
public TreePath getNextMatch(String prefix, int startingRow, Position.Bias bias) {
return null;
}
/**
* Gets the selection model for the check boxes. To retrieve the state of check boxes, you should use this selection
* model.
*
* @return the selection model for the check boxes.
*/
public CheckBoxTreeSelectionModel getCheckBoxTreeSelectionModel() {
return _checkBoxTreeSelectionModel;
}
/**
* Gets the value of property checkBoxEnabled. If true, user can click on check boxes on each tree node to select
* and deselect. If false, user can't click but you as developer can programmatically call API to select/deselect
* it.
*
* @return the value of property checkBoxEnabled.
*/
public boolean isCheckBoxEnabled() {
return _checkBoxEnabled;
}
/**
* Sets the value of property checkBoxEnabled.
*
* @param checkBoxEnabled true to allow to check the check box. False to disable it which means user can see whether
* a row is checked or not but they cannot change it.
*/
public void setCheckBoxEnabled(boolean checkBoxEnabled) {
if (checkBoxEnabled != _checkBoxEnabled) {
Boolean oldValue = _checkBoxEnabled ? Boolean.TRUE : Boolean.FALSE;
Boolean newValue = checkBoxEnabled ? Boolean.TRUE : Boolean.FALSE;
_checkBoxEnabled = checkBoxEnabled;
firePropertyChange(PROPERTY_CHECKBOX_ENABLED, oldValue, newValue);
repaint();
}
}
/**
* Checks if check box is enabled. There is no setter for it. The only way is to override this method to return true
* or false.
* <p/>
* However, in digIn mode, user can still select the disabled node by selecting all children nodes of that node.
* Also if user selects the parent node, the disabled children nodes will be selected too.
*
* @param path the tree path.
* @return true or false. If false, the check box on the particular tree path will be disabled.
*/
public boolean isCheckBoxEnabled(TreePath path) {
return true;
}
/**
* Checks if check box is visible. There is no setter for it. The only way is to override this method to return true
* or false.
*
* @param path the tree path.
* @return true or false. If false, the check box on the particular tree path will be disabled.
*/
public boolean isCheckBoxVisible(TreePath path) {
return true;
}
/**
* Gets the dig-in mode. If the CheckBoxTree is in dig-in mode, checking the parent node will check all the
* children. Correspondingly, getSelectionPaths() will only return the parent tree path. If not in dig-in mode, each
* tree node can be checked or unchecked independently
*
* @return true or false.
*/
public boolean isDigIn() {
return getCheckBoxTreeSelectionModel().isDigIn();
}
/**
* Sets the dig-in mode. If the CheckBoxTree is in dig-in mode, checking the parent node will check all the
* children. Correspondingly, getSelectionPaths() will only return the parent tree path. If not in dig-in mode, each
* tree node can be checked or unchecked independently
*
* @param digIn the new digIn mode.
*/
public void setDigIn(boolean digIn) {
boolean old = isDigIn();
if (old != digIn) {
getCheckBoxTreeSelectionModel().setDigIn(digIn);
firePropertyChange(PROPERTY_DIG_IN, old, digIn);
}
}
/**
* Gets the value of property clickInCheckBoxOnly. If true, user can click on check boxes on each tree node to
* select and deselect. If false, user can't click but you as developer can programmatically call API to
* select/deselect it.
*
* @return the value of property clickInCheckBoxOnly.
*/
public boolean isClickInCheckBoxOnly() {
return _clickInCheckBoxOnly;
}
/**
* Sets the value of property clickInCheckBoxOnly.
*
* @param clickInCheckBoxOnly true to allow to check the check box. False to disable it which means user can see
* whether a row is checked or not but they cannot change it.
*/
public void setClickInCheckBoxOnly(boolean clickInCheckBoxOnly) {
if (clickInCheckBoxOnly != _clickInCheckBoxOnly) {
boolean old = _clickInCheckBoxOnly;
_clickInCheckBoxOnly = clickInCheckBoxOnly;
firePropertyChange(PROPERTY_CLICK_IN_CHECKBOX_ONLY, old, _clickInCheckBoxOnly);
}
}
}
| true | true | private void toggleSelections(TreePath[] treePaths) {
if (treePaths == null || treePaths.length == 0 || !_tree.isEnabled()) {
return;
}
CheckBoxTreeSelectionModel selectionModel = _tree.getCheckBoxTreeSelectionModel();
List<TreePath> pathToAdded = new ArrayList<TreePath>();
List<TreePath> pathToRemoved = new ArrayList<TreePath>();
for (TreePath treePath : treePaths) {
boolean selected = selectionModel.isPathSelected(treePath, selectionModel.isDigIn());
if (selected) {
pathToRemoved.add(treePath);
}
else {
pathToAdded.add(treePath);
}
}
selectionModel.removeTreeSelectionListener(this);
try {
if (pathToAdded.size() > 0) {
selectionModel.addSelectionPaths(pathToAdded.toArray(new TreePath[pathToAdded.size()]));
}
if (pathToRemoved.size() > 0) {
selectionModel.removeSelectionPaths(pathToRemoved.toArray(new TreePath[pathToRemoved.size()]));
}
}
finally {
selectionModel.addTreeSelectionListener(this);
_tree.treeDidChange();
}
}
| private void toggleSelections(TreePath[] treePaths) {
if (treePaths == null || treePaths.length == 0 || !_tree.isEnabled()) {
return;
}
if (treePaths.length == 1 && !_tree.isCheckBoxEnabled(treePaths[0])) {
return;
}
CheckBoxTreeSelectionModel selectionModel = _tree.getCheckBoxTreeSelectionModel();
List<TreePath> pathToAdded = new ArrayList<TreePath>();
List<TreePath> pathToRemoved = new ArrayList<TreePath>();
for (TreePath treePath : treePaths) {
boolean selected = selectionModel.isPathSelected(treePath, selectionModel.isDigIn());
if (selected) {
pathToRemoved.add(treePath);
}
else {
pathToAdded.add(treePath);
}
}
selectionModel.removeTreeSelectionListener(this);
try {
if (pathToAdded.size() > 0) {
selectionModel.addSelectionPaths(pathToAdded.toArray(new TreePath[pathToAdded.size()]));
}
if (pathToRemoved.size() > 0) {
selectionModel.removeSelectionPaths(pathToRemoved.toArray(new TreePath[pathToRemoved.size()]));
}
}
finally {
selectionModel.addTreeSelectionListener(this);
_tree.treeDidChange();
}
}
|
diff --git a/src/org/springframework/richclient/form/builder/GridBagLayoutFormBuilder.java b/src/org/springframework/richclient/form/builder/GridBagLayoutFormBuilder.java
index fc80c793..56e7a308 100644
--- a/src/org/springframework/richclient/form/builder/GridBagLayoutFormBuilder.java
+++ b/src/org/springframework/richclient/form/builder/GridBagLayoutFormBuilder.java
@@ -1,329 +1,329 @@
/*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.richclient.form.builder;
import java.awt.*;
import javax.swing.*;
import org.springframework.enums.ShortCodedEnum;
import org.springframework.richclient.factory.ComponentFactory;
import org.springframework.richclient.forms.SwingFormModel;
import org.springframework.richclient.layout.GridBagLayoutBuilder;
import org.springframework.richclient.layout.LayoutBuilder;
/**
* This provides an easy way to create panels using a {@link GridBagLayout}.
* <p />
*
* Usage is:
*
* <pre>
* GridBagLayoutBuilder builder = new GridBagLayoutBuilder();
*
* builder.appendRightLabel("label.field1").appendField(field1);
* builder.appendRightLabel("label.field2").appendField(field2);
* builder.nextLine();
*
* builder.appendRightLabel("label.field3").appendField(field3);
* // because "field3" is the last component on this line, but the panel has
* // 4 columns, "field3" will span 3 columns
* builder.nextLine();
*
* // once everything's been put into the builder, ask it to build a panel
* // to use in the UI.
* JPanel panel = builder.getPanel();
* </pre>
*
* @author Jim Moore
* @see #setAutoSpanLastComponent(boolean)
* @see #setShowGuidelines(boolean)
* @see #setComponentFactory(ComponentFactory)
*/
public class GridBagLayoutFormBuilder extends AbstractFormBuilder
implements LayoutBuilder {
private final GridBagLayoutBuilder builder;
public static final class LabelOrientation extends ShortCodedEnum {
public static final LabelOrientation TOP =
new LabelOrientation(SwingConstants.TOP, "Top");
public static final LabelOrientation BOTTOM =
new LabelOrientation(SwingConstants.BOTTOM, "Bottom");
public static final LabelOrientation LEFT =
new LabelOrientation(SwingConstants.LEFT, "Left");
public static final LabelOrientation RIGHT =
new LabelOrientation(SwingConstants.RIGHT, "Right");
private LabelOrientation(int code, String label) {
super(code, label);
}
}
public GridBagLayoutFormBuilder(SwingFormModel swingFormModel) {
super(swingFormModel);
this.builder = new GridBagLayoutBuilder();
}
/**
* Returns the underlying {@link GridBagLayoutBuilder}. Should be used
* with caution.
*
* @return never null
*/
public final GridBagLayoutBuilder getBuilder() {
return builder;
}
public void setComponentFactory(ComponentFactory componentFactory) {
super.setComponentFactory(componentFactory);
builder.setComponentFactory(componentFactory);
}
/**
* Appends a label and field to the end of the current line.<p />
*
* The label will be to the left of the field, and be right-justified.<br />
* The field will "grow" horizontally as space allows.<p />
*
* @param propertyName the name of the property to create the controls for
*
* @return "this" to make it easier to string together append calls
*
* @see SwingFormModel#createLabel(String)
* @see SwingFormModel#createBoundControl(String)
*/
public GridBagLayoutFormBuilder appendLabeledField(String propertyName) {
return appendLabeledField(propertyName, LabelOrientation.LEFT);
}
/**
* Appends a label and field to the end of the current line.<p />
*
* The label will be to the left of the field, and be right-justified.<br />
* The field will "grow" horizontally as space allows.<p />
*
* @param propertyName the name of the property to create the controls for
* @param colSpan the number of columns the field should span
*
* @return "this" to make it easier to string together append calls
*
* @see SwingFormModel#createLabel(String)
* @see SwingFormModel#createBoundControl(String)
*/
public GridBagLayoutFormBuilder appendLabeledField(String propertyName,
int colSpan) {
return appendLabeledField(propertyName, LabelOrientation.LEFT,
colSpan);
}
/**
* Appends a label and field to the end of the current line.<p />
*
* The label will be to the left of the field, and be right-justified.<br />
* The field will "grow" horizontally as space allows.<p />
*
* @param propertyName the name of the property to create the controls for
*
* @return "this" to make it easier to string together append calls
*
* @see SwingFormModel#createLabel(String)
* @see SwingFormModel#createBoundControl(String)
*/
public GridBagLayoutFormBuilder appendLabeledField(String propertyName,
LabelOrientation labelOrientation) {
return appendLabeledField(propertyName, labelOrientation, 1);
}
/**
* Appends a label and field to the end of the current line.<p />
*
* The label will be to the left of the field, and be right-justified.<br />
* The field will "grow" horizontally as space allows.<p />
*
* @param propertyName the name of the property to create the controls for
* @param colSpan the number of columns the field should span
*
* @return "this" to make it easier to string together append calls
*
* @see SwingFormModel#createLabel(String)
* @see SwingFormModel#createBoundControl(String)
*/
public GridBagLayoutFormBuilder appendLabeledField(String propertyName,
LabelOrientation labelOrientation,
int colSpan) {
final JComponent field = getDefaultComponent(propertyName);
return appendLabeledField(propertyName, field, labelOrientation,
colSpan);
}
/**
* Appends a label and field to the end of the current line.<p />
*
* The label will be to the left of the field, and be right-justified.<br />
* The field will "grow" horizontally as space allows.<p />
*
* @param propertyName the name of the property to create the controls for
*
* @return "this" to make it easier to string together append calls
*
* @see SwingFormModel#createLabel(String)
* @see SwingFormModel#createBoundControl(String)
*/
public GridBagLayoutFormBuilder appendLabeledField(String propertyName,
final JComponent field,
LabelOrientation labelOrientation) {
return appendLabeledField(propertyName, field, labelOrientation, 1);
}
/**
* Appends a label and field to the end of the current line.<p />
*
* The label will be to the left of the field, and be right-justified.<br />
* The field will "grow" horizontally as space allows.<p />
*
* @param propertyName the name of the property to create the controls for
* @param colSpan the number of columns the field should span
*
* @return "this" to make it easier to string together append calls
*
* @see SwingFormModel#createLabel(String)
* @see FormComponentInterceptor#processLabel(String, JComponent)
*/
public GridBagLayoutFormBuilder appendLabeledField(String propertyName,
final JComponent field,
LabelOrientation labelOrientation,
int colSpan) {
return appendLabeledField(propertyName, field, labelOrientation,
colSpan, 1, true, false);
}
/**
* Appends a label and field to the end of the current line.<p />
*
* The label will be to the left of the field, and be right-justified.<br />
* The field will "grow" horizontally as space allows.<p />
*
* @param propertyName the name of the property to create the controls for
* @param colSpan the number of columns the field should span
*
* @return "this" to make it easier to string together append calls
*
* @see SwingFormModel#createLabel(String)
* @see FormComponentInterceptor#processLabel(String, JComponent)
*/
public GridBagLayoutFormBuilder appendLabeledField(String propertyName,
final JComponent field,
LabelOrientation labelOrientation,
int colSpan,
int rowSpan,
boolean expandX,
boolean expandY) {
final JLabel label = getLabelFor(propertyName, field);
if (labelOrientation == LabelOrientation.LEFT ||
labelOrientation == null) {
- label.setAlignmentX(JLabel.RIGHT_ALIGNMENT);
+ label.setHorizontalAlignment(JLabel.RIGHT);
builder.appendLabel(label).append(field, colSpan, rowSpan,
expandX, expandY);
}
else if (labelOrientation == LabelOrientation.RIGHT) {
- label.setAlignmentX(JLabel.LEFT_ALIGNMENT);
+ label.setHorizontalAlignment(JLabel.LEFT);
builder.append(field, colSpan, rowSpan, expandX, expandY)
.appendLabel(label);
}
else if (labelOrientation == LabelOrientation.TOP) {
- label.setAlignmentX(JLabel.LEFT_ALIGNMENT);
+ label.setHorizontalAlignment(JLabel.LEFT);
final int col = builder.getCurrentCol();
final int row = builder.getCurrentRow();
final Insets insets = builder.getDefaultInsets();
builder.append(label, col, row, colSpan, 1, false, expandY,
insets).append(field, col, row + 1, colSpan, rowSpan,
expandX, expandY, insets);
}
else if (labelOrientation == LabelOrientation.BOTTOM) {
- label.setAlignmentX(JLabel.LEFT_ALIGNMENT);
+ label.setHorizontalAlignment(JLabel.LEFT);
final int col = builder.getCurrentCol();
final int row = builder.getCurrentRow();
final Insets insets = builder.getDefaultInsets();
builder.append(field, col, row, colSpan, rowSpan, expandX,
expandY, insets).append(label, col, row + rowSpan,
colSpan, 1, false, expandY, insets);
}
return this;
}
/**
* Appends a seperator (usually a horizonal line). Has an implicit
* {@link #nextLine()} before and after it.
*
* @return "this" to make it easier to string together append calls
*/
public GridBagLayoutFormBuilder appendSeparator() {
return appendSeparator(null);
}
/**
* Appends a seperator (usually a horizonal line) using the provided
* string as the key to look in the
* {@link #setComponentFactory(ComponentFactory) ComponentFactory's}
* message bundle for the text to put along with the seperator. Has an
* implicit {@link #nextLine()} before and after it.
*
* @return "this" to make it easier to string together append calls
*/
public GridBagLayoutFormBuilder appendSeparator(String labelKey) {
builder.appendSeparator(labelKey);
return this;
}
/**
* Ends the current line and starts a new one
*
* @return "this" to make it easier to string together append calls
*/
public GridBagLayoutFormBuilder nextLine() {
builder.nextLine();
return this;
}
/**
* Should this show "guidelines"? Useful for debugging layouts.
*/
public void setShowGuidelines(boolean showGuidelines) {
builder.setShowGuidelines(showGuidelines);
}
/**
* Creates and returns a JPanel with all the given components in it, using
* the "hints" that were provided to the builder.
*
* @return a new JPanel with the components laid-out in it
*/
public JPanel getPanel() {
return builder.getPanel();
}
/**
* @see GridBagLayoutBuilder#setAutoSpanLastComponent(boolean)
*/
public void setAutoSpanLastComponent(boolean autoSpanLastComponent) {
builder.setAutoSpanLastComponent(autoSpanLastComponent);
}
}
| false | true | public GridBagLayoutFormBuilder appendLabeledField(String propertyName,
final JComponent field,
LabelOrientation labelOrientation,
int colSpan,
int rowSpan,
boolean expandX,
boolean expandY) {
final JLabel label = getLabelFor(propertyName, field);
if (labelOrientation == LabelOrientation.LEFT ||
labelOrientation == null) {
label.setAlignmentX(JLabel.RIGHT_ALIGNMENT);
builder.appendLabel(label).append(field, colSpan, rowSpan,
expandX, expandY);
}
else if (labelOrientation == LabelOrientation.RIGHT) {
label.setAlignmentX(JLabel.LEFT_ALIGNMENT);
builder.append(field, colSpan, rowSpan, expandX, expandY)
.appendLabel(label);
}
else if (labelOrientation == LabelOrientation.TOP) {
label.setAlignmentX(JLabel.LEFT_ALIGNMENT);
final int col = builder.getCurrentCol();
final int row = builder.getCurrentRow();
final Insets insets = builder.getDefaultInsets();
builder.append(label, col, row, colSpan, 1, false, expandY,
insets).append(field, col, row + 1, colSpan, rowSpan,
expandX, expandY, insets);
}
else if (labelOrientation == LabelOrientation.BOTTOM) {
label.setAlignmentX(JLabel.LEFT_ALIGNMENT);
final int col = builder.getCurrentCol();
final int row = builder.getCurrentRow();
final Insets insets = builder.getDefaultInsets();
builder.append(field, col, row, colSpan, rowSpan, expandX,
expandY, insets).append(label, col, row + rowSpan,
colSpan, 1, false, expandY, insets);
}
return this;
}
| public GridBagLayoutFormBuilder appendLabeledField(String propertyName,
final JComponent field,
LabelOrientation labelOrientation,
int colSpan,
int rowSpan,
boolean expandX,
boolean expandY) {
final JLabel label = getLabelFor(propertyName, field);
if (labelOrientation == LabelOrientation.LEFT ||
labelOrientation == null) {
label.setHorizontalAlignment(JLabel.RIGHT);
builder.appendLabel(label).append(field, colSpan, rowSpan,
expandX, expandY);
}
else if (labelOrientation == LabelOrientation.RIGHT) {
label.setHorizontalAlignment(JLabel.LEFT);
builder.append(field, colSpan, rowSpan, expandX, expandY)
.appendLabel(label);
}
else if (labelOrientation == LabelOrientation.TOP) {
label.setHorizontalAlignment(JLabel.LEFT);
final int col = builder.getCurrentCol();
final int row = builder.getCurrentRow();
final Insets insets = builder.getDefaultInsets();
builder.append(label, col, row, colSpan, 1, false, expandY,
insets).append(field, col, row + 1, colSpan, rowSpan,
expandX, expandY, insets);
}
else if (labelOrientation == LabelOrientation.BOTTOM) {
label.setHorizontalAlignment(JLabel.LEFT);
final int col = builder.getCurrentCol();
final int row = builder.getCurrentRow();
final Insets insets = builder.getDefaultInsets();
builder.append(field, col, row, colSpan, rowSpan, expandX,
expandY, insets).append(label, col, row + rowSpan,
colSpan, 1, false, expandY, insets);
}
return this;
}
|
diff --git a/src/org/jruby/util/Join.java b/src/org/jruby/util/Join.java
index 84e55ee9d..a521ef02d 100644
--- a/src/org/jruby/util/Join.java
+++ b/src/org/jruby/util/Join.java
@@ -1,129 +1,130 @@
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2008 MenTaLguY <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.util;
import java.util.LinkedList;
public final class Join {
private final LinkedList[] writes;
private long mask = 0;
private final Reaction[] reactions;
public static abstract class Reaction {
private final int[] indices;
private final long mask;
public Reaction(int ... indices) {
long mask = 0;
for ( int i = 0 ; i < indices.length ; ++i ) {
final int index = indices[i];
if ( index > 63 ) {
throw new IndexOutOfBoundsException();
}
mask |= 1L << index;
}
this.indices = indices.clone();
this.mask = mask;
}
public abstract void react(Join join, Object[] args);
}
public Join(final Reaction ... reactions) {
final LinkedList[] writes = new LinkedList[64];
long mask = 0;
for (Reaction reaction: reactions) {
mask |= reaction.mask;
}
int i;
for ( i = 0 ; mask != 0 && i < 64 ; ++i, mask >>= 1 ) {
if ( ( mask & 1 ) != 0 ) {
writes[i] = new LinkedList();
} else {
writes[i] = null;
}
}
this.reactions = reactions.clone();
this.writes = new LinkedList[i];
System.arraycopy(writes, 0, this.writes, 0, i);
}
public void send(int index, Object o) {
Reaction selectedReaction = null;
Object[] args = null;
synchronized (this) {
final LinkedList writing = writes[index];
if ( writing == null ) {
throw new IndexOutOfBoundsException();
}
writing.addLast(o);
mask |= 1L << index;
for (Reaction reaction: reactions) {
if ( ( reaction.mask & mask ) == reaction.mask ) {
selectedReaction = reaction;
final int[] indices = reaction.indices;
args = new Object[indices.length];
for ( int i = 0 ; i < indices.length ; ++i ) {
- final LinkedList reading = writes[indices[i]];
+ final int readIndex = indices[i];
+ final LinkedList reading = writes[readIndex];
args[i] = reading.removeFirst();
if (reading.isEmpty()) {
- mask &= ~(1L << i);
+ mask &= ~(1L << readIndex);
}
}
break;
}
}
}
if ( selectedReaction != null ) {
selectedReaction.react(this, args);
}
}
public static class SyncRequest {
private Object reply = null;
public SyncRequest() {}
public synchronized void sendReply(Object o) {
if ( o == null ) {
throw new NullPointerException();
} else if ( reply != null ) {
throw new IllegalStateException();
}
reply = o;
notifyAll();
}
public synchronized Object waitForReply() throws InterruptedException {
while ( reply == null ) {
wait();
}
return reply;
}
}
}
| false | true | public void send(int index, Object o) {
Reaction selectedReaction = null;
Object[] args = null;
synchronized (this) {
final LinkedList writing = writes[index];
if ( writing == null ) {
throw new IndexOutOfBoundsException();
}
writing.addLast(o);
mask |= 1L << index;
for (Reaction reaction: reactions) {
if ( ( reaction.mask & mask ) == reaction.mask ) {
selectedReaction = reaction;
final int[] indices = reaction.indices;
args = new Object[indices.length];
for ( int i = 0 ; i < indices.length ; ++i ) {
final LinkedList reading = writes[indices[i]];
args[i] = reading.removeFirst();
if (reading.isEmpty()) {
mask &= ~(1L << i);
}
}
break;
}
}
}
if ( selectedReaction != null ) {
selectedReaction.react(this, args);
}
}
| public void send(int index, Object o) {
Reaction selectedReaction = null;
Object[] args = null;
synchronized (this) {
final LinkedList writing = writes[index];
if ( writing == null ) {
throw new IndexOutOfBoundsException();
}
writing.addLast(o);
mask |= 1L << index;
for (Reaction reaction: reactions) {
if ( ( reaction.mask & mask ) == reaction.mask ) {
selectedReaction = reaction;
final int[] indices = reaction.indices;
args = new Object[indices.length];
for ( int i = 0 ; i < indices.length ; ++i ) {
final int readIndex = indices[i];
final LinkedList reading = writes[readIndex];
args[i] = reading.removeFirst();
if (reading.isEmpty()) {
mask &= ~(1L << readIndex);
}
}
break;
}
}
}
if ( selectedReaction != null ) {
selectedReaction.react(this, args);
}
}
|
diff --git a/src/test/java/com/ning/atlas/chef/TestUbuntuChefSoloInitializer.java b/src/test/java/com/ning/atlas/chef/TestUbuntuChefSoloInitializer.java
index 488dee9..bbd6751 100644
--- a/src/test/java/com/ning/atlas/chef/TestUbuntuChefSoloInitializer.java
+++ b/src/test/java/com/ning/atlas/chef/TestUbuntuChefSoloInitializer.java
@@ -1,256 +1,256 @@
package com.ning.atlas.chef;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.MoreExecutors;
import com.ning.atlas.Base;
import com.ning.atlas.BoundTemplate;
import com.ning.atlas.Environment;
import com.ning.atlas.InitializedServerTemplate;
import com.ning.atlas.InitializedTemplate;
import com.ning.atlas.Initializer;
import com.ning.atlas.My;
import com.ning.atlas.ProvisionedSystemTemplate;
import com.ning.atlas.ProvisionedTemplate;
import com.ning.atlas.SSH;
import com.ning.atlas.Server;
import com.ning.atlas.ServerTemplate;
import com.ning.atlas.aws.AWSConfig;
import com.ning.atlas.aws.EC2Provisioner;
import org.codehaus.jackson.map.ObjectMapper;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.skife.config.ConfigurationObjectFactory;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.ning.atlas.testing.AtlasMatchers.exists;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeThat;
import static org.junit.matchers.JUnitMatchers.containsString;
public class TestUbuntuChefSoloInitializer
{
private static final ObjectMapper mapper = new ObjectMapper();
private AWSConfig config;
private EC2Provisioner ec2;
private Properties props;
@Before
public void setUp() throws Exception
{
assumeThat(new File(".awscreds"), exists());
props = new Properties();
props.load(new FileInputStream(".awscreds"));
ConfigurationObjectFactory f = new ConfigurationObjectFactory(props);
config = f.build(AWSConfig.class);
this.ec2 = new EC2Provisioner(config);
}
@Test
public void testExplicitSpinUp() throws Exception
{
assumeThat(System.getProperty("RUN_EC2_TESTS"), notNullValue());
Environment env = new Environment("ec2");
Map<String, String> attributes =
ImmutableMap.of("ssh_user", "ubuntu",
"ssh_key_file", new File(props.getProperty("aws.key-file-path")).getAbsolutePath(),
"recipe_url", "https://s3.amazonaws.com/atlas-resources/chef-solo.tar.gz");
Initializer initializer = new UbuntuChefSoloInitializer(attributes);
Server s = ec2.provision(new Base("ubuntu", env, ImmutableMap.<String, String>of("ami", "ami-e2af508b")));
try {
Server init_server = initializer.initialize(s, "role[server]",
new ProvisionedSystemTemplate("root", "0", new My(),
Lists.<ProvisionedTemplate>newArrayList()));
SSH ssh = new SSH(new File(props.getProperty("aws.key-file-path")),
"ubuntu",
init_server.getExternalIpAddress());
String out = ssh.exec("java -version");
assertThat(out, containsString("Java(TM) SE Runtime Environment"));
}
finally {
ec2.destroy(s);
}
}
@Test
public void testInitializationVariations() throws Exception
{
Map<String, String> attributes =
ImmutableMap.of("ssh_user", "ubuntu",
"ssh_key_file", new File(props.getProperty("aws.key-file-path")).getAbsolutePath(),
"recipe_url", "https://s3.amazonaws.com/atlas-resources/chef-solo.tar.gz");
UbuntuChefSoloInitializer i = new UbuntuChefSoloInitializer(attributes);
String json = i.createNodeJsonFor("{ \"run_list\": [ \"role[java-core]\" ] }");
assertThat(mapper.readValue(json, UbuntuChefSoloInitializer.Node.class),
equalTo(new UbuntuChefSoloInitializer.Node("role[java-core]")));
}
@Test
public void testInitializationVariations2() throws Exception
{
Map<String, String> attributes =
ImmutableMap.of("ssh_user", "ubuntu",
"ssh_key_file", new File(props.getProperty("aws.key-file-path")).getAbsolutePath(),
"recipe_url", "https://s3.amazonaws.com/chefplay123/chef-solo.tar.gz");
UbuntuChefSoloInitializer i = new UbuntuChefSoloInitializer(attributes);
String json = i.createNodeJsonFor("role[java-core]");
assertThat(mapper.readValue(json, UbuntuChefSoloInitializer.Node.class),
equalTo(new UbuntuChefSoloInitializer.Node("role[java-core]")));
}
@Test
public void testInitializationVariations3() throws Exception
{
Map<String, String> attributes =
ImmutableMap.of("ssh_user", "ubuntu",
"ssh_key_file", new File(props.getProperty("aws.key-file-path")).getAbsolutePath(),
"recipe_url", "https://s3.amazonaws.com/atlas-resources/chef-solo.tar.gz");
UbuntuChefSoloInitializer i = new UbuntuChefSoloInitializer(attributes);
String json = i.createNodeJsonFor("role[java-core], recipe[emacs]");
assertThat(mapper.readValue(json, UbuntuChefSoloInitializer.Node.class),
equalTo(new UbuntuChefSoloInitializer.Node("role[java-core]", "recipe[emacs]")));
}
@Test
public void testWithEC2Provisioner() throws Exception
{
assumeThat(System.getProperty("RUN_EC2_TESTS"), notNullValue());
Environment env = new Environment("ec2");
env.setProvisioner(ec2);
ServerTemplate st = new ServerTemplate("server");
st.setBase("java-core");
Base java_core = new Base("java-core", env, ImmutableMap.<String, String>of("ami", "ami-e2af508b"));
java_core.addInit("chef-solo:role[server]");
env.addBase(java_core);
Map<String, String> attributes =
ImmutableMap.of("ssh_user", "ubuntu",
"ssh_key_file", new File(props.getProperty("aws.key-file-path")).getAbsolutePath(),
"recipe_url", "https://s3.amazonaws.com/atlas-resources/chef-solo.tar.gz");
env.addInitializer("chef-solo", new UbuntuChefSoloInitializer(attributes));
BoundTemplate bt = st.normalize(env);
ExecutorService ex = Executors.newCachedThreadPool();
ProvisionedTemplate pt = bt.provision(ex).get();
InitializedTemplate it = pt.initialize(ex, pt).get();
assertThat(it, instanceOf(InitializedServerTemplate.class));
InitializedServerTemplate ist = (InitializedServerTemplate) it;
Server s = ist.getServer();
SSH ssh = new SSH(new File(props.getProperty("aws.key-file-path")),
"ubuntu",
s.getExternalIpAddress());
String out = ssh.exec("java -version");
assertThat(out, containsString("Java(TM) SE Runtime Environment"));
ex.shutdown();
ec2.destroy(s);
}
@Test
public void testSystemMapMakesItUp() throws Exception
{
assumeThat(System.getProperty("RUN_EC2_TESTS"), notNullValue());
Environment env = new Environment("ec2");
env.setProvisioner(ec2);
ServerTemplate st = new ServerTemplate("server");
st.setBase("java-core");
Base java_core = new Base("java-core", env, ImmutableMap.<String, String>of("ami", "ami-e2af508b"));
- java_core.addInit("chef-solo:{\"run_list\":[\"role[java-core]\"]}");
+ java_core.addInit("chef-solo:{\"run_list\":[\"role[server]\"]}");
env.addBase(java_core);
Map<String, String> attributes =
ImmutableMap.of("ssh_user", "ubuntu",
"ssh_key_file", new File(props.getProperty("aws.key-file-path")).getAbsolutePath(),
"recipe_url", "https://s3.amazonaws.com/atlas-resources/chef-solo.tar.gz");
env.addInitializer("chef-solo", new UbuntuChefSoloInitializer(attributes));
BoundTemplate bt = st.normalize(env);
ExecutorService ex = Executors.newCachedThreadPool();
ProvisionedTemplate pt = bt.provision(ex).get();
InitializedTemplate it = pt.initialize(ex, pt).get();
assertThat(it, instanceOf(InitializedServerTemplate.class));
InitializedServerTemplate ist = (InitializedServerTemplate) it;
Server s = ist.getServer();
- SSH ssh = new SSH(new File(props.getProperty("aws.private-key-fle")),
+ SSH ssh = new SSH(new File(props.getProperty("aws.key-file-path")),
"ubuntu",
s.getExternalIpAddress());
String out = ssh.exec("cat /etc/atlas/system_map.json");
assertThat(out, containsString("\"name\" : \"server\""));
assertThat(out, containsString("externalIP"));
assertThat(out, containsString("internalIP"));
ex.shutdown();
ec2.destroy(s);
}
@Test
public void testEndToEndOnEC2() throws Exception
{
assumeThat(System.getProperty("RUN_EC2_TESTS"), notNullValue());
Environment env = new Environment("ec2");
env.setProvisioner(ec2);
Base java_core = new Base("server", env, ImmutableMap.<String, String>of("ami", "ami-e2af508b"));
java_core.addInit("chef-solo:role[server]");
env.addBase(java_core);
Map<String, String> attributes =
ImmutableMap.of("ssh_user", "ubuntu",
"ssh_key_file", new File(props.getProperty("aws.key-file-path")).getAbsolutePath(),
"recipe_url", "https://s3.amazonaws.com/atlas-resources/chef-solo.tar.gz");
env.addInitializer("chef-solo", new UbuntuChefSoloInitializer(attributes));
ServerTemplate st = new ServerTemplate("shell");
st.setBase("server");
st.setCardinality(asList("eshell"));
BoundTemplate bt = st.normalize(env);
ProvisionedTemplate pt = bt.provision(MoreExecutors.sameThreadExecutor()).get();
InitializedTemplate it = pt.initialize(MoreExecutors.sameThreadExecutor(), pt).get();
InitializedServerTemplate ist = (InitializedServerTemplate) it;
ec2.destroy(ist.getServer());
}
}
| false | true | public void testSystemMapMakesItUp() throws Exception
{
assumeThat(System.getProperty("RUN_EC2_TESTS"), notNullValue());
Environment env = new Environment("ec2");
env.setProvisioner(ec2);
ServerTemplate st = new ServerTemplate("server");
st.setBase("java-core");
Base java_core = new Base("java-core", env, ImmutableMap.<String, String>of("ami", "ami-e2af508b"));
java_core.addInit("chef-solo:{\"run_list\":[\"role[java-core]\"]}");
env.addBase(java_core);
Map<String, String> attributes =
ImmutableMap.of("ssh_user", "ubuntu",
"ssh_key_file", new File(props.getProperty("aws.key-file-path")).getAbsolutePath(),
"recipe_url", "https://s3.amazonaws.com/atlas-resources/chef-solo.tar.gz");
env.addInitializer("chef-solo", new UbuntuChefSoloInitializer(attributes));
BoundTemplate bt = st.normalize(env);
ExecutorService ex = Executors.newCachedThreadPool();
ProvisionedTemplate pt = bt.provision(ex).get();
InitializedTemplate it = pt.initialize(ex, pt).get();
assertThat(it, instanceOf(InitializedServerTemplate.class));
InitializedServerTemplate ist = (InitializedServerTemplate) it;
Server s = ist.getServer();
SSH ssh = new SSH(new File(props.getProperty("aws.private-key-fle")),
"ubuntu",
s.getExternalIpAddress());
String out = ssh.exec("cat /etc/atlas/system_map.json");
assertThat(out, containsString("\"name\" : \"server\""));
assertThat(out, containsString("externalIP"));
assertThat(out, containsString("internalIP"));
ex.shutdown();
ec2.destroy(s);
}
| public void testSystemMapMakesItUp() throws Exception
{
assumeThat(System.getProperty("RUN_EC2_TESTS"), notNullValue());
Environment env = new Environment("ec2");
env.setProvisioner(ec2);
ServerTemplate st = new ServerTemplate("server");
st.setBase("java-core");
Base java_core = new Base("java-core", env, ImmutableMap.<String, String>of("ami", "ami-e2af508b"));
java_core.addInit("chef-solo:{\"run_list\":[\"role[server]\"]}");
env.addBase(java_core);
Map<String, String> attributes =
ImmutableMap.of("ssh_user", "ubuntu",
"ssh_key_file", new File(props.getProperty("aws.key-file-path")).getAbsolutePath(),
"recipe_url", "https://s3.amazonaws.com/atlas-resources/chef-solo.tar.gz");
env.addInitializer("chef-solo", new UbuntuChefSoloInitializer(attributes));
BoundTemplate bt = st.normalize(env);
ExecutorService ex = Executors.newCachedThreadPool();
ProvisionedTemplate pt = bt.provision(ex).get();
InitializedTemplate it = pt.initialize(ex, pt).get();
assertThat(it, instanceOf(InitializedServerTemplate.class));
InitializedServerTemplate ist = (InitializedServerTemplate) it;
Server s = ist.getServer();
SSH ssh = new SSH(new File(props.getProperty("aws.key-file-path")),
"ubuntu",
s.getExternalIpAddress());
String out = ssh.exec("cat /etc/atlas/system_map.json");
assertThat(out, containsString("\"name\" : \"server\""));
assertThat(out, containsString("externalIP"));
assertThat(out, containsString("internalIP"));
ex.shutdown();
ec2.destroy(s);
}
|
diff --git a/tests/src/com/android/music/MusicPlayerStability.java b/tests/src/com/android/music/MusicPlayerStability.java
index 5654adb..d84d2f8 100644
--- a/tests/src/com/android/music/MusicPlayerStability.java
+++ b/tests/src/com/android/music/MusicPlayerStability.java
@@ -1,88 +1,90 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.music.tests;
import android.app.Instrumentation;
import com.android.music.TrackBrowserActivity;
import android.view.KeyEvent;
import android.widget.ListView;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
/**
* Junit / Instrumentation test case for the Music Player
*/
public class MusicPlayerStability extends ActivityInstrumentationTestCase2 <TrackBrowserActivity>{
private static String TAG = "musicplayerstability";
private static int PLAY_TIME = 30000;
private ListView mTrackList;
public MusicPlayerStability() {
super("com.android.music",TrackBrowserActivity.class);
}
@Override
protected void setUp() throws Exception {
getActivity();
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test case 1: This test case is for the power and general stability
* measurment. We don't need to do the validation. This test case simply
* play the mp3 for 30 seconds then stop.
* The sdcard should have the target mp3 files.
*/
@LargeTest
public void testPlay30sMP3() throws Exception {
// Launch the songs list. Pick the fisrt song and play
try {
Instrumentation inst = getInstrumentation();
+ //Make sure the song list shown up
+ Thread.sleep(2000);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
mTrackList = getActivity().getListView();
- int viewCount = mTrackList.getSelectedItemPosition();
+ int scrollCount = mTrackList.getMaxScrollAmount();
//Make sure there is at least one song in the sdcard
- if (viewCount != -1) {
+ if (scrollCount != -1) {
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
} else {
assertTrue("testPlayMP3", false);
}
Thread.sleep(PLAY_TIME);
} catch (Exception e) {
assertTrue("testPlayMP3", false);
}
}
@LargeTest
public void testLaunchMusicPlayer() throws Exception {
// Launch music player and sleep for 30 seconds to capture
// the music player power usage base line.
try {
Thread.sleep(PLAY_TIME);
} catch (Exception e) {
assertTrue("MusicPlayer Do Nothing", false);
}
assertTrue("MusicPlayer Do Nothing", true);
}
}
| false | true | public void testPlay30sMP3() throws Exception {
// Launch the songs list. Pick the fisrt song and play
try {
Instrumentation inst = getInstrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
mTrackList = getActivity().getListView();
int viewCount = mTrackList.getSelectedItemPosition();
//Make sure there is at least one song in the sdcard
if (viewCount != -1) {
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
} else {
assertTrue("testPlayMP3", false);
}
Thread.sleep(PLAY_TIME);
} catch (Exception e) {
assertTrue("testPlayMP3", false);
}
}
| public void testPlay30sMP3() throws Exception {
// Launch the songs list. Pick the fisrt song and play
try {
Instrumentation inst = getInstrumentation();
//Make sure the song list shown up
Thread.sleep(2000);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
mTrackList = getActivity().getListView();
int scrollCount = mTrackList.getMaxScrollAmount();
//Make sure there is at least one song in the sdcard
if (scrollCount != -1) {
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
} else {
assertTrue("testPlayMP3", false);
}
Thread.sleep(PLAY_TIME);
} catch (Exception e) {
assertTrue("testPlayMP3", false);
}
}
|
diff --git a/code/mnj/lua/Lua.java b/code/mnj/lua/Lua.java
index f98cf37..84936f0 100644
--- a/code/mnj/lua/Lua.java
+++ b/code/mnj/lua/Lua.java
@@ -1,3954 +1,3953 @@
/* $Header$
* (c) Copyright 2006, Intuwave Ltd. All Rights Reserved.
*
* Although Intuwave has tested this program and reviewed the documentation,
* Intuwave makes no warranty or representation, either expressed or implied,
* with respect to this software, its quality, performance, merchantability,
* or fitness for a particular purpose. As a result, this software is licensed
* "AS-IS", and you are assuming the entire risk as to its quality and
* performance.
*
* You are granted license to use this code as a basis for your own
* application(s) under the terms of the separate license between you and
* Intuwave.
*/
package mnj.lua;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Stack;
import java.util.Vector;
/**
* <p>
* Encapsulates a Lua execution environment. A lot of Jili's public API
* manifests as public methods in this class. A key part of the API is
* the ability to call Lua functions from Java (ultimately, all Lua code
* is executed in this manner).
* </p>
*
* <p>
* The Stack
* </p>
*
* <p>
* All arguments to Lua functions and all results returned by Lua
* functions are placed onto a stack. The stack can be indexed by an
* integer in the same way as the PUC-Rio implementation. A positive
* index is an absolute index and ranges from 1 (the bottom-most
* element) through to <var>n</var> (the top-most element),
* where <var>n</var> is the number of elements on the stack. Negative
* indexes are relative indexes, -1 is the top-most element, -2 is the
* element underneath that, and so on. 0 is not used.
* </p>
*
* <p>
* Note that in Jili the stack is used only for passing arguments and
* returning results, unlike PUC-Rio.
* </p>
*
* <p>
* The protocol for calling a function is described in the {@link Lua#call}
* method. In brief: push the function onto the stack, then push the
* arguments to the call.
* </p>
*
* <p>
* The methods {@link Lua#push}, {@link Lua#pop}, {@link Lua#value},
* {@link Lua#getTop}, {@link Lua#setTop} are used to manipulate the stack.
* </p>
*/
public final class Lua
{
/** Version string. */
public static final String VERSION = "Lua 5.1 (Jili 0.X.Y)";
/** Table of globals (global variables). This actually shared across
* all coroutines (with the same main thread), but kept in each Lua
* thread as an optimisation.
*/
private LuaTable global;
/** Reference the main Lua thread. Itself if this is the main Lua
* thread.
*/
private Lua main;
/** VM data stack. */
private Vector stack = new Vector();
private int base; // = 0;
int nCcalls; // = 0;
/** Instruction to resume execution at. Index into code array. */
private int savedpc; // = 0;
/**
* Vector of CallInfo records. Actually it's a Stack which is a
* subclass of Vector, but it mostly the Vector methods that are used.
*/
private Stack civ = new Stack();
{
civ.addElement(new CallInfo());
}
/** CallInfo record for currently active function. */
private CallInfo ci()
{
return (CallInfo)civ.lastElement();
}
/** Open Upvalues. All UpVal objects that reference the VM stack.
* openupval is a java.util.Vector of UpVal stored in order of stack
* slot index: higher stack indexes are stored at higher Vector
* positions.
*/
private Vector openupval = new Vector();
/** Number of list items to accumulate before a SETLIST instruction. */
static final int LFIELDS_PER_FLUSH = 50;
/** Limit for table tag-method chains (to avoid loops) */
private static final int MAXTAGLOOP = 100;
/** Used to communicate error status (ERRRUN, etc) from point where
* error is raised to the code that catches it.
*/
private int errorStatus;
/**
* The current error handler (set by {@link Lua#pcall}). A Lua
* function to call.
*/
private Object errfunc;
/**
* coroutine activation status.
*/
private int status;
/** Nonce object used by pcall and friends (to detect when an
* exception is a Lua error). */
private static final String LUA_ERROR = "";
/** Metatable for primitive types. Shared between all coroutines. */
private LuaTable[] metatable;
/**
* Maximum number of local variables per function. As per
* LUAI_MAXVARS from "luaconf.h". Default access so that {@link
* FuncState} can see it.
*/
static final int MAXVARS = 200;
static final int MAXSTACK = 250;
static final int MAXUPVALUES = 60;
/**
* Used to construct a Lua thread that shares its global state with
* another Lua state.
*/
private Lua(Lua L)
{
// Copy the global state, that's shared across all coroutines that
// share the same main thread, into the new Lua thread.
// Any more than this and the global state should be shunted to a
// separate object (as it is in PUC-Rio).
this.global = L.global;
this.metatable = L.metatable;
this.main = L;
}
//////////////////////////////////////////////////////////////////////
// Public API
/**
* Creates a fresh Lua state.
*/
public Lua()
{
this.global = new LuaTable();
this.metatable = new LuaTable[NUM_TAGS];
this.main = this;
}
/**
* Equivalent of LUA_MULTRET.
*/
// Required, by vmPoscall, to be negative.
public static final int MULTRET = -1;
/**
* The Lua <code>nil</code> value.
*/
public static final Object NIL = null;
// Lua type tags, from lua.h
/** Lua type tag, representing no stack value. */
public static final int TNONE = -1;
/** Lua type tag, representing <code>nil</code>. */
public static final int TNIL = 0;
/** Lua type tag, representing boolean. */
public static final int TBOOLEAN = 1;
// TLIGHTUSERDATA not available. :todo: make available?
/** Lua type tag, representing numbers. */
public static final int TNUMBER = 3;
/** Lua type tag, representing strings. */
public static final int TSTRING = 4;
/** Lua type tag, representing tables. */
public static final int TTABLE = 5;
/** Lua type tag, representing functions. */
public static final int TFUNCTION = 6;
/** Lua type tag, representing userdata. */
public static final int TUSERDATA = 7;
/** Lua type tag, representing threads. */
public static final int TTHREAD = 8;
/** Number of type tags. Should correspond to last entry in the list
* of tags.
*/
private static final int NUM_TAGS = 8;
/** Names for above type tags, starting from {@link Lua#TNIL}.
* Equivalent to luaT_typenames.
*/
private static final String[] TYPENAME =
{
"nil", "boolean", "userdata", "number",
"string", "table", "function", "userdata", "thread"
};
/**
* Minimum stack size that Lua Java functions gets. May turn out to
* be silly / redundant.
*/
public static final int MINSTACK = 20;
/** Status code, returned from pcall and friends, that indicates the
* coroutine has yielded.
*/
public static final int YIELD = 1;
/** Status code, returned from pcall and friends, that indicates
* a runtime error.
*/
public static final int ERRRUN = 2;
/** Status code, returned from pcall and friends, that indicates
* a syntax error.
*/
public static final int ERRSYNTAX = 3;
/** Status code, returned from pcall and friends, that indicates
* a memory allocation error.
*/
private static final int ERRMEM = 4;
/** Status code, returned from pcall and friends, that indicates
* an error whilst running the error handler function.
*/
public static final int ERRERR = 5;
/** Status code, returned from loadFile and friends, that indicates
* an IO error.
*/
public static final int ERRFILE = 6;
// Enums for gc().
/** Action, passed to {@link Lua#gc}, that requests the GC to stop. */
public static final int GCSTOP = 0;
/** Action, passed to {@link Lua#gc}, that requests the GC to restart. */
public static final int GCRESTART = 1;
/** Action, passed to {@link Lua#gc}, that requests a full collection. */
public static final int GCCOLLECT = 2;
/** Action, passed to {@link Lua#gc}, that returns amount of memory
* (in Kibibytes) in use (by the entire Java runtime).
*/
public static final int GCCOUNT = 3;
/** Action, passed to {@link Lua#gc}, that returns the remainder of
* dividing the amount of memory in use by 1024.
*/
public static final int GCCOUNTB = 4;
/** Action, passed to {@link Lua#gc}, that requests an incremental
* garbage collection be performed.
*/
public static final int GCSTEP = 5;
/** Action, passed to {@link Lua#gc}, that sets a new value for the
* <var>pause</var> of the collector.
*/
public static final int GCSETPAUSE = 6;
/** Action, passed to {@link Lua#gc}, that sets a new values for the
* <var>step multiplier</var> of the collector.
*/
public static final int GCSETSTEPMUL = 7;
/**
* Calls a Lua value. Normally this is called on functions, but the
* semantics of Lua permit calls on any value as long as its metatable
* permits it.
*
* In order to call a function, the function must be
* pushed onto the stack, then its arguments must be
* {@link Lua#push pushed} onto the stack; the first argument is pushed
* directly after the function,
* then the following arguments are pushed in order (direct
* order). The parameter <var>nargs</var> specifies the number of
* arguments (which may be 0).
*
* When the function returns the function value on the stack and all
* the arguments are removed from the stack and replaced with the
* results of the function, adjusted to the number specified by
* <var>nresults</var>. So the first result from the function call will
* be at the same index where the function was immediately prior to
* calling this method.
*
* @param nargs The number of arguments in this function call.
* @param nresults The number of results required.
*/
public void call(int nargs, int nresults)
{
apiChecknelems(nargs+1);
int func = stack.size() - (nargs + 1);
this.vmCall(func, nresults);
}
/**
* Closes a Lua state. In this implementation, this method does
* nothing.
*/
public void close()
{
}
/**
* Concatenate values (usually strings) on the stack.
* <var>n</var> values from the top of the stack are concatenated, as
* strings, and replaced with the resulting string.
* @param n the number of values to concatenate.
*/
public void concat(int n)
{
apiChecknelems(n);
if (n >= 2)
{
vmConcat(n, (stack.size() - base) - 1);
pop(n-1);
}
else if (n == 0) // push empty string
{
push("");
} // else n == 1; nothing to do
}
/**
* Creates a new empty table and returns it.
* @param narr number of array elements to pre-allocate.
* @param nrec number of non-array elements to pre-allocate.
* @return a fresh table.
* @see Lua#newTable
*/
public LuaTable createTable(int narr, int nrec)
{
return new LuaTable(narr, nrec);
}
/**
* Dumps a function as a binary chunk.
* @param function the Lua function to dump.
* @param writer the stream that receives the dumped binary.
* @throws IOException when writer does.
*/
public static void dump(Object function, OutputStream writer)
throws IOException
{
if (!(function instanceof LuaFunction))
{
throw new IOException("Cannot dump " + typeName(type(function)));
}
LuaFunction f = (LuaFunction)function;
uDump(f.proto(), writer, false);
}
/**
* Tests for equality according to the semantics of Lua's
* <code>==</code> operator (so may call metamethods).
* @param o1 a Lua value.
* @param o2 another Lua value.
* @return true when equal.
*/
public boolean equal(Object o1, Object o2)
{
return vmEqual(o1, o2);
}
/**
* Generates a Lua error using the error message.
* @param message the error message.
* @return never.
*/
public int error(Object message)
{
return gErrormsg(message);
}
/**
* Control garbage collector. Note that in Jili most of the options
* to this function make no sense and they will not do anything.
* @param what specifies what GC action to take.
* @param data data that may be used by the action.
* @return varies.
*/
public int gc(int what, int data)
{
Runtime rt;
switch (what)
{
case GCSTOP:
return 0;
case GCRESTART:
case GCCOLLECT:
case GCSTEP:
System.gc();
return 0;
case GCCOUNT:
rt = Runtime.getRuntime();
return (int)((rt.totalMemory() - rt.freeMemory()) / 1024);
case GCCOUNTB:
rt = Runtime.getRuntime();
return (int)((rt.totalMemory() - rt.freeMemory()) % 1024);
case GCSETPAUSE:
case GCSETSTEPMUL:
return 0;
}
return 0;
}
/**
* Returns the environment table of the Lua value.
* @param o the Lua value.
* @return its environment table.
*/
public LuaTable getFenv(Object o)
{
if (o instanceof LuaFunction)
{
LuaFunction f = (LuaFunction)o;
return f.getEnv();
}
if (o instanceof LuaJavaCallback)
{
LuaJavaCallback f = (LuaJavaCallback)o;
// :todo: implement this case.
return null;
}
if (o instanceof LuaUserdata)
{
LuaUserdata u = (LuaUserdata)o;
return u.getEnv();
}
if (o instanceof Lua)
{
Lua l = (Lua)o;
return l.global;
}
return null;
}
/**
* Get a field from a table (or other object).
* @param t The object whose field to retrieve.
* @param field The name of the field.
* @return the Lua value
*/
public Object getField(Object t, String field)
{
return vmGettable(t, field);
}
/**
* Get a global variable.
* @param name The name of the global variable.
* @return The value of the global variable.
*/
public Object getGlobal(String name)
{
return vmGettable(global, name);
}
/**
* Gets the global environment. The global environment, where global
* variables live, is returned as a <code>LuaTable</code>. Note that
* modifying this table has exactly the same effect as creating or
* changing global variables from within Lua.
* @return The global environment as a table.
*/
public LuaTable getGlobals()
{
return global;
}
/** Get metatable.
* @param o the Lua value whose metatable to retrieve.
* @return The metatable, or null if there is no metatable.
*/
public LuaTable getMetatable(Object o)
{
LuaTable mt;
if (o instanceof LuaTable)
{
LuaTable t = (LuaTable)o;
mt = t.getMetatable();
}
else if (o instanceof LuaUserdata)
{
LuaUserdata u = (LuaUserdata)o;
mt = u.getMetatable();
}
else
{
mt = metatable[type(o)];
}
return mt;
}
/**
* Indexes into a table and returns the value.
* @param t the Lua value to index.
* @param k the key whose value to return.
* @return the value t[k].
*/
public Object getTable(Object t, Object k)
{
return vmGettable(t, k);
}
/**
* Gets the number of elements in the stack. If the stack is not
* empty then this is the index of the top-most element.
* @return number of stack elements.
*/
public int getTop()
{
return stack.size() - base;
}
/**
* Insert Lua value into stack immediately at specified index. Values
* in stack at that index and higher get pushed up.
* @param o the Lua value to insert into the stack.
* @param idx the stack index at which to insert.
*/
public void insert(Object o, int idx)
{
idx = absIndex(idx);
stack.insertElementAt(o, idx);
}
/**
* Tests that an object is a Lua boolean.
* @param o the Object to test.
* @return true if and only if the object is a Lua boolean.
*/
public static boolean isBoolean(Object o)
{
return o instanceof Boolean;
}
/**
* Tests that an object is a Lua function implementated in Java (a Lua
* Java Function).
* @param o the Object to test.
* @return true if and only if the object is a Lua Java Function.
*/
public static boolean isJavaFunction(Object o)
{
return o instanceof LuaJavaCallback;
}
/**
* Tests that an object is a Lua function (implemented in Lua or
* Java).
* @param o the Object to test.
* @return true if and only if the object is a function.
*/
public static boolean isFunction(Object o)
{
return o instanceof LuaFunction ||
o instanceof LuaJavaCallback;
}
/**
* Tests that a Lua thread is the main thread.
* @return true if and only if is the main thread.
*/
public boolean isMain()
{
return this == main;
}
/**
* Tests that an object is Lua <code>nil</code>.
* @param o the Object to test.
* @return true if and only if the object is Lua <code>nil</code>.
*/
public static boolean isNil(Object o)
{
return null == o;
}
/**
* Tests that an object is a Lua number or a string convertible to a
* number.
* @param o the Object to test.
* @return true if and only if the object is a number or a convertible string.
*/
public static boolean isNumber(Object o)
{
return tonumber(o, NUMOP);
}
/**
* Tests that an object is a Lua string or a number (which is always
* convertible to a string).
* @param o the Object to test.
* @return true if and only if object is a string or number.
*/
public static boolean isString(Object o)
{
return o instanceof String;
}
/**
* Tests that an object is a Lua table.
* @param o the Object to test.
* @return <code>true</code> if and only if the object is a Lua table.
*/
public static boolean isTable(Object o)
{
return o instanceof LuaTable;
}
/**
* Tests that an object is a Lua thread.
* @param o the Object to test.
* @return <code>true</code> if and only if the object is a Lua thread.
*/
public static boolean isThread(Object o)
{
return o instanceof Lua;
}
/**
* Tests that an object is a Lua userdata.
* @param o the Object to test.
* @return true if and only if the object is a Lua userdata.
*/
public static boolean isUserdata(Object o)
{
return o instanceof LuaUserdata;
}
/**
* <p>
* Tests that an object is a Lua value. Returns <code>true</code> for
* an argument that is a Jili representation of a Lua value,
* <code>false</code> for Java references that are not Lua values.
* For example <code>isValue(new LuaTable())</code> is
* <code>true</code>, but <code>isValue(new Object[] { })</code> is
* <code>false</code> because Java arrays are not a representation of
* any Lua value.
* </p>
* <p>
* PUC-Rio Lua provides no
* counterpart for this method because in their implementation it is
* impossible to get non Lua values on the stack, whereas in Jili it
* is common to mix Lua values with ordinary, non Lua, Java objects.
* </p>
* @param o the Object to test.
* @return true if and if it represents a Lua value.
*/
public static boolean isValue(Object o)
{
return o == null ||
o instanceof Boolean ||
o instanceof String ||
o instanceof Double ||
o instanceof LuaFunction ||
o instanceof LuaJavaCallback ||
o instanceof LuaTable ||
o instanceof LuaUserdata;
}
/**
* Compares two Lua values according to the semantics of Lua's
* <code><</code> operator, so may call metamethods.
* @param o1 the left-hand operand.
* @param o2 the right-hand operand.
* @return true when <code>o1 < o2</code>.
*/
public boolean lessThan(Object o1, Object o2)
{
return vmLessthan(o1, o2);
}
/**
* <p>
* Loads a Lua chunk in binary or source form.
* Comparable to C's lua_load. If the chunk is determined to be
* binary then it is loaded directly. Otherwise the chunk is assumed
* to be a Lua source chunk and compilation is required first; the
* <code>InputStream</code> is used to create a <code>Reader</code>
* using the UTF-8 encoding
* (using a second argument of <code>"UTF-8"</code> to the
* {@link java.io.InputStreamReader#InputStreamReader(java.io.InputStream,
* java.lang.String)}
* constructor) and the Lua source is compiled.
* </p>
* <p>
* If successful, The compiled chunk, a Lua function, is pushed onto
* the stack and a zero status code is returned. Otherwise a non-zero
* status code is returned to indicate an error and the error message
* is pushed onto the stack.
* </p>
* @param in The binary chunk as an InputStream, for example from
* {@link Class#getResourceAsStream}.
* @param chunkname The name of the chunk.
* @return A status code.
*/
public int load(InputStream in, String chunkname)
{
push(new LuaInternal(in, chunkname));
return pcall(0, 1, null);
}
/**
* Loads a Lua chunk in source form.
* Comparable to C's lua_load. Since this takes a {@link
* java.io.Reader} parameter,
* this method is restricted to loading Lua chunks in source form.
* In every other respect this method is just like {@link
* Lua#load(InputStream, String)}.
* @param in The source chunk as a Reader, for example from
* <code>java.io.InputStreamReader(Class.getResourceAsStream())</code>.
* @param chunkname The name of the chunk.
* @return A status code.
* @see java.io.InputStreamReader
*/
public int load(Reader in, String chunkname)
{
push(new LuaInternal(in, chunkname));
return pcall(0, 1, null);
}
/**
* Slowly get the next key from a table. Unlike most other functions
* in the API this one uses the stack. The top-of-stack is popped and
* used to find the next key in the table at the position specified by
* index. If there is a next key then the key and its value are
* pushed onto the stack and <code>true</code> is returned.
* Otherwise (the end of the table has been reached)
* <code>false</code> is returned.
* @param idx stack index of table.
* @return true if and only if there are more keys in the table.
* @deprecated Use {@link Lua#tableKeys} enumeration protocol instead.
*/
public boolean next(int idx)
{
Object o = value(idx);
// :todo: api check
LuaTable t = (LuaTable)o;
Object key = value(-1);
pop(1);
Enumeration e = t.keys();
if (key == NIL)
{
if (e.hasMoreElements())
{
key = e.nextElement();
push(key);
push(t.get(key));
return true;
}
return false;
}
while (e.hasMoreElements())
{
Object k = e.nextElement();
if (k == key)
{
if (e.hasMoreElements())
{
key = e.nextElement();
push(key);
push(t.get(key));
return true;
}
return false;
}
}
// protocol error which we could potentially diagnose.
return false;
}
/**
* Creates a new empty table and returns it.
* @return a fresh table.
* @see Lua#createTable
*/
public LuaTable newTable()
{
return new LuaTable();
}
/**
* Creates a new Lua thread and returns it.
* @return a new Lua thread.
*/
public Lua newThread()
{
return new Lua(this);
}
/**
* Wraps an arbitrary Java reference in a Lua userdata and returns it.
* @param ref the Java reference to wrap.
* @return the new LuaUserdata.
*/
public LuaUserdata newUserdata(Object ref)
{
return new LuaUserdata(ref);
}
/**
* Return the <em>length</em> of a Lua value. For strings this is
* the string length; for tables, this is result of the <code>#</code>
* operator; for other values it is 0.
* @param o a Lua value.
* @return its length.
*/
public static int objLen(Object o)
{
if (o instanceof String)
{
String s = (String)o;
return s.length();
}
if (o instanceof LuaTable)
{
LuaTable t = (LuaTable)o;
return t.getn();
}
if (o instanceof Double)
{
return vmTostring(o).length();
}
return 0;
}
/**
* <p>
* Protected {@link Lua#call}. <var>nargs</var> and
* <var>nresults</var> have the same meaning as in {@link Lua#call}.
* If there are no errors during the call, this method behaves as
* {@link Lua#call}. Any errors are caught, the error object (usually
* a message) is pushed onto the stack, and a non-zero error code is
* returned.
* </p>
* <p>
* If <var>er</var> is <code>null</code> then the error object that is
* on the stack is the original error object. Otherwise
* <var>ef</var> specifies an <em>error handling function</em> which
* is called when the original error is generated; its return value
* becomes the error object left on the stack by <code>pcall</code>.
* </p>
* @param nargs number of arguments.
* @param nresults number of result required.
* @param ef error function to call in case of error.
* @return 0 if successful, else a non-zero error code.
*/
public int pcall(int nargs, int nresults, Object ef)
{
apiChecknelems(nargs+1);
int restoreStack = stack.size() - (nargs + 1);
// Most of this code comes from luaD_pcall
int restoreCi = civ.size();
int oldnCcalls = nCcalls;
Object old_errfunc = errfunc;
errfunc = ef;
// :todo: save and restore allowhooks
try
{
errorStatus = 0;
call(nargs, nresults);
}
catch (RuntimeException e)
{
if (e.getMessage() == LUA_ERROR)
{
fClose(restoreStack); // close eventual pending closures
dSeterrorobj(errorStatus, restoreStack);
nCcalls = oldnCcalls;
civ.setSize(restoreCi);
CallInfo ci = ci();
base = ci.base();
savedpc = ci.savedpc();
}
else
{
throw e;
}
}
errfunc = old_errfunc;
return errorStatus;
}
/**
* Removes (and discards) the top-most <var>n</var> elements from the stack.
* @param n the number of elements to remove.
*/
public void pop(int n)
{
if (n < 0)
{
throw new IllegalArgumentException();
}
stack.setSize(stack.size() - n);
}
/**
* Pushes a value onto the stack in preparation for calling a
* function (or returning from one). See {@link Lua#call} for
* the protocol to be used for calling functions. See {@link
* Lua#pushNumber} for pushing numbers, and {@link Lua#pushValue} for
* pushing a value that is already on the stack.
* @param o the Lua value to push.
*/
public void push(Object o)
{
stack.addElement(o);
}
/**
* Push boolean onto the stack.
* @param b the boolean to push.
*/
public void pushBoolean(boolean b)
{
push(valueOfBoolean(b));
}
/**
* Push literal string onto the stack.
* @param s the string to push.
*/
public void pushLiteral(String s)
{
push(s);
}
/** Push nil onto the stack. */
public void pushNil()
{
push(NIL);
}
/**
* Pushes a number onto the stack. See also {@link Lua#push}.
* @param d the number to push.
*/
public void pushNumber(double d)
{
push(new Double(d));
}
/**
* Push string onto the stack.
* @param s the string to push.
*/
public void pushString(String s)
{
push(s);
}
/**
* Copies a stack element onto the top of the stack.
* Equivalent to <code>L.push(L.value(idx))</code>.
* @param idx stack index of value to push.
*/
public void pushValue(int idx)
{
push(value(idx));
}
/**
* Implements equality without metamethods.
* @param o1 the first Lua value to compare.
* @param o2 the other Lua value.
* @return true if and only if they compare equal.
*/
public static boolean rawEqual(Object o1, Object o2)
{
return oRawequal(o1, o2);
}
/**
* Gets an element from a table, without using metamethods.
* @param t The table to access.
* @param k The index (key) into the table.
* @return The value at the specified index.
*/
public static Object rawGet(Object t, Object k)
{
LuaTable table = (LuaTable)t;
return table.get(k);
}
/**
* Gets an element from an array, without using metamethods.
* @param t the array (table).
* @param i the index of the element to retrieve.
* @return the value at the specified index.
*/
public static Object rawGetI(Object t, int i)
{
LuaTable table = (LuaTable)t;
return table.getnum(i);
}
/**
* Sets an element in a table, without using metamethods.
* @param t The table to modify.
* @param k The index into the table.
* @param v The new value to be stored at index <var>k</var>.
*/
public static void rawSet(Object t, Object k, Object v)
{
if (k == NIL)
{
throw new NullPointerException();
}
LuaTable table = (LuaTable)t;
table.put(k, v);
}
/**
* Sets an element in an array, without using metamethods.
* @param t the array (table).
* @param i the index of the element to set.
* @param v the new value to be stored at index <var>i</var>.
*/
public void rawSetI(Object t, int i, Object v)
{
apiCheck(t instanceof LuaTable);
LuaTable h = (LuaTable)t;
h.putnum(i, v);
}
/**
* Register a {@link LuaJavaCallback} as the new value of the global
* <var>name</var>.
* @param name the name of the global.
* @param f the LuaJavaCallback to register.
*/
public void register(String name, LuaJavaCallback f)
{
setGlobal(name, f);
}
/**
* Starts and resumes a coroutine.
* @param narg Number of values to pass to coroutine.
* @return Lua.YIELD, 0, or an error code.
*/
public int resume(int narg)
{
if (status != YIELD)
{
if (status != 0)
return resume_error("cannot resume dead coroutine");
else if (civ.size() != 1)
return resume_error("cannot resume non-suspended coroutine");
}
// assert errfunc == 0 && nCcalls == 0;
protect:
try
{
errorStatus = 0;
// This block is equivalent to resume from ldo.c
int firstArg = stack.size() - narg;
if (status == 0) // start coroutine?
{
// assert civ.size() == 1 && firstArg > base);
if (vmPrecall(firstArg - 1, MULTRET) != PCRLUA)
break protect;
}
else // resuming from previous yield
{
// assert status == YIELD;
status = 0;
if (!isLua(ci())) // 'common' yield
{
// finish interrupted execution of 'OP_CALL'
// assert ...
if (vmPoscall(firstArg)) // complete it...
stack.setSize(ci().top()); // and correct top
}
else // yielded inside a hook: just continue its execution
base = ci().base();
}
vmExecute(civ.size() - 1);
}
catch (RuntimeException e)
{
if (e.getMessage() == LUA_ERROR) // error?
{
status = errorStatus; // mark thread as 'dead'
dSeterrorobj(errorStatus, stack.size());
ci().setTop(stack.size());
}
else
{
throw e;
}
}
return status;
}
/**
* Set the environment for a function, thread, or userdata.
* @param o Object whose environment will be set.
* @param table Environment table to use.
* @return true if the object had its environment set, false otherwise.
*/
public boolean setFenv(Object o, Object table)
{
// :todo: consider implementing common env interface for
// LuaFunction, LuaJavaCallback, LuaUserdata, Lua. One cast to an
// interface and an interface method call may be shorter
// than this mess.
LuaTable t = (LuaTable)table;
if (o instanceof LuaFunction)
{
LuaFunction f = (LuaFunction)o;
f.setEnv(t);
return true;
}
if (o instanceof LuaJavaCallback)
{
LuaJavaCallback f = (LuaJavaCallback)o;
// :todo: implement this case.
return false;
}
if (o instanceof LuaUserdata)
{
LuaUserdata u = (LuaUserdata)o;
u.setEnv(t);
return true;
}
if (o instanceof Lua)
{
Lua l = (Lua)o;
l.global = t;
return true;
}
return false;
}
/**
* Set a field in a Lua value.
* @param t Lua value of which to set a field.
* @param name Name of field to set.
* @param v new Lua value for field.
*/
public void setField(Object t, String name, Object v)
{
vmSettable(t, name, v);
}
/**
* Sets the metatable for a Lua value.
* @param o Lua value of which to set metatable.
* @param mt The new metatable.
*/
public void setMetatable(Object o, Object mt)
{
if (isNil(mt))
{
mt = null;
}
else
{
apiCheck(mt instanceof LuaTable);
}
LuaTable mtt = (LuaTable)mt;
if (o instanceof LuaTable)
{
LuaTable t = (LuaTable)o;
t.setMetatable(mtt);
}
else if (o instanceof LuaUserdata)
{
LuaUserdata u = (LuaUserdata)o;
u.setMetatable(mtt);
}
else
{
metatable[type(o)] = mtt;
}
}
/**
* Set a global variable.
* @param name name of the global variable to set.
* @param value desired new value for the variable.
*/
public void setGlobal(String name, Object value)
{
vmSettable(global, name, value);
}
/**
* Does the equivalent of <code>t[k] = v</code>.
* @param t the table to modify.
* @param k the index to modify.
* @param v the new value at index <var>k</var>.
*/
public void setTable(Object t, Object k, Object v)
{
vmSettable(t, k, v);
}
/**
* Set the stack top.
* @param n the desired size of the stack (in elements).
*/
public void setTop(int n)
{
if (n < 0)
{
throw new IllegalArgumentException();
}
stack.setSize(base+n);
}
/**
* Status of a Lua thread.
* @return 0, an error code, or Lua.YIELD.
*/
public int status()
{
return status;
}
/**
* Returns an {@link java.util.Enumeration} for the keys of a table.
* @param t a Lua table.
* @return an Enumeration object.
*/
public Enumeration tableKeys(Object t)
{
if (!(t instanceof LuaTable))
{
error("table required");
// NOTREACHED
}
return ((LuaTable)t).keys();
}
/**
* Convert to boolean.
* @param o Lua value to convert.
* @return the resulting primitive boolean.
*/
public boolean toBoolean(Object o)
{
return !(o == NIL || Boolean.FALSE.equals(o));
}
/**
* Convert to integer and return it. Returns 0 if cannot be
* converted.
* @param o Lua value to convert.
* @return the resulting int.
*/
public int toInteger(Object o)
{
if (tonumber(o, NUMOP))
{
return (int)NUMOP[0];
}
return 0;
}
/**
* Convert to number and return it. Returns 0 if cannot be
* converted.
* @param o Lua value to convert.
* @return The resulting number.
*/
public double toNumber(Object o)
{
if (tonumber(o, NUMOP))
{
return NUMOP[0];
}
return 0;
}
/**
* Convert to string and return it. If value cannot be converted then
* null is returned. Note that unlike <code>lua_tostring</code> this
* does not modify the Lua value.
* @param o Lua value to convert.
* @return The resulting string.
*/
public String toString(Object o)
{
return vmTostring(o);
}
/**
* Convert to Lua thread and return it or <code>null</code>.
* @param o Lua value to convert.
* @return The resulting Lua instance.
*/
public Lua toThread(Object o)
{
if (!(o instanceof Lua))
{
return null;
}
return (Lua)o;
}
/**
* Convert to userdata or <code>null</code>. If value is a {@link
* LuaUserdata} then it is returned, otherwise, <code>null</code> is
* returned.
* @param o Lua value.
* @return value as userdata or <code>null</code>.
*/
public LuaUserdata toUserdata(Object o)
{
if (o instanceof LuaUserdata)
{
return (LuaUserdata)o;
}
return null;
}
/**
* Type of the Lua value at the specified stack index.
* @param idx stack index to type.
* @return the type, or {@link Lua#TNONE} if there is no value at <var>idx</var>
*/
public int type(int idx)
{
idx = absIndex(idx);
if (idx < 0)
{
return TNONE;
}
Object o = stack.elementAt(idx);
return type(o);
}
/**
* Type of a Lua value.
* @param o the Lua value whose type to return.
* @return the Lua type from an enumeration.
*/
public static int type(Object o)
{
if (o == NIL)
{
return TNIL;
}
else if (o instanceof Double)
{
return TNUMBER;
}
else if (o instanceof Boolean)
{
return TBOOLEAN;
}
else if (o instanceof String)
{
return TSTRING;
}
else if (o instanceof LuaTable)
{
return TTABLE;
}
else if (o instanceof LuaFunction || o instanceof LuaJavaCallback)
{
return TFUNCTION;
}
else if (o instanceof LuaUserdata)
{
return TUSERDATA;
}
else if (o instanceof Lua)
{
return TTHREAD;
}
return TNONE;
}
/**
* Name of type.
* @param type a Lua type from, for example, {@link Lua#type}.
* @return the type's name.
*/
public static String typeName(int type)
{
if (TNONE == type)
{
return "no value";
}
return TYPENAME[type];
}
/**
* Gets a value from the stack.
* If <var>idx</var> is positive and exceeds
* the size of the stack, {@link Lua#NIL} is returned.
* @param idx the stack index of the value to retrieve.
* @return the Lua value from the stack.
*/
public Object value(int idx)
{
idx = absIndex(idx);
if (idx < 0)
{
return NIL;
}
return stack.elementAt(idx);
}
/**
* Converts primitive boolean into a Lua value.
* @param b the boolean to convert.
* @return the resulting Lua value.
*/
public static Object valueOfBoolean(boolean b)
{
// If CLDC 1.1 had
// <code>java.lang.Boolean.valueOf(boolean);</code> then I probably
// wouldn't have written this. This does have a small advantage:
// code that uses this method does not need to assume that Lua booleans in
// Jili are represented using Java.lang.Boolean.
if (b)
{
return Boolean.TRUE;
}
else
{
return Boolean.FALSE;
}
}
/**
* Converts primitive number into a Lua value.
* @param d the number to convert.
* @return the resulting Lua value.
*/
public static Object valueOfNumber(double d)
{
// :todo: consider interning "common" numbers, like 0, 1, -1, etc.
return new Double(d);
}
/**
* Exchange values between different threads.
* @param to destination Lua thread.
* @param n numbers of stack items to move.
*/
public void xmove(Lua to, int n)
{
if (this == to)
{
return;
}
apiChecknelems(n);
// L.apiCheck(from.G() == to.G());
for (int i = 0; i < n; ++i)
{
to.push(value(-n+i));
}
pop(n);
}
/**
* Yields a coroutine. Should only be called as the return expression
* of a Lua Java function: <code>return L.yield(nresults);</code>.
* @param nresults Number of results to return to L.resume.
* @return a secret value.
*/
public int yield(int nresults)
{
if (nCcalls > 0)
gRunerror("attempt to yield across metamethod/Java-call boundary");
base = stack.size() - nresults; // protect stack slots below
status = YIELD;
return -1;
}
// Miscellaneous private functions.
/** Convert from Java API stack index to absolute index.
* @return an index into <code>this.stack</code> or -1 if out of range.
*/
private int absIndex(int idx)
{
int s = stack.size();
if (idx == 0)
{
return -1;
}
if (idx > 0)
{
if (idx + base > s)
{
return -1;
}
return base + idx - 1;
}
// idx < 0
if (s + idx < base)
{
return -1;
}
return s + idx;
}
//////////////////////////////////////////////////////////////////////
// Auxiliary API
// :todo: consider placing in separate class (or macroised) so that we
// can change its definition (to remove the check for example).
private void apiCheck(boolean cond)
{
if (!cond)
{
throw new IllegalArgumentException();
}
}
private void apiChecknelems(int n)
{
apiCheck(n <= stack.size() - base);
}
/**
* Checks a general condition and raises error if false.
* @param cond the (evaluated) condition to check.
* @param numarg argument index.
* @param extramsg extra error message to append.
*/
public void argCheck(boolean cond, int numarg, String extramsg)
{
if (cond)
{
return;
}
argError(numarg, extramsg);
}
/**
* Raise a general error for an argument.
* @param narg argument index.
* @param extramsg extra message string to append.
* @return never (used idiomatically in <code>return argError(...)</code>)
*/
public int argError(int narg, String extramsg)
{
// :todo: use debug API as per PUC-Rio
if (true)
{
return error("bad argument " + narg + " (" + extramsg + ")");
}
return 0;
}
/**
* Calls a metamethod. Pushes 1 result onto stack if method called.
* @param obj stack index of object whose metamethod to call
* @param event metamethod (event) name.
* @return true if and only if metamethod was found and called.
*/
public boolean callMeta(int obj, String event)
{
Object o = value(obj);
Object ev = getMetafield(o, event);
if (ev == null)
{
return false;
}
push(ev);
push(o);
call(1, 1);
return true;
}
/**
* Checks that an argument is present (can be anything).
* Raises error if not.
* @param narg argument index.
*/
public void checkAny(int narg)
{
if (type(narg) == TNONE)
{
argError(narg, "value expected");
}
}
/**
* Checks is a number and returns it as an integer. Raises error if
* not a number.
* @param narg argument index.
* @return the argument as an int.
*/
public int checkInt(int narg)
{
return (int)checkNumber(narg);
}
/**
* Checks is a number. Raises error if not a number.
* @param narg argument index.
* @return the argument as a double.
*/
public double checkNumber(int narg)
{
Object o = value(narg);
double d = toNumber(o);
if (d == 0 && !isNumber(o))
{
tagError(narg, TNUMBER);
}
return d;
}
/**
* Checks that an optional string argument is an element from a set of
* strings. Raises error if not.
* @param narg argument index.
* @param def default string to use if argument not present.
* @param lst the set of strings to match against.
* @return an index into <var>lst</var> specifying the matching string.
*/
public int checkOption(int narg, String def, String[] lst)
{
String name;
if (def == null)
{
name = checkString(narg);
}
else
{
name = optString(narg, def);
}
for (int i=0; i<lst.length; ++i)
{
if (lst[i].equals(name))
{
return i;
}
}
return argError(narg, "invalid option '" + name + "'");
}
/**
* Checks argument is a string and returns it. Raises error if not a
* string.
* @param narg argument index.
* @return the argument as a string.
*/
public String checkString(int narg)
{
String s = toString(value(narg));
if (s == null)
{
tagError(narg, TSTRING);
}
return s;
}
/**
* Checks the type of an argument, raises error if not matching.
* @param narg argument index.
* @param t typecode (from {@link Lua#type} for example).
*/
public void checkType(int narg, int t)
{
if (type(narg) != t)
{
tagError(narg, t);
}
}
/**
* Loads and runs the given string.
* @param s the string to run.
* @return a status code, as per {@link Lua#load}.
*/
public int doString(String s)
{
int status = load(Lua.stringReader(s), s);
if (status == 0)
{
status = pcall(0, MULTRET, null);
}
return status;
}
private int errfile(String what, String fname, Exception e)
{
push("cannot " + what + " " + fname + ": " + e.toString());
return ERRFILE;
}
/**
* Get a field (event) from an Lua value's metatable. Returns null
* if there is no field nor metatable.
* @param o Lua value to get metafield for.
* @param event name of metafield (event).
* @return the field from the metatable, or null.
*/
public Object getMetafield(Object o, String event)
{
LuaTable mt = getMetatable(o);
if (mt == null)
{
return null;
}
return mt.get(event);
}
boolean isNoneOrNil(int narg)
{
return type(narg) <= TNIL;
}
/**
* Loads a Lua chunk from a file. The <var>filename</var> argument is
* used in a call to {@link Class#getResourceAsStream} where
* <code>this</code> is the {@link Lua} instance, thus relative
* pathnames will be relative to the location of the
* <code>Lua.class</code> file. Pushes compiled chunk, or error
* message, onto stack.
* @param filename location of file.
* @return status code, as per {@link Lua#load}.
*/
public int loadFile(String filename)
{
if (filename == null)
{
throw new NullPointerException();
}
InputStream in = getClass().getResourceAsStream(filename);
if (in == null)
{
return errfile("open", filename, new IOException());
}
int status = 0;
try
{
in.mark(1);
int c = in.read();
if (c == '#') // Unix exec. file?
{
// :todo: handle this case
}
in.reset();
status = load(in, "@" + filename);
}
catch (IOException e)
{
return errfile("read", filename, e);
}
return status;
}
/**
* Loads a Lua chunk from a string. Pushes compiled chunk, or error
* message, onto stack.
* @param s the string to load.
* @param chunkname the name of the chunk.
* @return status code, as per {@link Lua#load}.
*/
public int loadString(String s, String chunkname)
{
return load(stringReader(s), chunkname);
}
/**
* Get optional integer argument. Raises error if non-number
* supplied.
* @param narg argument index.
* @param def default value for integer.
* @return an int.
*/
public int optInt(int narg, int def)
{
if (isNoneOrNil(narg))
{
return def;
}
return checkInt(narg);
}
/**
* Get optional number argument. Raises error if non-number supplied.
* @param narg argument index.
* @param def default value for number.
* @return a double.
*/
public double optNumber(int narg, double def)
{
if (isNoneOrNil(narg))
{
return def;
}
return checkNumber(narg);
}
/**
* Get optional string argument. Raises error if non-string supplied.
* @param narg argument index.
* @param def default value for string.
* @return a string.
*/
public String optString(int narg, String def)
{
if (isNoneOrNil(narg))
{
return def;
}
return checkString(narg);
}
private void tagError(int narg, int tag)
{
typerror(narg, typeName(tag));
}
/**
* Name of type of value at <var>idx</var>.
* @param idx stack index.
* @return the name of the value's type.
*/
public String typeNameOfIndex(int idx)
{
return TYPENAME[type(idx)];
}
/**
* Declare type error in argument.
* @param narg Index of argument.
* @param tname Name of type expected.
*/
public void typerror(int narg, String tname)
{
argError(narg, tname + " expected, got " + typeNameOfIndex(narg));
}
/**
* Return string identifying current position of the control at level
* <var>level</var>.
* @param level specifies the call-stack level.
* @return a description for that level.
*/
public String where(int level)
{
Debug ar = getStack(level); // check function at level
if (ar != null)
{
getInfo("Sl", ar); // get info about it
if (ar.currentline() > 0) // is there info?
{
return ar.shortsrc() + ":" + ar.currentline() + ": ";
}
}
return ""; // else, no information available...
}
/**
* Provide {@link java.io.Reader} interface over a <code>String</code>.
* Equivalent of {@link java.io.StringReader#StringReader} from J2SE.
* The ability to convert a <code>String</code> to a
* <code>Reader</code> is required internally,
* to provide the Lua function <code>loadstring</code>; exposed
* externally as a convenience.
* @param s the string from which to read.
* @return a {@link java.io.Reader} that reads successive chars from <var>s</var>.
*/
public static Reader stringReader(String s)
{
return new StringReader(s);
}
//////////////////////////////////////////////////////////////////////
// Debug
// Methods equivalent to debug API. In PUC-Rio most of these are in
// ldebug.c
private boolean getInfo(String what, Debug ar)
{
Object f = null;
CallInfo callinfo = null;
// :todo: complete me
if (ar.ici() > 0) // no tail call?
{
callinfo = (CallInfo)civ.elementAt(ar.ici());
f = stack.elementAt(callinfo.function());
// assert isFunction(f);
}
return auxgetinfo(what, ar, f, callinfo);
}
/**
* Locates function activation at specified call level and returns a
* {@link Debug}
* record for it, or <code>null</code> if level is too high.
* May become public.
* @param level the call level.
* @return a {@link Debug} instance describing the activation record.
*/
Debug getStack(int level)
{
int ici; // Index of CallInfo
for (ici=civ.size()-1; level > 0 && ici > 0; --ici)
{
CallInfo ci = (CallInfo)civ.elementAt(ici);
--level;
if (isLua(ci)) // Lua function?
{
level -= ci.tailcalls(); // skip lost tail calls
}
}
if (level == 0 && ici > 0) // level found?
{
return new Debug(ici);
}
else if (level < 0) // level is of a lost tail call?
{
return new Debug(0);
}
return null;
}
/**
* @return true is okay, false otherwise (for example, error).
*/
private boolean auxgetinfo(String what, Debug ar, Object f, CallInfo ci)
{
boolean status = true;
if (f == null)
{
// :todo: implement me
return status;
}
for (int i=0; i<what.length(); ++i)
{
switch (what.charAt(i))
{
case 'S':
funcinfo(ar, f);
break;
case 'l':
ar.setCurrentline((ci != null) ? currentline(ci) : -1);
break;
// :todo: more cases.
default:
status = false;
}
}
return status;
}
private int currentline(CallInfo ci)
{
int pc = currentpc(ci);
if (pc < 0)
{
return -1; // only active Lua functions have current-line info
}
else
{
Object faso = stack.elementAt(ci.function());
LuaFunction f = (LuaFunction)faso;
return f.proto().getline(pc);
}
}
private int currentpc(CallInfo ci)
{
if (!isLua(ci)) // function is not a Lua function?
{
return -1;
}
if (ci == ci())
{
ci.setSavedpc(savedpc);
}
return pcRel(ci.savedpc());
}
private void funcinfo(Debug ar, Object cl)
{
if (cl instanceof LuaJavaCallback)
{
ar.setSource("=[Java]");
ar.setLinedefined(-1);
ar.setLastlinedefined(-1);
ar.setWhat("Java");
}
else
{
Proto p = ((LuaFunction)cl).proto();
ar.setSource(p.source());
ar.setLinedefined(p.linedefined());
ar.setLastlinedefined(p.lastlinedefined());
ar.setWhat(ar.linedefined() == 0 ? "main" : "Lua");
}
}
/** Equivalent to macro isLua _and_ f_isLua from lstate.h. */
private boolean isLua(CallInfo callinfo)
{
Object f = stack.elementAt(callinfo.function());
return f instanceof LuaFunction;
}
private static int pcRel(int pc)
{
return pc - 1;
}
//////////////////////////////////////////////////////////////////////
// Do
// Methods equivalent to the file ldo.c. Prefixed with d.
// Some of these are in vm* instead.
/** Equivalent to luaD_seterrorobj. */
private void dSeterrorobj(int errcode, int oldtop)
{
switch (errcode)
{
case ERRERR:
stack.setElementAt("error in error handling", oldtop);
break;
case ERRSYNTAX:
case ERRRUN:
stack.setElementAt(stack.lastElement(), oldtop);
break;
}
stack.setSize(oldtop+1);
}
void dThrow(int status)
{
errorStatus = status;
throw new RuntimeException(LUA_ERROR);
}
//////////////////////////////////////////////////////////////////////
// Func
// Methods equivalent to the file lfunc.c. Prefixed with f.
/** Equivalent of luaF_close. All open upvalues referencing stack
* slots level or higher are closed.
* @param level Absolute stack index.
*/
private void fClose(int level)
{
int i = openupval.size();
while (--i >= 0)
{
UpVal uv = (UpVal)openupval.elementAt(i);
if (uv.offset() < level)
{
break;
}
uv.close();
}
openupval.setSize(i+1);
return;
}
private UpVal fFindupval(int idx)
{
/*
* We search from the end of the Vector towards the beginning,
* looking for an UpVal for the required stack-slot.
*/
int i = openupval.size();
while (--i >= 0)
{
UpVal uv = (UpVal)openupval.elementAt(i);
if (uv.offset() == idx)
{
return uv;
}
if (uv.offset() < idx)
{
break;
}
}
// i points to be position _after_ which we want to insert a new
// UpVal (it's -1 when we want to insert at the beginning).
UpVal uv = new UpVal(stack, idx);
openupval.insertElementAt(uv, i+1);
return uv;
}
//////////////////////////////////////////////////////////////////////
// Debug
// Methods equivalent to the file ldebug.c. Prefixed with g.
/** p1 and p2 are absolute stack indexes. Corrupts NUMOP[0]. */
private void gAritherror(int p1, int p2)
{
if (!tonumber(value(p1), NUMOP))
{
p2 = p1; // first operand is wrong
}
gTypeerror(value(p2), "perform arithmetic on");
}
/** p1 and p2 are absolute stack indexes. */
private void gConcaterror(int p1, int p2)
{
if (stack.elementAt(p1) instanceof String)
{
p1 = p2;
}
// assert !(p1 instanceof String);
gTypeerror(stack.elementAt(p1), "concatenate");
}
boolean gCheckcode(Proto p)
{
// :todo: implement me.
return true ;
}
private int gErrormsg(Object message)
{
push(message);
if (errfunc != null) // is there an error handling function
{
if (!isFunction(errfunc))
{
dThrow(ERRERR);
}
insert(errfunc, getTop()); // push function (under error arg)
vmCall(stack.size()-2, 1); // call it
}
dThrow(ERRRUN);
// NOTREACHED
return 0;
}
private boolean gOrdererror(Object p1, Object p2)
{
String t1 = typeName(type(p1));
String t2 = typeName(type(p2));
if (t1.charAt(2) == t2.charAt(2))
{
gRunerror("attempt to compare two " + t1 + "values");
}
else
{
gRunerror("attempt to compare " + t1 + " with " + t2);
}
// NOTREACHED
return false;
}
void gRunerror(String s)
{
gErrormsg(s);
}
private void gTypeerror(Object o, String op)
{
// :todo: PUC-Rio searches the stack to see if the value (which may
// be a reference to stack cell) is a local variable. Jili can't do
// that so easily. Consider changing interface.
String t = typeName(type(o));
gRunerror("attempt to " + op + " a " + t + " value");
}
//////////////////////////////////////////////////////////////////////
// Object
// Methods equivalent to the file lobject.c. Prefixed with o.
private static final int IDSIZE = 60;
/**
* @return a string no longer than IDSIZE.
*/
static String oChunkid(String source)
{
int len = IDSIZE;
if (source.startsWith("="))
{
if(source.length() < IDSIZE+1)
{
return source.substring(1);
}
else
{
return source.substring(1, 1+len);
}
}
// else "source" or "...source"
if (source.startsWith("@"))
{
len -= " '...' ".length();
int l = source.length();
if (l > len)
{
return "..." + // get last part of file name
source.substring(source.length()-len, source.length());
}
return source;
}
// else [string "string"]
int l = source.indexOf('\n');
if (l == -1)
{
l = source.length();
}
len -= " [string \"...\"] ".length();
if (l > len)
{
l = len;
}
StringBuffer buf = new StringBuffer();
buf.append("[string \"");
buf.append(source.substring(0, l));
if (source.length() > l) // must truncate
{
buf.append("...");
}
buf.append("\"]");
return buf.toString();
}
/** Equivalent to luaO_rawequalObj. */
private static boolean oRawequal(Object a, Object b)
{
// see also vmEqual
if (NIL == a)
{
return NIL == b;
}
// Now a is not null, so a.equals() is a valid call.
// Numbers (Doubles), Booleans, Strings all get compared by value,
// as they should; tables, functions, get compared by identity as
// they should.
return a.equals(b);
}
/** Equivalent to luaO_str2d. */
private static boolean oStr2d(String s, double[] out)
{
// :todo: using try/catch may be too slow. In which case we'll have
// to recognise the valid formats first.
try
{
out[0] = Double.parseDouble(s);
return true;
}
catch (NumberFormatException e0_)
{
try
{
// Attempt hexadecimal conversion.
// :todo: using String.trim is not strictly accurate, because it
// trims other ASCII control characters as well as whitespace.
s = s.trim().toUpperCase();
if (s.startsWith("0X"))
{
s = s.substring(2);
}
else if (s.startsWith("-0X"))
{
s = "-" + s.substring(3);
}
out[0] = Integer.parseInt(s, 16);
return true;
}
catch (NumberFormatException e1_)
{
return false;
}
}
}
////////////////////////////////////////////////////////////////////////
// VM
// Most of the methods in this section are equivalent to the files
// lvm.c and ldo.c from PUC-Rio. They're mostly prefixed with vm as
// well.
private static final int PCRLUA = 0;
private static final int PCRJ = 1;
private static final int PCRYIELD = 2;
// Instruction decomposition.
// There follows a series of methods that extract the various fields
// from a VM instruction. See lopcodes.h from PUC-Rio.
// :todo: Consider replacing with m4 macros (or similar).
// A brief overview of the instruction format:
// Logically an instruction has an opcode (6 bits), op, and up to
// three fields using one of three formats:
// A B C (8 bits, 9 bits, 9 bits)
// A Bx (8 bits, 18 bits)
// A sBx (8 bits, 18 bits signed - excess K)
// Some instructions do not use all the fields (EG OP_UNM only uses A
// and B).
// When packed into a word (an int in Jili) the following layouts are
// used:
// 31 (MSB) 23 22 14 13 6 5 0 (LSB)
// +--------------+--------------+------------+--------+
// | B | C | A | OPCODE |
// +--------------+--------------+------------+--------+
//
// +--------------+--------------+------------+--------+
// | Bx | A | OPCODE |
// +--------------+--------------+------------+--------+
//
// +--------------+--------------+------------+--------+
// | sBx | A | OPCODE |
// +--------------+--------------+------------+--------+
static final int NO_REG = 0xff; // SIZE_A == 8, (1 << 8)-1
// Hardwired values for speed.
/** Equivalent of macro GET_OPCODE */
static int OPCODE(int instruction)
{
// POS_OP == 0 (shift amount)
// SIZE_OP == 6 (opcode width)
return instruction & 0x3f;
}
/** Equivalent of macro GET_OPCODE */
static int SET_OPCODE(int i, int op)
{
// POS_OP == 0 (shift amount)
// SIZE_OP == 6 (opcode width)
return (i & ~0x3F) | (op & 0x3F);
}
/** Equivalent of macro GETARG_A */
static int ARGA(int instruction)
{
// POS_A == POS_OP + SIZE_OP == 6 (shift amount)
// SIZE_A == 8 (operand width)
return (instruction >>> 6) & 0xff;
}
static int SETARG_A(int i, int u)
{
return (i & ~(0xff << 6)) | ((u & 0xff) << 6);
}
/** Equivalent of macro GETARG_B */
static int ARGB(int instruction)
{
// POS_B == POS_OP + SIZE_OP + SIZE_A + SIZE_C == 23 (shift amount)
// SIZE_B == 9 (operand width)
/* No mask required as field occupies the most significant bits of a
* 32-bit int. */
return (instruction >>> 23);
}
static int SETARG_B(int i, int b)
{
return (i & ~(0x1ff << 23)) | ((b & 0x1ff) << 23);
}
/** Equivalent of macro GETARG_C */
static int ARGC(int instruction)
{
// POS_C == POS_OP + SIZE_OP + SIZE_A == 14 (shift amount)
// SIZE_C == 9 (operand width)
return (instruction >>> 14) & 0x1ff;
}
static int SETARG_C(int i, int c)
{
return (i & ~(0x1ff << 14)) | ((c & 0x1ff) << 14);
}
/** Equivalent of macro GETARG_Bx */
static int ARGBx(int instruction)
{
// POS_Bx = POS_C == 14
// SIZE_Bx == SIZE_C + SIZE_B == 18
/* No mask required as field occupies the most significant bits of a
* 32 bit int. */
return (instruction >>> 14);
}
static int SETARG_Bx(int i, int bx)
{
return (i & 0x3fff) | (bx << 14) ;
}
/** Equivalent of macro GETARG_sBx */
static int ARGsBx(int instruction)
{
// As ARGBx but with (2**17-1) subtracted.
return (instruction >>> 14) - MAXARG_sBx;
}
static int SETARG_sBx(int i, int bx)
{
return (i & 0x3fff) | ((bx+MAXARG_sBx) << 14) ; // CHECK THIS IS RIGHT
}
static boolean ISK(int field)
{
// The "is constant" bit position depends on the size of the B and C
// fields (required to be the same width).
// SIZE_B == 9
return field >= 0x100;
}
/**
* Near equivalent of macros RKB and RKC. Note: non-static as it
* requires stack and base instance members. Stands for "Register or
* Konstant" by the way, it gets value from either the register file
* (stack) or the constant array (k).
*/
private Object RK(Object[] k, int field)
{
if (ISK(field))
{
return k[field & 0xff];
}
return stack.elementAt(base + field);
}
// CREATE functions are required by FuncState, so default access.
static int CREATE_ABC(int o, int a, int b, int c)
{
// POS_OP == 0
// POS_A == 6
// POS_B == 23
// POS_C == 14
return o | (a << 6) | (b << 23) | (c << 14);
}
static int CREATE_ABx(int o, int a, int bc)
{
// POS_OP == 0
// POS_A == 6
// POS_Bx == POS_C == 14
return o | (a << 6) | (bc << 14);
}
// opcode enumeration.
// Generated by a script:
// awk -f opcode.awk < lopcodes.h
// and then pasted into here.
// Made default access so that code generation, in FuncState, can see
// the enumeration as well.
static final int OP_MOVE = 0;
static final int OP_LOADK = 1;
static final int OP_LOADBOOL = 2;
static final int OP_LOADNIL = 3;
static final int OP_GETUPVAL = 4;
static final int OP_GETGLOBAL = 5;
static final int OP_GETTABLE = 6;
static final int OP_SETGLOBAL = 7;
static final int OP_SETUPVAL = 8;
static final int OP_SETTABLE = 9;
static final int OP_NEWTABLE = 10;
static final int OP_SELF = 11;
static final int OP_ADD = 12;
static final int OP_SUB = 13;
static final int OP_MUL = 14;
static final int OP_DIV = 15;
static final int OP_MOD = 16;
static final int OP_POW = 17;
static final int OP_UNM = 18;
static final int OP_NOT = 19;
static final int OP_LEN = 20;
static final int OP_CONCAT = 21;
static final int OP_JMP = 22;
static final int OP_EQ = 23;
static final int OP_LT = 24;
static final int OP_LE = 25;
static final int OP_TEST = 26;
static final int OP_TESTSET = 27;
static final int OP_CALL = 28;
static final int OP_TAILCALL = 29;
static final int OP_RETURN = 30;
static final int OP_FORLOOP = 31;
static final int OP_FORPREP = 32;
static final int OP_TFORLOOP = 33;
static final int OP_SETLIST = 34;
static final int OP_CLOSE = 35;
static final int OP_CLOSURE = 36;
static final int OP_VARARG = 37;
// end of instruction decomposition
static final int SIZE_C = 9;
static final int SIZE_B = 9;
static final int SIZE_Bx = SIZE_C + SIZE_B;
static final int SIZE_A = 8;
static final int SIZE_OP = 6;
static final int POS_OP = 0;
static final int POS_A = POS_OP + SIZE_OP;
static final int POS_C = POS_A + SIZE_A;
static final int POS_B = POS_C + SIZE_C;
static final int POS_Bx = POS_C;
static final int MAXARG_Bx = (1<<SIZE_Bx)-1;
static final int MAXARG_sBx = MAXARG_Bx>>1; // `sBx' is signed
static final int MAXARG_A = (1<<SIZE_A)-1;
static final int MAXARG_B = (1<<SIZE_B)-1;
static final int MAXARG_C = (1<<SIZE_C)-1;
/* this bit 1 means constant (0 means register) */
static final int BITRK = 1 << (SIZE_B - 1) ;
static final int MAXINDEXRK = BITRK - 1 ;
/**
* Equivalent of luaD_call.
* @param func absolute stack index of function to call.
* @param r number of required results.
*/
private void vmCall(int func, int r)
{
++nCcalls;
if (vmPrecall(func, r) == PCRLUA)
{
vmExecute(1);
}
--nCcalls;
}
/** Equivalent of luaV_concat. */
private void vmConcat(int total, int last)
{
do
{
int top = base + last + 1;
int n = 2; // number of elements handled in this pass (at least 2)
if (!tostring(top-2)|| !tostring(top-1))
{
if (!call_binTM(top-2, top-1, top-2, "__concat"))
{
gConcaterror(top-2, top-1);
}
}
else if (((String)stack.elementAt(top-1)).length() > 0)
{
int tl = ((String)stack.elementAt(top-1)).length();
for (n = 1; n < total && tostring(top-n-1); ++n)
{
tl += ((String)stack.elementAt(top-n-1)).length();
if (tl < 0)
{
gRunerror("string length overflow");
}
}
StringBuffer buffer = new StringBuffer(tl);
for (int i=n; i>0; i--) // concat all strings
{
buffer.append(stack.elementAt(top-i));
}
stack.setElementAt(buffer.toString(), top-n);
}
total -= n-1; // got n strings to create 1 new
last -= n-1;
} while (total > 1); // repeat until only 1 result left
}
/**
* Primitive for testing Lua equality of two values. Equivalent of
* PUC-Rio's <code>equalobj</code> macro. Note that using null to
* model nil complicates this test, maybe we should use a nonce object.
* In the loosest sense, this is the equivalent of
* <code>luaV_equalval</code>.
*/
private boolean vmEqual(Object a, Object b)
{
// :todo: consider if (a == b) return true;
if (NIL == a)
{
return NIL == b;
}
// Now a is not null, so a.equals() is a valid call.
if (a.equals(b))
{
return true;
}
if (NIL == b)
{
return false;
}
// Now b is not null, so b.getClass() is a valid call.
if (a.getClass() != b.getClass())
{
return false;
}
// Same class, but different objects.
if (a instanceof LuaJavaCallback ||
a instanceof LuaTable)
{
// Resort to metamethods.
Object tm = get_compTM(getMetatable(a), getMetatable(b), "__eq");
if (null == tm) // no TM?
{
return false;
}
Object res = callTMres(tm, a, b); // call TM
return !isFalse(res);
}
return false;
}
/**
* Array of numeric operands. Used when converting strings to numbers
* by an arithmetic opcode (ADD, SUB, MUL, DIV, MOD, POW, UNM).
*/
private static final double[] NUMOP = new double[2];
/** The core VM execution engine. */
private void vmExecute(int nexeccalls)
{
// This labelled while loop is used to simulate the effect of C's
// goto. The end of the while loop is never reached. The beginning
// of the while loop is branched to using a "continue reentry;"
// statement (when a Lua function is called or returns).
reentry:
while (true)
{
// assert stack.elementAt[ci.function()] instanceof LuaFunction;
LuaFunction function = (LuaFunction)stack.elementAt(ci().function());
Proto proto = function.proto();
int[] code = proto.code();
Object[] k = proto.constant();
int pc = savedpc;
while (true) // main loop of interpreter
{
// Where the PUC-Rio code used the Protect macro, this has been
// replaced with "savedpc = pc" and a "// Protect" comment.
// Where the PUC-Rio code used the dojump macro, this has been
// replaced with the equivalent increment of the pc and a
// "//dojump" comment.
int i = code[pc++]; // VM instruction.
// :todo: count and line hook
int a = ARGA(i); // its A field.
Object rb;
Object rc;
switch (OPCODE(i))
{
case OP_MOVE:
stack.setElementAt(stack.elementAt(base+ARGB(i)), base+a);
continue;
case OP_LOADK:
stack.setElementAt(k[ARGBx(i)], base+a);
continue;
case OP_LOADBOOL:
stack.setElementAt(valueOfBoolean(ARGB(i) != 0), base+a);
if (ARGC(i) != 0)
{
++pc;
}
continue;
case OP_LOADNIL:
{
int b = base + ARGB(i);
do
{
stack.setElementAt(NIL, b--);
} while (b >= base + a);
continue;
}
case OP_GETUPVAL:
{
int b = ARGB(i);
stack.setElementAt(function.upVal(b).getValue(), base+a);
continue;
}
case OP_GETGLOBAL:
rb = k[ARGBx(i)];
// assert rb instance of String;
savedpc = pc; // Protect
stack.setElementAt(vmGettable(function.getEnv(), rb), base+a);
continue;
case OP_GETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+ARGB(i));
stack.setElementAt(vmGettable(t, RK(k, ARGC(i))), base+a);
continue;
}
case OP_SETUPVAL:
{
UpVal uv = function.upVal(ARGB(i));
uv.setValue(stack.elementAt(base+a));
continue;
}
case OP_SETGLOBAL:
savedpc = pc; // Protect
vmSettable(function.getEnv(), k[ARGBx(i)],
stack.elementAt(base+a));
continue;
case OP_SETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+a);
vmSettable(t, RK(k, ARGB(i)), RK(k, ARGC(i)));
continue;
}
case OP_NEWTABLE:
{
// :todo: use the b and c hints, currently ignored.
int b = ARGB(i);
int c = ARGC(i);
stack.setElementAt(new LuaTable(), base+a);
continue;
}
case OP_SELF:
{
int b = ARGB(i);
rb = stack.elementAt(base+b);
stack.setElementAt(rb, base+a+1);
savedpc = pc; // Protect
stack.setElementAt(vmGettable(rb, RK(k, ARGC(i))), base+a);
continue;
}
case OP_ADD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double sum = ((Double)rb).doubleValue() +
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double sum = NUMOP[0] + NUMOP[1];
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__add"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_SUB:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double difference = ((Double)rb).doubleValue() -
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double difference = NUMOP[0] - NUMOP[1];
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__sub"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MUL:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double product = ((Double)rb).doubleValue() *
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double product = NUMOP[0] * NUMOP[1];
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mul"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_DIV:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double quotient = ((Double)rb).doubleValue() /
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double quotient = NUMOP[0] / NUMOP[1];
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__div"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MOD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double db = ((Double)rb).doubleValue();
double dc = ((Double)rc).doubleValue();
double modulus = modulus(db, dc);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double modulus = modulus(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mod"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_POW:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double result = iNumpow(((Double)rb).doubleValue(),
((Double)rc).doubleValue());
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double result = iNumpow(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__pow"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_UNM:
{
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof Double)
{
double db = ((Double)rb).doubleValue();
stack.setElementAt(valueOfNumber(-db), base+a);
}
else if (tonumber(rb, NUMOP))
{
stack.setElementAt(valueOfNumber(-NUMOP[0]), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a,
"__unm"))
{
gAritherror(base+ARGB(i), base+ARGB(i));
}
continue;
}
case OP_NOT:
{
Object ra = stack.elementAt(base+ARGB(i));
stack.setElementAt(valueOfBoolean(isFalse(ra)), base+a);
continue;
}
case OP_LEN:
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof LuaTable)
{
LuaTable t = (LuaTable)rb;
stack.setElementAt(new Double(t.getn()), base+a);
continue;
}
else if (rb instanceof String)
{
String s = (String)rb;
stack.setElementAt(new Double(s.length()), base+a);
continue;
}
savedpc = pc; // Protect
if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__len"))
{
gTypeerror(rb, "get length of");
}
continue;
case OP_CONCAT:
{
int b = ARGB(i);
int c = ARGC(i);
savedpc = pc; // Protect
// :todo: The compiler assumes that all
// stack locations _above_ b end up with junk in them. In
// which case we can improve the speed of vmConcat (by not
// converting each stack slot, but simply using
// StringBuffer.append on whatever is there).
vmConcat(c - b + 1, c);
stack.setElementAt(stack.elementAt(base+b), base+a);
continue;
}
case OP_JMP:
// dojump
pc += ARGsBx(i);
continue;
case OP_EQ:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (vmEqual(rb, rc) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LT:
savedpc = pc; // Protect
if (vmLessthan(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LE:
savedpc = pc; // Protect
if (vmLessequal(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TEST:
if (isFalse(stack.elementAt(base+a)) != (ARGC(i) != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TESTSET:
rb = stack.elementAt(base+ARGB(i));
if (isFalse(rb) != (ARGC(i) != 0))
{
stack.setElementAt(rb, base+a);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_CALL:
{
int b = ARGB(i);
int nresults = ARGC(i) - 1;
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
switch (vmPrecall(base+a, nresults))
{
case PCRLUA:
nexeccalls++;
continue reentry;
case PCRJ:
// Was Java function called by precall, adjust result
if (nresults >= 0)
{
stack.setSize(ci().top());
}
continue;
default:
return; // yield
}
}
case OP_TAILCALL:
{
int b = ARGB(i);
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
// assert ARGC(i) - 1 == MULTRET
switch (vmPrecall(base+a, MULTRET))
{
case PCRLUA:
{
// tail call: put new frame in place of previous one.
CallInfo ci = (CallInfo)civ.elementAt(civ.size()-2);
int func = ci.function();
CallInfo fci = ci(); // Fresh CallInfo
int pfunc = fci.function();
fClose(ci.base());
base = func + (fci.base() - pfunc);
int aux; // loop index is used after loop ends
for (aux=0; pfunc+aux < stack.size(); ++aux)
{
// move frame down
stack.setElementAt(stack.elementAt(pfunc+aux), func+aux);
}
stack.setSize(func+aux); // correct top
// assert stack.size() == base + ((LuaFunction)stack.elementAt(func)).proto().maxstacksize();
ci.tailcall(base, stack.size());
dec_ci(); // remove new frame.
continue reentry;
}
case PCRJ: // It was a Java function
{
continue;
}
default:
{
return; // yield
}
}
}
case OP_RETURN:
{
fClose(base);
int b = ARGB(i);
if (b != 0)
{
int top = a + b - 1;
stack.setSize(base + top);
}
savedpc = pc;
// 'adjust' replaces aliased 'b' in PUC-Rio code.
boolean adjust = vmPoscall(base+a);
if (--nexeccalls == 0)
{
return;
}
if (adjust)
{
stack.setSize(ci().top());
}
continue reentry;
}
case OP_FORLOOP:
{
double step =
((Double)stack.elementAt(base+a+2)).doubleValue();
double idx =
((Double)stack.elementAt(base+a)).doubleValue() + step;
double limit =
((Double)stack.elementAt(base+a+1)).doubleValue();
if ((0 < step && idx <= limit) ||
(step <= 0 && limit <= idx))
{
// dojump
pc += ARGsBx(i);
Object d = valueOfNumber(idx);
stack.setElementAt(d, base+a); // internal index
stack.setElementAt(d, base+a+3); // external index
}
continue;
}
case OP_FORPREP:
{
int init = base+a;
int plimit = base+a+1;
int pstep = base+a+2;
savedpc = pc; // next steps may throw errors
if (!tonumber(init))
{
gRunerror("'for' initial value must be a number");
}
else if (!tonumber(plimit))
{
gRunerror("'for' limit must be a number");
}
else if (!tonumber(pstep))
{
gRunerror("'for' step must be a number");
}
double step =
((Double)stack.elementAt(pstep)).doubleValue();
double idx =
((Double)stack.elementAt(init)).doubleValue() - step;
stack.setElementAt(new Double(idx), init);
// dojump
pc += ARGsBx(i);
continue;
}
case OP_TFORLOOP:
{
int cb = base+a+3; // call base
stack.setElementAt(stack.elementAt(base+a+2), cb+2);
stack.setElementAt(stack.elementAt(base+a+1), cb+1);
stack.setElementAt(stack.elementAt(base+a), cb);
stack.setSize(cb+3);
savedpc = pc; // Protect
vmCall(cb, ARGC(i));
stack.setSize(ci().top());
if (NIL != stack.elementAt(cb)) // continue loop
{
stack.setElementAt(stack.elementAt(cb), cb-1);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
}
case OP_SETLIST:
{
int n = ARGB(i);
int c = ARGC(i);
int last;
LuaTable t;
if (0 == n)
{
n = (stack.size() - a) - 1;
- // :todo: check this against PUC-Rio
- // stack.setSize ??
+ stack.setSize(ci().top());
}
if (0 == c)
{
c = code[pc++];
}
t = (LuaTable)stack.elementAt(base+a);
last = ((c-1)*LFIELDS_PER_FLUSH) + n;
// :todo: consider expanding space in table
for (; n > 0; n--)
{
Object val = stack.elementAt(base+a+n);
t.putnum(last--, val);
}
continue;
}
case OP_CLOSE:
fClose(base+a);
continue;
case OP_CLOSURE:
{
Proto p = function.proto().proto()[ARGBx(i)];
int nup = p.nups();
UpVal[] up = new UpVal[nup];
for (int j=0; j<nup; j++, pc++)
{
int in = code[pc];
if (OPCODE(in) == OP_GETUPVAL)
{
up[j] = function.upVal(ARGB(in));
}
else
{
// assert OPCODE(in) == OP_MOVE;
up[j] = fFindupval(base + ARGB(in));
}
}
LuaFunction nf = new LuaFunction(p, up, function.getEnv());
stack.setElementAt(nf, base+a);
continue;
}
case OP_VARARG:
{
int b = ARGB(i)-1;
int n = (base - ci().function()) -
function.proto().numparams() - 1;
if (b == MULTRET)
{
// :todo: Protect
// :todo: check stack
b = n;
stack.setSize(base+a+n);
}
for (int j=0; j<b; ++j)
{
if (j < n)
{
Object src = stack.elementAt(base - n + j);
stack.setElementAt(src, base+a+j);
}
else
{
stack.setElementAt(NIL, base+a+j);
}
}
continue;
}
} /* switch */
} /* while */
} /* reentry: while */
}
double iNumpow(double a, double b)
{
// :todo: this needs proper checking for boundary cases
// EG, is currently wrong for (-0)^2.
boolean invert = b < 0.0 ;
if (invert) b = -b ;
if (a == 0.0)
return invert ? Double.NaN : a ;
double result = 1.0 ;
int ipow = (int) b ;
b -= ipow ;
double t = a ;
while (ipow > 0)
{
if ((ipow & 1) != 0)
result *= t ;
ipow >>= 1 ;
t = t*t ;
}
if (b != 0.0) // integer only case, save doing unnecessary work
{
if (a < 0.0) // doesn't work if a negative (complex result!)
return Double.NaN ;
t = Math.sqrt(a) ;
double half = 0.5 ;
while (b > 0.0)
{
if (b >= half)
{
result = result * t ;
b -= half ;
}
b = b+b ;
t = Math.sqrt(t) ;
if (t == 1.0)
break ;
}
}
return invert ? 1.0 / result : result ;
}
/** Equivalent of luaV_gettable. */
private Object vmGettable(Object t, Object key)
{
Object tm;
for (int loop = 0; loop < MAXTAGLOOP; ++loop)
{
if (t instanceof LuaTable) // 't' is a table?
{
LuaTable h = (LuaTable)t;
Object res = h.get(key);
if (!isNil(res))
return res;
tm = tagmethod(h, "__index");
if (tm == null)
return res;
// else will try the tag method
}
else
{
tm = tagmethod(t, "__index");
if (tm == null)
gTypeerror(t, "index");
}
if (isFunction(tm))
return callTMres(tm, t, key);
t = tm; // else repeat with 'tm'
}
gRunerror("loop in gettable");
// NOTREACHED
return null;
}
/** Equivalent of luaV_lessthan. */
private boolean vmLessthan(Object l, Object r)
{
// :todo: currently goes wrong when comparing nil. Fix it.
if (l.getClass() != r.getClass())
{
// :todo: Make Lua error
throw new IllegalArgumentException();
}
else if (l instanceof Double)
{
return ((Double)l).doubleValue() < ((Double)r).doubleValue();
}
else if (l instanceof String)
{
// :todo: PUC-Rio use strcoll, maybe we should use something
// equivalent.
return ((String)l).compareTo((String)r) < 0;
}
int res = call_orderTM(l, r, "__lt");
if (res >= 0)
{
return res != 0;
}
return gOrdererror(l, r);
}
/** Equivalent of luaV_lessequal. */
private boolean vmLessequal(Object l, Object r)
{
// :todo: currently goes wrong when comparing nil. Fix it.
if (l.getClass() != r.getClass())
{
// :todo: Make Lua error
throw new IllegalArgumentException();
}
else if (l instanceof Double)
{
return ((Double)l).doubleValue() <= ((Double)r).doubleValue();
}
else if (l instanceof String)
{
return ((String)l).compareTo((String)r) <= 0;
}
int res = call_orderTM(l, r, "__le"); // first try 'le'
if (res >= 0)
{
return res != 0;
}
res = call_orderTM(r, l, "__lt"); // else try 'lt'
if (res >= 0)
{
return res == 0;
}
return gOrdererror(l, r);
}
/**
* Equivalent of luaD_poscall.
* @param firstResult stack index (absolute) of the first result
*/
private boolean vmPoscall(int firstResult)
{
// :todo: call hook
CallInfo lci; // local copy, for faster access
lci = dec_ci();
// Now (as a result of the dec_ci call), lci is the CallInfo record
// for the current function (the function executing an OP_RETURN
// instruction), and this.ci is the CallInfo record for the function
// we are returning to.
int res = lci.res();
int wanted = lci.nresults(); // Caution: wanted could be == MULTRET
CallInfo cci = ci(); // Continuation CallInfo
base = cci.base();
savedpc = cci.savedpc();
// Move results (and pad with nils to required number if necessary)
int i = wanted;
int top = stack.size();
// The movement is always downwards, so copying from the top-most
// result first is always correct.
while (i != 0 && firstResult < top)
{
stack.setElementAt(stack.elementAt(firstResult++), res++);
i--;
}
if (i > 0)
{
stack.setSize(res+i);
}
// :todo: consider using two stack.setSize calls to nil out
// remaining required results.
// This trick only works if Lua.NIL == null, whereas the current
// code works regardless of what Lua.NIL is.
while (i-- > 0)
{
stack.setElementAt(NIL, res++);
}
stack.setSize(res);
return wanted != MULTRET;
}
/**
* Equivalent of LuaD_precall. This method expects that the arguments
* to the function are placed above the function on the stack.
* @param func absolute stack index of the function to call.
* @param r number of results expected.
*/
private int vmPrecall(int func, int r)
{
Object faso; // Function AS Object
faso = stack.elementAt(func);
if (!isFunction(faso))
{
faso = tryfuncTM(func);
}
ci().setSavedpc(savedpc);
if (faso instanceof LuaFunction)
{
LuaFunction f = (LuaFunction)faso;
Proto p = f.proto();
// :todo: ensure enough stack
if (!p.isVararg())
{
base = func + 1;
if (stack.size() > base + p.numparams())
{
// trim stack to the argument list
stack.setSize(base + p.numparams());
}
}
else
{
int nargs = (stack.size() - func) - 1;
base = adjust_varargs(p, nargs);
}
int top = base + p.maxstacksize();
inc_ci(func, base, top, r);
savedpc = 0;
// expand stack to the function's max stack size.
stack.setSize(top);
// :todo: implement call hook.
return PCRLUA;
}
else if (faso instanceof LuaJavaCallback)
{
LuaJavaCallback fj = (LuaJavaCallback)faso;
// :todo: checkstack (not sure it's necessary)
base = func + 1;
inc_ci(func, base, stack.size()+MINSTACK, r);
// :todo: call hook
int n = fj.luaFunction(this);
if (n < 0) // yielding?
{
return PCRYIELD;
}
else
{
vmPoscall(stack.size() - n);
return PCRJ;
}
}
throw new IllegalArgumentException();
}
/** Equivalent of luaV_settable. */
private void vmSettable(Object t, Object key, Object val)
{
for (int loop = 0; loop < MAXTAGLOOP; ++loop)
{
Object tm;
if (t instanceof LuaTable) // 't' is a table
{
LuaTable h = (LuaTable)t;
Object o = h.get(key);
if (o != NIL) // result is not nil?
{
h.put(key, val);
return;
}
tm = tagmethod(h, "__newindex");
if (tm == null) // or no TM?
{
h.put(key, val);
return;
}
// else will try the tag method
}
else
{
tm = tagmethod(t, "__newindex");
if (tm == null)
gTypeerror(t, "index");
}
if (isFunction(tm))
{
callTM(tm, t, key, val);
return;
}
t = tm; // else repeat with 'tm'
}
gRunerror("loop in settable");
}
private static String vmTostring(Object o)
{
if (o instanceof String)
{
return (String)o;
}
if (!(o instanceof Double))
{
return null;
}
// Convert number to string. PUC-Rio abstracts this operation into
// a macro, lua_number2str. The macro is only invoked from their
// equivalent of this code.
Double d = (Double)o;
String repr = d.toString();
// Note: A naive conversion results in 3..4 == "3.04.0" which isn't
// good. We special case the integers.
if (repr.endsWith(".0"))
{
repr = repr.substring(0, repr.length()-2);
}
return repr;
}
/** Equivalent of adjust_varargs in "ldo.c". */
private int adjust_varargs(Proto p, int actual)
{
int nfixargs = p.numparams();
for (; actual < nfixargs; ++actual)
{
stack.addElement(NIL);
}
// PUC-Rio's LUA_COMPAT_VARARG is not supported here.
// Move fixed parameters to final position
int fixed = stack.size() - actual; // first fixed argument
int newbase = stack.size(); // final position of first argument
for (int i=0; i<nfixargs; ++i)
{
stack.addElement(stack.elementAt(fixed+i));
stack.setElementAt(NIL, fixed+i);
}
return newbase;
}
/**
* @param p1 left hand operand. Absolute stack index.
* @param p2 right hand operand. Absolute stack index.
* @param res absolute stack index of result.
* @return false if no tagmethod, true otherwise
*/
private boolean call_binTM(int p1, int p2, int res, String event)
{
Object tm = tagmethod(value(p1), event); // try first operand
if (isNil(tm))
{
tm = tagmethod(value(p2), event); // try second operand
}
if (!isFunction(tm))
{
return false;
}
stack.setElementAt(callTMres(tm, value(p1), value(p2)), res);
return true;
}
/**
* @return -1 if no tagmethod, 0 false, 1 true
*/
private int call_orderTM(Object p1, Object p2, String event)
{
Object tm1 = tagmethod(p1, event);
if (tm1 == NIL) // not metamethod
{
return -1;
}
Object tm2 = tagmethod(p2, event);
if (!oRawequal(tm1, tm2)) // different metamethods?
{
return -1;
}
return isFalse(callTMres(tm1, p1, p2)) ? 0 : 1;
}
private void callTM(Object f, Object p1, Object p2, Object p3)
{
push(f);
push(p1);
push(p2);
push(p3);
vmCall(stack.size()-4, 0);
}
private Object callTMres(Object f, Object p1, Object p2)
{
push(f);
push(p1);
push(p2);
vmCall(stack.size()-3, 1);
Object res = stack.lastElement();
pop(1);
return res;
}
private Object get_compTM(LuaTable mt1, LuaTable mt2, String event)
{
if (mt1 == null)
{
return null;
}
Object tm1 = mt1.get(event);
if (isNil(tm1))
{
return null; // no metamethod
}
if (mt1 == mt2)
{
return tm1; // same metatables => same metamethods
}
if (mt2 == null)
{
return null;
}
Object tm2 = mt2.get(event);
if (isNil(tm2))
{
return null; // no metamethod
}
if (oRawequal(tm1, tm2)) // same metamethods?
{
return tm1;
}
return null;
}
/**
* Gets tagmethod for object.
*/
private Object tagmethod(Object o, String event)
{
LuaTable mt;
mt = getMetatable(o);
if (mt == null)
{
return null;
}
return mt.get(event);
}
/**
* Computes the result of Lua's modules operator (%). Note that this
* modulus operator does not match Java's %.
*/
private static double modulus(double x, double y)
{
return x - Math.floor(x/y)*y;
}
/**
* Convert to number. Returns true if the argument o was converted to
* a number. Converted number is placed in <var>out[0]</var>. Returns
* false if the argument <var>o</var> could not be converted to a number.
* Overloaded.
*/
private static boolean tonumber(Object o, double[] out)
{
if (o instanceof Double)
{
out[0] = ((Double)o).doubleValue();
return true;
}
if (!(o instanceof String))
{
return false;
}
if (oStr2d((String)o, out))
{
return true;
}
return false;
}
/**
* Converts a stack slot to number. Returns true if the element at
* the specified stack slot was converted to a number. False
* otherwise. Note that this actually modifies the element stored at
* <var>idx</var> in the stack (in faithful emulation of the PUC-Rio
* code). Corrupts <code>NUMOP[0]</code>. Overloaded.
* @param idx absolute stack slot.
*/
private boolean tonumber(int idx)
{
if (tonumber(stack.elementAt(idx), NUMOP))
{
stack.setElementAt(new Double(NUMOP[0]), idx);
return true;
}
return false;
}
/**
* Convert a pair of operands for an arithmetic opcode. Stores
* converted results in <code>out[0]</code> and <code>out[1]</code>.
* @return true if and only if both values converted to number.
*/
private static boolean toNumberPair(Object x, Object y, double[] out)
{
if (tonumber(y, out))
{
out[1] = out[0];
if (tonumber(x, out))
{
return true;
}
}
return false;
}
/**
* Convert to string. Returns true if element was number or string
* (the number will have been converted to a string), false otherwise.
* Note this actually modifies the element stored at <var>idx</var> in
* the stack (in faithful emulation of the PUC-Rio code).
*/
private boolean tostring(int idx)
{
Object o = stack.elementAt(idx);
String s = vmTostring(o);
if (s == null)
{
return false;
}
stack.setElementAt(s, idx);
return true;
}
/**
* @param func absolute stack index of the function object.
*/
private Object tryfuncTM(int func)
{
Object tm = tagmethod(stack.elementAt(func), "__call");
if (!isFunction(tm))
{
gTypeerror(stack.elementAt(func), "call");
}
insert(tm, func);
return tm;
}
/** Lua's is False predicate. */
private boolean isFalse(Object o)
{
return o == NIL || Boolean.FALSE.equals(o);
}
/** Make new CallInfo record. */
private CallInfo inc_ci(int func, int baseArg, int top, int nresults)
{
CallInfo ci = new CallInfo(func, baseArg, top, nresults);
civ.addElement(ci);
return ci;
}
/** Pop topmost CallInfo record and return it. */
private CallInfo dec_ci()
{
CallInfo ci = (CallInfo)civ.pop();
return ci;
}
/** Equivalent to resume_error from ldo.c */
private int resume_error(String msg)
{
stack.setSize(ci().base());
stack.addElement(msg);
return ERRRUN;
}
/**
* Corresponds to ldump's luaU_dump method, but with data gone and writer
* replaced by OutputStream.
*/
static int uDump(Proto f, OutputStream writer, boolean strip)
throws IOException
{
DumpState d = new DumpState(new DataOutputStream(writer), strip) ;
d.DumpHeader();
d.DumpFunction(f, null);
d.writer.flush();
return 0; // Any errors result in thrown exceptions.
}
}
final class DumpState
{
DataOutputStream writer;
boolean strip;
DumpState(DataOutputStream writer, boolean strip)
{
this.writer = writer ;
this.strip = strip ;
}
//////////////// dumper ////////////////////
void DumpHeader() throws IOException
{
/*
* In order to make the code more compact the dumper re-uses the
* header defined in Loader.java. It has to fix the endianness byte
* first.
*/
Loader.HEADER[6] = 0;
writer.write(Loader.HEADER) ;
}
private void DumpInt(int i) throws IOException
{
writer.writeInt(i) ; // big-endian
}
private void DumpNumber(double d) throws IOException
{
writer.writeDouble(d) ; // big-endian
}
void DumpFunction(Proto f, String p) throws IOException
{
DumpString((f.source == p || strip) ? null : f.source);
DumpInt(f.linedefined);
DumpInt(f.lastlinedefined);
writer.writeByte(f.nups);
writer.writeByte(f.numparams);
writer.writeBoolean(f.isVararg());
writer.writeByte(f.maxstacksize);
DumpCode(f);
DumpConstants(f);
DumpDebug(f);
}
private void DumpCode(Proto f) throws IOException
{
int n = f.sizecode ;
int [] code = f.code ;
DumpInt(n);
for (int i = 0 ; i < n ; i++)
DumpInt(code[i]) ;
}
private void DumpConstants(Proto f) throws IOException
{
int n = f.sizek;
Object [] k = f.k ;
DumpInt(n) ;
for (int i = 0 ; i < n ; i++)
{
Object o = k[i] ;
if (o == null)
{
writer.writeByte(Lua.TNIL) ;
}
else if (o instanceof Boolean)
{
writer.writeByte(Lua.TBOOLEAN) ;
writer.writeBoolean(((Boolean)o).booleanValue()) ;
}
else if (o instanceof Double)
{
writer.writeByte(Lua.TNUMBER) ;
DumpNumber(((Double)o).doubleValue()) ;
}
else if (o instanceof String)
{
writer.writeByte(Lua.TSTRING) ;
DumpString((String)o) ;
}
else
{
//lua_assert(false); /* cannot happen */
}
}
n = f.sizep ;
DumpInt(n) ;
for (int i = 0 ; i < n ; i++)
{
Proto subfunc = f.p[i] ;
DumpFunction(subfunc, f.source) ;
}
}
private void DumpString(String s) throws IOException
{
if (s == null)
{
DumpInt(0);
}
else
{
/*
* Strings are dumped by converting to UTF-8 encoding. The MIDP
* 2.0 spec guarantees that this encoding will be supported (see
* page 9 of midp-2_0-fr-spec.pdf). Nonetheless, any
* possible UnsupportedEncodingException is left to be thrown
* (it's a subclass of IOException which is declared to be thrown).
*/
byte [] contents = s.getBytes("UTF-8") ;
int size = contents.length ;
DumpInt(size+1) ;
writer.write(contents, 0, size) ;
writer.writeByte(0) ;
}
}
private void DumpDebug(Proto f) throws IOException
{
if (strip)
{
DumpInt(0) ;
DumpInt(0) ;
DumpInt(0) ;
return ;
}
int n = f.sizelineinfo;
DumpInt(n);
for (int i=0; i<n; i++)
DumpInt(f.lineinfo[i]) ;
n = f.sizelocvars;
DumpInt(n);
for (int i=0; i<n; i++)
{
LocVar locvar = f.locvars[i] ;
DumpString(locvar.varname);
DumpInt(locvar.startpc);
DumpInt(locvar.endpc);
}
n = f.sizeupvalues;
DumpInt(n);
for (int i=0; i<n; i++)
DumpString(f.upvalues[i]);
}
}
| true | true | private void vmExecute(int nexeccalls)
{
// This labelled while loop is used to simulate the effect of C's
// goto. The end of the while loop is never reached. The beginning
// of the while loop is branched to using a "continue reentry;"
// statement (when a Lua function is called or returns).
reentry:
while (true)
{
// assert stack.elementAt[ci.function()] instanceof LuaFunction;
LuaFunction function = (LuaFunction)stack.elementAt(ci().function());
Proto proto = function.proto();
int[] code = proto.code();
Object[] k = proto.constant();
int pc = savedpc;
while (true) // main loop of interpreter
{
// Where the PUC-Rio code used the Protect macro, this has been
// replaced with "savedpc = pc" and a "// Protect" comment.
// Where the PUC-Rio code used the dojump macro, this has been
// replaced with the equivalent increment of the pc and a
// "//dojump" comment.
int i = code[pc++]; // VM instruction.
// :todo: count and line hook
int a = ARGA(i); // its A field.
Object rb;
Object rc;
switch (OPCODE(i))
{
case OP_MOVE:
stack.setElementAt(stack.elementAt(base+ARGB(i)), base+a);
continue;
case OP_LOADK:
stack.setElementAt(k[ARGBx(i)], base+a);
continue;
case OP_LOADBOOL:
stack.setElementAt(valueOfBoolean(ARGB(i) != 0), base+a);
if (ARGC(i) != 0)
{
++pc;
}
continue;
case OP_LOADNIL:
{
int b = base + ARGB(i);
do
{
stack.setElementAt(NIL, b--);
} while (b >= base + a);
continue;
}
case OP_GETUPVAL:
{
int b = ARGB(i);
stack.setElementAt(function.upVal(b).getValue(), base+a);
continue;
}
case OP_GETGLOBAL:
rb = k[ARGBx(i)];
// assert rb instance of String;
savedpc = pc; // Protect
stack.setElementAt(vmGettable(function.getEnv(), rb), base+a);
continue;
case OP_GETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+ARGB(i));
stack.setElementAt(vmGettable(t, RK(k, ARGC(i))), base+a);
continue;
}
case OP_SETUPVAL:
{
UpVal uv = function.upVal(ARGB(i));
uv.setValue(stack.elementAt(base+a));
continue;
}
case OP_SETGLOBAL:
savedpc = pc; // Protect
vmSettable(function.getEnv(), k[ARGBx(i)],
stack.elementAt(base+a));
continue;
case OP_SETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+a);
vmSettable(t, RK(k, ARGB(i)), RK(k, ARGC(i)));
continue;
}
case OP_NEWTABLE:
{
// :todo: use the b and c hints, currently ignored.
int b = ARGB(i);
int c = ARGC(i);
stack.setElementAt(new LuaTable(), base+a);
continue;
}
case OP_SELF:
{
int b = ARGB(i);
rb = stack.elementAt(base+b);
stack.setElementAt(rb, base+a+1);
savedpc = pc; // Protect
stack.setElementAt(vmGettable(rb, RK(k, ARGC(i))), base+a);
continue;
}
case OP_ADD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double sum = ((Double)rb).doubleValue() +
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double sum = NUMOP[0] + NUMOP[1];
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__add"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_SUB:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double difference = ((Double)rb).doubleValue() -
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double difference = NUMOP[0] - NUMOP[1];
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__sub"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MUL:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double product = ((Double)rb).doubleValue() *
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double product = NUMOP[0] * NUMOP[1];
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mul"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_DIV:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double quotient = ((Double)rb).doubleValue() /
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double quotient = NUMOP[0] / NUMOP[1];
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__div"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MOD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double db = ((Double)rb).doubleValue();
double dc = ((Double)rc).doubleValue();
double modulus = modulus(db, dc);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double modulus = modulus(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mod"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_POW:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double result = iNumpow(((Double)rb).doubleValue(),
((Double)rc).doubleValue());
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double result = iNumpow(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__pow"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_UNM:
{
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof Double)
{
double db = ((Double)rb).doubleValue();
stack.setElementAt(valueOfNumber(-db), base+a);
}
else if (tonumber(rb, NUMOP))
{
stack.setElementAt(valueOfNumber(-NUMOP[0]), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a,
"__unm"))
{
gAritherror(base+ARGB(i), base+ARGB(i));
}
continue;
}
case OP_NOT:
{
Object ra = stack.elementAt(base+ARGB(i));
stack.setElementAt(valueOfBoolean(isFalse(ra)), base+a);
continue;
}
case OP_LEN:
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof LuaTable)
{
LuaTable t = (LuaTable)rb;
stack.setElementAt(new Double(t.getn()), base+a);
continue;
}
else if (rb instanceof String)
{
String s = (String)rb;
stack.setElementAt(new Double(s.length()), base+a);
continue;
}
savedpc = pc; // Protect
if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__len"))
{
gTypeerror(rb, "get length of");
}
continue;
case OP_CONCAT:
{
int b = ARGB(i);
int c = ARGC(i);
savedpc = pc; // Protect
// :todo: The compiler assumes that all
// stack locations _above_ b end up with junk in them. In
// which case we can improve the speed of vmConcat (by not
// converting each stack slot, but simply using
// StringBuffer.append on whatever is there).
vmConcat(c - b + 1, c);
stack.setElementAt(stack.elementAt(base+b), base+a);
continue;
}
case OP_JMP:
// dojump
pc += ARGsBx(i);
continue;
case OP_EQ:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (vmEqual(rb, rc) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LT:
savedpc = pc; // Protect
if (vmLessthan(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LE:
savedpc = pc; // Protect
if (vmLessequal(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TEST:
if (isFalse(stack.elementAt(base+a)) != (ARGC(i) != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TESTSET:
rb = stack.elementAt(base+ARGB(i));
if (isFalse(rb) != (ARGC(i) != 0))
{
stack.setElementAt(rb, base+a);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_CALL:
{
int b = ARGB(i);
int nresults = ARGC(i) - 1;
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
switch (vmPrecall(base+a, nresults))
{
case PCRLUA:
nexeccalls++;
continue reentry;
case PCRJ:
// Was Java function called by precall, adjust result
if (nresults >= 0)
{
stack.setSize(ci().top());
}
continue;
default:
return; // yield
}
}
case OP_TAILCALL:
{
int b = ARGB(i);
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
// assert ARGC(i) - 1 == MULTRET
switch (vmPrecall(base+a, MULTRET))
{
case PCRLUA:
{
// tail call: put new frame in place of previous one.
CallInfo ci = (CallInfo)civ.elementAt(civ.size()-2);
int func = ci.function();
CallInfo fci = ci(); // Fresh CallInfo
int pfunc = fci.function();
fClose(ci.base());
base = func + (fci.base() - pfunc);
int aux; // loop index is used after loop ends
for (aux=0; pfunc+aux < stack.size(); ++aux)
{
// move frame down
stack.setElementAt(stack.elementAt(pfunc+aux), func+aux);
}
stack.setSize(func+aux); // correct top
// assert stack.size() == base + ((LuaFunction)stack.elementAt(func)).proto().maxstacksize();
ci.tailcall(base, stack.size());
dec_ci(); // remove new frame.
continue reentry;
}
case PCRJ: // It was a Java function
{
continue;
}
default:
{
return; // yield
}
}
}
case OP_RETURN:
{
fClose(base);
int b = ARGB(i);
if (b != 0)
{
int top = a + b - 1;
stack.setSize(base + top);
}
savedpc = pc;
// 'adjust' replaces aliased 'b' in PUC-Rio code.
boolean adjust = vmPoscall(base+a);
if (--nexeccalls == 0)
{
return;
}
if (adjust)
{
stack.setSize(ci().top());
}
continue reentry;
}
case OP_FORLOOP:
{
double step =
((Double)stack.elementAt(base+a+2)).doubleValue();
double idx =
((Double)stack.elementAt(base+a)).doubleValue() + step;
double limit =
((Double)stack.elementAt(base+a+1)).doubleValue();
if ((0 < step && idx <= limit) ||
(step <= 0 && limit <= idx))
{
// dojump
pc += ARGsBx(i);
Object d = valueOfNumber(idx);
stack.setElementAt(d, base+a); // internal index
stack.setElementAt(d, base+a+3); // external index
}
continue;
}
case OP_FORPREP:
{
int init = base+a;
int plimit = base+a+1;
int pstep = base+a+2;
savedpc = pc; // next steps may throw errors
if (!tonumber(init))
{
gRunerror("'for' initial value must be a number");
}
else if (!tonumber(plimit))
{
gRunerror("'for' limit must be a number");
}
else if (!tonumber(pstep))
{
gRunerror("'for' step must be a number");
}
double step =
((Double)stack.elementAt(pstep)).doubleValue();
double idx =
((Double)stack.elementAt(init)).doubleValue() - step;
stack.setElementAt(new Double(idx), init);
// dojump
pc += ARGsBx(i);
continue;
}
case OP_TFORLOOP:
{
int cb = base+a+3; // call base
stack.setElementAt(stack.elementAt(base+a+2), cb+2);
stack.setElementAt(stack.elementAt(base+a+1), cb+1);
stack.setElementAt(stack.elementAt(base+a), cb);
stack.setSize(cb+3);
savedpc = pc; // Protect
vmCall(cb, ARGC(i));
stack.setSize(ci().top());
if (NIL != stack.elementAt(cb)) // continue loop
{
stack.setElementAt(stack.elementAt(cb), cb-1);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
}
case OP_SETLIST:
{
int n = ARGB(i);
int c = ARGC(i);
int last;
LuaTable t;
if (0 == n)
{
n = (stack.size() - a) - 1;
// :todo: check this against PUC-Rio
// stack.setSize ??
}
if (0 == c)
{
c = code[pc++];
}
t = (LuaTable)stack.elementAt(base+a);
last = ((c-1)*LFIELDS_PER_FLUSH) + n;
// :todo: consider expanding space in table
for (; n > 0; n--)
{
Object val = stack.elementAt(base+a+n);
t.putnum(last--, val);
}
continue;
}
case OP_CLOSE:
fClose(base+a);
continue;
case OP_CLOSURE:
{
Proto p = function.proto().proto()[ARGBx(i)];
int nup = p.nups();
UpVal[] up = new UpVal[nup];
for (int j=0; j<nup; j++, pc++)
{
int in = code[pc];
if (OPCODE(in) == OP_GETUPVAL)
{
up[j] = function.upVal(ARGB(in));
}
else
{
// assert OPCODE(in) == OP_MOVE;
up[j] = fFindupval(base + ARGB(in));
}
}
LuaFunction nf = new LuaFunction(p, up, function.getEnv());
stack.setElementAt(nf, base+a);
continue;
}
case OP_VARARG:
{
int b = ARGB(i)-1;
int n = (base - ci().function()) -
function.proto().numparams() - 1;
if (b == MULTRET)
{
// :todo: Protect
// :todo: check stack
b = n;
stack.setSize(base+a+n);
}
for (int j=0; j<b; ++j)
{
if (j < n)
{
Object src = stack.elementAt(base - n + j);
stack.setElementAt(src, base+a+j);
}
else
{
stack.setElementAt(NIL, base+a+j);
}
}
continue;
}
} /* switch */
} /* while */
} /* reentry: while */
}
| private void vmExecute(int nexeccalls)
{
// This labelled while loop is used to simulate the effect of C's
// goto. The end of the while loop is never reached. The beginning
// of the while loop is branched to using a "continue reentry;"
// statement (when a Lua function is called or returns).
reentry:
while (true)
{
// assert stack.elementAt[ci.function()] instanceof LuaFunction;
LuaFunction function = (LuaFunction)stack.elementAt(ci().function());
Proto proto = function.proto();
int[] code = proto.code();
Object[] k = proto.constant();
int pc = savedpc;
while (true) // main loop of interpreter
{
// Where the PUC-Rio code used the Protect macro, this has been
// replaced with "savedpc = pc" and a "// Protect" comment.
// Where the PUC-Rio code used the dojump macro, this has been
// replaced with the equivalent increment of the pc and a
// "//dojump" comment.
int i = code[pc++]; // VM instruction.
// :todo: count and line hook
int a = ARGA(i); // its A field.
Object rb;
Object rc;
switch (OPCODE(i))
{
case OP_MOVE:
stack.setElementAt(stack.elementAt(base+ARGB(i)), base+a);
continue;
case OP_LOADK:
stack.setElementAt(k[ARGBx(i)], base+a);
continue;
case OP_LOADBOOL:
stack.setElementAt(valueOfBoolean(ARGB(i) != 0), base+a);
if (ARGC(i) != 0)
{
++pc;
}
continue;
case OP_LOADNIL:
{
int b = base + ARGB(i);
do
{
stack.setElementAt(NIL, b--);
} while (b >= base + a);
continue;
}
case OP_GETUPVAL:
{
int b = ARGB(i);
stack.setElementAt(function.upVal(b).getValue(), base+a);
continue;
}
case OP_GETGLOBAL:
rb = k[ARGBx(i)];
// assert rb instance of String;
savedpc = pc; // Protect
stack.setElementAt(vmGettable(function.getEnv(), rb), base+a);
continue;
case OP_GETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+ARGB(i));
stack.setElementAt(vmGettable(t, RK(k, ARGC(i))), base+a);
continue;
}
case OP_SETUPVAL:
{
UpVal uv = function.upVal(ARGB(i));
uv.setValue(stack.elementAt(base+a));
continue;
}
case OP_SETGLOBAL:
savedpc = pc; // Protect
vmSettable(function.getEnv(), k[ARGBx(i)],
stack.elementAt(base+a));
continue;
case OP_SETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+a);
vmSettable(t, RK(k, ARGB(i)), RK(k, ARGC(i)));
continue;
}
case OP_NEWTABLE:
{
// :todo: use the b and c hints, currently ignored.
int b = ARGB(i);
int c = ARGC(i);
stack.setElementAt(new LuaTable(), base+a);
continue;
}
case OP_SELF:
{
int b = ARGB(i);
rb = stack.elementAt(base+b);
stack.setElementAt(rb, base+a+1);
savedpc = pc; // Protect
stack.setElementAt(vmGettable(rb, RK(k, ARGC(i))), base+a);
continue;
}
case OP_ADD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double sum = ((Double)rb).doubleValue() +
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double sum = NUMOP[0] + NUMOP[1];
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__add"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_SUB:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double difference = ((Double)rb).doubleValue() -
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double difference = NUMOP[0] - NUMOP[1];
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__sub"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MUL:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double product = ((Double)rb).doubleValue() *
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double product = NUMOP[0] * NUMOP[1];
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mul"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_DIV:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double quotient = ((Double)rb).doubleValue() /
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double quotient = NUMOP[0] / NUMOP[1];
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__div"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MOD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double db = ((Double)rb).doubleValue();
double dc = ((Double)rc).doubleValue();
double modulus = modulus(db, dc);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double modulus = modulus(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mod"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_POW:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double result = iNumpow(((Double)rb).doubleValue(),
((Double)rc).doubleValue());
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double result = iNumpow(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__pow"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_UNM:
{
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof Double)
{
double db = ((Double)rb).doubleValue();
stack.setElementAt(valueOfNumber(-db), base+a);
}
else if (tonumber(rb, NUMOP))
{
stack.setElementAt(valueOfNumber(-NUMOP[0]), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a,
"__unm"))
{
gAritherror(base+ARGB(i), base+ARGB(i));
}
continue;
}
case OP_NOT:
{
Object ra = stack.elementAt(base+ARGB(i));
stack.setElementAt(valueOfBoolean(isFalse(ra)), base+a);
continue;
}
case OP_LEN:
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof LuaTable)
{
LuaTable t = (LuaTable)rb;
stack.setElementAt(new Double(t.getn()), base+a);
continue;
}
else if (rb instanceof String)
{
String s = (String)rb;
stack.setElementAt(new Double(s.length()), base+a);
continue;
}
savedpc = pc; // Protect
if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__len"))
{
gTypeerror(rb, "get length of");
}
continue;
case OP_CONCAT:
{
int b = ARGB(i);
int c = ARGC(i);
savedpc = pc; // Protect
// :todo: The compiler assumes that all
// stack locations _above_ b end up with junk in them. In
// which case we can improve the speed of vmConcat (by not
// converting each stack slot, but simply using
// StringBuffer.append on whatever is there).
vmConcat(c - b + 1, c);
stack.setElementAt(stack.elementAt(base+b), base+a);
continue;
}
case OP_JMP:
// dojump
pc += ARGsBx(i);
continue;
case OP_EQ:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (vmEqual(rb, rc) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LT:
savedpc = pc; // Protect
if (vmLessthan(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LE:
savedpc = pc; // Protect
if (vmLessequal(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TEST:
if (isFalse(stack.elementAt(base+a)) != (ARGC(i) != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TESTSET:
rb = stack.elementAt(base+ARGB(i));
if (isFalse(rb) != (ARGC(i) != 0))
{
stack.setElementAt(rb, base+a);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_CALL:
{
int b = ARGB(i);
int nresults = ARGC(i) - 1;
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
switch (vmPrecall(base+a, nresults))
{
case PCRLUA:
nexeccalls++;
continue reentry;
case PCRJ:
// Was Java function called by precall, adjust result
if (nresults >= 0)
{
stack.setSize(ci().top());
}
continue;
default:
return; // yield
}
}
case OP_TAILCALL:
{
int b = ARGB(i);
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
// assert ARGC(i) - 1 == MULTRET
switch (vmPrecall(base+a, MULTRET))
{
case PCRLUA:
{
// tail call: put new frame in place of previous one.
CallInfo ci = (CallInfo)civ.elementAt(civ.size()-2);
int func = ci.function();
CallInfo fci = ci(); // Fresh CallInfo
int pfunc = fci.function();
fClose(ci.base());
base = func + (fci.base() - pfunc);
int aux; // loop index is used after loop ends
for (aux=0; pfunc+aux < stack.size(); ++aux)
{
// move frame down
stack.setElementAt(stack.elementAt(pfunc+aux), func+aux);
}
stack.setSize(func+aux); // correct top
// assert stack.size() == base + ((LuaFunction)stack.elementAt(func)).proto().maxstacksize();
ci.tailcall(base, stack.size());
dec_ci(); // remove new frame.
continue reentry;
}
case PCRJ: // It was a Java function
{
continue;
}
default:
{
return; // yield
}
}
}
case OP_RETURN:
{
fClose(base);
int b = ARGB(i);
if (b != 0)
{
int top = a + b - 1;
stack.setSize(base + top);
}
savedpc = pc;
// 'adjust' replaces aliased 'b' in PUC-Rio code.
boolean adjust = vmPoscall(base+a);
if (--nexeccalls == 0)
{
return;
}
if (adjust)
{
stack.setSize(ci().top());
}
continue reentry;
}
case OP_FORLOOP:
{
double step =
((Double)stack.elementAt(base+a+2)).doubleValue();
double idx =
((Double)stack.elementAt(base+a)).doubleValue() + step;
double limit =
((Double)stack.elementAt(base+a+1)).doubleValue();
if ((0 < step && idx <= limit) ||
(step <= 0 && limit <= idx))
{
// dojump
pc += ARGsBx(i);
Object d = valueOfNumber(idx);
stack.setElementAt(d, base+a); // internal index
stack.setElementAt(d, base+a+3); // external index
}
continue;
}
case OP_FORPREP:
{
int init = base+a;
int plimit = base+a+1;
int pstep = base+a+2;
savedpc = pc; // next steps may throw errors
if (!tonumber(init))
{
gRunerror("'for' initial value must be a number");
}
else if (!tonumber(plimit))
{
gRunerror("'for' limit must be a number");
}
else if (!tonumber(pstep))
{
gRunerror("'for' step must be a number");
}
double step =
((Double)stack.elementAt(pstep)).doubleValue();
double idx =
((Double)stack.elementAt(init)).doubleValue() - step;
stack.setElementAt(new Double(idx), init);
// dojump
pc += ARGsBx(i);
continue;
}
case OP_TFORLOOP:
{
int cb = base+a+3; // call base
stack.setElementAt(stack.elementAt(base+a+2), cb+2);
stack.setElementAt(stack.elementAt(base+a+1), cb+1);
stack.setElementAt(stack.elementAt(base+a), cb);
stack.setSize(cb+3);
savedpc = pc; // Protect
vmCall(cb, ARGC(i));
stack.setSize(ci().top());
if (NIL != stack.elementAt(cb)) // continue loop
{
stack.setElementAt(stack.elementAt(cb), cb-1);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
}
case OP_SETLIST:
{
int n = ARGB(i);
int c = ARGC(i);
int last;
LuaTable t;
if (0 == n)
{
n = (stack.size() - a) - 1;
stack.setSize(ci().top());
}
if (0 == c)
{
c = code[pc++];
}
t = (LuaTable)stack.elementAt(base+a);
last = ((c-1)*LFIELDS_PER_FLUSH) + n;
// :todo: consider expanding space in table
for (; n > 0; n--)
{
Object val = stack.elementAt(base+a+n);
t.putnum(last--, val);
}
continue;
}
case OP_CLOSE:
fClose(base+a);
continue;
case OP_CLOSURE:
{
Proto p = function.proto().proto()[ARGBx(i)];
int nup = p.nups();
UpVal[] up = new UpVal[nup];
for (int j=0; j<nup; j++, pc++)
{
int in = code[pc];
if (OPCODE(in) == OP_GETUPVAL)
{
up[j] = function.upVal(ARGB(in));
}
else
{
// assert OPCODE(in) == OP_MOVE;
up[j] = fFindupval(base + ARGB(in));
}
}
LuaFunction nf = new LuaFunction(p, up, function.getEnv());
stack.setElementAt(nf, base+a);
continue;
}
case OP_VARARG:
{
int b = ARGB(i)-1;
int n = (base - ci().function()) -
function.proto().numparams() - 1;
if (b == MULTRET)
{
// :todo: Protect
// :todo: check stack
b = n;
stack.setSize(base+a+n);
}
for (int j=0; j<b; ++j)
{
if (j < n)
{
Object src = stack.elementAt(base - n + j);
stack.setElementAt(src, base+a+j);
}
else
{
stack.setElementAt(NIL, base+a+j);
}
}
continue;
}
} /* switch */
} /* while */
} /* reentry: while */
}
|
diff --git a/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java b/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java
index a5ee98cb..4c9b8987 100644
--- a/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java
+++ b/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java
@@ -1,189 +1,190 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package info.papyri.dispatch;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.net.MalformedURLException;
import javax.servlet.ServletConfig;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
/**
*
* @author hcayless
*/
public class BiblioSearch extends HttpServlet {
private String solrUrl;
private URL searchURL;
private String xmlPath = "";
private String htmlPath = "";
private String home = "";
private FileUtils util;
private SolrUtils solrutil;
private static String BiblioSearch = "biblio-search/";
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
solrUrl = config.getInitParameter("solrUrl");
xmlPath = config.getInitParameter("xmlPath");
htmlPath = config.getInitParameter("htmlPath");
home = config.getInitParameter("home");
util = new FileUtils(xmlPath, htmlPath);
solrutil = new SolrUtils(config);
try {
searchURL = new URL("file://" + home + "/" + "bibliosearch.html");
} catch (MalformedURLException e) {
throw new ServletException(e);
}
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
BufferedReader reader = null;
try {
String q = request.getParameter("q");
reader = new BufferedReader(new InputStreamReader(searchURL.openStream()));
String line = "";
while ((line = reader.readLine()) != null) {
if (line.contains("<!-- Results -->") && !("".equals(q) || q == null)) {
SolrServer solr = new CommonsHttpSolrServer(solrUrl + BiblioSearch);
int rows = 30;
try {
rows = Integer.parseInt(request.getParameter("rows"));
} catch (Exception e) {
}
int start = 0;
try {
start = Integer.parseInt(request.getParameter("start"));
} catch (Exception e) {}
SolrQuery sq = new SolrQuery();
try {
sq.setQuery(q);
sq.setStart(start);
sq.setRows(rows);
- sq.setSortField("sort", SolrQuery.ORDER.desc);
+ sq.addSortField("year", SolrQuery.ORDER.asc);
+ sq.addSortField("sort", SolrQuery.ORDER.asc);
QueryRequest req = new QueryRequest(sq);
req.setMethod(METHOD.POST);
QueryResponse rs = req.process(solr);
SolrDocumentList docs = rs.getResults();
out.println("<p>" + docs.getNumFound() + " hits on \"" + q.toString() + "\".</p>");
out.println("<table>");
String uq = q;
try {
uq = URLEncoder.encode(q, "UTF-8");
} catch (Exception e) {
}
for (SolrDocument doc : docs) {
StringBuilder row = new StringBuilder("<tr class=\"result-record\"><td>");
row.append("<a href=\"");
row.append("/biblio/");
row.append(((String) doc.getFieldValue("id")));
row.append("/?q=");
row.append(uq);
row.append("\">");
row.append(doc.getFieldValue("display"));
row.append("</a>");
row.append("</td>");
row.append("</tr>");
out.print(row);
}
out.println("</table>");
if (docs.getNumFound() > rows) {
out.println("<div id=\"pagination\">");
int pages = (int) Math.ceil((double) docs.getNumFound() / (double) rows);
int p = 0;
while (p < pages) {
if ((p * rows) == start) {
out.print("<div class=\"page current\">");
out.print((p + 1) + " ");
out.print("</div>");
} else {
StringBuilder plink = new StringBuilder(uq + "&start=" + p * rows + "&rows=" + rows);
out.print("<div class=\"page\"><a href=\"/bibliosearch?q=" + plink + "\">" + (p + 1) + "</a></div>");
}
p++;
}
out.println("</div>");
}
} catch (SolrServerException e) {
out.println("<p>Unable to execute query. Please try again.</p>");
throw new ServletException(e);
}
} else {
out.println(line);
}
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| true | true | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
BufferedReader reader = null;
try {
String q = request.getParameter("q");
reader = new BufferedReader(new InputStreamReader(searchURL.openStream()));
String line = "";
while ((line = reader.readLine()) != null) {
if (line.contains("<!-- Results -->") && !("".equals(q) || q == null)) {
SolrServer solr = new CommonsHttpSolrServer(solrUrl + BiblioSearch);
int rows = 30;
try {
rows = Integer.parseInt(request.getParameter("rows"));
} catch (Exception e) {
}
int start = 0;
try {
start = Integer.parseInt(request.getParameter("start"));
} catch (Exception e) {}
SolrQuery sq = new SolrQuery();
try {
sq.setQuery(q);
sq.setStart(start);
sq.setRows(rows);
sq.setSortField("sort", SolrQuery.ORDER.desc);
QueryRequest req = new QueryRequest(sq);
req.setMethod(METHOD.POST);
QueryResponse rs = req.process(solr);
SolrDocumentList docs = rs.getResults();
out.println("<p>" + docs.getNumFound() + " hits on \"" + q.toString() + "\".</p>");
out.println("<table>");
String uq = q;
try {
uq = URLEncoder.encode(q, "UTF-8");
} catch (Exception e) {
}
for (SolrDocument doc : docs) {
StringBuilder row = new StringBuilder("<tr class=\"result-record\"><td>");
row.append("<a href=\"");
row.append("/biblio/");
row.append(((String) doc.getFieldValue("id")));
row.append("/?q=");
row.append(uq);
row.append("\">");
row.append(doc.getFieldValue("display"));
row.append("</a>");
row.append("</td>");
row.append("</tr>");
out.print(row);
}
out.println("</table>");
if (docs.getNumFound() > rows) {
out.println("<div id=\"pagination\">");
int pages = (int) Math.ceil((double) docs.getNumFound() / (double) rows);
int p = 0;
while (p < pages) {
if ((p * rows) == start) {
out.print("<div class=\"page current\">");
out.print((p + 1) + " ");
out.print("</div>");
} else {
StringBuilder plink = new StringBuilder(uq + "&start=" + p * rows + "&rows=" + rows);
out.print("<div class=\"page\"><a href=\"/bibliosearch?q=" + plink + "\">" + (p + 1) + "</a></div>");
}
p++;
}
out.println("</div>");
}
} catch (SolrServerException e) {
out.println("<p>Unable to execute query. Please try again.</p>");
throw new ServletException(e);
}
} else {
out.println(line);
}
}
} finally {
out.close();
}
}
| protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
BufferedReader reader = null;
try {
String q = request.getParameter("q");
reader = new BufferedReader(new InputStreamReader(searchURL.openStream()));
String line = "";
while ((line = reader.readLine()) != null) {
if (line.contains("<!-- Results -->") && !("".equals(q) || q == null)) {
SolrServer solr = new CommonsHttpSolrServer(solrUrl + BiblioSearch);
int rows = 30;
try {
rows = Integer.parseInt(request.getParameter("rows"));
} catch (Exception e) {
}
int start = 0;
try {
start = Integer.parseInt(request.getParameter("start"));
} catch (Exception e) {}
SolrQuery sq = new SolrQuery();
try {
sq.setQuery(q);
sq.setStart(start);
sq.setRows(rows);
sq.addSortField("year", SolrQuery.ORDER.asc);
sq.addSortField("sort", SolrQuery.ORDER.asc);
QueryRequest req = new QueryRequest(sq);
req.setMethod(METHOD.POST);
QueryResponse rs = req.process(solr);
SolrDocumentList docs = rs.getResults();
out.println("<p>" + docs.getNumFound() + " hits on \"" + q.toString() + "\".</p>");
out.println("<table>");
String uq = q;
try {
uq = URLEncoder.encode(q, "UTF-8");
} catch (Exception e) {
}
for (SolrDocument doc : docs) {
StringBuilder row = new StringBuilder("<tr class=\"result-record\"><td>");
row.append("<a href=\"");
row.append("/biblio/");
row.append(((String) doc.getFieldValue("id")));
row.append("/?q=");
row.append(uq);
row.append("\">");
row.append(doc.getFieldValue("display"));
row.append("</a>");
row.append("</td>");
row.append("</tr>");
out.print(row);
}
out.println("</table>");
if (docs.getNumFound() > rows) {
out.println("<div id=\"pagination\">");
int pages = (int) Math.ceil((double) docs.getNumFound() / (double) rows);
int p = 0;
while (p < pages) {
if ((p * rows) == start) {
out.print("<div class=\"page current\">");
out.print((p + 1) + " ");
out.print("</div>");
} else {
StringBuilder plink = new StringBuilder(uq + "&start=" + p * rows + "&rows=" + rows);
out.print("<div class=\"page\"><a href=\"/bibliosearch?q=" + plink + "\">" + (p + 1) + "</a></div>");
}
p++;
}
out.println("</div>");
}
} catch (SolrServerException e) {
out.println("<p>Unable to execute query. Please try again.</p>");
throw new ServletException(e);
}
} else {
out.println(line);
}
}
} finally {
out.close();
}
}
|
diff --git a/src/main/java/swsec/Exit.java b/src/main/java/swsec/Exit.java
index 1120fd4..96d2997 100644
--- a/src/main/java/swsec/Exit.java
+++ b/src/main/java/swsec/Exit.java
@@ -1,24 +1,25 @@
package swsec;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Exit extends HttpServlet {
private static final long serialVersionUID = 1L;
public Exit() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
- session.invalidate();
+ if (session != null)
+ session.invalidate();
response.sendRedirect("index.jsp");
}
}
| true | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
session.invalidate();
response.sendRedirect("index.jsp");
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null)
session.invalidate();
response.sendRedirect("index.jsp");
}
|
diff --git a/runtime/src/main/java/org/qi4j/runtime/entity/UnitOfWorkCompositeBuilder.java b/runtime/src/main/java/org/qi4j/runtime/entity/UnitOfWorkCompositeBuilder.java
index 49b1094d6..c6b50fc6f 100644
--- a/runtime/src/main/java/org/qi4j/runtime/entity/UnitOfWorkCompositeBuilder.java
+++ b/runtime/src/main/java/org/qi4j/runtime/entity/UnitOfWorkCompositeBuilder.java
@@ -1,154 +1,154 @@
/*
* Copyright (c) 2007, Rickard Öberg. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.qi4j.runtime.entity;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import org.qi4j.association.AbstractAssociation;
import org.qi4j.association.Association;
import org.qi4j.association.ManyAssociation;
import org.qi4j.composite.Composite;
import org.qi4j.composite.InstantiationException;
import org.qi4j.composite.InvalidApplicationException;
import org.qi4j.entity.EntityComposite;
import org.qi4j.entity.Identity;
import org.qi4j.entity.IdentityGenerator;
import org.qi4j.entity.Lifecycle;
import org.qi4j.entity.UnitOfWorkException;
import org.qi4j.runtime.composite.CompositeContext;
import org.qi4j.runtime.composite.EntityCompositeInstance;
import org.qi4j.runtime.structure.CompositeBuilderImpl;
import org.qi4j.runtime.structure.ModuleInstance;
import org.qi4j.spi.entity.EntityState;
import org.qi4j.spi.entity.EntityStore;
import org.qi4j.spi.entity.StoreException;
/**
* TODO
*/
public final class UnitOfWorkCompositeBuilder<T extends Composite>
extends CompositeBuilderImpl<T>
{
private static final Method IDENTITY_METHOD;
private UnitOfWorkInstance uow;
private EntityStore store;
static
{
try
{
IDENTITY_METHOD = Identity.class.getMethod( "identity" );
}
catch( NoSuchMethodException e )
{
throw new InternalError( "Qi4j Core Runtime codebase is corrupted. Contact Qi4j team: UnitOfWorkCompositeBuilder" );
}
}
public UnitOfWorkCompositeBuilder( ModuleInstance moduleInstance, CompositeContext compositeContext, UnitOfWorkInstance uow, EntityStore store )
{
super( moduleInstance, compositeContext );
this.uow = uow;
this.store = store;
}
public void use( Object... usedObjects )
{
throw new InvalidApplicationException( "Entities may not use other objects" );
}
public T newInstance()
{
EntityState state;
- String identity = getPropertyValues().get( IDENTITY_METHOD ).toString();
+ String identity = (String) getPropertyValues().get( IDENTITY_METHOD );
if( identity == null )
{
Class compositeType = context.getCompositeModel().getCompositeClass();
IdentityGenerator identityGenerator = uow.stateServices.getIdentityGenerator( compositeType );
if( identityGenerator == null )
{
throw new UnitOfWorkException( "No identity generator found for type " + compositeType.getName() );
}
identity = identityGenerator.generate( compositeType );
}
Map<Method, Object> propertyValues = getPropertyValues();
try
{
state = store.newEntityState( uow, identity, context.getCompositeBinding(), propertyValues );
}
catch( StoreException e )
{
throw new InstantiationException( "Could not create new entity in store", e );
}
Map<Method, AbstractAssociation> associationValues = getAssociationValues();
for( Map.Entry<Method, AbstractAssociation> association : associationValues.entrySet() )
{
AbstractAssociation associationValue = state.getAssociation( association.getKey() );
if( associationValue instanceof ManyAssociation )
{
ManyAssociation manyAssociation = (ManyAssociation) associationValue;
ManyAssociation newAssociation = (ManyAssociation) association;
manyAssociation.addAll( newAssociation );
}
else
{
Association singleAssociation = (Association) associationValue;
Association newAssociation = (Association) association;
singleAssociation.set( newAssociation.get() );
}
}
EntityCompositeInstance compositeInstance = context.newEntityCompositeInstance( moduleInstance, uow, store, identity );
context.newEntityMixins( moduleInstance, compositeInstance, state );
T instance = compositeInterface.cast( compositeInstance.getProxy() );
uow.createEntity( (EntityComposite) instance );
// Invoke lifecycle create() method
if( instance instanceof Lifecycle )
{
context.invokeCreate( instance, compositeInstance );
}
return instance;
}
public Iterator<T> iterator()
{
final Iterator<T> decoratedIterator = super.iterator();
return new Iterator<T>()
{
public boolean hasNext()
{
return true;
}
public T next()
{
T instance = decoratedIterator.next();
uow.createEntity( (EntityComposite) instance );
return instance;
}
public void remove()
{
}
};
}
}
| true | true | public T newInstance()
{
EntityState state;
String identity = getPropertyValues().get( IDENTITY_METHOD ).toString();
if( identity == null )
{
Class compositeType = context.getCompositeModel().getCompositeClass();
IdentityGenerator identityGenerator = uow.stateServices.getIdentityGenerator( compositeType );
if( identityGenerator == null )
{
throw new UnitOfWorkException( "No identity generator found for type " + compositeType.getName() );
}
identity = identityGenerator.generate( compositeType );
}
Map<Method, Object> propertyValues = getPropertyValues();
try
{
state = store.newEntityState( uow, identity, context.getCompositeBinding(), propertyValues );
}
catch( StoreException e )
{
throw new InstantiationException( "Could not create new entity in store", e );
}
Map<Method, AbstractAssociation> associationValues = getAssociationValues();
for( Map.Entry<Method, AbstractAssociation> association : associationValues.entrySet() )
{
AbstractAssociation associationValue = state.getAssociation( association.getKey() );
if( associationValue instanceof ManyAssociation )
{
ManyAssociation manyAssociation = (ManyAssociation) associationValue;
ManyAssociation newAssociation = (ManyAssociation) association;
manyAssociation.addAll( newAssociation );
}
else
{
Association singleAssociation = (Association) associationValue;
Association newAssociation = (Association) association;
singleAssociation.set( newAssociation.get() );
}
}
EntityCompositeInstance compositeInstance = context.newEntityCompositeInstance( moduleInstance, uow, store, identity );
context.newEntityMixins( moduleInstance, compositeInstance, state );
T instance = compositeInterface.cast( compositeInstance.getProxy() );
uow.createEntity( (EntityComposite) instance );
// Invoke lifecycle create() method
if( instance instanceof Lifecycle )
{
context.invokeCreate( instance, compositeInstance );
}
return instance;
}
| public T newInstance()
{
EntityState state;
String identity = (String) getPropertyValues().get( IDENTITY_METHOD );
if( identity == null )
{
Class compositeType = context.getCompositeModel().getCompositeClass();
IdentityGenerator identityGenerator = uow.stateServices.getIdentityGenerator( compositeType );
if( identityGenerator == null )
{
throw new UnitOfWorkException( "No identity generator found for type " + compositeType.getName() );
}
identity = identityGenerator.generate( compositeType );
}
Map<Method, Object> propertyValues = getPropertyValues();
try
{
state = store.newEntityState( uow, identity, context.getCompositeBinding(), propertyValues );
}
catch( StoreException e )
{
throw new InstantiationException( "Could not create new entity in store", e );
}
Map<Method, AbstractAssociation> associationValues = getAssociationValues();
for( Map.Entry<Method, AbstractAssociation> association : associationValues.entrySet() )
{
AbstractAssociation associationValue = state.getAssociation( association.getKey() );
if( associationValue instanceof ManyAssociation )
{
ManyAssociation manyAssociation = (ManyAssociation) associationValue;
ManyAssociation newAssociation = (ManyAssociation) association;
manyAssociation.addAll( newAssociation );
}
else
{
Association singleAssociation = (Association) associationValue;
Association newAssociation = (Association) association;
singleAssociation.set( newAssociation.get() );
}
}
EntityCompositeInstance compositeInstance = context.newEntityCompositeInstance( moduleInstance, uow, store, identity );
context.newEntityMixins( moduleInstance, compositeInstance, state );
T instance = compositeInterface.cast( compositeInstance.getProxy() );
uow.createEntity( (EntityComposite) instance );
// Invoke lifecycle create() method
if( instance instanceof Lifecycle )
{
context.invokeCreate( instance, compositeInstance );
}
return instance;
}
|
diff --git a/Client/src/main/java/menu/DelayNode.java b/Client/src/main/java/menu/DelayNode.java
index 7823438..0709428 100644
--- a/Client/src/main/java/menu/DelayNode.java
+++ b/Client/src/main/java/menu/DelayNode.java
@@ -1,143 +1,144 @@
package menu;
import repository.DelayCom;
import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
/**
* This class is a GridPane that contains all the text and
* buttons for setting delay.
* @author Stian
*/
public class DelayNode extends GridPane {
private Text header, unit, error, confirm;
private TextField delayField;
private Button setButton;
DelayCom action;
public DelayNode() {
super();
action = new DelayCom();
header = new Text("Slideshow Intervall");
header.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
unit = new Text("Sekunder");
unit.setFont(Font.font("Tahoma", FontWeight.NORMAL, 15));
error = new Text("");
error.setVisible(false);
error.setFont(Font.font("Tahoma", FontWeight.NORMAL, 15));
error.setFill(Color.RED);
confirm = new Text("Nytt Intervall Satt!");
confirm.setVisible(false);
confirm.setFont(Font.font("Tahoma", FontWeight.NORMAL, 15));
+ delayField = new TextField();
if (getDelay() == 0) {
error.setVisible(true);
} else {
- delayField = new TextField(getDelay() + "");
+ delayField.setText(getDelay() + "");
}
delayField.setPrefSize(80, 30);
delayField.setAlignment(Pos.CENTER_RIGHT);
delayField.setTooltip(new Tooltip("Delay må være 1 sekund eller mer"));
delayField.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
confirm.setVisible(false);
String input = delayField.getText();
if (testInput(input)) {
error.setVisible(false);
} else {
error.setVisible(true);
}
}
});
setButton = new Button("Sett Intervall");
setButton.setPrefSize(180, 30);
setButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
error.setVisible(false);
confirm.setVisible(false);
String input = delayField.getText();
if (testInput(input)) {
int ok = setDelay(Integer.parseInt(input));
if (ok != 0) {
confirm.setVisible(true);
delayField.setText(ok + "");
} else {
error.setVisible(true);
}
} else {
error.setVisible(true);
}
}
});
this.setTranslateX(10);
this.setVgap(5);
this.setHgap(5);
this.add(header, 0, 0, 2, 1);
this.add(delayField, 0, 1);
this.add(unit, 1, 1);
this.add(error, 0, 2, 2, 1);
this.add(confirm, 0, 2, 2, 1);
this.add(setButton, 0, 3, 2, 1);
}
//Tests if the input is valid
private boolean testInput(String input) {
int i;
try {
i = Integer.parseInt(input);
} catch (NumberFormatException e) {
//e.printStackTrace();
error.setText("Ugyldig input");
return false;
}
if (i < 1) {
error.setText("Minimum delay er 1");
return false;
}
return true;
}
private int getDelay() {
int i;
try {
i = action.getDelay();
} catch (IOException ex) {
//ex.printStackTrace();
error.setText("Server utilgjengelig");
return 0;
}
return i;
}
private int setDelay(int delay) {
int newDelay;
try {
newDelay = action.setDelay(delay);
} catch (IOException ex) {
//ex.printStackTrace();
error.setText("Server utilgjengelig");
return 0;
}
return newDelay;
}
}
| false | true | public DelayNode() {
super();
action = new DelayCom();
header = new Text("Slideshow Intervall");
header.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
unit = new Text("Sekunder");
unit.setFont(Font.font("Tahoma", FontWeight.NORMAL, 15));
error = new Text("");
error.setVisible(false);
error.setFont(Font.font("Tahoma", FontWeight.NORMAL, 15));
error.setFill(Color.RED);
confirm = new Text("Nytt Intervall Satt!");
confirm.setVisible(false);
confirm.setFont(Font.font("Tahoma", FontWeight.NORMAL, 15));
if (getDelay() == 0) {
error.setVisible(true);
} else {
delayField = new TextField(getDelay() + "");
}
delayField.setPrefSize(80, 30);
delayField.setAlignment(Pos.CENTER_RIGHT);
delayField.setTooltip(new Tooltip("Delay må være 1 sekund eller mer"));
delayField.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
confirm.setVisible(false);
String input = delayField.getText();
if (testInput(input)) {
error.setVisible(false);
} else {
error.setVisible(true);
}
}
});
setButton = new Button("Sett Intervall");
setButton.setPrefSize(180, 30);
setButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
error.setVisible(false);
confirm.setVisible(false);
String input = delayField.getText();
if (testInput(input)) {
int ok = setDelay(Integer.parseInt(input));
if (ok != 0) {
confirm.setVisible(true);
delayField.setText(ok + "");
} else {
error.setVisible(true);
}
} else {
error.setVisible(true);
}
}
});
this.setTranslateX(10);
this.setVgap(5);
this.setHgap(5);
this.add(header, 0, 0, 2, 1);
this.add(delayField, 0, 1);
this.add(unit, 1, 1);
this.add(error, 0, 2, 2, 1);
this.add(confirm, 0, 2, 2, 1);
this.add(setButton, 0, 3, 2, 1);
}
| public DelayNode() {
super();
action = new DelayCom();
header = new Text("Slideshow Intervall");
header.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
unit = new Text("Sekunder");
unit.setFont(Font.font("Tahoma", FontWeight.NORMAL, 15));
error = new Text("");
error.setVisible(false);
error.setFont(Font.font("Tahoma", FontWeight.NORMAL, 15));
error.setFill(Color.RED);
confirm = new Text("Nytt Intervall Satt!");
confirm.setVisible(false);
confirm.setFont(Font.font("Tahoma", FontWeight.NORMAL, 15));
delayField = new TextField();
if (getDelay() == 0) {
error.setVisible(true);
} else {
delayField.setText(getDelay() + "");
}
delayField.setPrefSize(80, 30);
delayField.setAlignment(Pos.CENTER_RIGHT);
delayField.setTooltip(new Tooltip("Delay må være 1 sekund eller mer"));
delayField.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
confirm.setVisible(false);
String input = delayField.getText();
if (testInput(input)) {
error.setVisible(false);
} else {
error.setVisible(true);
}
}
});
setButton = new Button("Sett Intervall");
setButton.setPrefSize(180, 30);
setButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
error.setVisible(false);
confirm.setVisible(false);
String input = delayField.getText();
if (testInput(input)) {
int ok = setDelay(Integer.parseInt(input));
if (ok != 0) {
confirm.setVisible(true);
delayField.setText(ok + "");
} else {
error.setVisible(true);
}
} else {
error.setVisible(true);
}
}
});
this.setTranslateX(10);
this.setVgap(5);
this.setHgap(5);
this.add(header, 0, 0, 2, 1);
this.add(delayField, 0, 1);
this.add(unit, 1, 1);
this.add(error, 0, 2, 2, 1);
this.add(confirm, 0, 2, 2, 1);
this.add(setButton, 0, 3, 2, 1);
}
|
diff --git a/src/com/anwpteuz/bomberman/Fire.java b/src/com/anwpteuz/bomberman/Fire.java
index 24940d0..1ba75c1 100644
--- a/src/com/anwpteuz/bomberman/Fire.java
+++ b/src/com/anwpteuz/bomberman/Fire.java
@@ -1,82 +1,83 @@
package com.anwpteuz.bomberman;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Random;
public class Fire extends GridObject implements Updateable {
private int range;
private Direction direction;
private int millisLifetime = 1000;
private int millisLived;
private int millisSpreadTime = 200;
private boolean isParent;
private Color color = (new Random().nextInt(2) == 0) ? Color.RED : Color.YELLOW;
// Images
private ArrayList<Image> images = new ArrayList<Image>();
private Image currentImage;
/**
*
* @param g The Game
* @param dirX -1 0 1 x-wise
* @param dirY -1 0 1 y-wise
* @param range The number of Fires left to place in direction given
*/
public Fire(Game g, Direction dir, int range) {
super(g);
this.range = range;
this.direction = dir;
// Add images
images.add(AssetsManager.getInstance().loadImage("fire_1"));
images.add(AssetsManager.getInstance().loadImage("fire_2"));
images.add(AssetsManager.getInstance().loadImage("fire_3"));
images.add(AssetsManager.getInstance().loadImage("fire_4"));
images.add(AssetsManager.getInstance().loadImage("fire_5"));
// Set first image
currentImage = images.get(0);
}
private void placeFireChild() {
Tile nextTile = getGame().getGrid().nextTile(this.getTile(), this.direction);
if(nextTile != null) {
GridObjectFactory.addFire(nextTile.getX(), nextTile.getY(), direction, range-1);
}
}
@Override
public void paint(Graphics g) {
g.drawImage(currentImage, getTile().getX()*Grid.CELL_SIZE, getTile().getY()*Grid.CELL_SIZE, Grid.CELL_SIZE, Grid.CELL_SIZE, null);
}
@Override
public void update() {
millisLived += Game.targetTime;
/**
* Run placeFireChild only if all the following applies:
* 1. Range isn't reached
* 2. This ain't yet a parent
* 3. It has lived long enough to spread
*/
if(range > 0 && !isParent && millisLived >= millisSpreadTime) {
placeFireChild();
isParent = true;
}
if(millisLived >= millisLifetime)
this.getTile().remove(this);
float time = (millisLived / (float)millisLifetime);
- int imageIndex = (int)(time * images.size());
+ int imageIndex = (int)(time * images.size() * 2);
if(time > 0.5f) imageIndex = images.size() - imageIndex;
+ if(imageIndex < 0) imageIndex = 0;
currentImage = images.get(imageIndex);
}
}
| false | true | public void update() {
millisLived += Game.targetTime;
/**
* Run placeFireChild only if all the following applies:
* 1. Range isn't reached
* 2. This ain't yet a parent
* 3. It has lived long enough to spread
*/
if(range > 0 && !isParent && millisLived >= millisSpreadTime) {
placeFireChild();
isParent = true;
}
if(millisLived >= millisLifetime)
this.getTile().remove(this);
float time = (millisLived / (float)millisLifetime);
int imageIndex = (int)(time * images.size());
if(time > 0.5f) imageIndex = images.size() - imageIndex;
currentImage = images.get(imageIndex);
}
| public void update() {
millisLived += Game.targetTime;
/**
* Run placeFireChild only if all the following applies:
* 1. Range isn't reached
* 2. This ain't yet a parent
* 3. It has lived long enough to spread
*/
if(range > 0 && !isParent && millisLived >= millisSpreadTime) {
placeFireChild();
isParent = true;
}
if(millisLived >= millisLifetime)
this.getTile().remove(this);
float time = (millisLived / (float)millisLifetime);
int imageIndex = (int)(time * images.size() * 2);
if(time > 0.5f) imageIndex = images.size() - imageIndex;
if(imageIndex < 0) imageIndex = 0;
currentImage = images.get(imageIndex);
}
|
diff --git a/plugins/org.eclipse.tcf.debug/src/org/eclipse/tcf/internal/debug/tests/TestExpressions.java b/plugins/org.eclipse.tcf.debug/src/org/eclipse/tcf/internal/debug/tests/TestExpressions.java
index 47e589f74..f9ebee153 100644
--- a/plugins/org.eclipse.tcf.debug/src/org/eclipse/tcf/internal/debug/tests/TestExpressions.java
+++ b/plugins/org.eclipse.tcf.debug/src/org/eclipse/tcf/internal/debug/tests/TestExpressions.java
@@ -1,896 +1,896 @@
/*******************************************************************************
* Copyright (c) 2008, 2013 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.internal.debug.tests;
import java.math.BigInteger;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.eclipse.tcf.protocol.IChannel;
import org.eclipse.tcf.protocol.IErrorReport;
import org.eclipse.tcf.protocol.IToken;
import org.eclipse.tcf.protocol.JSON;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.services.IBreakpoints;
import org.eclipse.tcf.services.IDPrintf;
import org.eclipse.tcf.services.IDiagnostics;
import org.eclipse.tcf.services.IExpressions;
import org.eclipse.tcf.services.IRunControl;
import org.eclipse.tcf.services.IStackTrace;
import org.eclipse.tcf.services.IStreams;
import org.eclipse.tcf.services.ISymbols;
import org.eclipse.tcf.services.IExpressions.Value;
class TestExpressions implements ITCFTest,
IRunControl.RunControlListener, IExpressions.ExpressionsListener, IBreakpoints.BreakpointsListener {
private final TCFTestSuite test_suite;
private final RunControl test_rc;
private final IDiagnostics srv_diag;
private final IExpressions srv_expr;
private final ISymbols srv_syms;
private final IStackTrace srv_stk;
private final IRunControl srv_rc;
private final IBreakpoints srv_bp;
private final IDPrintf srv_dprintf;
private final IStreams srv_streams;
private final Random rnd = new Random();
private String test_id;
private String bp_id;
private boolean bp_ok;
private IDiagnostics.ISymbol sym_func3;
private String test_ctx_id;
private String process_id;
private String thread_id;
private boolean run_to_bp_done;
private boolean loc_info_done;
private boolean no_cpp;
private boolean dprintf_done;
private boolean test_done;
private boolean cancel_test_sent;
private IRunControl.RunControlContext test_ctx;
private IRunControl.RunControlContext thread_ctx;
private String suspended_pc;
private boolean waiting_suspend;
private String[] stack_trace;
private IStackTrace.StackTraceContext[] stack_frames;
private String[] local_var_expr_ids;
private final Set<IToken> cmds = new HashSet<IToken>();
private final Map<String,String> global_var_ids = new HashMap<String,String>();
private final Map<String,String> local_var_ids = new HashMap<String,String>();
private final Map<String,SymbolLocation> global_var_location = new HashMap<String,SymbolLocation>();
private final Map<String,SymbolLocation> local_var_location = new HashMap<String,SymbolLocation>();
private final Map<String,IExpressions.Expression> expr_ctx = new HashMap<String,IExpressions.Expression>();
private final Map<String,IExpressions.Value> expr_val = new HashMap<String,IExpressions.Value>();
private final Map<String,ISymbols.Symbol> expr_sym = new HashMap<String,ISymbols.Symbol>();
private final Map<String,String[]> expr_chld = new HashMap<String,String[]>();
private final Set<String> expr_to_dispose = new HashSet<String>();
private int timer = 0;
private static String[] global_var_names = {
"tcf_test_char",
"tcf_test_short",
"tcf_test_long",
"tcf_cpp_test_bool",
};
private static final String[] test_expressions = {
"func2_local1",
"func2_local2",
"func2_local3",
"func2_local1 == func2_local1",
"func2_local1 != func2_local2",
"1.34 == 1.34",
"1.34 != 1.35",
"1 ? 1 : 0",
"!func2_local1 ? 0 : 1",
"(0 || 0) == 0",
"(0 || func2_local1) == 1",
"(func2_local1 || 0) == 1",
"(func2_local1 || func2_local1) == 1",
"(0 && 0) == 0",
"(0 && func2_local1) == 0",
"(func2_local1 && 0) == 0",
"(func2_local1 && func2_local1) == 1",
"(func2_local1 | func2_local2) == 3",
"(func2_local1 & func2_local2) == 0",
"(func2_local1 ^ func2_local2) == 3",
"(func2_local1 < func2_local2)",
"(func2_local1 <= func2_local2)",
"!(func2_local1 > func2_local2)",
"!(func2_local1 >= func2_local2)",
"(func2_local1 < 1.1)",
"(func2_local1 <= 1.1)",
"!(func2_local1 > 1.1)",
"!(func2_local1 >= 1.1)",
"(func2_local2 << 2) == 8",
"(func2_local2 >> 1) == 1",
"+func2_local2 == 2",
"-func2_local2 == -2",
"(short)(int)(long)((char *)func2_local2 + 1) == 3",
"((func2_local1 + func2_local2) * 2 - 2) / 2 == 2",
"func2_local3.f_struct->f_struct->f_struct == &func2_local3",
"(char *)func2_local3.f_struct",
"(char[4])func2_local3.f_struct",
"&((test_struct *)0)->f_float",
"&((struct test_struct *)0)->f_float",
"tcf_test_func3",
"&tcf_test_func3",
"tcf_test_array + 10",
"*(tcf_test_array + 10) | 1",
"&*(char *)(int *)0 == 0",
"(bool)0 == false",
"(bool)1 == true",
"sizeof(bool) == sizeof true",
"tcf_cpp_test_class::s_int == 1",
"sizeof tcf_cpp_test_class::s_int == sizeof signed",
"tcf_cpp_test_class::tcf_cpp_test_class_nested::s_int == 2",
"tcf_cpp_test_class_extension::tcf_cpp_test_class_nested::s_int == 2",
"enum_val1 == 1 && enum_val2 == 2 && enum_val3 == 3",
};
private static final String[] test_dprintfs = {
"$printf", null,
"$printf(", null,
"$printf()", null,
"$printf(1)", null,
"$printf(\"abc\")", "abc",
"$printf(\"%s\",\"abc\")", "abc",
"$printf(\"%d\",1)", "1",
"$printf(\"%d\",enum_val2)", "2",
"$printf(\"%u\",func2_local3.f_enum)", "3",
"$printf(\"%g\",func2_local3.f_float)", "3.14",
"$printf(\"%g\",func2_local3.f_double)", "2.71",
};
@SuppressWarnings("unused")
private static class SymbolLocation {
Exception error;
Map<String,Object> props;
}
TestExpressions(TCFTestSuite test_suite, RunControl test_rc, IChannel channel) {
this.test_suite = test_suite;
this.test_rc = test_rc;
srv_diag = channel.getRemoteService(IDiagnostics.class);
srv_expr = channel.getRemoteService(IExpressions.class);
srv_syms = channel.getRemoteService(ISymbols.class);
srv_stk = channel.getRemoteService(IStackTrace.class);
srv_rc = channel.getRemoteService(IRunControl.class);
srv_bp = channel.getRemoteService(IBreakpoints.class);
srv_dprintf = channel.getRemoteService(IDPrintf.class);
srv_streams = channel.getRemoteService(IStreams.class);
}
public void start() {
if (srv_diag == null || srv_expr == null || srv_stk == null || srv_rc == null || srv_bp == null) {
test_suite.done(this, null);
}
else {
srv_expr.addListener(this);
srv_rc.addListener(this);
srv_bp.addListener(this);
srv_diag.getTestList(new IDiagnostics.DoneGetTestList() {
public void doneGetTestList(IToken token, Throwable error, String[] list) {
if (!test_suite.isActive(TestExpressions.this)) return;
if (error != null) {
exit(error);
}
else {
if (list.length > 0) {
test_id = list[rnd.nextInt(list.length)];
runTest();
Protocol.invokeLater(100, new Runnable() {
public void run() {
if (!test_suite.isActive(TestExpressions.this)) return;
timer++;
if (test_suite.cancel) {
exit(null);
}
else if (timer < 600) {
if (test_done && !cancel_test_sent) {
test_rc.cancel(test_ctx_id);
cancel_test_sent = true;
}
Protocol.invokeLater(100, this);
}
else if (test_ctx_id == null) {
exit(new Error("Timeout waiting for reply of Diagnostics.runTest command"));
}
else {
exit(new Error("Missing 'contextRemoved' event for " + test_ctx_id));
}
}
});
return;
}
exit(null);
}
}
});
}
}
public boolean canResume(String id) {
if (test_ctx_id != null && thread_ctx == null) return false;
if (thread_ctx != null && !test_done) {
assert thread_ctx.getID().equals(thread_id);
IRunControl.RunControlContext ctx = test_rc.getContext(id);
if (ctx == null) return false;
String grp = ctx.getRCGroup();
if (id.equals(thread_id) || grp != null && grp.equals(thread_ctx.getRCGroup())) {
if (run_to_bp_done) return false;
if (sym_func3 == null) return false;
if (suspended_pc == null) return false;
BigInteger pc0 = JSON.toBigInteger(sym_func3.getValue());
BigInteger pc1 = new BigInteger(suspended_pc);
if (pc0.equals(pc1)) return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
private void runTest() {
timer = 0;
if (cmds.size() > 0) return;
if (bp_id == null) {
srv_bp.set(null, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_id = "TestExpressionsBP";
runTest();
}
}
});
return;
}
if (!bp_ok) {
Map<String,Object> m = new HashMap<String,Object>();
m.put(IBreakpoints.PROP_ID, bp_id);
m.put(IBreakpoints.PROP_ENABLED, Boolean.TRUE);
m.put(IBreakpoints.PROP_LOCATION, "tcf_test_func3");
srv_bp.set(new Map[]{ m }, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_ok = true;
runTest();
}
}
});
return;
}
if (test_ctx_id == null) {
srv_diag.runTest(test_id, new IDiagnostics.DoneRunTest() {
public void doneRunTest(IToken token, Throwable error, String id) {
if (error != null) {
exit(error);
}
else if (id == null) {
exit(new Exception("Test context ID must not be null"));
}
else if (test_rc.getContext(id) == null) {
exit(new Exception("Missing context added event"));
}
else {
test_ctx_id = id;
runTest();
}
}
});
return;
}
if (test_ctx == null) {
srv_rc.getContext(test_ctx_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Invalid test execution context"));
}
else {
test_ctx = ctx;
process_id = test_ctx.getProcessID();
if (test_ctx.hasState()) thread_id = test_ctx_id;
runTest();
}
}
});
return;
}
if (thread_id == null) {
srv_rc.getChildren(process_id, new IRunControl.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] ids) {
if (error != null) {
exit(error);
}
else if (ids == null || ids.length == 0) {
exit(new Exception("Test process has no threads"));
}
else if (ids.length != 1) {
exit(new Exception("Test process has too many threads"));
}
else {
thread_id = ids[0];
runTest();
}
}
});
return;
}
if (thread_ctx == null) {
srv_rc.getContext(thread_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null || !ctx.hasState()) {
exit(new Exception("Invalid thread context"));
}
else {
thread_ctx = ctx;
runTest();
}
}
});
return;
}
if (suspended_pc == null) {
thread_ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error,
boolean suspended, String pc, String reason,
Map<String,Object> params) {
if (error != null) {
exit(new Exception("Cannot get context state", error));
}
else if (!suspended) {
waiting_suspend = true;
}
else if (pc == null || pc.length() == 0 || pc.equals("0")) {
exit(new Exception("Invalid context PC"));
}
else {
suspended_pc = pc;
runTest();
}
}
});
return;
}
if (sym_func3 == null) {
srv_diag.getSymbol(process_id, "tcf_test_func3", new IDiagnostics.DoneGetSymbol() {
public void doneGetSymbol(IToken token, Throwable error, IDiagnostics.ISymbol symbol) {
if (error != null) {
exit(error);
}
else if (symbol == null) {
exit(new Exception("Symbol must not be null: tcf_test_func3"));
}
else {
sym_func3 = symbol;
runTest();
}
}
});
return;
}
if (!run_to_bp_done) {
BigInteger pc0 = JSON.toBigInteger(sym_func3.getValue());
BigInteger pc1 = new BigInteger(suspended_pc);
if (!pc0.equals(pc1)) {
waiting_suspend = true;
return;
}
run_to_bp_done = true;
}
assert test_done || !canResume(thread_id);
if (stack_trace == null) {
srv_stk.getChildren(thread_id, new IStackTrace.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else if (context_ids == null || context_ids.length < 2) {
exit(new Exception("Invalid stack trace"));
}
else {
stack_trace = context_ids;
runTest();
}
}
});
return;
}
if (stack_frames == null) {
srv_stk.getContext(stack_trace, new IStackTrace.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IStackTrace.StackTraceContext[] frames) {
if (error != null) {
exit(error);
}
else if (frames == null || frames.length != stack_trace.length) {
exit(new Exception("Invalid stack trace"));
}
else {
stack_frames = frames;
runTest();
}
}
});
return;
}
if (local_var_expr_ids == null) {
srv_expr.getChildren(stack_trace[stack_trace.length - 2], new IExpressions.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null || context_ids == null) {
// Need to continue tests even if local variables info is not available.
// TODO: need to distinguish absence of debug info from other errors.
local_var_expr_ids = new String[0];
runTest();
}
else {
local_var_expr_ids = context_ids;
runTest();
}
}
});
return;
}
for (final String id : local_var_expr_ids) {
if (expr_ctx.get(id) == null) {
srv_expr.getContext(id, new IExpressions.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_ctx.put(id, ctx);
local_var_ids.put(id, ctx.getSymbolID());
runTest();
}
}
});
return;
}
}
if (srv_syms != null && local_var_expr_ids.length > 0) {
for (final String nm : global_var_names) {
if (!global_var_ids.containsKey(nm)) {
srv_syms.find(process_id, new BigInteger(suspended_pc), nm, new ISymbols.DoneFind() {
public void doneFind(IToken token, Exception error, String symbol_id) {
if (error != null) {
if (nm.startsWith("tcf_cpp_") && error instanceof IErrorReport &&
((IErrorReport)error).getErrorCode() == IErrorReport.TCF_ERROR_SYM_NOT_FOUND) {
global_var_ids.put(nm, null);
no_cpp = true;
runTest();
return;
}
exit(error);
}
else if (symbol_id == null) {
exit(new Exception("Invalid symbol ID"));
}
else {
global_var_ids.put(nm, symbol_id);
runTest();
}
}
});
return;
}
}
}
if (srv_syms != null && !loc_info_done) {
for (final String id : global_var_ids.values()) {
if (id != null && global_var_location.get(id) == null) {
srv_syms.getLocationInfo(id, new ISymbols.DoneGetLocationInfo() {
public void doneGetLocationInfo(IToken token, Exception error, Map<String, Object> props) {
SymbolLocation l = new SymbolLocation();
l.error = error;
l.props = props;
global_var_location.put(id, l);
if (error != null) {
if (error instanceof IErrorReport &&
((IErrorReport)error).getErrorCode() == IErrorReport.TCF_ERROR_INV_COMMAND) {
runTest();
return;
}
exit(error);
}
else if (props == null) {
exit(new Exception("Invalid symbol location info: props = null"));
}
else {
List<Object> cmds = (List<Object>)props.get(ISymbols.LOC_VALUE_CMDS);
if (cmds == null || cmds.size() == 0) {
exit(new Exception("Invalid symbol location info: ValueCmds = null"));
}
else {
runTest();
}
}
}
});
return;
}
}
for (final String id : local_var_ids.values()) {
if (id != null && local_var_location.get(id) == null) {
srv_syms.getLocationInfo(id, new ISymbols.DoneGetLocationInfo() {
public void doneGetLocationInfo(IToken token, Exception error, Map<String, Object> props) {
SymbolLocation l = new SymbolLocation();
l.error = error;
l.props = props;
local_var_location.put(id, l);
List<Object> cmds = (List<Object>)props.get(ISymbols.LOC_VALUE_CMDS);
if (error != null) {
if (error instanceof IErrorReport &&
((IErrorReport)error).getErrorCode() == IErrorReport.TCF_ERROR_INV_COMMAND) {
runTest();
return;
}
exit(error);
}
else if (cmds == null || cmds.size() == 0) {
exit(new Exception("Invalid symbol location info"));
}
else {
runTest();
}
}
});
return;
}
}
loc_info_done = true;
}
for (final String txt : test_expressions) {
if (local_var_expr_ids.length == 0) {
// Debug info not available
if (txt.indexOf("func2_local") >= 0) continue;
if (txt.indexOf("test_struct") >= 0) continue;
if (txt.indexOf("tcf_test_array") >= 0) continue;
if (txt.indexOf("(char *)") >= 0) continue;
if (txt.indexOf("enum_val") >= 0) continue;
}
if (local_var_expr_ids.length == 0 || no_cpp) {
// Agent is not build with C++ compiler
if (txt.indexOf("tcf_cpp_test") >= 0) continue;
if (txt.indexOf("(bool)") >= 0) continue;
}
if (expr_ctx.get(txt) == null) {
srv_expr.create(stack_trace[stack_trace.length - 2], null, txt, new IExpressions.DoneCreate() {
public void doneCreate(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_to_dispose.add(ctx.getID());
expr_ctx.put(txt, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : local_var_expr_ids) {
if (expr_val.get(id) == null) {
srv_expr.evaluate(id, new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : expr_ctx.keySet()) {
if (expr_val.get(id) == null) {
srv_expr.evaluate(expr_ctx.get(id).getID(), new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
byte[] arr = ctx.getValue();
boolean b = false;
for (byte x : arr) {
if (x != 0) b = true;
}
if (!b) exit(new Exception("Invalid value of expression \"" + id + "\""));
runTest();
}
}
});
return;
}
}
if (srv_syms != null) {
for (final String id : expr_val.keySet()) {
if (expr_sym.get(id) == null) {
IExpressions.Value v = expr_val.get(id);
String type_id = v.getTypeID();
if (type_id != null) {
srv_syms.getContext(type_id, new ISymbols.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, ISymbols.Symbol ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Symbol.getContext returned null"));
}
else {
expr_sym.put(id, ctx);
runTest();
}
}
});
return;
}
}
}
for (final String id : expr_sym.keySet()) {
if (expr_chld.get(id) == null) {
ISymbols.Symbol sym = expr_sym.get(id);
srv_syms.getChildren(sym.getID(), new ISymbols.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else {
if (context_ids == null) context_ids = new String[0];
expr_chld.put(id, context_ids);
runTest();
}
}
});
return;
}
}
}
- if (srv_dprintf != null && !dprintf_done) {
+ if (srv_dprintf != null && !dprintf_done && local_var_expr_ids.length > 0) {
cmds.add(srv_dprintf.open(null, new IDPrintf.DoneCommandOpen() {
int test_cnt;
int char_cnt;
@Override
public void doneCommandOpen(IToken token, Exception error, final String id) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
cmds.add(srv_streams.connect(id, new IStreams.DoneConnect() {
@Override
public void doneConnect(IToken token, Exception error) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
}
}));
cmds.add(srv_streams.read(id, 256, new IStreams.DoneRead() {
@Override
public void doneRead(IToken token, Exception error, int lost_size, byte[] data, boolean eos) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
if (eos) {
exit(new Exception("Unexpected EOS"));
return;
}
for (byte b : data) {
while (test_dprintfs[test_cnt * 2 + 1] == null) test_cnt++;
char ch = test_dprintfs[test_cnt * 2 + 1].charAt(char_cnt++);
if (b != ch) {
exit(new Exception("Invalid ouptput of $printf"));
return;
}
if (char_cnt == test_dprintfs[test_cnt * 2 + 1].length()) {
char_cnt = 0;
test_cnt++;
}
}
if (test_cnt >= test_dprintfs.length / 2) {
cmds.add(srv_streams.disconnect(id, new IStreams.DoneDisconnect() {
@Override
public void doneDisconnect(IToken token, Exception error) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
runTest();
}
}));
}
else {
cmds.add(srv_streams.read(id, 256, this));
}
}
}));
for (int n = 0; n < test_dprintfs.length; n += 2) {
String txt = test_dprintfs[n];
final String res = test_dprintfs[n + 1];
cmds.add(srv_expr.create(stack_trace[stack_trace.length - 2], null, txt, new IExpressions.DoneCreate() {
public void doneCreate(IToken token, Exception error, IExpressions.Expression ctx) {
cmds.remove(token);
if (error != null) {
if (res != null) exit(error);
}
else {
if (res == null) exit(new Exception("Expressions service was expected to return error"));
expr_to_dispose.add(ctx.getID());
cmds.add(srv_expr.evaluate(ctx.getID(), new IExpressions.DoneEvaluate() {
@Override
public void doneEvaluate(IToken token, Exception error, Value value) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
}
}));
}
}
}));
}
}
}));
dprintf_done = true;
return;
}
for (final String id : expr_to_dispose) {
srv_expr.dispose(id, new IExpressions.DoneDispose() {
public void doneDispose(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
expr_to_dispose.remove(id);
runTest();
}
}
});
return;
}
test_done = true;
}
private void exit(Throwable x) {
if (!test_suite.isActive(this)) return;
srv_expr.removeListener(this);
srv_bp.removeListener(this);
srv_rc.removeListener(this);
test_suite.done(this, x);
}
//--------------------------- Run Control listener ---------------------------//
public void containerResumed(String[] context_ids) {
for (String id : context_ids) contextResumed(id);
}
public void containerSuspended(String context, String pc, String reason,
Map<String,Object> params, String[] suspended_ids) {
for (String id : suspended_ids) {
contextSuspended(id, null, null, null);
}
}
public void contextAdded(IRunControl.RunControlContext[] contexts) {
}
public void contextChanged(IRunControl.RunControlContext[] contexts) {
}
public void contextException(String context, String msg) {
if (test_done) return;
IRunControl.RunControlContext ctx = test_rc.getContext(context);
if (ctx != null) {
String p = ctx.getParentID();
String c = ctx.getCreatorID();
if (!test_ctx_id.equals(c) && !test_ctx_id.equals(p)) return;
}
exit(new Exception("Context exception: " + msg));
}
public void contextRemoved(String[] context_ids) {
for (String id : context_ids) {
if (id.equals(test_ctx_id)) {
if (test_done) {
srv_bp.set(null, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
exit(error);
}
});
}
else {
exit(new Exception("Test process exited too soon"));
}
return;
}
}
}
public void contextResumed(String id) {
if (id.equals(thread_id)) {
if (run_to_bp_done && !test_done) {
assert thread_ctx != null;
assert !canResume(thread_id);
exit(new Exception("Unexpected contextResumed event: " + id));
}
suspended_pc = null;
}
}
public void contextSuspended(String id, String pc, String reason, Map<String,Object> params) {
assert id != null;
if (id.equals(thread_id) && waiting_suspend) {
suspended_pc = pc;
waiting_suspend = false;
runTest();
}
}
//--------------------------- Expressions listener ---------------------------//
public void valueChanged(String id) {
}
//--------------------------- Breakpoints listener ---------------------------//
@SuppressWarnings("unchecked")
public void breakpointStatusChanged(String id, Map<String,Object> status) {
if (id.equals(bp_id) && process_id != null && !test_done) {
String s = (String)status.get(IBreakpoints.STATUS_ERROR);
if (s != null) exit(new Exception("Invalid BP status: " + s));
Collection<Map<String,Object>> list = (Collection<Map<String,Object>>)status.get(IBreakpoints.STATUS_INSTANCES);
if (list == null) return;
String err = null;
for (Map<String,Object> map : list) {
String ctx = (String)map.get(IBreakpoints.INSTANCE_CONTEXT);
if (process_id.equals(ctx) && map.get(IBreakpoints.INSTANCE_ERROR) != null)
err = (String)map.get(IBreakpoints.INSTANCE_ERROR);
}
if (err != null) exit(new Exception("Invalid BP status: " + err));
}
}
public void contextAdded(Map<String,Object>[] bps) {
}
public void contextChanged(Map<String,Object>[] bps) {
}
}
| true | true | private void runTest() {
timer = 0;
if (cmds.size() > 0) return;
if (bp_id == null) {
srv_bp.set(null, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_id = "TestExpressionsBP";
runTest();
}
}
});
return;
}
if (!bp_ok) {
Map<String,Object> m = new HashMap<String,Object>();
m.put(IBreakpoints.PROP_ID, bp_id);
m.put(IBreakpoints.PROP_ENABLED, Boolean.TRUE);
m.put(IBreakpoints.PROP_LOCATION, "tcf_test_func3");
srv_bp.set(new Map[]{ m }, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_ok = true;
runTest();
}
}
});
return;
}
if (test_ctx_id == null) {
srv_diag.runTest(test_id, new IDiagnostics.DoneRunTest() {
public void doneRunTest(IToken token, Throwable error, String id) {
if (error != null) {
exit(error);
}
else if (id == null) {
exit(new Exception("Test context ID must not be null"));
}
else if (test_rc.getContext(id) == null) {
exit(new Exception("Missing context added event"));
}
else {
test_ctx_id = id;
runTest();
}
}
});
return;
}
if (test_ctx == null) {
srv_rc.getContext(test_ctx_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Invalid test execution context"));
}
else {
test_ctx = ctx;
process_id = test_ctx.getProcessID();
if (test_ctx.hasState()) thread_id = test_ctx_id;
runTest();
}
}
});
return;
}
if (thread_id == null) {
srv_rc.getChildren(process_id, new IRunControl.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] ids) {
if (error != null) {
exit(error);
}
else if (ids == null || ids.length == 0) {
exit(new Exception("Test process has no threads"));
}
else if (ids.length != 1) {
exit(new Exception("Test process has too many threads"));
}
else {
thread_id = ids[0];
runTest();
}
}
});
return;
}
if (thread_ctx == null) {
srv_rc.getContext(thread_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null || !ctx.hasState()) {
exit(new Exception("Invalid thread context"));
}
else {
thread_ctx = ctx;
runTest();
}
}
});
return;
}
if (suspended_pc == null) {
thread_ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error,
boolean suspended, String pc, String reason,
Map<String,Object> params) {
if (error != null) {
exit(new Exception("Cannot get context state", error));
}
else if (!suspended) {
waiting_suspend = true;
}
else if (pc == null || pc.length() == 0 || pc.equals("0")) {
exit(new Exception("Invalid context PC"));
}
else {
suspended_pc = pc;
runTest();
}
}
});
return;
}
if (sym_func3 == null) {
srv_diag.getSymbol(process_id, "tcf_test_func3", new IDiagnostics.DoneGetSymbol() {
public void doneGetSymbol(IToken token, Throwable error, IDiagnostics.ISymbol symbol) {
if (error != null) {
exit(error);
}
else if (symbol == null) {
exit(new Exception("Symbol must not be null: tcf_test_func3"));
}
else {
sym_func3 = symbol;
runTest();
}
}
});
return;
}
if (!run_to_bp_done) {
BigInteger pc0 = JSON.toBigInteger(sym_func3.getValue());
BigInteger pc1 = new BigInteger(suspended_pc);
if (!pc0.equals(pc1)) {
waiting_suspend = true;
return;
}
run_to_bp_done = true;
}
assert test_done || !canResume(thread_id);
if (stack_trace == null) {
srv_stk.getChildren(thread_id, new IStackTrace.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else if (context_ids == null || context_ids.length < 2) {
exit(new Exception("Invalid stack trace"));
}
else {
stack_trace = context_ids;
runTest();
}
}
});
return;
}
if (stack_frames == null) {
srv_stk.getContext(stack_trace, new IStackTrace.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IStackTrace.StackTraceContext[] frames) {
if (error != null) {
exit(error);
}
else if (frames == null || frames.length != stack_trace.length) {
exit(new Exception("Invalid stack trace"));
}
else {
stack_frames = frames;
runTest();
}
}
});
return;
}
if (local_var_expr_ids == null) {
srv_expr.getChildren(stack_trace[stack_trace.length - 2], new IExpressions.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null || context_ids == null) {
// Need to continue tests even if local variables info is not available.
// TODO: need to distinguish absence of debug info from other errors.
local_var_expr_ids = new String[0];
runTest();
}
else {
local_var_expr_ids = context_ids;
runTest();
}
}
});
return;
}
for (final String id : local_var_expr_ids) {
if (expr_ctx.get(id) == null) {
srv_expr.getContext(id, new IExpressions.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_ctx.put(id, ctx);
local_var_ids.put(id, ctx.getSymbolID());
runTest();
}
}
});
return;
}
}
if (srv_syms != null && local_var_expr_ids.length > 0) {
for (final String nm : global_var_names) {
if (!global_var_ids.containsKey(nm)) {
srv_syms.find(process_id, new BigInteger(suspended_pc), nm, new ISymbols.DoneFind() {
public void doneFind(IToken token, Exception error, String symbol_id) {
if (error != null) {
if (nm.startsWith("tcf_cpp_") && error instanceof IErrorReport &&
((IErrorReport)error).getErrorCode() == IErrorReport.TCF_ERROR_SYM_NOT_FOUND) {
global_var_ids.put(nm, null);
no_cpp = true;
runTest();
return;
}
exit(error);
}
else if (symbol_id == null) {
exit(new Exception("Invalid symbol ID"));
}
else {
global_var_ids.put(nm, symbol_id);
runTest();
}
}
});
return;
}
}
}
if (srv_syms != null && !loc_info_done) {
for (final String id : global_var_ids.values()) {
if (id != null && global_var_location.get(id) == null) {
srv_syms.getLocationInfo(id, new ISymbols.DoneGetLocationInfo() {
public void doneGetLocationInfo(IToken token, Exception error, Map<String, Object> props) {
SymbolLocation l = new SymbolLocation();
l.error = error;
l.props = props;
global_var_location.put(id, l);
if (error != null) {
if (error instanceof IErrorReport &&
((IErrorReport)error).getErrorCode() == IErrorReport.TCF_ERROR_INV_COMMAND) {
runTest();
return;
}
exit(error);
}
else if (props == null) {
exit(new Exception("Invalid symbol location info: props = null"));
}
else {
List<Object> cmds = (List<Object>)props.get(ISymbols.LOC_VALUE_CMDS);
if (cmds == null || cmds.size() == 0) {
exit(new Exception("Invalid symbol location info: ValueCmds = null"));
}
else {
runTest();
}
}
}
});
return;
}
}
for (final String id : local_var_ids.values()) {
if (id != null && local_var_location.get(id) == null) {
srv_syms.getLocationInfo(id, new ISymbols.DoneGetLocationInfo() {
public void doneGetLocationInfo(IToken token, Exception error, Map<String, Object> props) {
SymbolLocation l = new SymbolLocation();
l.error = error;
l.props = props;
local_var_location.put(id, l);
List<Object> cmds = (List<Object>)props.get(ISymbols.LOC_VALUE_CMDS);
if (error != null) {
if (error instanceof IErrorReport &&
((IErrorReport)error).getErrorCode() == IErrorReport.TCF_ERROR_INV_COMMAND) {
runTest();
return;
}
exit(error);
}
else if (cmds == null || cmds.size() == 0) {
exit(new Exception("Invalid symbol location info"));
}
else {
runTest();
}
}
});
return;
}
}
loc_info_done = true;
}
for (final String txt : test_expressions) {
if (local_var_expr_ids.length == 0) {
// Debug info not available
if (txt.indexOf("func2_local") >= 0) continue;
if (txt.indexOf("test_struct") >= 0) continue;
if (txt.indexOf("tcf_test_array") >= 0) continue;
if (txt.indexOf("(char *)") >= 0) continue;
if (txt.indexOf("enum_val") >= 0) continue;
}
if (local_var_expr_ids.length == 0 || no_cpp) {
// Agent is not build with C++ compiler
if (txt.indexOf("tcf_cpp_test") >= 0) continue;
if (txt.indexOf("(bool)") >= 0) continue;
}
if (expr_ctx.get(txt) == null) {
srv_expr.create(stack_trace[stack_trace.length - 2], null, txt, new IExpressions.DoneCreate() {
public void doneCreate(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_to_dispose.add(ctx.getID());
expr_ctx.put(txt, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : local_var_expr_ids) {
if (expr_val.get(id) == null) {
srv_expr.evaluate(id, new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : expr_ctx.keySet()) {
if (expr_val.get(id) == null) {
srv_expr.evaluate(expr_ctx.get(id).getID(), new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
byte[] arr = ctx.getValue();
boolean b = false;
for (byte x : arr) {
if (x != 0) b = true;
}
if (!b) exit(new Exception("Invalid value of expression \"" + id + "\""));
runTest();
}
}
});
return;
}
}
if (srv_syms != null) {
for (final String id : expr_val.keySet()) {
if (expr_sym.get(id) == null) {
IExpressions.Value v = expr_val.get(id);
String type_id = v.getTypeID();
if (type_id != null) {
srv_syms.getContext(type_id, new ISymbols.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, ISymbols.Symbol ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Symbol.getContext returned null"));
}
else {
expr_sym.put(id, ctx);
runTest();
}
}
});
return;
}
}
}
for (final String id : expr_sym.keySet()) {
if (expr_chld.get(id) == null) {
ISymbols.Symbol sym = expr_sym.get(id);
srv_syms.getChildren(sym.getID(), new ISymbols.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else {
if (context_ids == null) context_ids = new String[0];
expr_chld.put(id, context_ids);
runTest();
}
}
});
return;
}
}
}
if (srv_dprintf != null && !dprintf_done) {
cmds.add(srv_dprintf.open(null, new IDPrintf.DoneCommandOpen() {
int test_cnt;
int char_cnt;
@Override
public void doneCommandOpen(IToken token, Exception error, final String id) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
cmds.add(srv_streams.connect(id, new IStreams.DoneConnect() {
@Override
public void doneConnect(IToken token, Exception error) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
}
}));
cmds.add(srv_streams.read(id, 256, new IStreams.DoneRead() {
@Override
public void doneRead(IToken token, Exception error, int lost_size, byte[] data, boolean eos) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
if (eos) {
exit(new Exception("Unexpected EOS"));
return;
}
for (byte b : data) {
while (test_dprintfs[test_cnt * 2 + 1] == null) test_cnt++;
char ch = test_dprintfs[test_cnt * 2 + 1].charAt(char_cnt++);
if (b != ch) {
exit(new Exception("Invalid ouptput of $printf"));
return;
}
if (char_cnt == test_dprintfs[test_cnt * 2 + 1].length()) {
char_cnt = 0;
test_cnt++;
}
}
if (test_cnt >= test_dprintfs.length / 2) {
cmds.add(srv_streams.disconnect(id, new IStreams.DoneDisconnect() {
@Override
public void doneDisconnect(IToken token, Exception error) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
runTest();
}
}));
}
else {
cmds.add(srv_streams.read(id, 256, this));
}
}
}));
for (int n = 0; n < test_dprintfs.length; n += 2) {
String txt = test_dprintfs[n];
final String res = test_dprintfs[n + 1];
cmds.add(srv_expr.create(stack_trace[stack_trace.length - 2], null, txt, new IExpressions.DoneCreate() {
public void doneCreate(IToken token, Exception error, IExpressions.Expression ctx) {
cmds.remove(token);
if (error != null) {
if (res != null) exit(error);
}
else {
if (res == null) exit(new Exception("Expressions service was expected to return error"));
expr_to_dispose.add(ctx.getID());
cmds.add(srv_expr.evaluate(ctx.getID(), new IExpressions.DoneEvaluate() {
@Override
public void doneEvaluate(IToken token, Exception error, Value value) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
}
}));
}
}
}));
}
}
}));
dprintf_done = true;
return;
}
for (final String id : expr_to_dispose) {
srv_expr.dispose(id, new IExpressions.DoneDispose() {
public void doneDispose(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
expr_to_dispose.remove(id);
runTest();
}
}
});
return;
}
test_done = true;
}
| private void runTest() {
timer = 0;
if (cmds.size() > 0) return;
if (bp_id == null) {
srv_bp.set(null, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_id = "TestExpressionsBP";
runTest();
}
}
});
return;
}
if (!bp_ok) {
Map<String,Object> m = new HashMap<String,Object>();
m.put(IBreakpoints.PROP_ID, bp_id);
m.put(IBreakpoints.PROP_ENABLED, Boolean.TRUE);
m.put(IBreakpoints.PROP_LOCATION, "tcf_test_func3");
srv_bp.set(new Map[]{ m }, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_ok = true;
runTest();
}
}
});
return;
}
if (test_ctx_id == null) {
srv_diag.runTest(test_id, new IDiagnostics.DoneRunTest() {
public void doneRunTest(IToken token, Throwable error, String id) {
if (error != null) {
exit(error);
}
else if (id == null) {
exit(new Exception("Test context ID must not be null"));
}
else if (test_rc.getContext(id) == null) {
exit(new Exception("Missing context added event"));
}
else {
test_ctx_id = id;
runTest();
}
}
});
return;
}
if (test_ctx == null) {
srv_rc.getContext(test_ctx_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Invalid test execution context"));
}
else {
test_ctx = ctx;
process_id = test_ctx.getProcessID();
if (test_ctx.hasState()) thread_id = test_ctx_id;
runTest();
}
}
});
return;
}
if (thread_id == null) {
srv_rc.getChildren(process_id, new IRunControl.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] ids) {
if (error != null) {
exit(error);
}
else if (ids == null || ids.length == 0) {
exit(new Exception("Test process has no threads"));
}
else if (ids.length != 1) {
exit(new Exception("Test process has too many threads"));
}
else {
thread_id = ids[0];
runTest();
}
}
});
return;
}
if (thread_ctx == null) {
srv_rc.getContext(thread_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null || !ctx.hasState()) {
exit(new Exception("Invalid thread context"));
}
else {
thread_ctx = ctx;
runTest();
}
}
});
return;
}
if (suspended_pc == null) {
thread_ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error,
boolean suspended, String pc, String reason,
Map<String,Object> params) {
if (error != null) {
exit(new Exception("Cannot get context state", error));
}
else if (!suspended) {
waiting_suspend = true;
}
else if (pc == null || pc.length() == 0 || pc.equals("0")) {
exit(new Exception("Invalid context PC"));
}
else {
suspended_pc = pc;
runTest();
}
}
});
return;
}
if (sym_func3 == null) {
srv_diag.getSymbol(process_id, "tcf_test_func3", new IDiagnostics.DoneGetSymbol() {
public void doneGetSymbol(IToken token, Throwable error, IDiagnostics.ISymbol symbol) {
if (error != null) {
exit(error);
}
else if (symbol == null) {
exit(new Exception("Symbol must not be null: tcf_test_func3"));
}
else {
sym_func3 = symbol;
runTest();
}
}
});
return;
}
if (!run_to_bp_done) {
BigInteger pc0 = JSON.toBigInteger(sym_func3.getValue());
BigInteger pc1 = new BigInteger(suspended_pc);
if (!pc0.equals(pc1)) {
waiting_suspend = true;
return;
}
run_to_bp_done = true;
}
assert test_done || !canResume(thread_id);
if (stack_trace == null) {
srv_stk.getChildren(thread_id, new IStackTrace.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else if (context_ids == null || context_ids.length < 2) {
exit(new Exception("Invalid stack trace"));
}
else {
stack_trace = context_ids;
runTest();
}
}
});
return;
}
if (stack_frames == null) {
srv_stk.getContext(stack_trace, new IStackTrace.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IStackTrace.StackTraceContext[] frames) {
if (error != null) {
exit(error);
}
else if (frames == null || frames.length != stack_trace.length) {
exit(new Exception("Invalid stack trace"));
}
else {
stack_frames = frames;
runTest();
}
}
});
return;
}
if (local_var_expr_ids == null) {
srv_expr.getChildren(stack_trace[stack_trace.length - 2], new IExpressions.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null || context_ids == null) {
// Need to continue tests even if local variables info is not available.
// TODO: need to distinguish absence of debug info from other errors.
local_var_expr_ids = new String[0];
runTest();
}
else {
local_var_expr_ids = context_ids;
runTest();
}
}
});
return;
}
for (final String id : local_var_expr_ids) {
if (expr_ctx.get(id) == null) {
srv_expr.getContext(id, new IExpressions.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_ctx.put(id, ctx);
local_var_ids.put(id, ctx.getSymbolID());
runTest();
}
}
});
return;
}
}
if (srv_syms != null && local_var_expr_ids.length > 0) {
for (final String nm : global_var_names) {
if (!global_var_ids.containsKey(nm)) {
srv_syms.find(process_id, new BigInteger(suspended_pc), nm, new ISymbols.DoneFind() {
public void doneFind(IToken token, Exception error, String symbol_id) {
if (error != null) {
if (nm.startsWith("tcf_cpp_") && error instanceof IErrorReport &&
((IErrorReport)error).getErrorCode() == IErrorReport.TCF_ERROR_SYM_NOT_FOUND) {
global_var_ids.put(nm, null);
no_cpp = true;
runTest();
return;
}
exit(error);
}
else if (symbol_id == null) {
exit(new Exception("Invalid symbol ID"));
}
else {
global_var_ids.put(nm, symbol_id);
runTest();
}
}
});
return;
}
}
}
if (srv_syms != null && !loc_info_done) {
for (final String id : global_var_ids.values()) {
if (id != null && global_var_location.get(id) == null) {
srv_syms.getLocationInfo(id, new ISymbols.DoneGetLocationInfo() {
public void doneGetLocationInfo(IToken token, Exception error, Map<String, Object> props) {
SymbolLocation l = new SymbolLocation();
l.error = error;
l.props = props;
global_var_location.put(id, l);
if (error != null) {
if (error instanceof IErrorReport &&
((IErrorReport)error).getErrorCode() == IErrorReport.TCF_ERROR_INV_COMMAND) {
runTest();
return;
}
exit(error);
}
else if (props == null) {
exit(new Exception("Invalid symbol location info: props = null"));
}
else {
List<Object> cmds = (List<Object>)props.get(ISymbols.LOC_VALUE_CMDS);
if (cmds == null || cmds.size() == 0) {
exit(new Exception("Invalid symbol location info: ValueCmds = null"));
}
else {
runTest();
}
}
}
});
return;
}
}
for (final String id : local_var_ids.values()) {
if (id != null && local_var_location.get(id) == null) {
srv_syms.getLocationInfo(id, new ISymbols.DoneGetLocationInfo() {
public void doneGetLocationInfo(IToken token, Exception error, Map<String, Object> props) {
SymbolLocation l = new SymbolLocation();
l.error = error;
l.props = props;
local_var_location.put(id, l);
List<Object> cmds = (List<Object>)props.get(ISymbols.LOC_VALUE_CMDS);
if (error != null) {
if (error instanceof IErrorReport &&
((IErrorReport)error).getErrorCode() == IErrorReport.TCF_ERROR_INV_COMMAND) {
runTest();
return;
}
exit(error);
}
else if (cmds == null || cmds.size() == 0) {
exit(new Exception("Invalid symbol location info"));
}
else {
runTest();
}
}
});
return;
}
}
loc_info_done = true;
}
for (final String txt : test_expressions) {
if (local_var_expr_ids.length == 0) {
// Debug info not available
if (txt.indexOf("func2_local") >= 0) continue;
if (txt.indexOf("test_struct") >= 0) continue;
if (txt.indexOf("tcf_test_array") >= 0) continue;
if (txt.indexOf("(char *)") >= 0) continue;
if (txt.indexOf("enum_val") >= 0) continue;
}
if (local_var_expr_ids.length == 0 || no_cpp) {
// Agent is not build with C++ compiler
if (txt.indexOf("tcf_cpp_test") >= 0) continue;
if (txt.indexOf("(bool)") >= 0) continue;
}
if (expr_ctx.get(txt) == null) {
srv_expr.create(stack_trace[stack_trace.length - 2], null, txt, new IExpressions.DoneCreate() {
public void doneCreate(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_to_dispose.add(ctx.getID());
expr_ctx.put(txt, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : local_var_expr_ids) {
if (expr_val.get(id) == null) {
srv_expr.evaluate(id, new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : expr_ctx.keySet()) {
if (expr_val.get(id) == null) {
srv_expr.evaluate(expr_ctx.get(id).getID(), new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
byte[] arr = ctx.getValue();
boolean b = false;
for (byte x : arr) {
if (x != 0) b = true;
}
if (!b) exit(new Exception("Invalid value of expression \"" + id + "\""));
runTest();
}
}
});
return;
}
}
if (srv_syms != null) {
for (final String id : expr_val.keySet()) {
if (expr_sym.get(id) == null) {
IExpressions.Value v = expr_val.get(id);
String type_id = v.getTypeID();
if (type_id != null) {
srv_syms.getContext(type_id, new ISymbols.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, ISymbols.Symbol ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Symbol.getContext returned null"));
}
else {
expr_sym.put(id, ctx);
runTest();
}
}
});
return;
}
}
}
for (final String id : expr_sym.keySet()) {
if (expr_chld.get(id) == null) {
ISymbols.Symbol sym = expr_sym.get(id);
srv_syms.getChildren(sym.getID(), new ISymbols.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else {
if (context_ids == null) context_ids = new String[0];
expr_chld.put(id, context_ids);
runTest();
}
}
});
return;
}
}
}
if (srv_dprintf != null && !dprintf_done && local_var_expr_ids.length > 0) {
cmds.add(srv_dprintf.open(null, new IDPrintf.DoneCommandOpen() {
int test_cnt;
int char_cnt;
@Override
public void doneCommandOpen(IToken token, Exception error, final String id) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
cmds.add(srv_streams.connect(id, new IStreams.DoneConnect() {
@Override
public void doneConnect(IToken token, Exception error) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
}
}));
cmds.add(srv_streams.read(id, 256, new IStreams.DoneRead() {
@Override
public void doneRead(IToken token, Exception error, int lost_size, byte[] data, boolean eos) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
if (eos) {
exit(new Exception("Unexpected EOS"));
return;
}
for (byte b : data) {
while (test_dprintfs[test_cnt * 2 + 1] == null) test_cnt++;
char ch = test_dprintfs[test_cnt * 2 + 1].charAt(char_cnt++);
if (b != ch) {
exit(new Exception("Invalid ouptput of $printf"));
return;
}
if (char_cnt == test_dprintfs[test_cnt * 2 + 1].length()) {
char_cnt = 0;
test_cnt++;
}
}
if (test_cnt >= test_dprintfs.length / 2) {
cmds.add(srv_streams.disconnect(id, new IStreams.DoneDisconnect() {
@Override
public void doneDisconnect(IToken token, Exception error) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
runTest();
}
}));
}
else {
cmds.add(srv_streams.read(id, 256, this));
}
}
}));
for (int n = 0; n < test_dprintfs.length; n += 2) {
String txt = test_dprintfs[n];
final String res = test_dprintfs[n + 1];
cmds.add(srv_expr.create(stack_trace[stack_trace.length - 2], null, txt, new IExpressions.DoneCreate() {
public void doneCreate(IToken token, Exception error, IExpressions.Expression ctx) {
cmds.remove(token);
if (error != null) {
if (res != null) exit(error);
}
else {
if (res == null) exit(new Exception("Expressions service was expected to return error"));
expr_to_dispose.add(ctx.getID());
cmds.add(srv_expr.evaluate(ctx.getID(), new IExpressions.DoneEvaluate() {
@Override
public void doneEvaluate(IToken token, Exception error, Value value) {
cmds.remove(token);
if (error != null) {
exit(error);
return;
}
}
}));
}
}
}));
}
}
}));
dprintf_done = true;
return;
}
for (final String id : expr_to_dispose) {
srv_expr.dispose(id, new IExpressions.DoneDispose() {
public void doneDispose(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
expr_to_dispose.remove(id);
runTest();
}
}
});
return;
}
test_done = true;
}
|
diff --git a/src/ui/TradeRecordTable.java b/src/ui/TradeRecordTable.java
index 1e5fe25..5f6b19e 100644
--- a/src/ui/TradeRecordTable.java
+++ b/src/ui/TradeRecordTable.java
@@ -1,182 +1,183 @@
/**
*
*/
package ui;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import model.TradeRecord;
import util.Helper;
/**
* @author tuya
*
*/
public class TradeRecordTable extends DefaultTableModel {
private final List<TradeRecord> myRecords = new ArrayList<TradeRecord>();
private final int COL_TRADE_TIME = 0;
private final int COL_TRADE_AMOUNT = 1;
private final int COL_TRADE_PRISE = 2;
private final int COL_TRADE_TYPE = 3;
private final int COL_TRADE_MONEY = 4;
private final int COL_MAX = 5;
private final TableColumn[] myColumns = new TableColumn[COL_MAX];
private JTable myTable;
private final boolean myColumnEditable[] = {
// COL_TRADE_TIME
false,
// COL_TRADE_AMOUNT
true,
// COL_TRADE_PRISE
true,
// COL_TRADE_TYPE
false,
// COL_TRADE_MONEY
false };
/**
*
*/
private static final long serialVersionUID = -3117841222887703411L;
public TradeRecordTable(JTable table) {
setTable(table);
table.setModel(this);
refresh();
}
public TradeRecordTable(Object[][] objects, String[] headers) {
super(objects, headers);
}
private void updateColumns() {
for (int col = 0; col < COL_MAX; col++) {
if (myColumns[col] == null) {
myColumns[col] = new TableColumn();
myColumns[col].setModelIndex(col);
myTable.getColumnModel().addColumn(myColumns[col]);
}
}
TableColumn column = null;
column = myColumns[COL_TRADE_TIME];
column.setPreferredWidth(200);
column.setResizable(true);
}
/**
* @return the myTable
*/
public JTable getTable() {
return myTable;
}
/**
* @param myTable
* the myTable to set
*/
public void setTable(JTable myTable) {
this.myTable = myTable;
}
@Override
public boolean isCellEditable(int row, int column) {
return myColumnEditable[column];
}
@SuppressWarnings("deprecation")
@Override
public void setValueAt(Object val, int row, int col) {
TradeRecord tr = null;
if (myRecords.size() <= row) {
tr = new TradeRecord(System.currentTimeMillis(), 0, 0);
addTrade(tr);
} else {
tr = myRecords.get(row);
}
String valueStr = String.valueOf(val);
switch (col) {
case COL_TRADE_TIME: {
tr.setTime(Date.parse(valueStr));
break;
}
case COL_TRADE_PRISE:
tr.setPrise(Helper.getCurrencyValue(valueStr));
break;
case COL_TRADE_AMOUNT:
tr.setAmount(parseIntegerInput(valueStr));
break;
case COL_TRADE_TYPE:
break;
case COL_TRADE_MONEY:
break;
default:
}
}
@SuppressWarnings("deprecation")
@Override
public Object getValueAt(int row, int col) {
if (myRecords.size() <= row) {
return "";
}
TradeRecord tr = myRecords.get(row);
switch (col) {
case COL_TRADE_TIME: {
Date date = new Date(tr.getTime());
return date.toLocaleString();
}
case COL_TRADE_PRISE:
return Helper.getCurrencyString(Math.abs(tr.getPrise()));
case COL_TRADE_AMOUNT:
return tr.getAmount();
case COL_TRADE_TYPE: {
switch (tr.getType()) {
case BUY:
return "买入";
case SELL:
return "卖出";
case NOT_A_TRADE:
return "无效交易";
}
}
- case COL_TRADE_MONEY:
+ break;
+ case COL_TRADE_MONEY:
return Helper.getCurrencyString(tr.getMoney());
default:
}
return "";
}
public void setDatas(List<TradeRecord> rList) {
myRecords.clear();
myRecords.addAll(rList);
refresh();
}
public void addTrade(TradeRecord tr) {
myRecords.add(tr);
refresh();
}
public void addTrade(long time, int amount, double prise) {
addTrade(new TradeRecord(time, amount, prise));
}
protected void refresh() {
updateColumns();
this.setRowCount(myRecords.size() + 1);
}
protected int parseIntegerInput(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
return Integer.valueOf(str);
}
}
| true | true | public Object getValueAt(int row, int col) {
if (myRecords.size() <= row) {
return "";
}
TradeRecord tr = myRecords.get(row);
switch (col) {
case COL_TRADE_TIME: {
Date date = new Date(tr.getTime());
return date.toLocaleString();
}
case COL_TRADE_PRISE:
return Helper.getCurrencyString(Math.abs(tr.getPrise()));
case COL_TRADE_AMOUNT:
return tr.getAmount();
case COL_TRADE_TYPE: {
switch (tr.getType()) {
case BUY:
return "买入";
case SELL:
return "卖出";
case NOT_A_TRADE:
return "无效交易";
}
}
case COL_TRADE_MONEY:
return Helper.getCurrencyString(tr.getMoney());
default:
}
return "";
}
| public Object getValueAt(int row, int col) {
if (myRecords.size() <= row) {
return "";
}
TradeRecord tr = myRecords.get(row);
switch (col) {
case COL_TRADE_TIME: {
Date date = new Date(tr.getTime());
return date.toLocaleString();
}
case COL_TRADE_PRISE:
return Helper.getCurrencyString(Math.abs(tr.getPrise()));
case COL_TRADE_AMOUNT:
return tr.getAmount();
case COL_TRADE_TYPE: {
switch (tr.getType()) {
case BUY:
return "买入";
case SELL:
return "卖出";
case NOT_A_TRADE:
return "无效交易";
}
}
break;
case COL_TRADE_MONEY:
return Helper.getCurrencyString(tr.getMoney());
default:
}
return "";
}
|
diff --git a/SWADroid/src/es/ugr/swad/swadroid/Preferences.java b/SWADroid/src/es/ugr/swad/swadroid/Preferences.java
index 1f4ef1e5..6faa74b4 100644
--- a/SWADroid/src/es/ugr/swad/swadroid/Preferences.java
+++ b/SWADroid/src/es/ugr/swad/swadroid/Preferences.java
@@ -1,183 +1,184 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <[email protected]>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.widget.Toast;
/**
* Preferences window of application.
* @author Juan Miguel Boyero Corral <[email protected]>
*/
public class Preferences extends PreferenceActivity {
/**
* Application preferences
*/
private SharedPreferences prefs;
/**
* User identifier.
*/
private String userID;
/**
* User password.
*/
private String userPassword;
/**
* Old user identifier
*/
private String oldUserID;
/**
* Old user password
*/
private String oldUserPassword;
/**
* Gets user identifier.
* @return User identifier.
*/
public String getUserID() {
return userID;
}
/**
* Gets User password.
* @return User password.
*/
public String getUserPassword() {
return userPassword;
}
/**
* Gets old user identifier
* @return Old user identifier
*/
public String getOldUserID() {
return oldUserID;
}
/**
* Gets old user password
* @return Old user password
*/
public String getOldUserPassword() {
return oldUserPassword;
}
/**
* Get if this is the first run
*
* @return returns true, if this is the first run
*/
public boolean getFirstRun() {
return prefs.getBoolean("firstRun", true);
}
/**
* Store the first run
*/
public void setRunned() {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean("firstRun", false);
edit.commit();
}
/**
* Initializes preferences of activity.
* @param ctx Context of activity.
*/
public void getPreferences(Context ctx) {
// Get the xml/preferences.xml preferences
prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
userID = prefs.getString("userIDPref", "");
userPassword = prefs.getString("userPasswordPref", "");
}
/* (non-Javadoc)
* @see android.app.Activity#onCreate()
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
//Get the custom preference
Preference savePref = findPreference("savePref");
Preference userIDPref = findPreference("userIDPref");
Preference userPasswordPref = findPreference("userPasswordPref");
userIDPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
/**
* Called when a preference is selected.
* @param preference Preference selected.
*/
public boolean onPreferenceClick(Preference preference) {
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
userID = prefs.getString("userIDPref", "");
//Save userID before change it
oldUserID = userID;
return true;
}
});
userPasswordPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
/**
* Called when a preference is selected.
* @param preference Preference selected.
*/
public boolean onPreferenceClick(Preference preference) {
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
userPassword = prefs.getString("userPasswordPref", "");
//Save userPassword before change it
oldUserPassword = userPassword;
return true;
}
});
savePref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
/**
* Called when a preference is selected.
* @param preference Preference selected.
*/
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getBaseContext(),
R.string.saveMsg_preferences,
Toast.LENGTH_LONG).show();
SharedPreferences saveSharedPreference = getSharedPreferences(
Global.getPrefsName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = saveSharedPreference.edit();
//If user ID or password have changed, logout automatically to force a new login
- if(!userID.equals(oldUserID) || !userPassword.equals(oldUserPassword)) {
+ if(userID != null && oldUserID != null && userPassword != null && oldUserPassword != null &&
+ (!userID.equals(oldUserID) || !userPassword.equals(oldUserPassword))) {
Global.setLogged(false);
}
editor.putString("userIDPref", userID);
editor.putString("userPasswordPref", userPassword);
editor.commit();
return true;
}
});
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
//Get the custom preference
Preference savePref = findPreference("savePref");
Preference userIDPref = findPreference("userIDPref");
Preference userPasswordPref = findPreference("userPasswordPref");
userIDPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
/**
* Called when a preference is selected.
* @param preference Preference selected.
*/
public boolean onPreferenceClick(Preference preference) {
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
userID = prefs.getString("userIDPref", "");
//Save userID before change it
oldUserID = userID;
return true;
}
});
userPasswordPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
/**
* Called when a preference is selected.
* @param preference Preference selected.
*/
public boolean onPreferenceClick(Preference preference) {
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
userPassword = prefs.getString("userPasswordPref", "");
//Save userPassword before change it
oldUserPassword = userPassword;
return true;
}
});
savePref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
/**
* Called when a preference is selected.
* @param preference Preference selected.
*/
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getBaseContext(),
R.string.saveMsg_preferences,
Toast.LENGTH_LONG).show();
SharedPreferences saveSharedPreference = getSharedPreferences(
Global.getPrefsName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = saveSharedPreference.edit();
//If user ID or password have changed, logout automatically to force a new login
if(!userID.equals(oldUserID) || !userPassword.equals(oldUserPassword)) {
Global.setLogged(false);
}
editor.putString("userIDPref", userID);
editor.putString("userPasswordPref", userPassword);
editor.commit();
return true;
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
//Get the custom preference
Preference savePref = findPreference("savePref");
Preference userIDPref = findPreference("userIDPref");
Preference userPasswordPref = findPreference("userPasswordPref");
userIDPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
/**
* Called when a preference is selected.
* @param preference Preference selected.
*/
public boolean onPreferenceClick(Preference preference) {
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
userID = prefs.getString("userIDPref", "");
//Save userID before change it
oldUserID = userID;
return true;
}
});
userPasswordPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
/**
* Called when a preference is selected.
* @param preference Preference selected.
*/
public boolean onPreferenceClick(Preference preference) {
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
userPassword = prefs.getString("userPasswordPref", "");
//Save userPassword before change it
oldUserPassword = userPassword;
return true;
}
});
savePref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
/**
* Called when a preference is selected.
* @param preference Preference selected.
*/
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getBaseContext(),
R.string.saveMsg_preferences,
Toast.LENGTH_LONG).show();
SharedPreferences saveSharedPreference = getSharedPreferences(
Global.getPrefsName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = saveSharedPreference.edit();
//If user ID or password have changed, logout automatically to force a new login
if(userID != null && oldUserID != null && userPassword != null && oldUserPassword != null &&
(!userID.equals(oldUserID) || !userPassword.equals(oldUserPassword))) {
Global.setLogged(false);
}
editor.putString("userIDPref", userID);
editor.putString("userPasswordPref", userPassword);
editor.commit();
return true;
}
});
}
|
diff --git a/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedOverlay.java b/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedOverlay.java
index 404b005..a97fb31 100644
--- a/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedOverlay.java
+++ b/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedOverlay.java
@@ -1,283 +1,283 @@
// Created by plusminus on 23:18:23 - 02.10.2008
package org.osmdroid.views.overlay;
import java.util.ArrayList;
import org.osmdroid.ResourceProxy;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapView.Projection;
import org.osmdroid.views.overlay.OverlayItem.HotspotPlace;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
/**
* Draws a list of {@link OverlayItem} as markers to a map. The item with the lowest index is drawn
* as last and therefore the 'topmost' marker. It also gets checked for onTap first. This class is
* generic, because you then you get your custom item-class passed back in onTap().
*
* @author Marc Kurtz
* @author Nicolas Gramlich
* @author Theodore Hong
* @author Fred Eisele
*
* @param <Item>
*/
public abstract class ItemizedOverlay<Item extends OverlayItem> extends Overlay implements
Overlay.Snappable {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final Drawable mDefaultMarker;
private final ArrayList<Item> mInternalItemList;
private final Rect mRect = new Rect();
private final Point mCurScreenCoords = new Point();
protected boolean mDrawFocusedItem = true;
private Item mFocusedItem;
// ===========================================================
// Abstract methods
// ===========================================================
/**
* Method by which subclasses create the actual Items. This will only be called from populate()
* we'll cache them for later use.
*/
protected abstract Item createItem(int i);
/**
* The number of items in this overlay.
*/
public abstract int size();
// ===========================================================
// Constructors
// ===========================================================
public ItemizedOverlay(final Drawable pDefaultMarker, final ResourceProxy pResourceProxy) {
super(pResourceProxy);
if (pDefaultMarker == null) {
throw new IllegalArgumentException("You must pass a default marker to ItemizedOverlay.");
}
this.mDefaultMarker = pDefaultMarker;
mInternalItemList = new ArrayList<Item>();
}
// ===========================================================
// Methods from SuperClass/Interfaces (and supporting methods)
// ===========================================================
/**
* Draw a marker on each of our items. populate() must have been called first.<br/>
* <br/>
* The marker will be drawn twice for each Item in the Overlay--once in the shadow phase, skewed
* and darkened, then again in the non-shadow phase. The bottom-center of the marker will be
* aligned with the geographical coordinates of the Item.<br/>
* <br/>
* The order of drawing may be changed by overriding the getIndexToDraw(int) method. An item may
* provide an alternate marker via its OverlayItem.getMarker(int) method. If that method returns
* null, the default marker is used.<br/>
* <br/>
* The focused item is always drawn last, which puts it visually on top of the other items.<br/>
*
* @param canvas
* the Canvas upon which to draw. Note that this may already have a transformation
* applied, so be sure to leave it the way you found it
* @param mapView
* the MapView that requested the draw. Use MapView.getProjection() to convert
* between on-screen pixels and latitude/longitude pairs
* @param shadow
* if true, draw the shadow layer. If false, draw the overlay contents.
*/
@Override
public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) {
if (shadow) {
return;
}
final Projection pj = mapView.getProjection();
final int size = this.mInternalItemList.size() - 1;
/* Draw in backward cycle, so the items with the least index are on the front. */
for (int i = size; i >= 0; i--) {
final Item item = getItem(i);
pj.toMapPixels(item.mGeoPoint, mCurScreenCoords);
onDrawItem(canvas, item, mCurScreenCoords);
}
}
// ===========================================================
// Methods
// ===========================================================
/**
* Utility method to perform all processing on a new ItemizedOverlay. Subclasses provide Items
* through the createItem(int) method. The subclass should call this as soon as it has data,
* before anything else gets called.
*/
protected final void populate() {
final int size = size();
mInternalItemList.clear();
mInternalItemList.ensureCapacity(size);
for (int a = 0; a < size; a++) {
mInternalItemList.add(createItem(a));
}
}
/**
* Returns the Item at the given index.
*
* @param position
* the position of the item to return
* @return the Item of the given index.
*/
public final Item getItem(final int position) {
return mInternalItemList.get(position);
}
/**
* Draws an item located at the provided screen coordinates to the canvas.
*
* @param canvas
* what the item is drawn upon
* @param item
* the item to be drawn
* @param curScreenCoords
* the screen coordinates of the item
*/
protected void onDrawItem(final Canvas canvas, final Item item, final Point curScreenCoords) {
final int state = (mDrawFocusedItem && (mFocusedItem == item) ? OverlayItem.ITEM_STATE_FOCUSED_MASK
: 0);
final Drawable marker = (item.getMarker(state) == null) ? getDefaultMarker(state) : item
.getMarker(state);
final HotspotPlace hotspot = item.getMarkerHotspot();
boundToHotspot(marker, hotspot);
// draw it
Overlay.drawAt(canvas, marker, curScreenCoords.x, curScreenCoords.y, false);
}
private Drawable getDefaultMarker(final int state) {
OverlayItem.setState(mDefaultMarker, state);
return mDefaultMarker;
}
/**
* See if a given hit point is within the bounds of an item's marker. Override to modify the way
* an item is hit tested. The hit point is relative to the marker's bounds. The default
* implementation just checks to see if the hit point is within the touchable bounds of the
* marker.
*
* @param item
* the item to hit test
* @param marker
* the item's marker
* @param hitX
* x coordinate of point to check
* @param hitY
* y coordinate of point to check
* @return true if the hit point is within the marker
*/
protected boolean hitTest(final Item item, final android.graphics.drawable.Drawable marker, final int hitX,
final int hitY) {
return marker.getBounds().contains(hitX, hitY);
}
/**
* Set whether or not to draw the focused item. The default is to draw it, but some clients may
* prefer to draw the focused item themselves.
*/
public void setDrawFocusedItem(final boolean drawFocusedItem) {
mDrawFocusedItem = drawFocusedItem;
}
/**
* If the given Item is found in the overlay, force it to be the current focus-bearer. Any
* registered {@link ItemizedOverlay#OnFocusChangeListener} will be notified. This does not move
* the map, so if the Item isn't already centered, the user may get confused. If the Item is not
* found, this is a no-op. You can also pass null to remove focus.
*/
public void setFocus(final Item item) {
mFocusedItem = item;
}
/**
*
* @return the currently-focused item, or null if no item is currently focused.
*/
public Item getFocus() {
return mFocusedItem;
}
/**
* Adjusts a drawable's bounds so that (0,0) is a pixel in the location described by the hotspot
* parameter. Useful for "pin"-like graphics. For convenience, returns the same drawable that
* was passed in.
*
* @param marker
* the drawable to adjust
* @param hotspot
* the hotspot for the drawable
* @return the same drawable that was passed in.
*/
protected synchronized Drawable boundToHotspot(final Drawable marker, HotspotPlace hotspot) {
final int markerWidth = (int) (marker.getIntrinsicWidth() * mScale);
final int markerHeight = (int) (marker.getIntrinsicHeight() * mScale);
mRect.set(0, 0, 0 + markerWidth, 0 + markerHeight);
if (hotspot == null) {
hotspot = HotspotPlace.BOTTOM_CENTER;
}
switch (hotspot) {
default:
case NONE:
break;
case CENTER:
mRect.offset(-markerWidth / 2, -markerHeight / 2);
break;
case BOTTOM_CENTER:
mRect.offset(-markerWidth / 2, -markerHeight);
break;
case TOP_CENTER:
mRect.offset(-markerWidth / 2, 0);
break;
case RIGHT_CENTER:
mRect.offset(-markerWidth, -markerHeight / 2);
break;
case LEFT_CENTER:
mRect.offset(0, -markerHeight / 2);
break;
case UPPER_RIGHT_CORNER:
mRect.offset(-markerWidth, 0);
break;
case LOWER_RIGHT_CORNER:
mRect.offset(-markerWidth, -markerHeight);
break;
case UPPER_LEFT_CORNER:
mRect.offset(0, 0);
break;
case LOWER_LEFT_CORNER:
- mRect.offset(0, markerHeight); /// TODO test - should this be -markerHeight ???
+ mRect.offset(0, -markerHeight);
break;
}
marker.setBounds(mRect);
return marker;
}
}
| true | true | protected synchronized Drawable boundToHotspot(final Drawable marker, HotspotPlace hotspot) {
final int markerWidth = (int) (marker.getIntrinsicWidth() * mScale);
final int markerHeight = (int) (marker.getIntrinsicHeight() * mScale);
mRect.set(0, 0, 0 + markerWidth, 0 + markerHeight);
if (hotspot == null) {
hotspot = HotspotPlace.BOTTOM_CENTER;
}
switch (hotspot) {
default:
case NONE:
break;
case CENTER:
mRect.offset(-markerWidth / 2, -markerHeight / 2);
break;
case BOTTOM_CENTER:
mRect.offset(-markerWidth / 2, -markerHeight);
break;
case TOP_CENTER:
mRect.offset(-markerWidth / 2, 0);
break;
case RIGHT_CENTER:
mRect.offset(-markerWidth, -markerHeight / 2);
break;
case LEFT_CENTER:
mRect.offset(0, -markerHeight / 2);
break;
case UPPER_RIGHT_CORNER:
mRect.offset(-markerWidth, 0);
break;
case LOWER_RIGHT_CORNER:
mRect.offset(-markerWidth, -markerHeight);
break;
case UPPER_LEFT_CORNER:
mRect.offset(0, 0);
break;
case LOWER_LEFT_CORNER:
mRect.offset(0, markerHeight); /// TODO test - should this be -markerHeight ???
break;
}
marker.setBounds(mRect);
return marker;
}
| protected synchronized Drawable boundToHotspot(final Drawable marker, HotspotPlace hotspot) {
final int markerWidth = (int) (marker.getIntrinsicWidth() * mScale);
final int markerHeight = (int) (marker.getIntrinsicHeight() * mScale);
mRect.set(0, 0, 0 + markerWidth, 0 + markerHeight);
if (hotspot == null) {
hotspot = HotspotPlace.BOTTOM_CENTER;
}
switch (hotspot) {
default:
case NONE:
break;
case CENTER:
mRect.offset(-markerWidth / 2, -markerHeight / 2);
break;
case BOTTOM_CENTER:
mRect.offset(-markerWidth / 2, -markerHeight);
break;
case TOP_CENTER:
mRect.offset(-markerWidth / 2, 0);
break;
case RIGHT_CENTER:
mRect.offset(-markerWidth, -markerHeight / 2);
break;
case LEFT_CENTER:
mRect.offset(0, -markerHeight / 2);
break;
case UPPER_RIGHT_CORNER:
mRect.offset(-markerWidth, 0);
break;
case LOWER_RIGHT_CORNER:
mRect.offset(-markerWidth, -markerHeight);
break;
case UPPER_LEFT_CORNER:
mRect.offset(0, 0);
break;
case LOWER_LEFT_CORNER:
mRect.offset(0, -markerHeight);
break;
}
marker.setBounds(mRect);
return marker;
}
|
diff --git a/4dnest/src/org/fourdnest/androidclient/services/TagSuggestionService.java b/4dnest/src/org/fourdnest/androidclient/services/TagSuggestionService.java
index 667a613..89f92b8 100644
--- a/4dnest/src/org/fourdnest/androidclient/services/TagSuggestionService.java
+++ b/4dnest/src/org/fourdnest/androidclient/services/TagSuggestionService.java
@@ -1,314 +1,316 @@
package org.fourdnest.androidclient.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.fourdnest.androidclient.FourDNestApplication;
import org.fourdnest.androidclient.Nest;
import org.fourdnest.androidclient.NestManager;
import org.fourdnest.androidclient.Tag;
import org.fourdnest.androidclient.comm.Protocol;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
/**
* A service that keeps caches of recent and/or popular tags,
* both local and remote.
*/
public class TagSuggestionService extends IntentService {
/** Tag string used to indicate source in logging */
public static final String TAG = TagSuggestionService.class.getSimpleName();
/** Intent should have this category when remote tags should be updated */
public static final String UPDATE_REMOTE_TAGS = "UPDATE_REMOTE_TAGS_CATEGORY";
/** Intent should have this category when requesting tag broadcast */
public static final String GET_TAGS = "GET_TAGS_CATEGORY";
/** Intent should have this category when setting last used tags */
public static final String SET_LAST_USED_TAGS = "SET_LAST_USED_TAGS_CATEGORY";
/** Broadcast Intent will have this action if it contains autocomplete suggestions */
public static final String ACTION_AUTOCOMPLETE_TAGS = "org.fourdnest.androidclient.AUTOCOMPLETE_TAGS";
/** Broadcast Intent will have this action if it contains last used tags */
public static final String ACTION_LAST_USED_TAGS = "org.fourdnest.androidclient.LAST_USED_TAGS";
/** Key for current Nest id in Intent extras */
public static final String BUNDLE_NEST_ID = "BUNDLE_NEST_ID";
/** Key for tag list in Intent extras */
public static final String BUNDLE_TAG_LIST = "BUNDLE_TAG_LIST";
/** How long we initially wait before fetching the remote tags
* This is done each time the service is started (which happens frequently despite START_STICKY,
* not only when initially starting the app. Therefore setting this to 0 will cause double fetching.
*/
public static final long FIRST_INTERVAL = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
private static final int REMOTE_TAG_COUNT = 1024;
private LocalBroadcastManager mLocalBroadcastManager;
private FourDNestApplication app;
/**
* Constructor, simply calls super. Never used explicitly in user code.
*/
public TagSuggestionService() {
super(TagSuggestionService.class.getName());
}
/**
* Constructor, simply calls super. Never used explicitly in user code.
* @param name Name of service
*/
public TagSuggestionService(String name) {
super(name);
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
synchronized(this) {
this.app = FourDNestApplication.getApplication();
this.mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
Intent alarmIntent = new Intent(app, TagSuggestionService.class);
alarmIntent.addCategory(UPDATE_REMOTE_TAGS);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setInexactRepeating( //Be power efficient: we don't need exact timing
AlarmManager.ELAPSED_REALTIME, // Don't wake up phone just for this
System.currentTimeMillis() + FIRST_INTERVAL, // Time of first execution,
AlarmManager.INTERVAL_FIFTEEN_MINUTES, // Update frequency
PendingIntent.getService(
app, // The context
0,
alarmIntent,
0
)
);
}
}
@Override
/**
* FIXME, only for logging purposes
*/
public void onDestroy() {
Log.d(TAG, "onDestroy");
}
/**
* Requests an immediate update
*
* @param context
* The application context
*/
public static void requestUpdate(Context context) {
Intent intent = new Intent(context, TagSuggestionService.class);
intent.addCategory(UPDATE_REMOTE_TAGS);
context.startService(intent);
}
/**
* Request broadcasting of the current tag suggestions
*/
public static void requestTagBroadcast(Context context) {
FourDNestApplication app = (FourDNestApplication) context;
Integer currentNestId = Integer.valueOf(app.getCurrentNestId());
Log.d(TAG, "requestTagBroadcast for nest with id " + currentNestId.toString());
Intent intent = new Intent(context, TagSuggestionService.class);
intent.addCategory(GET_TAGS);
intent.putExtra(BUNDLE_NEST_ID, currentNestId);
context.startService(intent);
}
/**
* Stores the tags used in sending an Egg,
* so that when sending the next one they can be retrieved
* and used as suggestions.
* @param tags The tags attached to the last sent Egg.
*/
public static void setLastUsedTags(Context context, List<Tag> tags) {
Log.d(TAG, "setLastUsedTags");
FourDNestApplication app = (FourDNestApplication) context;
Integer currentNestId = Integer.valueOf(app.getCurrentNestId());
Intent intent = new Intent(context, TagSuggestionService.class);
intent.addCategory(SET_LAST_USED_TAGS);
intent.putExtra(BUNDLE_NEST_ID, currentNestId);
intent.putExtra(BUNDLE_TAG_LIST, tagListToStringArray(tags));
context.startService(intent);
}
/**
* Default Intent handler for IntentService. All Intents get sent here.
* Asynch processing of tasks with inexact timing goes here.
*/
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "onHandleIntent");
if(intent.hasCategory(UPDATE_REMOTE_TAGS)) {
updateRemoteTags();
}
}
/**
* Timing sensitive fast tasks are handled here
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
if(intent != null) {
if(intent.hasCategory(GET_TAGS)) {
broadcastTags(intent);
} else if(intent.hasCategory(SET_LAST_USED_TAGS)) {
handleLastUsedTags(intent);
} else {
super.onStartCommand(intent, flags, startId);
}
}
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
/**
* Loops through all Nests updating their tag cache
*/
private synchronized void updateRemoteTags() {
TagCache cache = app.getTagCache();
synchronized(cache) {
Log.d(TAG, "updateRemoteTags");
NestManager nestManager = app.getNestManager();
List<Nest> nests = nestManager.listNests();
for(Nest nest : nests) {
Integer nestId = Integer.valueOf(nest.getId());
Protocol protocol = nest.getProtocol();
List<Tag> tags = protocol.topTags(REMOTE_TAG_COUNT);
if(tags != null) {
Log.d(TAG, "Tags updated for Nest with id " + nestId);
cache.putRemoteTags(nestId, tagListToStringArray(tags));
} else {
Log.w(TAG, "Nest with id " + nestId + " returned null topTags");
}
}
}
}
/**
* Loops through all Nests updating their tag cache
*/
private synchronized void broadcastTags(Intent intent) {
TagCache cache = app.getTagCache();
synchronized(cache) {
// First broadcast the autocomplete suggestions
Integer currentNestId = Integer.valueOf(intent.getIntExtra(BUNDLE_NEST_ID, -1));
- List<String> out = new ArrayList<String>();
+ Set<String> out;
Set<String> lt = cache.getLocalTags(currentNestId);
if(lt != null) {
- out.addAll(lt);
+ out = new HashSet<String>(lt);
+ } else {
+ out = new HashSet<String>();
}
String[] rt = cache.getRemoteTags(currentNestId);
if(rt != null) {
for(String tag : rt) {
out.add(tag);
}
}
Intent broadcastIntent = new Intent(ACTION_AUTOCOMPLETE_TAGS);
broadcastIntent.putExtra(BUNDLE_NEST_ID, currentNestId);
broadcastIntent.putExtra(BUNDLE_TAG_LIST, out.toArray(new String[out.size()]));
mLocalBroadcastManager.sendBroadcast(broadcastIntent);
// Then broadcast the last used tags
broadcastIntent.putExtra(BUNDLE_NEST_ID, currentNestId);
broadcastIntent = new Intent(ACTION_LAST_USED_TAGS);
String[] tags = cache.getLastUsedTags(currentNestId);
if(tags == null) {
tags = new String[0];
}
broadcastIntent.putExtra(BUNDLE_TAG_LIST, tags);
mLocalBroadcastManager.sendBroadcast(broadcastIntent);
}
}
/**
* Stores the last used tags
*/
private synchronized void handleLastUsedTags(Intent intent) {
TagCache cache = app.getTagCache();
synchronized(cache) {
Integer currentNestId = Integer.valueOf(intent.getIntExtra(BUNDLE_NEST_ID, -1));
String[] tags = intent.getStringArrayExtra(BUNDLE_TAG_LIST);
cache.putLastUsedTags(currentNestId, tags);
Set<String> lt = cache.getLocalTags(currentNestId);
if(lt == null) {
lt = new HashSet<String>();
cache.putLocalTags(currentNestId, lt);
}
for(String tag : tags) {
lt.add(tag);
}
}
}
/**
* Helper function to convert between List<Tag> and String[]
*/
private static String[] tagListToStringArray(List<Tag> tags) {
String[] out = new String[tags.size()];
int i = 0;
for(Tag tag : tags) {
out[i++] = tag.getName();
}
return out;
}
/**
* Stupid wrapper around the tag cache maps, for safekeeping in FourDNestApplication
*/
public static class TagCache {
public Object getLastUsedTags;
/** Use String[] instead of List<Tag>, to avoid converting back and forth.
* Intents only support standard types. */
private Map<Integer, String[]> lastUsedTags;
private Map<Integer, Set<String>> localTags;
private Map<Integer, String[]> remoteTags;
public TagCache() {
this.lastUsedTags = new HashMap<Integer, String[]>();
this.localTags = new HashMap<Integer, Set<String>>();
this.remoteTags = new HashMap<Integer, String[]>();
}
public void putLastUsedTags(Integer currentNestId, String[] tags) {
this.lastUsedTags.put(currentNestId, tags);
}
public void putRemoteTags(Integer nestId, String[] tags) {
this.remoteTags.put(nestId, tags);
}
public void putLocalTags(Integer currentNestId, Set<String> lt) {
this.localTags.put(currentNestId, lt);
}
public String[] getLastUsedTags(Integer currentNestId) {
return this.lastUsedTags.get(currentNestId);
}
public String[] getRemoteTags(Integer currentNestId) {
return this.remoteTags.get(currentNestId);
}
public Set<String> getLocalTags(Integer currentNestId) {
return this.localTags.get(currentNestId);
}
}
}
| false | true | private synchronized void broadcastTags(Intent intent) {
TagCache cache = app.getTagCache();
synchronized(cache) {
// First broadcast the autocomplete suggestions
Integer currentNestId = Integer.valueOf(intent.getIntExtra(BUNDLE_NEST_ID, -1));
List<String> out = new ArrayList<String>();
Set<String> lt = cache.getLocalTags(currentNestId);
if(lt != null) {
out.addAll(lt);
}
String[] rt = cache.getRemoteTags(currentNestId);
if(rt != null) {
for(String tag : rt) {
out.add(tag);
}
}
Intent broadcastIntent = new Intent(ACTION_AUTOCOMPLETE_TAGS);
broadcastIntent.putExtra(BUNDLE_NEST_ID, currentNestId);
broadcastIntent.putExtra(BUNDLE_TAG_LIST, out.toArray(new String[out.size()]));
mLocalBroadcastManager.sendBroadcast(broadcastIntent);
// Then broadcast the last used tags
broadcastIntent.putExtra(BUNDLE_NEST_ID, currentNestId);
broadcastIntent = new Intent(ACTION_LAST_USED_TAGS);
String[] tags = cache.getLastUsedTags(currentNestId);
if(tags == null) {
tags = new String[0];
}
broadcastIntent.putExtra(BUNDLE_TAG_LIST, tags);
mLocalBroadcastManager.sendBroadcast(broadcastIntent);
}
}
| private synchronized void broadcastTags(Intent intent) {
TagCache cache = app.getTagCache();
synchronized(cache) {
// First broadcast the autocomplete suggestions
Integer currentNestId = Integer.valueOf(intent.getIntExtra(BUNDLE_NEST_ID, -1));
Set<String> out;
Set<String> lt = cache.getLocalTags(currentNestId);
if(lt != null) {
out = new HashSet<String>(lt);
} else {
out = new HashSet<String>();
}
String[] rt = cache.getRemoteTags(currentNestId);
if(rt != null) {
for(String tag : rt) {
out.add(tag);
}
}
Intent broadcastIntent = new Intent(ACTION_AUTOCOMPLETE_TAGS);
broadcastIntent.putExtra(BUNDLE_NEST_ID, currentNestId);
broadcastIntent.putExtra(BUNDLE_TAG_LIST, out.toArray(new String[out.size()]));
mLocalBroadcastManager.sendBroadcast(broadcastIntent);
// Then broadcast the last used tags
broadcastIntent.putExtra(BUNDLE_NEST_ID, currentNestId);
broadcastIntent = new Intent(ACTION_LAST_USED_TAGS);
String[] tags = cache.getLastUsedTags(currentNestId);
if(tags == null) {
tags = new String[0];
}
broadcastIntent.putExtra(BUNDLE_TAG_LIST, tags);
mLocalBroadcastManager.sendBroadcast(broadcastIntent);
}
}
|
diff --git a/src/main/ed/net/httpclient/HttpConnection.java b/src/main/ed/net/httpclient/HttpConnection.java
index b3f7a0810..f946d6df9 100644
--- a/src/main/ed/net/httpclient/HttpConnection.java
+++ b/src/main/ed/net/httpclient/HttpConnection.java
@@ -1,815 +1,816 @@
// HttpConnection.java
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ed.net.httpclient;
import java.net.*;
import java.util.*;
import java.util.regex.*;
import java.util.concurrent.*;
import java.io.*;
import javax.net.*;
import javax.net.ssl.*;
import org.apache.commons.httpclient.ChunkedInputStream;
import ed.log.*;
import ed.net.*;
import ed.util.*;
/**
*/
class HttpConnection{
public static int keepAliveMillis = 1000 * 5; // 5 seconds - this is how long we'll leave a connection idle before killing it
public static int maxKeepAliveMillis = 1000 * 60 * 5; // 5 minutes - this is the max amount of time we'll use a single connection
public static boolean DUMP_HEADERS = false;
public static int CONNECT_TIMEOUT_SECONDS = 60;
static boolean DEBUG = Boolean.getBoolean( "DEBUG.HTTPC" );
static int HTTP_CONNECTION_NUMBER = 1;
static final Logger LOGGER = Logger.getLogger("ed.net.httpclient.HttpConnection" );
static final Logger KA_LOGGER = Logger.getLogger( "ed.net.httpclient.HttpConnection.KeepAlive" );
static {
LOGGER.setLevel( DEBUG ? Level.DEBUG : Level.INFO );
KA_LOGGER.setLevel( DEBUG ? Level.DEBUG : Level.INFO );
}
static public HttpConnection get( URL url )
throws IOException {
HCKey key = new HCKey( url );
HttpConnection conn = _kac.get( key );
if ( conn == null )
conn = new HttpConnection( key , url );
else {
conn.reset( url, true );
LOGGER.debug( "using old connection" );
}
return conn;
}
private HttpConnection( HCKey key , URL url ){
_key = key;
reset( url, true );
}
private void reset( URL url, boolean initial ){
assert( initial || _currentUrl == url );
_currentUrl = url;
_closed = false;
if( initial ) {
_headers.clear();
if ( url.getPort() > 0 && url.getPort() != 80 )
_headers.put("Host" , url.getHost() + ":" + url.getPort() );
else
_headers.put("Host" , url.getHost() );
_headers.put("User-Agent" , HttpClient.USER_AGENT );
_requestMethod = "GET";
}
_responseHeaders.clear();
_rc = -1;
_httpVersion = -1;
_message = null;
_timeout = CONNECT_TIMEOUT_SECONDS * 1000;
}
public void printHeaders() {
for( Map.Entry entry : (Set<Map.Entry>)_headers.entrySet() )
System.out.println( entry.getKey() + ": " + entry.getValue() );
}
public void done()
throws IOException {
_timeOutKeeper.remove( this );
/*
if( !_keepAlive ) {
System.out.println("TEMP DWIGHT: warning httpconnection.done() keepalive=" + _keepAlive);
}
*/
if ( _userIn != null && _keepAlive ) {
byte buf[] = new byte[1024];
while ( _userIn != null && _userIn.read( buf ) >= 0 );
}
_lastAccess = System.currentTimeMillis();
if ( _keepAlive ){
_kac.add( this );
}
else{
close();
}
}
protected void finalize(){
close();
}
protected void close(){
_closed = true;
if ( _sock != null ){
try {
if ( ! _usingSLL ){
if ( _sock != null )
_sock.shutdownInput();
if ( _sock != null )
_sock.shutdownOutput();
}
}
catch ( IOException ioe ){}
}
if ( _userIn != null ){
try {
_userIn.close();
}
catch ( Exception e ){}
}
if ( _in != null && _in != _userIn ){
try {
_in.close();
}
catch ( Exception e ){}
}
if ( _sock != null ){
try {
_sock.close();
}
catch ( Exception e ){}
}
_userIn = null;
_in = null;
_sock = null;
_keepAlive = false;
}
public void setRequestMethod( String rm ){
_requestMethod = rm;
}
public void setRequestProperty( String name , String value ){
_headers.put( name, value);
}
/**
reconstrucs status line
*/
public String getStatus(){
return "HTTP/" + _httpVersion + " " + _rc + " " + ( _message == null ? "" : _message );
}
public void go()
throws IOException {
boolean doIWantKeepAlive = true;
_lastAccess = System.currentTimeMillis();
if ( _sock == null ){
int port = _currentUrl.getPort();
if ( port < 0 ){
if ( _currentUrl.getProtocol().equalsIgnoreCase("https") )
port = 443;
else
port = 80;
}
if ( DEBUG ) LOGGER.debug( "creating new socket to " + _key.getAddress() );
InetSocketAddress isa = new InetSocketAddress( _key.getAddress() , port );
_sock = new Socket();
_sock.connect( isa , _timeout );
_sock.setSoTimeout( _timeout * 5 );
if ( _currentUrl.getProtocol().equalsIgnoreCase("https") ){
try {
_sock = getDefaultSSLSocketFactory().createSocket( _sock , _currentUrl.getHost() , port , true );
_usingSLL = true;
doIWantKeepAlive = false; // don't trust this with SSL yet
}
catch ( Exception e ){
throw new RuntimeException(e);
}
}
if ( _sock == null ){
RuntimeException re = new RuntimeException("_sock can't be null here. close called? " + _closed );
re.fillInStackTrace();
LOGGER.error("weird...",re);
throw re;
}
if ( _sock.getInputStream() == null )
throw new RuntimeException("_sock.getInputStream() is null!!"); // should never happen, should be IOException
_in = new BufferedInputStream( _sock.getInputStream() );
}
StringBuilder buf = new StringBuilder();
// First Line
buf.append( _requestMethod).append(" ");
String f = _currentUrl.getFile();
if ( f == null || f.trim().length() == 0 )
f = "/";
buf.append( f.replace(' ','+') );
buf.append( " HTTP/1.1\r\n");
for ( Iterator i = _headers.keySet().iterator() ; i.hasNext() ; ){
String name = (String)i.next();
String value = String.valueOf( _headers.get(name) );
buf.append( name ).append(": ").append(value).append("\r\n");
if ( name.equalsIgnoreCase("connection") && value.equalsIgnoreCase("close") )
doIWantKeepAlive = false;
}
buf.append("\r\n");
String headerString = buf.toString();
if ( DEBUG ) System.out.println( headerString );
try {
_sock.getOutputStream().write( headerString.getBytes() );
if ( _postData != null )
_sock.getOutputStream().write( _postData );
int timeoutSeconds = 60;
_timeOutKeeper.add( this , timeoutSeconds );
_in.mark(10);
if ( _in.read() < 0 )
throw new IOException("stream closed on be ya bastard");
_in.reset();
if ( DEBUG ) System.out.println("sent header and seems to be ok");
}
catch ( IOException ioe ){
if ( _keepAlive ){
if ( DEBUG ) LOGGER.debug( "trying again");
// if we previously had a keep alive connection, maybe it died, so rety
_keepAlive = false;
_key.reset();
close();
reset( _currentUrl, false );
go();
return;
}
throw ioe;
}
// need to look for end of headers
byte currentLine[] = new byte[2048];
int idx = 0;
boolean gotStatus = false;
boolean chunked = false;
int lineNumber = 0;
boolean previousSlashR = false;
while ( true ){
if ( idx >= currentLine.length ){
byte temp[] = new byte[currentLine.length * 2];
for ( int i=0; i<currentLine.length; i++)
temp[i] = currentLine[i];
currentLine = temp;
}
int t = -1;
try {
t = _in.read();
} catch ( NullPointerException e ) {
throw new IOException( "input stream was closed while parsing headers" );
}
if ( t < 0 )
throw new IOException("input stream got closed while parsing headers" );
currentLine[idx] = (byte)t;
if ( currentLine[idx] == '\r' ){
currentLine[idx] = ' ';
}
else if ( currentLine[idx] == '\n' ){
String line = new String(currentLine,0,idx).trim();
if ( DEBUG ) System.out.println( line );
if ( line.length() == 0 ){
if ( DEBUG ) System.out.println( "rc:" + _rc );
if ( _rc == 100 ){
if ( DEBUG ) System.out.println("got Continue");
gotStatus = false;
lineNumber = 0;
idx = 0;
continue;
}
break;
}
if ( ! gotStatus ){
gotStatus = true;
Matcher m = STATUS_PATTERN.matcher( line );
if ( ! m.find() )
throw new IOException("invalid status line:" + line );
_httpVersion = Double.parseDouble( m.group(1) );
_rc = Integer.parseInt( m.group(2) );
_message = m.group(3);
_responseHeaderFields[0] = line;
}
else {
int colon = line.indexOf(":");
if ( colon < 0 ) {
//throw new IOException("invalid header[" + line + "]");
LOGGER.error("weird error : {" + line + "} does not have a colon, using the whole line as the value and SWBadHeader as the key");
line = "SWBadHeader:" + line;
colon = line.indexOf(":");
}
String name = line.substring(0,colon).trim();
String value = line.substring(colon+1).trim();
_responseHeaders.put( name , value );
if ( name.equalsIgnoreCase("Transfer-Encoding") &&
value.equalsIgnoreCase("chunked") )
chunked = true;
if ( lineNumber >= ( _responseHeaderFields.length - 2 ) ){
// need to enlarge header...
String keys[] = new String[_responseHeaderFieldKeys.length*2];
String values[] = new String[_responseHeaderFields.length*2];
for ( int i=0; i<lineNumber; i++ ){
keys[i] = _responseHeaderFieldKeys[i];
values[i] = _responseHeaderFields[i];
}
_responseHeaderFieldKeys = keys;
_responseHeaderFields = values;
}
_responseHeaderFieldKeys[lineNumber] = name;
_responseHeaderFields[lineNumber] = value;
}
if ( DEBUG ) System.out.println( "\t" + _responseHeaderFieldKeys[lineNumber] + ":" + _responseHeaderFields[lineNumber] );
lineNumber++;
idx = -1;
}
idx++;
}
_responseHeaderFieldKeys[lineNumber] = null;
_responseHeaderFields[lineNumber] = null;
// TODO: obey max? etc...?
_keepAlive = false;
if ( doIWantKeepAlive && (chunked || getContentLength() >= 0 || _rc == 304) ) {
String hf = null;
if ( hf == null )
hf = "Connection";
if ( _httpVersion > 1 ){
_keepAlive =
getHeaderField( hf ) == null ||
getHeaderField( hf ).toLowerCase().indexOf("close") < 0;
}
else {
_keepAlive =
getHeaderField( hf ) != null &&
getHeaderField( hf ).toLowerCase().indexOf("keep-alive") >= 0 ;
}
}
if ( DEBUG ) System.out.println( "_keepAlive=" + _keepAlive );
/* DM: TODO --------------------------------
fix keepalive it's not set if no content length
*/
if( !_requestMethod.equals("HEAD") ) {
- if ( chunked ) {
+ if ( chunked ){
_userIn = new ChunkedInputStream( _in );
- } else if ( _keepAlive ){
+ }
+ else if ( _keepAlive || _usingSLL ){
_userIn = new MaxReadInputStream( _in , getContentLength() );
}
else {
_userIn = _in; // just pass throgh
}
}
_lastAccess = System.currentTimeMillis();
}
public String getHeaderFieldKey( int i ){
return _responseHeaderFieldKeys[i];
}
public String getHeaderField( int i ){
return _responseHeaderFields[i];
}
public String getHeaderField( String name ){
return (String)_responseHeaders.get(name);
}
public int getResponseCode(){
return _rc;
}
public InputStream getInputStream(){
return _userIn;
}
public int getContentLength(){
return StringParseUtil.parseInt( getHeaderField("Content-Length") , -1 );
}
public String getContentEncoding(){
String s = getHeaderField("Content-Type");
if ( s == null )
return null;
String pcs[] = s.toLowerCase().split("charset=");
if ( pcs.length < 2 )
return null;
return pcs[1];
}
boolean isOk(){
long now = System.currentTimeMillis();
return
_keepAlive &&
_sock != null &&
_lastAccess + _keepAliveMillis > now &&
_creation + _maxKeepAliveMillis > now &&
! _sock.isClosed() &&
_sock.isConnected() &&
! _sock.isInputShutdown() &&
! _sock.isOutputShutdown() ;
}
public int hashCode(){
return _id;
}
public boolean equals( Object o ){
return _id == o.hashCode();
}
public void setPostData( byte b[] ){
_postData = b;
if (b != null) {
_headers.put( "Content-Length" , b.length );
_headers.put( "Content-Type" , "application/x-www-form-urlencoded" );
}
}
public byte[] getPostData () {
return _postData;
}
public void setTimeOut( int timeout ){
_timeout = timeout;
}
private static int ID = 1;
private int _id = ID++;
private URL _currentUrl;
private HCKey _key;
private String _requestMethod;
private int _timeout = CONNECT_TIMEOUT_SECONDS * 1000;
private byte _postData[];
private Map _headers = new StringMap();
private Map _responseHeaders = new StringMap();
private String _responseHeaderFieldKeys[] = new String[50];
private String _responseHeaderFields[] = new String[50];
private Socket _sock;
private BufferedInputStream _in;
private boolean _usingSLL = false;
private InputStream _userIn;
private int _rc ;
private double _httpVersion;
private String _message;
private boolean _keepAlive = false;
private long _lastAccess = System.currentTimeMillis();
private final long _creation = System.currentTimeMillis();
private long _keepAliveMillis = keepAliveMillis;
private long _maxKeepAliveMillis = maxKeepAliveMillis;
private boolean _closed = false;
private static Pattern STATUS_PATTERN = Pattern.compile("HTTP/([\\d\\.]+)\\s+(\\d+)\\s*(.*)" , Pattern.CASE_INSENSITIVE );
static class HCKey {
HCKey( URL url )
throws IOException {
_host = url.getHost();
_port = url.getPort();
_string = _host + ":" + _port;
_hash = _string.hashCode();
reset();
}
void reset()
throws IOException {
_address = DNSUtil.getByName( _host );
}
final InetAddress getAddress(){
return _address;
}
public final int hashCode(){
return _hash;
}
public String toString(){
return _string;
}
public boolean equals( Object o ){
HCKey other = (HCKey)o;
return
this._string.equals( other._string );
}
final String _host;
final int _port;
final int _hash;
final String _string;
private InetAddress _address;
}
private static KeepAliveCache _kac = new KeepAliveCache();
static class KeepAliveCache {
KeepAliveCache(){
_cleaner = new KeepAliveCacheCleaner();
_cleaner.start();
_closer = new KeepAliveCacheCloser();
_closer.start();
}
synchronized HttpConnection get( HCKey key ){
List<HttpConnection> l = _hostKeyToList.get( key );
if ( l == null ){
if ( DEBUG ) System.out.println("no kept alive list for:" + key );
return null;
}
while ( l.size() > 0 ){
HttpConnection conn = l.remove(0);
if ( conn.isOk() ){
if ( DEBUG ) System.out.println("found kept alive for:" + key );
return conn;
}
conn.close();
if ( DEBUG ) System.out.println("closing kept alive for:" + key );
// otherwise it'll just get garbage collected
}
/*
note: i'm not removing the empty list on purpose/
because i think it will get created and deleted very often
technically, there is a chance i'm wrong ;)
*/
return null;
}
synchronized void add( HttpConnection conn ){
if ( DEBUG ) System.out.println( "adding connection for:" + conn._key );
List<HttpConnection> l = _hostKeyToList.get( conn._key );
if ( l == null ){
l = new ArrayList<HttpConnection>();
_hostKeyToList.put( conn._key , l );
}
l.add( conn );
}
private synchronized void clean(){
for ( Iterator<HCKey> i = _hostKeyToList.keySet().iterator() ; i.hasNext() ; ){
HCKey key = i.next();
List<HttpConnection> l = _hostKeyToList.get( key );
for ( Iterator<HttpConnection> j = l.iterator(); j.hasNext() ; ){
HttpConnection hc = j.next();
if ( ! hc.isOk() ){
//hc.close();
_closer._toClose.offer( hc );
j.remove();
KA_LOGGER.debug( "removing a " + key );
}
else {
KA_LOGGER.debug( "keeping a " + key );
}
}
}
}
private Map<HCKey,List<HttpConnection>> _hostKeyToList = new HashMap<HCKey,List<HttpConnection>>();
private Thread _cleaner;
private KeepAliveCacheCloser _closer;
class KeepAliveCacheCloser extends Thread {
KeepAliveCacheCloser(){
super("KeepAliveCacheCloser");
setDaemon( true );
}
public void run(){
while ( true ){
try {
HttpConnection hc = _toClose.take();
if ( hc != null ){
try {
hc.close();
}
catch ( Exception e ){
KA_LOGGER.debug( "error closing" , e );
}
}
}
catch ( Exception e ){
KA_LOGGER.error("error running" , e );
}
}
}
BlockingQueue<HttpConnection> _toClose = new ArrayBlockingQueue<HttpConnection>(10000);
}
class KeepAliveCacheCleaner extends Thread {
KeepAliveCacheCleaner(){
super("KeepAliveCacheCleaner");
setDaemon( true );
}
public void run(){
while ( true ){
try {
Thread.sleep( 1000 * 30 );
clean();
}
catch ( Exception e ){
KA_LOGGER.error("error cleaning" , e );
}
}
}
}
}
static TimeOutKeeper _timeOutKeeper = new TimeOutKeeper();
static class TimeOutKeeper extends Thread {
TimeOutKeeper(){
super("TimeOutKeeper");
setDaemon(true);
start();
}
void add( HttpConnection conn , long seconds ){
synchronized ( _lock ){
_connectionToKillTime.put( conn , new Long( System.currentTimeMillis() + ( seconds * 1000 ) ) );
}
}
void remove( HttpConnection conn ){
synchronized ( _lock ){
_connectionToKillTime.remove( conn );
}
}
public void run(){
while ( true ){
try {
Thread.sleep( 1000 * 5 );
}
catch ( InterruptedException ie ){
}
List toRemove = new ArrayList();
synchronized ( _lock ){
for ( Iterator i = _connectionToKillTime.keySet().iterator() ; i.hasNext() ; ){
HttpConnection conn = (HttpConnection)i.next();
Long time = (Long)_connectionToKillTime.get( conn );
if ( time.longValue() < System.currentTimeMillis() ){
LOGGER.debug( "timing out a connection" );
i.remove();
toRemove.add( conn );
}
}
}
for ( Iterator i = toRemove.iterator() ; i.hasNext() ; ){
HttpConnection conn = (HttpConnection)i.next();
conn.close();
}
}
}
private String _lock = "HttpConnection-LOCK";
private Map _connectionToKillTime = new HashMap();
}
static class MaxReadInputStream extends InputStream {
MaxReadInputStream( InputStream in , int max ){
_in = in;
_toGo = max;
}
public int available()
throws IOException {
return _in.available();
}
public int read()
throws IOException {
/** [dm] this was returning zero, which is bad as you then get a file downloaded
on a timeout that ends with a bunch of zeroes and no error reported! it might
be better to throw an ioexception rather than return -1. -1 worked for my
purposes. feel free to change that if you like that better.
*/
if ( _in == null || _closed )
return -1;
if ( _toGo <= 0 )
return -1;
int val = _in.read();
_toGo--;
return val;
}
public void close(){
_closed = true;
}
private InputStream _in;
private int _toGo;
private boolean _closed = false;
}
public static SSLSocketFactory getDefaultSSLSocketFactory(){
SocketFactory f = SSLSocketFactory.getDefault();
return (SSLSocketFactory)f;
}
}
| false | true | public void go()
throws IOException {
boolean doIWantKeepAlive = true;
_lastAccess = System.currentTimeMillis();
if ( _sock == null ){
int port = _currentUrl.getPort();
if ( port < 0 ){
if ( _currentUrl.getProtocol().equalsIgnoreCase("https") )
port = 443;
else
port = 80;
}
if ( DEBUG ) LOGGER.debug( "creating new socket to " + _key.getAddress() );
InetSocketAddress isa = new InetSocketAddress( _key.getAddress() , port );
_sock = new Socket();
_sock.connect( isa , _timeout );
_sock.setSoTimeout( _timeout * 5 );
if ( _currentUrl.getProtocol().equalsIgnoreCase("https") ){
try {
_sock = getDefaultSSLSocketFactory().createSocket( _sock , _currentUrl.getHost() , port , true );
_usingSLL = true;
doIWantKeepAlive = false; // don't trust this with SSL yet
}
catch ( Exception e ){
throw new RuntimeException(e);
}
}
if ( _sock == null ){
RuntimeException re = new RuntimeException("_sock can't be null here. close called? " + _closed );
re.fillInStackTrace();
LOGGER.error("weird...",re);
throw re;
}
if ( _sock.getInputStream() == null )
throw new RuntimeException("_sock.getInputStream() is null!!"); // should never happen, should be IOException
_in = new BufferedInputStream( _sock.getInputStream() );
}
StringBuilder buf = new StringBuilder();
// First Line
buf.append( _requestMethod).append(" ");
String f = _currentUrl.getFile();
if ( f == null || f.trim().length() == 0 )
f = "/";
buf.append( f.replace(' ','+') );
buf.append( " HTTP/1.1\r\n");
for ( Iterator i = _headers.keySet().iterator() ; i.hasNext() ; ){
String name = (String)i.next();
String value = String.valueOf( _headers.get(name) );
buf.append( name ).append(": ").append(value).append("\r\n");
if ( name.equalsIgnoreCase("connection") && value.equalsIgnoreCase("close") )
doIWantKeepAlive = false;
}
buf.append("\r\n");
String headerString = buf.toString();
if ( DEBUG ) System.out.println( headerString );
try {
_sock.getOutputStream().write( headerString.getBytes() );
if ( _postData != null )
_sock.getOutputStream().write( _postData );
int timeoutSeconds = 60;
_timeOutKeeper.add( this , timeoutSeconds );
_in.mark(10);
if ( _in.read() < 0 )
throw new IOException("stream closed on be ya bastard");
_in.reset();
if ( DEBUG ) System.out.println("sent header and seems to be ok");
}
catch ( IOException ioe ){
if ( _keepAlive ){
if ( DEBUG ) LOGGER.debug( "trying again");
// if we previously had a keep alive connection, maybe it died, so rety
_keepAlive = false;
_key.reset();
close();
reset( _currentUrl, false );
go();
return;
}
throw ioe;
}
// need to look for end of headers
byte currentLine[] = new byte[2048];
int idx = 0;
boolean gotStatus = false;
boolean chunked = false;
int lineNumber = 0;
boolean previousSlashR = false;
while ( true ){
if ( idx >= currentLine.length ){
byte temp[] = new byte[currentLine.length * 2];
for ( int i=0; i<currentLine.length; i++)
temp[i] = currentLine[i];
currentLine = temp;
}
int t = -1;
try {
t = _in.read();
} catch ( NullPointerException e ) {
throw new IOException( "input stream was closed while parsing headers" );
}
if ( t < 0 )
throw new IOException("input stream got closed while parsing headers" );
currentLine[idx] = (byte)t;
if ( currentLine[idx] == '\r' ){
currentLine[idx] = ' ';
}
else if ( currentLine[idx] == '\n' ){
String line = new String(currentLine,0,idx).trim();
if ( DEBUG ) System.out.println( line );
if ( line.length() == 0 ){
if ( DEBUG ) System.out.println( "rc:" + _rc );
if ( _rc == 100 ){
if ( DEBUG ) System.out.println("got Continue");
gotStatus = false;
lineNumber = 0;
idx = 0;
continue;
}
break;
}
if ( ! gotStatus ){
gotStatus = true;
Matcher m = STATUS_PATTERN.matcher( line );
if ( ! m.find() )
throw new IOException("invalid status line:" + line );
_httpVersion = Double.parseDouble( m.group(1) );
_rc = Integer.parseInt( m.group(2) );
_message = m.group(3);
_responseHeaderFields[0] = line;
}
else {
int colon = line.indexOf(":");
if ( colon < 0 ) {
//throw new IOException("invalid header[" + line + "]");
LOGGER.error("weird error : {" + line + "} does not have a colon, using the whole line as the value and SWBadHeader as the key");
line = "SWBadHeader:" + line;
colon = line.indexOf(":");
}
String name = line.substring(0,colon).trim();
String value = line.substring(colon+1).trim();
_responseHeaders.put( name , value );
if ( name.equalsIgnoreCase("Transfer-Encoding") &&
value.equalsIgnoreCase("chunked") )
chunked = true;
if ( lineNumber >= ( _responseHeaderFields.length - 2 ) ){
// need to enlarge header...
String keys[] = new String[_responseHeaderFieldKeys.length*2];
String values[] = new String[_responseHeaderFields.length*2];
for ( int i=0; i<lineNumber; i++ ){
keys[i] = _responseHeaderFieldKeys[i];
values[i] = _responseHeaderFields[i];
}
_responseHeaderFieldKeys = keys;
_responseHeaderFields = values;
}
_responseHeaderFieldKeys[lineNumber] = name;
_responseHeaderFields[lineNumber] = value;
}
if ( DEBUG ) System.out.println( "\t" + _responseHeaderFieldKeys[lineNumber] + ":" + _responseHeaderFields[lineNumber] );
lineNumber++;
idx = -1;
}
idx++;
}
_responseHeaderFieldKeys[lineNumber] = null;
_responseHeaderFields[lineNumber] = null;
// TODO: obey max? etc...?
_keepAlive = false;
if ( doIWantKeepAlive && (chunked || getContentLength() >= 0 || _rc == 304) ) {
String hf = null;
if ( hf == null )
hf = "Connection";
if ( _httpVersion > 1 ){
_keepAlive =
getHeaderField( hf ) == null ||
getHeaderField( hf ).toLowerCase().indexOf("close") < 0;
}
else {
_keepAlive =
getHeaderField( hf ) != null &&
getHeaderField( hf ).toLowerCase().indexOf("keep-alive") >= 0 ;
}
}
if ( DEBUG ) System.out.println( "_keepAlive=" + _keepAlive );
/* DM: TODO --------------------------------
fix keepalive it's not set if no content length
*/
if( !_requestMethod.equals("HEAD") ) {
if ( chunked ) {
_userIn = new ChunkedInputStream( _in );
} else if ( _keepAlive ){
_userIn = new MaxReadInputStream( _in , getContentLength() );
}
else {
_userIn = _in; // just pass throgh
}
}
_lastAccess = System.currentTimeMillis();
}
| public void go()
throws IOException {
boolean doIWantKeepAlive = true;
_lastAccess = System.currentTimeMillis();
if ( _sock == null ){
int port = _currentUrl.getPort();
if ( port < 0 ){
if ( _currentUrl.getProtocol().equalsIgnoreCase("https") )
port = 443;
else
port = 80;
}
if ( DEBUG ) LOGGER.debug( "creating new socket to " + _key.getAddress() );
InetSocketAddress isa = new InetSocketAddress( _key.getAddress() , port );
_sock = new Socket();
_sock.connect( isa , _timeout );
_sock.setSoTimeout( _timeout * 5 );
if ( _currentUrl.getProtocol().equalsIgnoreCase("https") ){
try {
_sock = getDefaultSSLSocketFactory().createSocket( _sock , _currentUrl.getHost() , port , true );
_usingSLL = true;
doIWantKeepAlive = false; // don't trust this with SSL yet
}
catch ( Exception e ){
throw new RuntimeException(e);
}
}
if ( _sock == null ){
RuntimeException re = new RuntimeException("_sock can't be null here. close called? " + _closed );
re.fillInStackTrace();
LOGGER.error("weird...",re);
throw re;
}
if ( _sock.getInputStream() == null )
throw new RuntimeException("_sock.getInputStream() is null!!"); // should never happen, should be IOException
_in = new BufferedInputStream( _sock.getInputStream() );
}
StringBuilder buf = new StringBuilder();
// First Line
buf.append( _requestMethod).append(" ");
String f = _currentUrl.getFile();
if ( f == null || f.trim().length() == 0 )
f = "/";
buf.append( f.replace(' ','+') );
buf.append( " HTTP/1.1\r\n");
for ( Iterator i = _headers.keySet().iterator() ; i.hasNext() ; ){
String name = (String)i.next();
String value = String.valueOf( _headers.get(name) );
buf.append( name ).append(": ").append(value).append("\r\n");
if ( name.equalsIgnoreCase("connection") && value.equalsIgnoreCase("close") )
doIWantKeepAlive = false;
}
buf.append("\r\n");
String headerString = buf.toString();
if ( DEBUG ) System.out.println( headerString );
try {
_sock.getOutputStream().write( headerString.getBytes() );
if ( _postData != null )
_sock.getOutputStream().write( _postData );
int timeoutSeconds = 60;
_timeOutKeeper.add( this , timeoutSeconds );
_in.mark(10);
if ( _in.read() < 0 )
throw new IOException("stream closed on be ya bastard");
_in.reset();
if ( DEBUG ) System.out.println("sent header and seems to be ok");
}
catch ( IOException ioe ){
if ( _keepAlive ){
if ( DEBUG ) LOGGER.debug( "trying again");
// if we previously had a keep alive connection, maybe it died, so rety
_keepAlive = false;
_key.reset();
close();
reset( _currentUrl, false );
go();
return;
}
throw ioe;
}
// need to look for end of headers
byte currentLine[] = new byte[2048];
int idx = 0;
boolean gotStatus = false;
boolean chunked = false;
int lineNumber = 0;
boolean previousSlashR = false;
while ( true ){
if ( idx >= currentLine.length ){
byte temp[] = new byte[currentLine.length * 2];
for ( int i=0; i<currentLine.length; i++)
temp[i] = currentLine[i];
currentLine = temp;
}
int t = -1;
try {
t = _in.read();
} catch ( NullPointerException e ) {
throw new IOException( "input stream was closed while parsing headers" );
}
if ( t < 0 )
throw new IOException("input stream got closed while parsing headers" );
currentLine[idx] = (byte)t;
if ( currentLine[idx] == '\r' ){
currentLine[idx] = ' ';
}
else if ( currentLine[idx] == '\n' ){
String line = new String(currentLine,0,idx).trim();
if ( DEBUG ) System.out.println( line );
if ( line.length() == 0 ){
if ( DEBUG ) System.out.println( "rc:" + _rc );
if ( _rc == 100 ){
if ( DEBUG ) System.out.println("got Continue");
gotStatus = false;
lineNumber = 0;
idx = 0;
continue;
}
break;
}
if ( ! gotStatus ){
gotStatus = true;
Matcher m = STATUS_PATTERN.matcher( line );
if ( ! m.find() )
throw new IOException("invalid status line:" + line );
_httpVersion = Double.parseDouble( m.group(1) );
_rc = Integer.parseInt( m.group(2) );
_message = m.group(3);
_responseHeaderFields[0] = line;
}
else {
int colon = line.indexOf(":");
if ( colon < 0 ) {
//throw new IOException("invalid header[" + line + "]");
LOGGER.error("weird error : {" + line + "} does not have a colon, using the whole line as the value and SWBadHeader as the key");
line = "SWBadHeader:" + line;
colon = line.indexOf(":");
}
String name = line.substring(0,colon).trim();
String value = line.substring(colon+1).trim();
_responseHeaders.put( name , value );
if ( name.equalsIgnoreCase("Transfer-Encoding") &&
value.equalsIgnoreCase("chunked") )
chunked = true;
if ( lineNumber >= ( _responseHeaderFields.length - 2 ) ){
// need to enlarge header...
String keys[] = new String[_responseHeaderFieldKeys.length*2];
String values[] = new String[_responseHeaderFields.length*2];
for ( int i=0; i<lineNumber; i++ ){
keys[i] = _responseHeaderFieldKeys[i];
values[i] = _responseHeaderFields[i];
}
_responseHeaderFieldKeys = keys;
_responseHeaderFields = values;
}
_responseHeaderFieldKeys[lineNumber] = name;
_responseHeaderFields[lineNumber] = value;
}
if ( DEBUG ) System.out.println( "\t" + _responseHeaderFieldKeys[lineNumber] + ":" + _responseHeaderFields[lineNumber] );
lineNumber++;
idx = -1;
}
idx++;
}
_responseHeaderFieldKeys[lineNumber] = null;
_responseHeaderFields[lineNumber] = null;
// TODO: obey max? etc...?
_keepAlive = false;
if ( doIWantKeepAlive && (chunked || getContentLength() >= 0 || _rc == 304) ) {
String hf = null;
if ( hf == null )
hf = "Connection";
if ( _httpVersion > 1 ){
_keepAlive =
getHeaderField( hf ) == null ||
getHeaderField( hf ).toLowerCase().indexOf("close") < 0;
}
else {
_keepAlive =
getHeaderField( hf ) != null &&
getHeaderField( hf ).toLowerCase().indexOf("keep-alive") >= 0 ;
}
}
if ( DEBUG ) System.out.println( "_keepAlive=" + _keepAlive );
/* DM: TODO --------------------------------
fix keepalive it's not set if no content length
*/
if( !_requestMethod.equals("HEAD") ) {
if ( chunked ){
_userIn = new ChunkedInputStream( _in );
}
else if ( _keepAlive || _usingSLL ){
_userIn = new MaxReadInputStream( _in , getContentLength() );
}
else {
_userIn = _in; // just pass throgh
}
}
_lastAccess = System.currentTimeMillis();
}
|
diff --git a/src/main/java/edu/stanford/mobisocial/bumblebee/RabbitMQMessengerService.java b/src/main/java/edu/stanford/mobisocial/bumblebee/RabbitMQMessengerService.java
index e63489e..ede7fd8 100644
--- a/src/main/java/edu/stanford/mobisocial/bumblebee/RabbitMQMessengerService.java
+++ b/src/main/java/edu/stanford/mobisocial/bumblebee/RabbitMQMessengerService.java
@@ -1,261 +1,261 @@
package edu.stanford.mobisocial.bumblebee;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.jivesoftware.smack.packet.Message;
import org.xbill.DNS.CNAMERecord;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ReturnListener;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.ShutdownSignalException;
import edu.stanford.mobisocial.bumblebee.util.Base64;
public class RabbitMQMessengerService extends MessengerService {
ConnectionFactory factory;
Connection conn;
Channel inChannel;
Channel outChannel;
String exchangeKey;
String queueName;
Thread outThread;
Thread inThread;
Thread connectThread;
private LinkedBlockingQueue<OutgoingMessage> mSendQ =
new LinkedBlockingQueue<OutgoingMessage>();
private MessageFormat mFormat = null;
static String encodeRSAPublicKey(RSAPublicKey key) {
try {
byte[] mod = key.getModulus().toByteArray();
byte[] exp = key.getPublicExponent().toByteArray();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream data = new DataOutputStream(bytes);
data.write(255);
data.write(mod.length);
data.write(mod);
data.write(exp.length);
data.write(exp);
data.flush();
byte[] raw = bytes.toByteArray();
return Base64.encodeToString(raw, false);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
synchronized void teardown() {
inChannel = null;
outChannel = null;
conn = null;
}
public RabbitMQMessengerService(TransportIdentityProvider ident,
ConnectionStatus status) {
super(ident, status);
mFormat = new MessageFormat(ident);
exchangeKey = new String(encodeRSAPublicKey(ident.userPublicKey()));
queueName = exchangeKey;
factory = new ConnectionFactory();
factory.setHost("pepperjack.stanford.edu");
//may want this higher for battery
factory.setRequestedHeartbeat(30);
connectThread = new Thread(new Runnable() {
public void run() {
//open the connection
while(true) {
try {
conn = factory.newConnection();
} catch(IOException e) {
signalConnectionStatus("Failed initial AMQP connection", e);
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
continue;
}
signalConnectionStatus("AMQP connected", null);
//once its opened the rabbitmq library handles reconnect
outThread = new Thread() {
@Override
public void run() {
for(;;) {
try {
outChannel = conn.createChannel();
outChannel.setReturnListener(new ReturnListener() {
public void handleReturn(int reply_code, String arg1, String arg2, String arg3,
BasicProperties arg4, byte[] body) throws IOException {
if(reply_code != 200)
signalConnectionStatus("Message delivery failure: " + Base64.encodeToString(body, false), null);
}
});
while (true) {
OutgoingMessage m = null;
try {
try {
m = mSendQ.poll(15, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
if(!conn.isOpen())
return;
if(m == null)
continue;
String plain = m.contents();
byte[] cyphered = mFormat.encodeOutgoingMessage(
plain, m.toPublicKeys());
for(RSAPublicKey pubKey : m.toPublicKeys()){
String dest = encodeRSAPublicKey(pubKey);
outChannel.basicPublish("", dest, true, false, null, cyphered);
}
} catch(CryptoException e) {
signalConnectionStatus("Failed to handle message crypto", e);
try {
conn.close();
} catch(IOException e1) {}
} catch (IOException e) {
signalConnectionStatus("Failed to send message over AMQP connection", e);
mSendQ.add(m);
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
} catch(ShutdownSignalException e) {
signalConnectionStatus("Forced shutdown in send AMQP", e);
return;
}
}
} catch(IOException e) {
}
}
}
};
outThread.start();
inThread = new Thread(new Runnable() {
public void run() {
boolean autoAck = false;
- QueueingConsumer consumer = new QueueingConsumer(inChannel);
for(;;) {
try {
inChannel = conn.createChannel();
+ QueueingConsumer consumer = new QueueingConsumer(inChannel);
inChannel.queueDeclare(queueName, true, false, false, null);
inChannel.basicConsume(queueName, autoAck, consumer);
for(;;) {
QueueingConsumer.Delivery delivery;
try {
delivery = consumer.nextDelivery(15000);
} catch (InterruptedException ie) {
continue;
}
if(!conn.isOpen())
return;
if(delivery == null)
continue;
final byte[] body = delivery.getBody();
if(body == null) throw new RuntimeException("Could not decode message.");
final String id = mFormat.getMessagePersonId(body);
if (id == null) {
System.err.println("WTF! person id in message does not match sender!.");
return;
}
RSAPublicKey pubKey = identity().publicKeyForPersonId(id);
if (pubKey == null) {
System.err.println("WTF! message from unrecognized sender! " + id);
return;
}
final String contents = mFormat.decodeIncomingMessage(body, pubKey);
signalMessageReceived(
new IncomingMessage() {
public String from() { return id; }
public String contents() { return contents; }
public String toString() { return contents(); }
});
inChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
} catch(CryptoException e) {
signalConnectionStatus("Failed to handle message crypto", e);
try {
conn.close();
} catch(IOException e1) {}
return;
} catch(IOException e) {
signalConnectionStatus("Failed to receive message over AMQP connection", e);
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
} catch(ShutdownSignalException e) {
signalConnectionStatus("Forced shutdown in receive AMQP", e);
return;
}
}
}
});
inThread.start();
for(;;) {
try {
inThread.join();
break;
} catch(InterruptedException e) {
continue;
}
}
for(;;) {
try {
outThread.join();
break;
} catch(InterruptedException e) {
continue;
}
}
inThread = null;
outThread = null;
conn = null;
inChannel = null;
outChannel = null;
}
}
});
connectThread.start();
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public void sendMessage(OutgoingMessage m) {
try {
mSendQ.put(m);
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
}
| false | true | public RabbitMQMessengerService(TransportIdentityProvider ident,
ConnectionStatus status) {
super(ident, status);
mFormat = new MessageFormat(ident);
exchangeKey = new String(encodeRSAPublicKey(ident.userPublicKey()));
queueName = exchangeKey;
factory = new ConnectionFactory();
factory.setHost("pepperjack.stanford.edu");
//may want this higher for battery
factory.setRequestedHeartbeat(30);
connectThread = new Thread(new Runnable() {
public void run() {
//open the connection
while(true) {
try {
conn = factory.newConnection();
} catch(IOException e) {
signalConnectionStatus("Failed initial AMQP connection", e);
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
continue;
}
signalConnectionStatus("AMQP connected", null);
//once its opened the rabbitmq library handles reconnect
outThread = new Thread() {
@Override
public void run() {
for(;;) {
try {
outChannel = conn.createChannel();
outChannel.setReturnListener(new ReturnListener() {
public void handleReturn(int reply_code, String arg1, String arg2, String arg3,
BasicProperties arg4, byte[] body) throws IOException {
if(reply_code != 200)
signalConnectionStatus("Message delivery failure: " + Base64.encodeToString(body, false), null);
}
});
while (true) {
OutgoingMessage m = null;
try {
try {
m = mSendQ.poll(15, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
if(!conn.isOpen())
return;
if(m == null)
continue;
String plain = m.contents();
byte[] cyphered = mFormat.encodeOutgoingMessage(
plain, m.toPublicKeys());
for(RSAPublicKey pubKey : m.toPublicKeys()){
String dest = encodeRSAPublicKey(pubKey);
outChannel.basicPublish("", dest, true, false, null, cyphered);
}
} catch(CryptoException e) {
signalConnectionStatus("Failed to handle message crypto", e);
try {
conn.close();
} catch(IOException e1) {}
} catch (IOException e) {
signalConnectionStatus("Failed to send message over AMQP connection", e);
mSendQ.add(m);
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
} catch(ShutdownSignalException e) {
signalConnectionStatus("Forced shutdown in send AMQP", e);
return;
}
}
} catch(IOException e) {
}
}
}
};
outThread.start();
inThread = new Thread(new Runnable() {
public void run() {
boolean autoAck = false;
QueueingConsumer consumer = new QueueingConsumer(inChannel);
for(;;) {
try {
inChannel = conn.createChannel();
inChannel.queueDeclare(queueName, true, false, false, null);
inChannel.basicConsume(queueName, autoAck, consumer);
for(;;) {
QueueingConsumer.Delivery delivery;
try {
delivery = consumer.nextDelivery(15000);
} catch (InterruptedException ie) {
continue;
}
if(!conn.isOpen())
return;
if(delivery == null)
continue;
final byte[] body = delivery.getBody();
if(body == null) throw new RuntimeException("Could not decode message.");
final String id = mFormat.getMessagePersonId(body);
if (id == null) {
System.err.println("WTF! person id in message does not match sender!.");
return;
}
RSAPublicKey pubKey = identity().publicKeyForPersonId(id);
if (pubKey == null) {
System.err.println("WTF! message from unrecognized sender! " + id);
return;
}
final String contents = mFormat.decodeIncomingMessage(body, pubKey);
signalMessageReceived(
new IncomingMessage() {
public String from() { return id; }
public String contents() { return contents; }
public String toString() { return contents(); }
});
inChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
} catch(CryptoException e) {
signalConnectionStatus("Failed to handle message crypto", e);
try {
conn.close();
} catch(IOException e1) {}
return;
} catch(IOException e) {
signalConnectionStatus("Failed to receive message over AMQP connection", e);
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
} catch(ShutdownSignalException e) {
signalConnectionStatus("Forced shutdown in receive AMQP", e);
return;
}
}
}
});
inThread.start();
for(;;) {
try {
inThread.join();
break;
} catch(InterruptedException e) {
continue;
}
}
for(;;) {
try {
outThread.join();
break;
} catch(InterruptedException e) {
continue;
}
}
inThread = null;
outThread = null;
conn = null;
inChannel = null;
outChannel = null;
}
}
});
connectThread.start();
}
| public RabbitMQMessengerService(TransportIdentityProvider ident,
ConnectionStatus status) {
super(ident, status);
mFormat = new MessageFormat(ident);
exchangeKey = new String(encodeRSAPublicKey(ident.userPublicKey()));
queueName = exchangeKey;
factory = new ConnectionFactory();
factory.setHost("pepperjack.stanford.edu");
//may want this higher for battery
factory.setRequestedHeartbeat(30);
connectThread = new Thread(new Runnable() {
public void run() {
//open the connection
while(true) {
try {
conn = factory.newConnection();
} catch(IOException e) {
signalConnectionStatus("Failed initial AMQP connection", e);
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
continue;
}
signalConnectionStatus("AMQP connected", null);
//once its opened the rabbitmq library handles reconnect
outThread = new Thread() {
@Override
public void run() {
for(;;) {
try {
outChannel = conn.createChannel();
outChannel.setReturnListener(new ReturnListener() {
public void handleReturn(int reply_code, String arg1, String arg2, String arg3,
BasicProperties arg4, byte[] body) throws IOException {
if(reply_code != 200)
signalConnectionStatus("Message delivery failure: " + Base64.encodeToString(body, false), null);
}
});
while (true) {
OutgoingMessage m = null;
try {
try {
m = mSendQ.poll(15, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
if(!conn.isOpen())
return;
if(m == null)
continue;
String plain = m.contents();
byte[] cyphered = mFormat.encodeOutgoingMessage(
plain, m.toPublicKeys());
for(RSAPublicKey pubKey : m.toPublicKeys()){
String dest = encodeRSAPublicKey(pubKey);
outChannel.basicPublish("", dest, true, false, null, cyphered);
}
} catch(CryptoException e) {
signalConnectionStatus("Failed to handle message crypto", e);
try {
conn.close();
} catch(IOException e1) {}
} catch (IOException e) {
signalConnectionStatus("Failed to send message over AMQP connection", e);
mSendQ.add(m);
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
} catch(ShutdownSignalException e) {
signalConnectionStatus("Forced shutdown in send AMQP", e);
return;
}
}
} catch(IOException e) {
}
}
}
};
outThread.start();
inThread = new Thread(new Runnable() {
public void run() {
boolean autoAck = false;
for(;;) {
try {
inChannel = conn.createChannel();
QueueingConsumer consumer = new QueueingConsumer(inChannel);
inChannel.queueDeclare(queueName, true, false, false, null);
inChannel.basicConsume(queueName, autoAck, consumer);
for(;;) {
QueueingConsumer.Delivery delivery;
try {
delivery = consumer.nextDelivery(15000);
} catch (InterruptedException ie) {
continue;
}
if(!conn.isOpen())
return;
if(delivery == null)
continue;
final byte[] body = delivery.getBody();
if(body == null) throw new RuntimeException("Could not decode message.");
final String id = mFormat.getMessagePersonId(body);
if (id == null) {
System.err.println("WTF! person id in message does not match sender!.");
return;
}
RSAPublicKey pubKey = identity().publicKeyForPersonId(id);
if (pubKey == null) {
System.err.println("WTF! message from unrecognized sender! " + id);
return;
}
final String contents = mFormat.decodeIncomingMessage(body, pubKey);
signalMessageReceived(
new IncomingMessage() {
public String from() { return id; }
public String contents() { return contents; }
public String toString() { return contents(); }
});
inChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
} catch(CryptoException e) {
signalConnectionStatus("Failed to handle message crypto", e);
try {
conn.close();
} catch(IOException e1) {}
return;
} catch(IOException e) {
signalConnectionStatus("Failed to receive message over AMQP connection", e);
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
} catch(ShutdownSignalException e) {
signalConnectionStatus("Forced shutdown in receive AMQP", e);
return;
}
}
}
});
inThread.start();
for(;;) {
try {
inThread.join();
break;
} catch(InterruptedException e) {
continue;
}
}
for(;;) {
try {
outThread.join();
break;
} catch(InterruptedException e) {
continue;
}
}
inThread = null;
outThread = null;
conn = null;
inChannel = null;
outChannel = null;
}
}
});
connectThread.start();
}
|
diff --git a/src/it/example/storygame/Read.java b/src/it/example/storygame/Read.java
index 6763f52..da076fc 100644
--- a/src/it/example/storygame/Read.java
+++ b/src/it/example/storygame/Read.java
@@ -1,53 +1,54 @@
package it.example.storygame;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Read extends Activity {
Button Indietro;
Button story1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read);
story1=(Button)findViewById(R.id.story1);
story1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent storyintent = new Intent(Read.this, story1.class);
startActivity(storyintent);
}
});
Indietro= (Button)findViewById(R.id.Indietroread);
Indietro.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
- finish();
+ Intent indietro = new Intent(Read.this, MainActivity.class);
+ startActivity(indietro);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read);
story1=(Button)findViewById(R.id.story1);
story1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent storyintent = new Intent(Read.this, story1.class);
startActivity(storyintent);
}
});
Indietro= (Button)findViewById(R.id.Indietroread);
Indietro.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read);
story1=(Button)findViewById(R.id.story1);
story1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent storyintent = new Intent(Read.this, story1.class);
startActivity(storyintent);
}
});
Indietro= (Button)findViewById(R.id.Indietroread);
Indietro.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent indietro = new Intent(Read.this, MainActivity.class);
startActivity(indietro);
}
});
}
|
diff --git a/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelGenotyperV2Walker.java b/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelGenotyperV2Walker.java
index 954157005..7a3b05f1b 100644
--- a/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelGenotyperV2Walker.java
+++ b/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelGenotyperV2Walker.java
@@ -1,1693 +1,1692 @@
/*
* Copyright (c) 2010 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.sting.gatk.walkers.indels;
import net.sf.samtools.*;
import org.broad.tribble.FeatureSource;
import org.broad.tribble.util.variantcontext.Allele;
import org.broad.tribble.util.variantcontext.VariantContext;
import org.broad.tribble.util.variantcontext.Genotype;
import org.broad.tribble.vcf.*;
import org.broadinstitute.sting.gatk.filters.*;
import org.broadinstitute.sting.gatk.refdata.*;
import org.broadinstitute.sting.gatk.refdata.features.refseq.RefSeqCodec;
import org.broadinstitute.sting.gatk.refdata.features.refseq.RefSeqFeature;
import org.broadinstitute.sting.gatk.refdata.tracks.builders.TribbleRMDTrackBuilder;
import org.broadinstitute.sting.gatk.refdata.utils.FeatureToGATKFeatureIterator;
import org.broadinstitute.sting.gatk.refdata.utils.LocationAwareSeekableRODIterator;
import org.broadinstitute.sting.gatk.refdata.utils.RODRecordList;
import org.broadinstitute.sting.gatk.walkers.ReadFilters;
import org.broadinstitute.sting.gatk.walkers.ReadWalker;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.datasources.simpleDataSources.ReferenceDataSource;
import org.broadinstitute.sting.gatk.datasources.simpleDataSources.SAMReaderID;
import org.broadinstitute.sting.utils.*;
import org.broadinstitute.sting.utils.exceptions.UserException;
import org.broadinstitute.sting.utils.exceptions.StingException;
import org.broadinstitute.sting.utils.sam.AlignmentUtils;
import org.broadinstitute.sting.utils.collections.CircularArray;
import org.broadinstitute.sting.utils.collections.PrimitivePair;
import org.broadinstitute.sting.commandline.Argument;
import org.broadinstitute.sting.commandline.Output;
import org.broadinstitute.sting.commandline.CommandLineUtils;
import java.io.*;
import java.util.*;
/**
* This is a simple, counts-and-cutoffs based tool for calling indels from aligned (preferrably MSA cleaned) sequencing
* data. Two output formats supported are: BED format (minimal output, required), and extended output that includes read
* and mismtach statistics around the calls (tuned on with --verbose). The calls can be performed from a single/pooled sample,
* or from a matched pair of samples (with --somatic option). In the latter case, two input bam files must be specified,
* the order is important: indels are called from the second sample ("Tumor") and additionally annotated as germline
* if even a weak evidence for the same indel, not necessarily a confident call, exists in the first sample ("Normal"), or as somatic
* if first bam has coverage at the site but no indication for an indel. In the --somatic mode, BED output contains
* only somatic calls, while --verbose output contains all calls annotated with GERMLINE/SOMATIC keywords.
*/
@ReadFilters({Platform454Filter.class, ZeroMappingQualityReadFilter.class, PlatformUnitFilter.class})
public class IndelGenotyperV2Walker extends ReadWalker<Integer,Integer> {
// @Output
// PrintStream out;
@Output(doc="File to which variants should be written",required=true)
protected VCFWriter vcf_writer = null;
@Argument(fullName="outputFile", shortName="O", doc="output file name (BED format). DEPRECATED> Use --bed", required=true)
@Deprecated
java.io.File output_file;
@Argument(fullName = "metrics_file", shortName = "metrics", doc = "File to print callability metrics output", required = false)
public PrintStream metricsWriter = null;
// @Argument(fullName="vcf_format", shortName="vcf", doc="generate output file in VCF format", required=false)
// boolean FORMAT_VCF = false;
@Argument(fullName="somatic", shortName="somatic",
doc="Perform somatic calls; two input alignment files (-I option) must be specified. Calls are performed from the second file (\"tumor\") against the first one (\"normal\").", required=false)
boolean call_somatic = false;
@Argument(fullName="verboseOutput", shortName="verbose",
doc="Verbose output file in text format", required=false)
java.io.File verboseOutput = null;
@Argument(fullName="bedOutput", shortName="bed",
doc="Lightweight bed output file (only positions and events, no stats/annotations)", required=false)
java.io.File bedOutput = null;
@Argument(fullName="minCoverage", shortName="minCoverage",
doc="indel calls will be made only at sites with coverage of minCoverage or more reads; with --somatic this value is applied to tumor sample", required=false)
int minCoverage = 6;
@Argument(fullName="minNormalCoverage", shortName="minNormalCoverage",
doc="used only with --somatic; normal sample must have at least minNormalCoverage or more reads at the site to call germline/somatic indel, otherwise the indel (in tumor) is ignored", required=false)
int minNormalCoverage = 4;
@Argument(fullName="minFraction", shortName="minFraction",
doc="Minimum fraction of reads with CONSENSUS indel at a site, out of all reads covering the site, required for making a call"+
" (fraction of non-consensus indels at the site is not considered here, see minConsensusFraction)", required=false)
double minFraction = 0.3;
@Argument(fullName="minConsensusFraction", shortName="minConsensusFraction",
doc="Indel call is made only if fraction of CONSENSUS indel observations at a site wrt all indel observations at the site exceeds this threshold", required=false)
double minConsensusFraction = 0.7;
@Argument(fullName="minIndelCount", shortName="minCnt",
doc="Minimum count of reads supporting consensus indel required for making the call. "+
" This filter supercedes minFraction, i.e. indels with acceptable minFraction at low coverage "+
"(minIndelCount not met) will not pass.", required=false)
int minIndelCount = 0;
@Argument(fullName="refseq", shortName="refseq",
doc="Name of RefSeq transcript annotation file. If specified, indels will be annotated with GENOMIC/UTR/INTRON/CODING and with the gene name", required=false)
String RefseqFileName = null;
@Argument(fullName="blacklistedLanes", shortName="BL",
doc="Name of lanes (platform units) that should be ignored. Reads coming from these lanes will never be seen "+
"by this application, so they will not contribute indels to consider and will not be counted.", required=false)
PlatformUnitFilterHelper dummy;
@Argument(fullName="indel_debug", shortName="idebug", doc="Detailed printout for debugging, do not turn this on",required=false) Boolean DEBUG = false;
@Argument(fullName="window_size", shortName="ws", doc="Size (bp) of the sliding window used for accumulating the coverage. "+
"May need to be increased to accomodate longer reads or longer deletions.",required=false) int WINDOW_SIZE = 200;
@Argument(fullName="maxNumberOfReads",shortName="mnr",doc="Maximum number of reads to cache in the window; if number of reads exceeds this number,"+
" the window will be skipped and no calls will be made from it",required=false) int MAX_READ_NUMBER = 10000;
private WindowContext tumor_context;
private WindowContext normal_context;
private int currentContigIndex = -1;
private int contigLength = -1; // we see to much messy data with reads hanging out of contig ends...
private int currentPosition = -1; // position of the last read we've seen on the current contig
private String refName = null;
private java.io.Writer output = null;
private GenomeLoc location = null;
private long normalCallsMade = 0L, tumorCallsMade = 0L;
boolean outOfContigUserWarned = false;
private LocationAwareSeekableRODIterator refseqIterator=null;
// private Set<String> normalReadGroups; // we are going to remember which read groups are normals and which are tumors in order to be able
// private Set<String> tumorReadGroups ; // to properly assign the reads coming from a merged stream
private Set<String> normalSamples; // we are going to remember which samples are normal and which are tumor:
private Set<String> tumorSamples ; // these are used only to generate genotypes for vcf output
private int NQS_WIDTH = 5; // 5 bases on each side of the indel for NQS-style statistics
private Writer bedWriter = null;
private Writer verboseWriter = null;
private static String annGenomic = "GENOMIC";
private static String annIntron = "INTRON";
private static String annUTR = "UTR";
private static String annCoding = "CODING";
private static String annUnknown = "UNKNOWN";
private SAMRecord lastRead;
private byte[] refBases;
private ReferenceDataSource refData;
// "/humgen/gsa-scr1/GATK_Data/refGene.sorted.txt"
private Set<VCFHeaderLine> getVCFHeaderInfo() {
Set<VCFHeaderLine> headerInfo = new HashSet<VCFHeaderLine>();
// first, the basic info
headerInfo.add(new VCFHeaderLine("source", "IndelGenotyperV2"));
headerInfo.add(new VCFHeaderLine("reference", getToolkit().getArguments().referenceFile.getName()));
// FORMAT and INFO fields
// headerInfo.addAll(VCFUtils.getSupportedHeaderStrings());
if ( call_somatic ) {
headerInfo.addAll(VCFIndelAttributes.getAttributeHeaderLines("N_","In NORMAL: "));
headerInfo.addAll(VCFIndelAttributes.getAttributeHeaderLines("T_","In TUMOR: "));
headerInfo.add(new VCFInfoHeaderLine(VCFConstants.SOMATIC_KEY, 0, VCFHeaderLineType.Flag, "Somatic event"));
} else {
headerInfo.addAll(VCFIndelAttributes.getAttributeHeaderLines("",""));
}
// all of the arguments from the argument collection
Set<Object> args = new HashSet<Object>();
args.add(this);
args.addAll(getToolkit().getFilters());
Map<String,String> commandLineArgs = CommandLineUtils.getApproximateCommandLineArguments(args);
for ( Map.Entry<String, String> commandLineArg : commandLineArgs.entrySet() )
headerInfo.add(new VCFHeaderLine(String.format("IGv2_%s", commandLineArg.getKey()), commandLineArg.getValue()));
// also, the list of input bams
for ( File file : getToolkit().getArguments().samFiles )
headerInfo.add(new VCFHeaderLine("IGv2_bam_file_used", file.getName()));
return headerInfo;
}
@Override
public void initialize() {
normal_context = new WindowContext(0,WINDOW_SIZE);
normalSamples = new HashSet<String>();
if ( bedOutput != null && output_file != null ) {
throw new UserException.DeprecatedArgument("-O", "-O option is deprecated and -bed option replaces it; you can not use both at the same time");
}
if ( RefseqFileName != null ) {
logger.info("Using RefSeq annotations from "+RefseqFileName);
TribbleRMDTrackBuilder builder = new TribbleRMDTrackBuilder();
FeatureSource refseq = builder.createFeatureReader(RefSeqCodec.class,new File(RefseqFileName)).first;
try {
refseqIterator = new SeekableRODIterator(new FeatureToGATKFeatureIterator(refseq.iterator(),"refseq"));
} catch (IOException e) {
throw new UserException.CouldNotReadInputFile(new File(RefseqFileName), "Write failed", e);
}
}
if ( refseqIterator == null ) logger.info("No gene annotations available");
int nSams = getToolkit().getArguments().samFiles.size();
if ( call_somatic ) {
if ( nSams < 2 ) throw new UserException.BadInput("At least two bam files (normal and tumor) must be specified in somatic mode");
tumor_context = new WindowContext(0,WINDOW_SIZE);
tumorSamples = new HashSet<String>();
}
int nNorm = 0;
int nTum = 0;
for ( SAMReaderID rid : getToolkit().getDataSource().getReaderIDs() ) {
List<String> tags = rid.getTags() ;
if ( tags.isEmpty() && call_somatic )
throw new UserException.BadInput("In somatic mode all input bam files must be tagged as either 'normal' or 'tumor'. Untagged file: "+
getToolkit().getSourceFileForReaderID(rid));
boolean normal = false;
boolean tumor = false;
for ( String s : tags ) { // we allow additional unrelated tags (and we do not use them), but we REQUIRE one of Tumor/Normal to be present if --somatic is on
if ( "NORMAL".equals(s.toUpperCase()) ) {
normal = true;
nNorm++;
}
if ( "TUMOR".equals(s.toUpperCase()) ) {
tumor = true;
nTum++ ;
}
}
if ( call_somatic && normal && tumor ) throw new UserException.BadInput("Input bam file "+
getToolkit().getSourceFileForReaderID(rid)+" is tagged both as normal and as tumor. Which one is it??");
if ( call_somatic && !normal && ! tumor )
throw new UserException.BadInput("In somatic mode all input bams must be tagged as either normal or tumor. Encountered untagged file: "+
getToolkit().getSourceFileForReaderID(rid));
if ( ! call_somatic && (normal || tumor) )
System.out.println("WARNING: input bam file "+getToolkit().getSourceFileForReaderID(rid)
+" is tagged as Normal and/or Tumor, but somatic mode is not on. Tags will ne IGNORED");
if ( call_somatic && tumor ) {
for ( SAMReadGroupRecord rg : getToolkit().getSAMFileHeader(rid).getReadGroups() ) {
tumorSamples.add(rg.getSample());
}
} else {
for ( SAMReadGroupRecord rg : getToolkit().getSAMFileHeader(rid).getReadGroups() ) {
normalSamples.add(rg.getSample());
}
}
}
location = GenomeLocParser.createGenomeLoc(0,1);
// List<Set<String>> readGroupSets = getToolkit().getMergedReadGroupsByReaders();
// List<Set<String>> sampleSets = getToolkit().getSamplesByReaders();
normalSamples = getToolkit().getSamplesByReaders().get(0);
// if ( call_somatic ) {
// if ( nSams != 2 ) {
// System.out.println("In --somatic mode two input bam files must be specified (normal/tumor)");
// System.exit(1);
// }
// normalReadGroups = readGroupSets.get(0); // first -I option must specify normal.bam
// System.out.println(normalReadGroups.size() + " normal read groups");
// for ( String rg : normalReadGroups ) System.out.println("Normal RG: "+rg);
// tumorReadGroups = readGroupSets.get(1); // second -I option must specify tumor.bam
// System.out.println(tumorReadGroups.size() + " tumor read groups");
// for ( String rg : tumorReadGroups ) System.out.println("Tumor RG: "+rg);
// tumorSamples = sampleSets.get(1);
// } else {
// if ( nSams != 1 ) System.out.println("WARNING: multiple input files specified. \n"+
// "WARNING: Without --somatic option they will be merged and processed as a single sample");
// }
try {
// we already checked that bedOutput and output_file are not set simultaneously
if ( bedOutput != null ) bedWriter = new FileWriter(bedOutput);
if ( output_file != null ) bedWriter = new FileWriter(output_file);
} catch (java.io.IOException e) {
throw new UserException.CouldNotReadInputFile(bedOutput, "Failed to open BED file for writing.", e);
}
try {
if ( verboseOutput != null ) verboseWriter = new FileWriter(verboseOutput);
} catch (java.io.IOException e) {
throw new UserException.CouldNotReadInputFile(verboseOutput, "Failed to open BED file for writing.", e);
}
vcf_writer.writeHeader(new VCFHeader(getVCFHeaderInfo(), SampleUtils.getSAMFileSamples(getToolkit().getSAMFileHeader()))) ;
refData = new ReferenceDataSource(getToolkit().getArguments().referenceFile);
}
@Override
public Integer map(ReferenceContext ref, SAMRecord read, ReadMetaDataTracker metaDataTracker) {
// if ( read.getReadName().equals("428EFAAXX090610:2:36:1384:639#0") ) System.out.println("GOT READ");
if ( DEBUG ) {
// System.out.println("DEBUG>> read at "+ read.getAlignmentStart()+"-"+read.getAlignmentEnd()+
// "("+read.getCigarString()+")");
if ( read.getDuplicateReadFlag() ) System.out.println("DEBUG>> Duplicated read (IGNORED)");
}
if ( AlignmentUtils.isReadUnmapped(read) ||
read.getDuplicateReadFlag() ||
read.getNotPrimaryAlignmentFlag() ||
read.getMappingQuality() == 0 ) {
return 0; // we do not need those reads!
}
if ( read.getReferenceIndex() != currentContigIndex ) {
// we just jumped onto a new contig
if ( DEBUG ) System.out.println("DEBUG>>> Moved to contig "+read.getReferenceName());
if ( read.getReferenceIndex() < currentContigIndex ) // paranoidal
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName()+": contig is out of order; input BAM file is unsorted");
// print remaining indels from the previous contig (if any);
if ( call_somatic ) emit_somatic(1000000000, true);
else emit(1000000000,true);
currentContigIndex = read.getReferenceIndex();
currentPosition = read.getAlignmentStart();
refName = new String(read.getReferenceName());
location = GenomeLocParser.setContig(location,refName);
contigLength = GenomeLocParser.getContigInfo(refName).getSequenceLength();
outOfContigUserWarned = false;
normal_context.clear(); // reset coverage window; this will also set reference position to 0
if ( call_somatic) tumor_context.clear();
refBases = new String(refData.getReference().getSequence(read.getReferenceName()).getBases()).toUpperCase().getBytes();
}
// we have reset the window to the new contig if it was required and emitted everything we collected
// on a previous contig. At this point we are guaranteed that we are set up properly for working
// with the contig of the current read.
// NOTE: all the sanity checks and error messages below use normal_context only. We make sure that normal_context and
// tumor_context are synchronized exactly (windows are always shifted together by emit_somatic), so it's safe
if ( read.getAlignmentStart() < currentPosition ) // oops, read out of order?
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName() +" out of order on the contig\n"+
"Read starts at "+refName+":"+read.getAlignmentStart()+"; last read seen started at "+refName+":"+currentPosition
+"\nLast read was: "+lastRead.getReadName()+" RG="+lastRead.getAttribute("RG")+" at "+lastRead.getAlignmentStart()+"-"
+lastRead.getAlignmentEnd()+" cigar="+lastRead.getCigarString());
currentPosition = read.getAlignmentStart();
lastRead = read;
if ( read.getAlignmentEnd() > contigLength ) {
if ( ! outOfContigUserWarned ) {
System.out.println("WARNING: Reads aligned past contig length on "+ location.getContig()+"; all such reads will be skipped");
outOfContigUserWarned = true;
}
return 0;
}
long alignmentEnd = read.getAlignmentEnd();
Cigar c = read.getCigar();
int lastNonClippedElement = 0; // reverse offset to the last unclipped element
CigarOperator op = null;
// moving backwards from the end of the cigar, skip trailing S or H cigar elements:
do {
lastNonClippedElement++;
op = c.getCigarElement( c.numCigarElements()-lastNonClippedElement ).getOperator();
} while ( op == CigarOperator.H || op == CigarOperator.S );
// now op is the last non-S/H operator in the cigar.
// a little trick here: we want to make sure that current read completely fits into the current
// window so that we can accumulate indel observations over the whole length of the read.
// The ::getAlignmentEnd() method returns the last position on the reference where bases from the
// read actually match (M cigar elements). After our cleaning procedure, we can have reads that end
// with I element, which is not gonna be counted into alignment length on the reference. On the other hand,
// in this program we assign insertions, internally, to the first base *after* the insertion position.
// Hence, we have to make sure that that extra base is already in the window or we will get IndexOutOfBounds.
if ( op == CigarOperator.I) alignmentEnd++;
if ( alignmentEnd > normal_context.getStop()) {
// we don't emit anything until we reach a read that does not fit into the current window.
// At that point we try shifting the window to the start of that read (or reasonably close) and emit everything prior to
// that position. This is legitimate, since the reads are sorted and we are not gonna see any more coverage at positions
// below the current read's start.
// Clearly, we assume here that window is large enough to accomodate any single read, so simply shifting
// the window to around the read's start will ensure that the read fits...
if ( DEBUG) System.out.println("DEBUG>> Window at "+normal_context.getStart()+"-"+normal_context.getStop()+", read at "+
read.getAlignmentStart()+": trying to emit and shift" );
if ( call_somatic ) emit_somatic( read.getAlignmentStart(), false );
else emit( read.getAlignmentStart(), false );
// let's double check now that the read fits after the shift
if ( read.getAlignmentEnd() > normal_context.getStop()) {
// ooops, looks like the read does not fit into the window even after the latter was shifted!!
- throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName()+": out of coverage window bounds. Probably window is too small.\n"+
+ throw new UserException.BadArgumentValue("window_size", "Read "+read.getReadName()+": out of coverage window bounds. Probably window is too small, so increase the value of the window_size argument.\n"+
"Read length="+read.getReadLength()+"; cigar="+read.getCigarString()+"; start="+
read.getAlignmentStart()+"; end="+read.getAlignmentEnd()+
- "; window start (after trying to accomodate the read)="+normal_context.getStart()+
- "; window end="+normal_context.getStop());
+ "; window start (after trying to accomodate the read)="+normal_context.getStart()+"; window end="+normal_context.getStop());
}
}
if ( call_somatic ) {
List<String> tags = getToolkit().getReaderIDForRead(read).getTags();
boolean assigned = false;
for ( String s : tags ) {
if ( "NORMAL".equals(s.toUpperCase()) ) {
normal_context.add(read,ref.getBases());
assigned = true;
break;
}
if ( "TUMOR".equals(s.toUpperCase()) ) {
tumor_context.add(read,ref.getBases());
assigned = true;
break;
}
}
if ( ! assigned )
throw new StingException("Read "+read.getReadName()+" from "+getToolkit().getSourceFileForReaderID(getToolkit().getReaderIDForRead(read))+
"has no Normal/Tumor tag associated with it");
// String rg = (String)read.getAttribute("RG");
// if ( rg == null )
// throw new UserException.MalformedBam(read, "Read "+read.getReadName()+" has no read group in merged stream. RG is required for somatic calls.");
// if ( normalReadGroups.contains(rg) ) {
// normal_context.add(read,ref.getBases());
// } else if ( tumorReadGroups.contains(rg) ) {
// tumor_context.add(read,ref.getBases());
// } else {
// throw new UserException.MalformedBam(read, "Unrecognized read group in merged stream: "+rg);
// }
if ( tumor_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+tumor_context.getStart()+'-'+tumor_context.getStop()+" in tumor sample. The whole window will be dropped.");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+" in normal sample. The whole window will be dropped");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
} else {
normal_context.add(read, ref.getBases());
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+". The whole window will be dropped");
normal_context.shift(WINDOW_SIZE);
}
}
return 1;
}
/** Output indel calls up to the specified position and shift the window: after this method is executed, the
* first element of the window maps onto 'position', if possible, or at worst a few bases to the left of 'position' if we may need more
* reads to get full NQS-style statistics for an indel in the close proximity of 'position'.
*
* @param position
*/
private void emit(long position, boolean force) {
long adjustedPosition = adjustPosition(position);
if ( adjustedPosition == -1 ) {
// failed to find appropriate shift position, the data are probably to messy anyway so we drop them altogether
normal_context.shift((int)(position-normal_context.getStart()));
return;
}
long move_to = adjustedPosition;
for ( long pos = normal_context.getStart() ; pos < Math.min(adjustedPosition,normal_context.getStop()+1) ; pos++ ) {
if ( normal_context.indelsAt(pos).size() == 0 ) continue; // no indels
IndelPrecall normalCall = new IndelPrecall(normal_context,pos,NQS_WIDTH);
if ( normalCall.getCoverage() < minCoverage ) {
if ( DEBUG ) {
System.out.println("DEBUG>> Indel at "+pos+"; coverare in normal="+normalCall.getCoverage()+" (SKIPPED)");
}
continue; // low coverage
}
if ( DEBUG ) System.out.println("DEBUG>> Indel at "+pos);
long left = Math.max( pos-NQS_WIDTH, normal_context.getStart() );
long right = pos+normalCall.getVariant().lengthOnRef()+NQS_WIDTH-1;
if ( right >= adjustedPosition && ! force) {
// we are not asked to force-shift, and there is more coverage around the current indel that we still need to collect
// we are not asked to force-shift, and there's still additional coverage to the right of current indel, so its too early to emit it;
// instead we shift only up to current indel pos - MISMATCH_WIDTH, so that we could keep collecting that coverage
move_to = adjustPosition(left);
if ( move_to == -1 ) {
// failed to find appropriate shift position, the data are probably to messy anyway so we drop them altogether
normal_context.shift((int)(adjustedPosition-normal_context.getStart()));
return;
}
if ( DEBUG ) System.out.println("DEBUG>> waiting for coverage; actual shift performed to "+ move_to);
break;
}
// if indel is too close to the end of the window but we need to emit anyway (force-shift), adjust right:
if ( right > normal_context.getStop() ) right = normal_context.getStop();
location = GenomeLocParser.setStart(location,pos);
location = GenomeLocParser.setStop(location,pos); // retrieve annotation data
if ( normalCall.isCall() ) {
normalCallsMade++;
printVCFLine(vcf_writer,normalCall);
if ( bedWriter != null ) normalCall.printBedLine(bedWriter);
if ( verboseWriter != null ) {
RODRecordList annotationList = (refseqIterator == null ? null : refseqIterator.seekForward(location));
String annotationString = (refseqIterator == null ? "" : getAnnotationString(annotationList));
StringBuilder fullRecord = new StringBuilder();
fullRecord.append(makeFullRecord(normalCall));
fullRecord.append(annotationString);
try {
verboseWriter.write(fullRecord.toString());
verboseWriter.write('\n');
} catch (IOException e) {
throw new UserException.CouldNotCreateOutputFile(verboseOutput, "Write failed", e);
}
}
}
normal_context.indelsAt(pos).clear();
// we dealt with this indel; don't want to see it again
// (we might otherwise in the case when 1) there is another indel that follows
// within MISMATCH_WIDTH bases and 2) we'd need to wait for more coverage for that next indel)
// for ( IndelVariant var : variants ) {
// System.out.print("\t"+var.getType()+"\t"+var.getBases()+"\t"+var.getCount());
// }
}
if ( DEBUG ) System.out.println("DEBUG>> Actual shift to " + move_to + " ("+adjustedPosition+")");
normal_context.shift((int)(move_to - normal_context.getStart() ) );
}
/** A shortcut. Returns true if we got indels within the specified interval in single and only window context
* (for single-sample calls) or in either of the two window contexts (for two-sample/somatic calls)
*
*/
private boolean indelsPresentInInterval(long start, long stop) {
if ( tumor_context == null ) return normal_context.hasIndelsInInterval(start,stop);
return tumor_context.hasIndelsInInterval(start,stop) ||
normal_context.hasIndelsInInterval(start,stop);
}
/** Takes the position, to which window shift is requested, and tries to adjust it in such a way that no NQS window is broken.
* Namely, this method checks, iteratively, if there is an indel within NQS_WIDTH bases ahead of initially requested or adjusted
* shift position. If there is such an indel,
* then shifting to that position would lose some or all NQS-window bases to the left of the indel (since it's not going to be emitted
* just yet). Instead, this method tries to readjust the shift position leftwards so that full NQS window to the left of the next indel
* is preserved. This method tries thie strategy 4 times (so that it would never walk away too far to the left), and if it fails to find
* an appropriate adjusted shift position (which could happen if there are many indels following each other at short intervals), it will give up,
* go back to the original requested shift position and try finding the first shift poisition that has no indel associated with it.
*/
private long adjustPosition(long request) {
long initial_request = request;
int attempts = 0;
boolean failure = false;
while ( indelsPresentInInterval(request,request+NQS_WIDTH) ) {
request -= NQS_WIDTH;
if ( DEBUG ) System.out.println("DEBUG>> indel observations present within "+NQS_WIDTH+" bases ahead. Resetting shift to "+request);
attempts++;
if ( attempts == 4 ) {
if ( DEBUG ) System.out.println("DEBUG>> attempts to preserve full NQS window failed; now trying to find any suitable position.") ;
failure = true;
break;
}
}
if ( failure ) {
// we tried 4 times but did not find a good shift position that would preserve full nqs window
// around all indels. let's fall back and find any shift position as long and there's no indel at the very
// first position after the shift (this is bad for other reasons); if it breaks a nqs window, so be it
request = initial_request;
attempts = 0;
while ( indelsPresentInInterval(request,request+1) ) {
request--;
if ( DEBUG ) System.out.println("DEBUG>> indel observations present within "+NQS_WIDTH+" bases ahead. Resetting shift to "+request);
attempts++;
if ( attempts == 50 ) {
System.out.println("WARNING: Indel at every position in the interval "+refName+":"+request+"-"+initial_request+
". Can not find a break to shift context window to; no calls will be attempted in the current window.");
return -1;
}
}
}
if ( DEBUG ) System.out.println("DEBUG>> Found acceptable target position "+request);
return request;
}
/** Output somatic indel calls up to the specified position and shift the coverage array(s): after this method is executed
* first elements of the coverage arrays map onto 'position', or a few bases prior to the specified position
* if there is an indel in close proximity to 'position' so that we may get more coverage around it later.
*
* @param position
*/
private void emit_somatic(long position, boolean force) {
long adjustedPosition = adjustPosition(position);
if ( adjustedPosition == -1 ) {
// failed to find appropriate shift position, the data are probably to messy anyway so we drop them altogether
normal_context.shift((int)(position-normal_context.getStart()));
tumor_context.shift((int)(position-tumor_context.getStart()));
return;
}
long move_to = adjustedPosition;
if ( DEBUG ) System.out.println("DEBUG>> Emitting in somatic mode up to "+position+" force shift="+force+" current window="+tumor_context.getStart()+"-"+tumor_context.getStop());
for ( long pos = tumor_context.getStart() ; pos < Math.min(adjustedPosition,tumor_context.getStop()+1) ; pos++ ) {
if ( tumor_context.indelsAt(pos).size() == 0 ) continue; // no indels in tumor
IndelPrecall tumorCall = new IndelPrecall(tumor_context,pos,NQS_WIDTH);
IndelPrecall normalCall = new IndelPrecall(normal_context,pos,NQS_WIDTH);
if ( tumorCall.getCoverage() < minCoverage ) {
if ( DEBUG ) {
System.out.println("DEBUG>> Indel in tumor at "+pos+"; coverare in tumor="+tumorCall.getCoverage()+" (SKIPPED)");
}
continue; // low coverage
}
if ( normalCall.getCoverage() < minNormalCoverage ) {
if ( DEBUG ) {
System.out.println("DEBUG>> Indel in tumor at "+pos+"; coverare in normal="+normalCall.getCoverage()+" (SKIPPED)");
}
continue; // low coverage
}
if ( DEBUG ) System.out.println("DEBUG>> Indel in tumor at "+pos);
long left = Math.max( pos-NQS_WIDTH, tumor_context.getStart() );
long right = pos+tumorCall.getVariant().lengthOnRef()+NQS_WIDTH-1;
if ( right >= adjustedPosition && ! force) {
// we are not asked to force-shift, and there is more coverage around the current indel that we still need to collect
// we are not asked to force-shift, and there's still additional coverage to the right of current indel, so its too early to emit it;
// instead we shift only up to current indel pos - MISMATCH_WIDTH, so that we could keep collecting that coverage
move_to = adjustPosition(left);
if ( move_to == -1 ) {
// failed to find appropriate shift position, the data are probably to messy anyway so we drop them altogether
normal_context.shift((int)(adjustedPosition-normal_context.getStart()));
tumor_context.shift((int)(adjustedPosition-tumor_context.getStart()));
return;
}
if ( DEBUG ) System.out.println("DEBUG>> waiting for coverage; actual shift performed to "+ move_to);
break;
}
if ( right > tumor_context.getStop() ) right = tumor_context.getStop(); // if indel is too close to the end of the window but we need to emit anyway (force-shift), adjust right
location = GenomeLocParser.setStart(location,pos);
location = GenomeLocParser.setStop(location,pos); // retrieve annotation data
if ( tumorCall.isCall() ) {
tumorCallsMade++;
printVCFLine(vcf_writer,normalCall,tumorCall);
if ( bedWriter != null ) tumorCall.printBedLine(bedWriter);
if ( verboseWriter != null ) {
RODRecordList annotationList = (refseqIterator == null ? null : refseqIterator.seekForward(location));
String annotationString = (refseqIterator == null ? "" : getAnnotationString(annotationList));
StringBuilder fullRecord = new StringBuilder();
fullRecord.append(makeFullRecord(normalCall,tumorCall));
if ( normalCall.getVariant() == null ) {
fullRecord.append("SOMATIC");
} else {
fullRecord.append("GERMLINE");
}
try {
verboseWriter.write(fullRecord + "\t"+ annotationString);
verboseWriter.write('\n');
} catch (IOException e) {
throw new UserException.CouldNotCreateOutputFile(verboseOutput, "Write failed", e);
}
}
}
tumor_context.indelsAt(pos).clear();
normal_context.indelsAt(pos).clear();
// we dealt with this indel; don't want to see it again
// (we might otherwise in the case when 1) there is another indel that follows
// within MISMATCH_WIDTH bases and 2) we'd need to wait for more coverage for that next indel)
// for ( IndelVariant var : variants ) {
// System.out.print("\t"+var.getType()+"\t"+var.getBases()+"\t"+var.getCount());
// }
}
if ( DEBUG ) System.out.println("DEBUG>> Actual shift to " + move_to + " ("+adjustedPosition+")");
tumor_context.shift((int)(move_to - tumor_context.getStart() ) );
normal_context.shift((int)(move_to - normal_context.getStart() ) );
}
private String makeFullRecord(IndelPrecall normalCall, IndelPrecall tumorCall) {
StringBuilder fullRecord = new StringBuilder();
fullRecord.append(tumorCall.makeEventString());
fullRecord.append('\t');
fullRecord.append(normalCall.makeStatsString("N_"));
fullRecord.append('\t');
fullRecord.append(tumorCall.makeStatsString("T_"));
fullRecord.append('\t');
return fullRecord.toString();
}
private String makeFullRecord(IndelPrecall normalCall) {
StringBuilder fullRecord = new StringBuilder();
fullRecord.append(normalCall.makeEventString());
fullRecord.append('\t');
fullRecord.append(normalCall.makeStatsString(""));
fullRecord.append('\t');
return fullRecord.toString();
}
private String getAnnotationString(RODRecordList ann) {
if ( ann == null ) return annGenomic;
else {
StringBuilder b = new StringBuilder();
if ( RefSeqFeature.isExon(ann) ) {
if ( RefSeqFeature.isCodingExon(ann) ) b.append(annCoding); // both exon and coding = coding exon sequence
else b.append(annUTR); // exon but not coding = UTR
} else {
if ( RefSeqFeature.isCoding(ann) ) b.append(annIntron); // not in exon, but within the coding region = intron
else b.append(annUnknown); // we have no idea what this is. this may actually happen when we have a fully non-coding exon...
}
b.append('\t');
b.append(((Transcript)ann.get(0).getUnderlyingObject()).getGeneName()); // there is at least one transcript in the list, guaranteed
// while ( it.hasNext() ) { //
// t.getGeneName()
// }
return b.toString();
}
}
public void printVCFLine(VCFWriter vcf, IndelPrecall call) {
int event_length = call.getVariant().lengthOnRef();
if ( event_length < 0 ) event_length = 0;
long start = call.getPosition()-1;
// If the beginning of the chromosome is deleted (possible, however unlikely), it's unclear how to proceed.
// The suggestion is instead of putting the base before the indel, to put the base after the indel.
// For now, just don't print out that site.
if ( start == 0 )
return;
long stop = start;
List<Allele> alleles = new ArrayList<Allele>(2);
if ( event_length == 0 ) { // insertion
alleles.add( Allele.create(Allele.NULL_ALLELE_STRING,true) );
alleles.add( Allele.create(call.getVariant().getBases(), false ));
} else { //deletion:
alleles.add( Allele.create(Allele.NULL_ALLELE_STRING,false) );
alleles.add( Allele.create(call.getVariant().getBases(), true ));
stop += event_length;
}
Map<String,Genotype> genotypes = new HashMap<String,Genotype>();
for ( String sample : normalSamples ) {
genotypes.put(sample,new Genotype(sample, alleles));
}
VariantContext vc = new VariantContext("IGv2_Indel_call", refName, start, stop, alleles, genotypes,
-1.0 /* log error */, null /* filters */, call.makeStatsAttributes("",null));
vcf.add(vc,refBases[(int)start-1]);
}
public void printVCFLine(VCFWriter vcf, IndelPrecall nCall, IndelPrecall tCall) {
int event_length = tCall.getVariant().lengthOnRef();
if ( event_length < 0 ) event_length = 0;
long start = tCall.getPosition()-1;
long stop = start;
Map<String,Object> attrs = nCall.makeStatsAttributes("N_",null);
attrs = tCall.makeStatsAttributes("T_",attrs);
boolean isSomatic = false;
if ( nCall.getVariant() == null ) {
isSomatic = true;
attrs.put(VCFConstants.SOMATIC_KEY,true);
}
List<Allele> alleles = new ArrayList<Allele>(2);
List<Allele> homRefAlleles = isSomatic ? new ArrayList<Allele>(2) : null ; // we need this only for somatic calls
if ( event_length == 0 ) { // insertion
alleles.add( Allele.create(Allele.NULL_ALLELE_STRING,true) );
alleles.add( Allele.create(tCall.getVariant().getBases(), false ));
if ( isSomatic ) {
// create alleles of hom-ref genotype for normal sample
homRefAlleles.add( Allele.create(Allele.NULL_ALLELE_STRING,true) );
homRefAlleles.add( Allele.create(Allele.NULL_ALLELE_STRING,true) );
}
} else { //deletion:
alleles.add( Allele.create(Allele.NULL_ALLELE_STRING,false) );
alleles.add( Allele.create(tCall.getVariant().getBases(), true ));
stop += event_length;
if ( isSomatic ) {
// create alleles of hom-ref genotype for normal sample
homRefAlleles.add( Allele.create(tCall.getVariant().getBases(), true ));
homRefAlleles.add( Allele.create(tCall.getVariant().getBases(), true ));
}
}
Map<String,Genotype> genotypes = new HashMap<String,Genotype>();
for ( String sample : normalSamples ) {
genotypes.put(sample,new Genotype(sample, isSomatic ? homRefAlleles : alleles,0));
}
for ( String sample : tumorSamples ) {
genotypes.put(sample,new Genotype(sample, alleles,0) );
}
VariantContext vc = new VariantContext("IGv2_Indel_call", refName, start, stop, alleles, genotypes,
-1.0 /* log error */, null /* filters */, attrs);
vcf.add(vc,refBases[(int)start-1]);
}
@Override
public void onTraversalDone(Integer result) {
if ( call_somatic ) emit_somatic(1000000000, true);
else emit(1000000000,true); // emit everything we might have left
if ( metricsWriter != null ) {
metricsWriter.println(String.format("Normal calls made %d", normalCallsMade));
metricsWriter.println(String.format("Tumor calls made %d", tumorCallsMade));
metricsWriter.close();
}
try {
if ( bedWriter != null ) bedWriter.close();
if ( verboseWriter != null ) verboseWriter.close();
} catch (IOException e) {
System.out.println("Failed to close output BED file gracefully, data may be lost");
e.printStackTrace();
}
super.onTraversalDone(result);
}
@Override
public Integer reduce(Integer value, Integer sum) {
if ( value == -1 ) {
onTraversalDone(sum);
System.exit(1);
}
sum += value;
return sum;
}
@Override
public Integer reduceInit() {
return new Integer(0);
}
static class IndelVariant {
public static enum Type { I, D};
private String bases;
private Type type;
private Set<ExpandedSAMRecord> reads = new HashSet<ExpandedSAMRecord>(); // keep track of reads that have this indel
private Set<String> samples = new HashSet<String>(); // which samples had the indel described by this object
public IndelVariant(ExpandedSAMRecord read , Type type, String bases) {
this.type = type;
this.bases = bases.toUpperCase();
addObservation(read);
}
/** Adds another observation for the current indel. It is assumed that the read being registered
* does contain the observation, no checks are performed. Read's sample is added to the list of samples
* this indel was observed in as well.
* @param read
*/
public void addObservation(ExpandedSAMRecord read) {
if ( reads.contains(read) ) {
//TODO fix CleanedReadInjector and reinstate exception here: duplicate records may signal a problem with the bam
// seeing the same read again can mean only one thing: the input bam file is corrupted and contains
// duplicate records. We KNOW that this may happen for the time being due to bug in CleanedReadInjector
// so this is a short-term patch: don't cry, but just ignore the duplicate record
//throw new StingException("Attempting to add indel observation that was already registered");
return;
}
reads.add(read);
String sample = null;
if ( read.getSAMRecord().getReadGroup() != null ) sample = read.getSAMRecord().getReadGroup().getSample();
if ( sample != null ) samples.add(sample);
}
/** Returns length of the event on the reference (number of deleted bases
* for deletions, -1 for insertions.
* @return
*/
public int lengthOnRef() {
if ( type == Type.D ) return bases.length();
else return 0;
}
public void addSample(String sample) {
if ( sample != null )
samples.add(sample);
}
public String getSamples() {
StringBuffer sb = new StringBuffer();
Iterator<String> i = samples.iterator();
while ( i.hasNext() ) {
sb.append(i.next());
if ( i.hasNext() )
sb.append(",");
}
return sb.toString();
}
public Set<ExpandedSAMRecord> getReadSet() { return reads; }
public int getCount() { return reads.size(); }
public String getBases() { return bases; }
public Type getType() { return type; }
@Override
public boolean equals(Object o) {
if ( ! ( o instanceof IndelVariant ) ) return false;
IndelVariant that = (IndelVariant)o;
return ( this.type == that.type && this.bases.equals(that.bases) );
}
public boolean equals(Type type, String bases) {
return ( this.type == type && this.bases.equals(bases.toUpperCase()) );
}
}
/**
* Utility class that encapsulates the logic related to collecting all the stats and counts required to
* make (or discard) a call, as well as the calling heuristics that uses those data.
*/
class IndelPrecall {
// private boolean DEBUG = false;
private int NQS_MISMATCH_CUTOFF = 1000000;
private double AV_MISMATCHES_PER_READ = 1.5;
private int nqs = 0;
private IndelVariant consensus_indel = null; // indel we are going to call
private long pos = -1 ; // position on the ref
private int total_coverage = 0; // total number of reads overlapping with the event
private int consensus_indel_count = 0; // number of reads, in which consensus indel was observed
private int all_indel_count = 0 ; // number of reads, in which any indel was observed at current position
private int total_mismatches_in_nqs_window = 0; // total number of mismatches in the nqs window around the indel
private int total_bases_in_nqs_window = 0; // total number of bases in the nqs window (some reads may not fully span the window so it's not coverage*nqs_size)
private int total_base_qual_in_nqs_window = 0; // sum of qualitites of all the bases in the nqs window
private int total_mismatching_base_qual_in_nqs_window = 0; // sum of qualitites of all mismatching bases in the nqs window
private int indel_read_mismatches_in_nqs_window = 0; // mismatches inside the nqs window in indel-containing reads only
private int indel_read_bases_in_nqs_window = 0; // number of bases in the nqs window from indel-containing reads only
private int indel_read_base_qual_in_nqs_window = 0; // sum of qualitites of bases in nqs window from indel-containing reads only
private int indel_read_mismatching_base_qual_in_nqs_window = 0; // sum of qualitites of mismatching bases in the nqs window from indel-containing reads only
private int consensus_indel_read_mismatches_in_nqs_window = 0; // mismatches within the nqs window from consensus indel reads only
private int consensus_indel_read_bases_in_nqs_window = 0; // number of bases in the nqs window from consensus indel-containing reads only
private int consensus_indel_read_base_qual_in_nqs_window = 0; // sum of qualitites of bases in nqs window from consensus indel-containing reads only
private int consensus_indel_read_mismatching_base_qual_in_nqs_window = 0; // sum of qualitites of mismatching bases in the nqs window from consensus indel-containing reads only
private double consensus_indel_read_total_mm = 0.0; // sum of all mismatches in reads that contain consensus indel
private double all_indel_read_total_mm = 0.0; // sum of all mismatches in reads that contain any indel at given position
private double all_read_total_mm = 0.0; // sum of all mismatches in all reads
private double consensus_indel_read_total_mapq = 0.0; // sum of mapping qualitites of all reads with consensus indel
private double all_indel_read_total_mapq = 0.0 ; // sum of mapping qualitites of all reads with (any) indel at current position
private double all_read_total_mapq = 0.0; // sum of all mapping qualities of all reads
private PrimitivePair.Int consensus_indel_read_orientation_cnt = new PrimitivePair.Int();
private PrimitivePair.Int all_indel_read_orientation_cnt = new PrimitivePair.Int();
private PrimitivePair.Int all_read_orientation_cnt = new PrimitivePair.Int();
public IndelPrecall(WindowContext context, long position, int nqs_width) {
this.pos = position;
this.nqs = nqs_width;
total_coverage = context.coverageAt(pos,true);
List<IndelVariant> variants = context.indelsAt(pos);
findConsensus(variants);
// pos is the first base after the event: first deleted base or first base after insertion.
// hence, [pos-nqs, pos+nqs-1] (inclusive) is the window with nqs bases on each side of a no-event or an insertion
// and [pos-nqs, pos+Ndeleted+nqs-1] is the window with nqs bases on each side of a deletion.
// we initialize the nqs window for no-event/insertion case
long left = Math.max( pos-nqs, context.getStart() );
long right = Math.min(pos+nqs-1, context.getStop());
//if ( pos == 3534096 ) System.out.println("pos="+pos +" total reads: "+context.getReads().size());
Iterator<ExpandedSAMRecord> read_iter = context.getReads().iterator();
while ( read_iter.hasNext() ) {
ExpandedSAMRecord rec = read_iter.next();
SAMRecord read = rec.getSAMRecord();
byte[] flags = rec.getExpandedMMFlags();
byte[] quals = rec.getExpandedQuals();
int mm = rec.getMMCount();
if( read.getAlignmentStart() > pos || read.getAlignmentEnd() < pos ) continue;
long local_right = right; // end of nqs window for this particular read. May need to be advanced further right
// if read has a deletion. The gap in the middle of nqs window will be skipped
// automatically since flags/quals are set to -1 there
boolean read_has_a_variant = false;
boolean read_has_consensus = ( consensus_indel!= null && consensus_indel.getReadSet().contains(rec) );
for ( IndelVariant v : variants ) {
if ( v.getReadSet().contains(rec) ) {
read_has_a_variant = true;
local_right += v.lengthOnRef();
break;
}
}
if ( read_has_consensus ) {
consensus_indel_read_total_mm += mm;
consensus_indel_read_total_mapq += read.getMappingQuality();
if ( read.getReadNegativeStrandFlag() ) consensus_indel_read_orientation_cnt.second++;
else consensus_indel_read_orientation_cnt.first++;
}
if ( read_has_a_variant ) {
all_indel_read_total_mm += mm;
all_indel_read_total_mapq += read.getMappingQuality();
if ( read.getReadNegativeStrandFlag() ) all_indel_read_orientation_cnt.second++;
else all_indel_read_orientation_cnt.first++;
}
all_read_total_mm+= mm;
all_read_total_mapq += read.getMappingQuality();
if ( read.getReadNegativeStrandFlag() ) all_read_orientation_cnt.second++;
else all_read_orientation_cnt.first++;
for ( int pos_in_flags = Math.max((int)(left - read.getAlignmentStart()),0);
pos_in_flags <= Math.min((int)local_right-read.getAlignmentStart(),flags.length - 1);
pos_in_flags++) {
if ( flags[pos_in_flags] == -1 ) continue; // gap (deletion), skip it; we count only bases aligned to the ref
total_bases_in_nqs_window++;
if ( read_has_consensus ) consensus_indel_read_bases_in_nqs_window++;
if ( read_has_a_variant ) indel_read_bases_in_nqs_window++;
if ( quals[pos_in_flags] != -1 ) {
total_base_qual_in_nqs_window += quals[pos_in_flags];
if ( read_has_a_variant ) indel_read_base_qual_in_nqs_window += quals[pos_in_flags];
if ( read_has_consensus ) consensus_indel_read_base_qual_in_nqs_window += quals[pos_in_flags];
}
if ( flags[pos_in_flags] == 1 ) { // it's a mismatch
total_mismatches_in_nqs_window++;
total_mismatching_base_qual_in_nqs_window += quals[pos_in_flags];
if ( read_has_consensus ) {
consensus_indel_read_mismatches_in_nqs_window++;
consensus_indel_read_mismatching_base_qual_in_nqs_window += quals[pos_in_flags];
}
if ( read_has_a_variant ) {
indel_read_mismatches_in_nqs_window++;
indel_read_mismatching_base_qual_in_nqs_window += quals[pos_in_flags];
}
}
}
// if ( pos == 3534096 ) {
// System.out.println(read.getReadName());
// System.out.println(" cons nqs bases="+consensus_indel_read_bases_in_nqs_window);
// System.out.println(" qual sum="+consensus_indel_read_base_qual_in_nqs_window);
// }
}
}
public long getPosition() { return pos; }
public boolean hasObservation() { return consensus_indel != null; }
public int getCoverage() { return total_coverage; }
public double getTotalMismatches() { return all_read_total_mm; }
public double getConsensusMismatches() { return consensus_indel_read_total_mm; }
public double getAllVariantMismatches() { return all_indel_read_total_mm; }
/** Returns average number of mismatches per consensus indel-containing read */
public double getAvConsensusMismatches() {
return ( consensus_indel_count != 0 ? consensus_indel_read_total_mm/consensus_indel_count : 0.0 );
}
/** Returns average number of mismatches per read across all reads matching the ref (not containing any indel variants) */
public double getAvRefMismatches() {
int coverage_ref = total_coverage-all_indel_count;
return ( coverage_ref != 0 ? (all_read_total_mm - all_indel_read_total_mm )/coverage_ref : 0.0 );
}
public PrimitivePair.Int getConsensusStrandCounts() {
return consensus_indel_read_orientation_cnt;
}
public PrimitivePair.Int getRefStrandCounts() {
return new PrimitivePair.Int(all_read_orientation_cnt.first-all_indel_read_orientation_cnt.first,
all_read_orientation_cnt.second - all_indel_read_orientation_cnt.second);
}
/** Returns a sum of mapping qualities of all reads spanning the event. */
public double getTotalMapq() { return all_read_total_mapq; }
/** Returns a sum of mapping qualities of all reads, in which the consensus variant is observed. */
public double getConsensusMapq() { return consensus_indel_read_total_mapq; }
/** Returns a sum of mapping qualities of all reads, in which any variant is observed at the current event site. */
public double getAllVariantMapq() { return all_indel_read_total_mapq; }
/** Returns average mapping quality per consensus indel-containing read. */
public double getAvConsensusMapq() {
return ( consensus_indel_count != 0 ? consensus_indel_read_total_mapq/consensus_indel_count : 0.0 );
}
/** Returns average number of mismatches per read across all reads matching the ref (not containing any indel variants). */
public double getAvRefMapq() {
int coverage_ref = total_coverage-all_indel_count;
return ( coverage_ref != 0 ? (all_read_total_mapq - all_indel_read_total_mapq )/coverage_ref : 0.0 );
}
/** Returns fraction of bases in NQS window around the indel that are mismatches, across all reads,
* in which consensus indel is observed. NOTE: NQS window for indel containing reads is defined around
* the indel itself (e.g. for a 10-base deletion spanning [X,X+9], the 5-NQS window is {[X-5,X-1],[X+10,X+15]}
* */
public double getNQSConsensusMMRate() {
if ( consensus_indel_read_bases_in_nqs_window == 0 ) return 0;
return ((double)consensus_indel_read_mismatches_in_nqs_window)/consensus_indel_read_bases_in_nqs_window;
}
/** Returns fraction of bases in NQS window around the indel start position that are mismatches, across all reads
* that align to the ref (i.e. contain no indel observation at the current position). NOTE: NQS window for ref
* reads is defined around the event start position, NOT around the actual consensus indel.
* */
public double getNQSRefMMRate() {
int num_ref_bases = total_bases_in_nqs_window - indel_read_bases_in_nqs_window;
if ( num_ref_bases == 0 ) return 0;
return ((double)(total_mismatches_in_nqs_window - indel_read_mismatches_in_nqs_window))/num_ref_bases;
}
/** Returns average base quality in NQS window around the indel, across all reads,
* in which consensus indel is observed. NOTE: NQS window for indel containing reads is defined around
* the indel itself (e.g. for a 10-base deletion spanning [X,X+9], the 5-NQS window is {[X-5,X-1],[X+10,X+15]}
* */
public double getNQSConsensusAvQual() {
if ( consensus_indel_read_bases_in_nqs_window == 0 ) return 0;
return ((double)consensus_indel_read_base_qual_in_nqs_window)/consensus_indel_read_bases_in_nqs_window;
}
/** Returns fraction of bases in NQS window around the indel start position that are mismatches, across all reads
* that align to the ref (i.e. contain no indel observation at the current position). NOTE: NQS window for ref
* reads is defined around the event start position, NOT around the actual consensus indel.
* */
public double getNQSRefAvQual() {
int num_ref_bases = total_bases_in_nqs_window - indel_read_bases_in_nqs_window;
if ( num_ref_bases == 0 ) return 0;
return ((double)(total_base_qual_in_nqs_window - indel_read_base_qual_in_nqs_window))/num_ref_bases;
}
public int getTotalNQSMismatches() { return total_mismatches_in_nqs_window; }
public int getAllVariantCount() { return all_indel_count; }
public int getConsensusVariantCount() { return consensus_indel_count; }
// public boolean failsNQSMismatch() {
// //TODO wrong fraction: mismatches are counted only in indel-containing reads, but total_coverage is used!
// return ( indel_read_mismatches_in_nqs_window > NQS_MISMATCH_CUTOFF ) ||
// ( indel_read_mismatches_in_nqs_window > total_coverage * AV_MISMATCHES_PER_READ );
// }
public IndelVariant getVariant() { return consensus_indel; }
public boolean isCall() {
boolean ret = ( consensus_indel_count >= minIndelCount &&
(double)consensus_indel_count > minFraction * total_coverage &&
(double) consensus_indel_count > minConsensusFraction*all_indel_count );
if ( DEBUG && ! ret ) System.out.println("DEBUG>> NOT a call: count="+consensus_indel_count+
" total_count="+all_indel_count+" cov="+total_coverage+
" minConsensusF="+((double)consensus_indel_count)/all_indel_count+
" minF="+((double)consensus_indel_count)/total_coverage);
return ret;
}
/** Utility method: finds the indel variant with the largest count (ie consensus) among all the observed
* variants, and sets the counts of consensus observations and all observations of any indels (including non-consensus)
* @param variants
* @return
*/
private void findConsensus(List<IndelVariant> variants) {
for ( IndelVariant var : variants ) {
if ( DEBUG ) System.out.println("DEBUG>> Variant "+var.getBases()+" (cnt="+var.getCount()+")");
int cnt = var.getCount();
all_indel_count +=cnt;
if ( cnt > consensus_indel_count ) {
consensus_indel = var;
consensus_indel_count = cnt;
}
}
if ( DEBUG && consensus_indel != null ) System.out.println("DEBUG>> Returning: "+consensus_indel.getBases()+
" (cnt="+consensus_indel.getCount()+") with total count of "+all_indel_count);
}
public void printBedLine(Writer bed) {
int event_length = consensus_indel.lengthOnRef();
if ( event_length < 0 ) event_length = 0;
StringBuffer message = new StringBuffer();
message.append(refName+"\t"+(pos-1)+"\t");
message.append((pos-1+event_length)+"\t"+(event_length>0? "-":"+")+consensus_indel.getBases() +":"+all_indel_count+"/"+total_coverage);
try {
bed.write(message.toString()+"\n");
} catch (IOException e) {
throw new UserException.CouldNotCreateOutputFile(bedOutput, "Error encountered while writing into output BED file", e);
}
}
public String makeEventString() {
int event_length = consensus_indel.lengthOnRef();
if ( event_length < 0 ) event_length = 0;
StringBuffer message = new StringBuffer();
message.append(refName);
message.append('\t');
message.append(pos-1);
message.append('\t');
message.append(pos-1+event_length);
message.append('\t');
message.append((event_length>0?'-':'+'));
message.append(consensus_indel.getBases());
return message.toString();
}
public String makeStatsString(String prefix) {
StringBuilder message = new StringBuilder();
message.append(prefix+"OBS_COUNTS[C/A/T]:"+getConsensusVariantCount()+"/"+getAllVariantCount()+"/"+getCoverage());
message.append('\t');
message.append(prefix+"AV_MM[C/R]:"+String.format("%.2f/%.2f",getAvConsensusMismatches(),
getAvRefMismatches()));
message.append('\t');
message.append(prefix+"AV_MAPQ[C/R]:"+String.format("%.2f/%.2f",getAvConsensusMapq(),
getAvRefMapq()));
message.append('\t');
message.append(prefix+"NQS_MM_RATE[C/R]:"+String.format("%.2f/%.2f",getNQSConsensusMMRate(),getNQSRefMMRate()));
message.append('\t');
message.append(prefix+"NQS_AV_QUAL[C/R]:"+String.format("%.2f/%.2f",getNQSConsensusAvQual(),getNQSRefAvQual()));
PrimitivePair.Int strand_cons = getConsensusStrandCounts();
PrimitivePair.Int strand_ref = getRefStrandCounts();
message.append('\t');
message.append(prefix+"STRAND_COUNTS[C/C/R/R]:"+strand_cons.first+"/"+strand_cons.second+"/"+strand_ref.first+"/"+strand_ref.second);
return message.toString();
}
/**
* Places alignment statistics into attribute map and returns the map. If attr parameter is null,
* a new map is allocated, filled and returned. If attr is not null, new attributes are added to that
* preexisting map, and the same instance of the (updated) map is returned.
* @param prefix
* @param attr
* @return
*/
public Map<String,Object> makeStatsAttributes(String prefix, Map<String,Object> attr) {
if ( attr == null ) attr = new HashMap<String, Object>();
VCFIndelAttributes.recordDepth(prefix,getConsensusVariantCount(),getAllVariantCount(),getCoverage(),attr);
VCFIndelAttributes.recordAvMM(prefix,getAvConsensusMismatches(),getAvRefMismatches(),attr);
VCFIndelAttributes.recordAvMapQ(prefix,getAvConsensusMapq(),getAvRefMapq(),attr);
VCFIndelAttributes.recordNQSMMRate(prefix,getNQSConsensusMMRate(),getNQSRefMMRate(),attr);
VCFIndelAttributes.recordNQSAvQ(prefix,getNQSConsensusAvQual(),getNQSRefAvQual(),attr);
PrimitivePair.Int strand_cons = getConsensusStrandCounts();
PrimitivePair.Int strand_ref = getRefStrandCounts();
VCFIndelAttributes.recordStrandCounts(prefix,strand_cons.first,strand_cons.second,strand_ref.first,strand_ref.second,attr);
return attr;
}
}
interface IndelListener {
public void addObservation(int pos, IndelVariant.Type t, String bases, ExpandedSAMRecord r);
}
class WindowContext implements IndelListener {
private Set<ExpandedSAMRecord> reads;
private long start=0; // where the window starts on the ref, 1-based
private CircularArray< List< IndelVariant > > indels;
private List<IndelVariant> emptyIndelList = new ArrayList<IndelVariant>();
public WindowContext(long start, int length) {
this.start = start;
indels = new CircularArray< List<IndelVariant> >(length);
// reads = new LinkedList<SAMRecord>();
reads = new HashSet<ExpandedSAMRecord>();
}
/** Returns 1-based reference start position of the interval this object keeps context for.
*
* @return
*/
public long getStart() { return start; }
/** Returns 1-based reference stop position (inclusive) of the interval this object keeps context for.
*
* @return
*/
public long getStop() { return start + indels.length() - 1; }
/** Resets reference start position to 0 and clears the context.
*
*/
public void clear() {
start = 0;
reads.clear();
indels.clear();
}
/**
* Returns true if any indel observations are present in the specified interval
* [begin,end] (1-based, inclusive). Interval can be partially of fully outside of the
* current context window: positions outside of the window will be ignored.
* @param begin
* @param end
*/
public boolean hasIndelsInInterval(long begin, long end) {
for ( long k = Math.max(start,begin); k < Math.min(getStop(),end); k++ ) {
if ( indelsAt(k) != emptyIndelList ) return true;
}
return false;
}
public Set<ExpandedSAMRecord> getReads() { return reads; }
/** Returns the number of reads spanning over the specified reference position
* (regardless of whether they have a base or indel at that specific location).
* The second argument controls whether to count with indels in mind (this is relevant for insertions only,
* deletions do not require any special treatment since they occupy non-zero length on the ref and since
* alignment can not start or end with a deletion). For insertions, note that, internally, we assign insertions
* to the reference position right after the actual event, and we count all events assigned to a given position.
* This count (reads with indels) should be contrasted to reads without indels, or more rigorously, reads
* that support the ref rather than the indel. Few special cases may occur here:
* 1) an alignment that ends (as per getAlignmentEnd()) right before the current position but has I as its
* last element: we have to count that read into the "coverage" at the current position for the purposes of indel
* assessment, as the indel in that read <i>will</i> be counted at the current position, so the total coverage
* should be consistent with that.
*/
/* NOT IMPLEMENTED: 2) alsignments that start exactly at the current position do <i>not</i> count for the purpose of insertion
* assessment since they do not contribute any evidence to either Ref or Alt=insertion hypothesis, <i>unless</i>
* the alignment starts with I (so that we do have evidence for an indel assigned to the current position and
* read should be counted). For deletions, reads starting at the current position should always be counted (as they
* show no deletion=ref).
* @param refPos position on the reference; must be within the bounds of the window
*/
public int coverageAt(final long refPos, boolean countForIndels) {
int cov = 0;
for ( ExpandedSAMRecord read : reads ) {
if ( read.getSAMRecord().getAlignmentStart() > refPos || read.getSAMRecord().getAlignmentEnd() < refPos ) {
if ( countForIndels && read.getSAMRecord().getAlignmentEnd() == refPos - 1) {
Cigar c = read.getSAMRecord().getCigar();
if ( c.getCigarElement(c.numCigarElements()-1).getOperator() == CigarOperator.I ) cov++;
}
continue;
}
cov++;
}
return cov;
}
/** Shifts current window to the right along the reference contig by the specified number of bases.
* The context will be updated accordingly (indels and reads that go out of scope will be dropped).
* @param offset
*/
public void shift(int offset) {
start += offset;
indels.shiftData(offset);
if ( indels.get(0) != null && indels.get(0).size() != 0 ) {
IndelVariant indel = indels.get(0).get(0);
System.out.println("WARNING: Indel(s) at first position in the window ("+refName+":"+start+"): currently not supported: "+
(indel.getType()==IndelVariant.Type.I?"+":"-")+indel.getBases()+"; read: "+indel.getReadSet().iterator().next().getSAMRecord().getReadName()+"; site ignored");
indels.get(0).clear();
// throw new StingException("Indel found at the first position ("+start+") after a shift was performed: currently not supported: "+
// (indel.getType()==IndelVariant.Type.I?"+":"-")+indel.getBases()+"; reads: "+indel.getReadSet().iterator().next().getSAMRecord().getReadName());
}
Iterator<ExpandedSAMRecord> read_iter = reads.iterator();
while ( read_iter.hasNext() ) {
ExpandedSAMRecord r = read_iter.next();
if ( r.getSAMRecord().getAlignmentEnd() < start ) { // discard reads and associated data that went out of scope
read_iter.remove();
}
}
}
public void add(SAMRecord read, byte [] ref) {
if ( read.getAlignmentStart() < start ) return; // silently ignore reads starting before the window start
ExpandedSAMRecord er = new ExpandedSAMRecord(read,ref,read.getAlignmentStart()-start,this);
//TODO duplicate records may actually indicate a problem with input bam file; throw an exception when the bug in CleanedReadInjector is fixed
if ( reads.contains(er)) return; // ignore duplicate records
reads.add(er);
}
public void addObservation(int pos, IndelVariant.Type type, String bases, ExpandedSAMRecord rec) {
List<IndelVariant> indelsAtSite;
try {
indelsAtSite = indels.get(pos);
} catch (IndexOutOfBoundsException e) {
SAMRecord r = rec.getSAMRecord();
System.out.println("Failed to add indel observation, probably out of coverage window bounds (trailing indel?):\nRead "+
r.getReadName()+": "+
"read length="+r.getReadLength()+"; cigar="+r.getCigarString()+"; start="+
r.getAlignmentStart()+"; end="+r.getAlignmentEnd()+"; window start="+getStart()+
"; window end="+getStop());
throw e;
}
if ( indelsAtSite == null ) {
indelsAtSite = new ArrayList<IndelVariant>();
indels.set(pos, indelsAtSite);
}
boolean found = false;
for ( IndelVariant v : indelsAtSite ) {
if ( ! v.equals(type, bases) ) continue;
v.addObservation(rec);
found = true;
break;
}
if ( ! found ) {
IndelVariant v = new IndelVariant(rec, type, bases);
indelsAtSite.add(v);
}
}
public List<IndelVariant> indelsAt( final long refPos ) {
List<IndelVariant> l = indels.get((int)( refPos - start ));
if ( l == null ) return emptyIndelList;
else return l;
}
}
class ExpandedSAMRecord {
private SAMRecord read;
private byte[] mismatch_flags;
private byte[] expanded_quals;
private int mms;
public ExpandedSAMRecord(SAMRecord r, byte [] ref, long offset, IndelListener l) {
read = r;
final long rStart = read.getAlignmentStart();
final long rStop = read.getAlignmentEnd();
final byte[] readBases = read.getReadString().toUpperCase().getBytes();
ref = new String(ref).toUpperCase().getBytes();
mismatch_flags = new byte[(int)(rStop-rStart+1)];
expanded_quals = new byte[(int)(rStop-rStart+1)];
// now let's extract indels:
Cigar c = read.getCigar();
final int nCigarElems = c.numCigarElements();
int posOnRead = 0;
int posOnRef = 0; // the chunk of reference ref[] that we have access to is aligned with the read:
// its start on the actual full reference contig is r.getAlignmentStart()
for ( int i = 0 ; i < nCigarElems ; i++ ) {
final CigarElement ce = c.getCigarElement(i);
IndelVariant.Type type = null;
String indel_bases = null;
int eventPosition = posOnRef;
switch(ce.getOperator()) {
case H: break; // hard clipped reads do not have clipped indel_bases in their sequence, so we just ignore the H element...
case I:
type = IndelVariant.Type.I;
indel_bases = read.getReadString().substring(posOnRead,posOnRead+ce.getLength());
// will increment position on the read below, there's no 'break' statement yet...
case S:
// here we also skip soft-clipped indel_bases on the read; according to SAM format specification,
// alignment start position on the reference points to where the actually aligned
// (not clipped) indel_bases go, so we do not need to increment reference position here
posOnRead += ce.getLength();
break;
case D:
type = IndelVariant.Type.D;
indel_bases = new String( ref, posOnRef, ce.getLength() );
for( int k = 0 ; k < ce.getLength(); k++, posOnRef++ ) mismatch_flags[posOnRef] = expanded_quals[posOnRef] = -1;
break;
case M:
for ( int k = 0; k < ce.getLength(); k++, posOnRef++, posOnRead++ ) {
if ( readBases[posOnRead] != ref[posOnRef] ) { // mismatch!
mms++;
mismatch_flags[posOnRef] = 1;
}
expanded_quals[posOnRef] = read.getBaseQualities()[posOnRead];
}
break; // advance along the gapless block in the alignment
default :
throw new IllegalArgumentException("Unexpected operator in cigar string: "+ce.getOperator());
}
if ( type == null ) continue; // element was not an indel, go grab next element...
// we got an indel if we are here...
if ( i == 0 ) logger.debug("Indel at the start of the read "+read.getReadName());
if ( i == nCigarElems - 1) logger.debug("Indel at the end of the read "+read.getReadName());
// note that here we will be assigning indels to the first deleted base or to the first
// base after insertion, not to the last base before the event!
l.addObservation((int)(offset+eventPosition), type, indel_bases, this);
}
}
public SAMRecord getSAMRecord() { return read; }
public byte [] getExpandedMMFlags() { return mismatch_flags; }
public byte [] getExpandedQuals() { return expanded_quals; }
public int getMMCount() { return mms; }
public boolean equals(Object o) {
if ( this == o ) return true;
if ( read == null ) return false;
if ( o instanceof SAMRecord ) return read.equals(o);
if ( o instanceof ExpandedSAMRecord ) return read.equals(((ExpandedSAMRecord)o).read);
return false;
}
}
}
class VCFIndelAttributes {
public static String DEPTH_INDEL_KEY = VCFConstants.ALLELE_COUNT_KEY;
public static String DEPTH_TOTAL_KEY = VCFConstants.DEPTH_KEY;
public static String MAPQ_KEY = "MQ";
public static String MM_KEY = "MM";
public static String NQS_MMRATE_KEY = "NQSMM";
public static String NQS_AVQ_KEY = "NQSBQ";
public static String STRAND_COUNT_KEY = "SC";
public static Set<VCFInfoHeaderLine> getAttributeHeaderLines(String prefix, String descr_prefix) {
Set<VCFInfoHeaderLine> lines = new HashSet<VCFInfoHeaderLine>();
lines.add(new VCFInfoHeaderLine(prefix+DEPTH_INDEL_KEY, 2, VCFHeaderLineType.Integer, descr_prefix+"# of reads supporting consensus indel/any indel at the site"));
lines.add(new VCFInfoHeaderLine(prefix+DEPTH_TOTAL_KEY, 1, VCFHeaderLineType.Integer, descr_prefix+"total coverage at the site"));
lines.add(new VCFInfoHeaderLine(prefix+MAPQ_KEY, 2, VCFHeaderLineType.Float, descr_prefix+"average mapping quality of consensus indel-supporting reads/reference-supporting reads"));
lines.add(new VCFInfoHeaderLine(prefix+MM_KEY, 2, VCFHeaderLineType.Float, descr_prefix+"average # of mismatches per consensus indel-supporting read/per reference-supporting read"));
lines.add(new VCFInfoHeaderLine(prefix+NQS_MMRATE_KEY, 2, VCFHeaderLineType.Float, descr_prefix+"Within NQS window: fraction of mismatching bases in consensus indel-supporting reads/in reference-supporting reads"));
lines.add(new VCFInfoHeaderLine(prefix+NQS_AVQ_KEY, 2, VCFHeaderLineType.Float, descr_prefix+"Within NQS window: average quality of bases from consensus indel-supporting reads/from reference-supporting reads"));
lines.add(new VCFInfoHeaderLine(prefix+STRAND_COUNT_KEY, 4, VCFHeaderLineType.Integer, descr_prefix+"strandness: counts of forward-/reverse-aligned indel-supporting reads / forward-/reverse-aligned reference supporting reads"));
return lines;
}
public static Map<String,Object> recordStrandCounts(String prefix, int cnt_cons_fwd, int cnt_cons_rev, int cnt_ref_fwd, int cnt_ref_rev, Map<String,Object> attrs) {
attrs.put(prefix+STRAND_COUNT_KEY, new Integer[] {cnt_cons_fwd, cnt_cons_rev, cnt_ref_fwd, cnt_ref_rev} );
return attrs;
}
public static Map<String,Object> recordDepth(String prefix, int cnt_cons, int cnt_indel, int cnt_total, Map<String,Object> attrs) {
attrs.put(prefix+DEPTH_INDEL_KEY, new Integer[] {cnt_cons, cnt_indel} );
attrs.put(prefix+DEPTH_TOTAL_KEY, cnt_total);
return attrs;
}
public static Map<String,Object> recordAvMapQ(String prefix, double cons, double ref, Map<String,Object> attrs) {
attrs.put(prefix+MAPQ_KEY, new Float[] {(float)cons, (float)ref} );
return attrs;
}
public static Map<String,Object> recordAvMM(String prefix, double cons, double ref, Map<String,Object> attrs) {
attrs.put(prefix+MM_KEY, new Float[] {(float)cons, (float)ref} );
return attrs;
}
public static Map<String,Object> recordNQSMMRate(String prefix, double cons, double ref, Map<String,Object> attrs) {
attrs.put(prefix+NQS_MMRATE_KEY, new Float[] {(float)cons, (float)ref} );
return attrs;
}
public static Map<String,Object> recordNQSAvQ(String prefix, double cons, double ref, Map<String,Object> attrs) {
attrs.put(prefix+NQS_AVQ_KEY, new Float[] {(float)cons, (float)ref} );
return attrs;
}
}
| false | true | public Integer map(ReferenceContext ref, SAMRecord read, ReadMetaDataTracker metaDataTracker) {
// if ( read.getReadName().equals("428EFAAXX090610:2:36:1384:639#0") ) System.out.println("GOT READ");
if ( DEBUG ) {
// System.out.println("DEBUG>> read at "+ read.getAlignmentStart()+"-"+read.getAlignmentEnd()+
// "("+read.getCigarString()+")");
if ( read.getDuplicateReadFlag() ) System.out.println("DEBUG>> Duplicated read (IGNORED)");
}
if ( AlignmentUtils.isReadUnmapped(read) ||
read.getDuplicateReadFlag() ||
read.getNotPrimaryAlignmentFlag() ||
read.getMappingQuality() == 0 ) {
return 0; // we do not need those reads!
}
if ( read.getReferenceIndex() != currentContigIndex ) {
// we just jumped onto a new contig
if ( DEBUG ) System.out.println("DEBUG>>> Moved to contig "+read.getReferenceName());
if ( read.getReferenceIndex() < currentContigIndex ) // paranoidal
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName()+": contig is out of order; input BAM file is unsorted");
// print remaining indels from the previous contig (if any);
if ( call_somatic ) emit_somatic(1000000000, true);
else emit(1000000000,true);
currentContigIndex = read.getReferenceIndex();
currentPosition = read.getAlignmentStart();
refName = new String(read.getReferenceName());
location = GenomeLocParser.setContig(location,refName);
contigLength = GenomeLocParser.getContigInfo(refName).getSequenceLength();
outOfContigUserWarned = false;
normal_context.clear(); // reset coverage window; this will also set reference position to 0
if ( call_somatic) tumor_context.clear();
refBases = new String(refData.getReference().getSequence(read.getReferenceName()).getBases()).toUpperCase().getBytes();
}
// we have reset the window to the new contig if it was required and emitted everything we collected
// on a previous contig. At this point we are guaranteed that we are set up properly for working
// with the contig of the current read.
// NOTE: all the sanity checks and error messages below use normal_context only. We make sure that normal_context and
// tumor_context are synchronized exactly (windows are always shifted together by emit_somatic), so it's safe
if ( read.getAlignmentStart() < currentPosition ) // oops, read out of order?
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName() +" out of order on the contig\n"+
"Read starts at "+refName+":"+read.getAlignmentStart()+"; last read seen started at "+refName+":"+currentPosition
+"\nLast read was: "+lastRead.getReadName()+" RG="+lastRead.getAttribute("RG")+" at "+lastRead.getAlignmentStart()+"-"
+lastRead.getAlignmentEnd()+" cigar="+lastRead.getCigarString());
currentPosition = read.getAlignmentStart();
lastRead = read;
if ( read.getAlignmentEnd() > contigLength ) {
if ( ! outOfContigUserWarned ) {
System.out.println("WARNING: Reads aligned past contig length on "+ location.getContig()+"; all such reads will be skipped");
outOfContigUserWarned = true;
}
return 0;
}
long alignmentEnd = read.getAlignmentEnd();
Cigar c = read.getCigar();
int lastNonClippedElement = 0; // reverse offset to the last unclipped element
CigarOperator op = null;
// moving backwards from the end of the cigar, skip trailing S or H cigar elements:
do {
lastNonClippedElement++;
op = c.getCigarElement( c.numCigarElements()-lastNonClippedElement ).getOperator();
} while ( op == CigarOperator.H || op == CigarOperator.S );
// now op is the last non-S/H operator in the cigar.
// a little trick here: we want to make sure that current read completely fits into the current
// window so that we can accumulate indel observations over the whole length of the read.
// The ::getAlignmentEnd() method returns the last position on the reference where bases from the
// read actually match (M cigar elements). After our cleaning procedure, we can have reads that end
// with I element, which is not gonna be counted into alignment length on the reference. On the other hand,
// in this program we assign insertions, internally, to the first base *after* the insertion position.
// Hence, we have to make sure that that extra base is already in the window or we will get IndexOutOfBounds.
if ( op == CigarOperator.I) alignmentEnd++;
if ( alignmentEnd > normal_context.getStop()) {
// we don't emit anything until we reach a read that does not fit into the current window.
// At that point we try shifting the window to the start of that read (or reasonably close) and emit everything prior to
// that position. This is legitimate, since the reads are sorted and we are not gonna see any more coverage at positions
// below the current read's start.
// Clearly, we assume here that window is large enough to accomodate any single read, so simply shifting
// the window to around the read's start will ensure that the read fits...
if ( DEBUG) System.out.println("DEBUG>> Window at "+normal_context.getStart()+"-"+normal_context.getStop()+", read at "+
read.getAlignmentStart()+": trying to emit and shift" );
if ( call_somatic ) emit_somatic( read.getAlignmentStart(), false );
else emit( read.getAlignmentStart(), false );
// let's double check now that the read fits after the shift
if ( read.getAlignmentEnd() > normal_context.getStop()) {
// ooops, looks like the read does not fit into the window even after the latter was shifted!!
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName()+": out of coverage window bounds. Probably window is too small.\n"+
"Read length="+read.getReadLength()+"; cigar="+read.getCigarString()+"; start="+
read.getAlignmentStart()+"; end="+read.getAlignmentEnd()+
"; window start (after trying to accomodate the read)="+normal_context.getStart()+
"; window end="+normal_context.getStop());
}
}
if ( call_somatic ) {
List<String> tags = getToolkit().getReaderIDForRead(read).getTags();
boolean assigned = false;
for ( String s : tags ) {
if ( "NORMAL".equals(s.toUpperCase()) ) {
normal_context.add(read,ref.getBases());
assigned = true;
break;
}
if ( "TUMOR".equals(s.toUpperCase()) ) {
tumor_context.add(read,ref.getBases());
assigned = true;
break;
}
}
if ( ! assigned )
throw new StingException("Read "+read.getReadName()+" from "+getToolkit().getSourceFileForReaderID(getToolkit().getReaderIDForRead(read))+
"has no Normal/Tumor tag associated with it");
// String rg = (String)read.getAttribute("RG");
// if ( rg == null )
// throw new UserException.MalformedBam(read, "Read "+read.getReadName()+" has no read group in merged stream. RG is required for somatic calls.");
// if ( normalReadGroups.contains(rg) ) {
// normal_context.add(read,ref.getBases());
// } else if ( tumorReadGroups.contains(rg) ) {
// tumor_context.add(read,ref.getBases());
// } else {
// throw new UserException.MalformedBam(read, "Unrecognized read group in merged stream: "+rg);
// }
if ( tumor_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+tumor_context.getStart()+'-'+tumor_context.getStop()+" in tumor sample. The whole window will be dropped.");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+" in normal sample. The whole window will be dropped");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
} else {
normal_context.add(read, ref.getBases());
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+". The whole window will be dropped");
normal_context.shift(WINDOW_SIZE);
}
}
return 1;
}
| public Integer map(ReferenceContext ref, SAMRecord read, ReadMetaDataTracker metaDataTracker) {
// if ( read.getReadName().equals("428EFAAXX090610:2:36:1384:639#0") ) System.out.println("GOT READ");
if ( DEBUG ) {
// System.out.println("DEBUG>> read at "+ read.getAlignmentStart()+"-"+read.getAlignmentEnd()+
// "("+read.getCigarString()+")");
if ( read.getDuplicateReadFlag() ) System.out.println("DEBUG>> Duplicated read (IGNORED)");
}
if ( AlignmentUtils.isReadUnmapped(read) ||
read.getDuplicateReadFlag() ||
read.getNotPrimaryAlignmentFlag() ||
read.getMappingQuality() == 0 ) {
return 0; // we do not need those reads!
}
if ( read.getReferenceIndex() != currentContigIndex ) {
// we just jumped onto a new contig
if ( DEBUG ) System.out.println("DEBUG>>> Moved to contig "+read.getReferenceName());
if ( read.getReferenceIndex() < currentContigIndex ) // paranoidal
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName()+": contig is out of order; input BAM file is unsorted");
// print remaining indels from the previous contig (if any);
if ( call_somatic ) emit_somatic(1000000000, true);
else emit(1000000000,true);
currentContigIndex = read.getReferenceIndex();
currentPosition = read.getAlignmentStart();
refName = new String(read.getReferenceName());
location = GenomeLocParser.setContig(location,refName);
contigLength = GenomeLocParser.getContigInfo(refName).getSequenceLength();
outOfContigUserWarned = false;
normal_context.clear(); // reset coverage window; this will also set reference position to 0
if ( call_somatic) tumor_context.clear();
refBases = new String(refData.getReference().getSequence(read.getReferenceName()).getBases()).toUpperCase().getBytes();
}
// we have reset the window to the new contig if it was required and emitted everything we collected
// on a previous contig. At this point we are guaranteed that we are set up properly for working
// with the contig of the current read.
// NOTE: all the sanity checks and error messages below use normal_context only. We make sure that normal_context and
// tumor_context are synchronized exactly (windows are always shifted together by emit_somatic), so it's safe
if ( read.getAlignmentStart() < currentPosition ) // oops, read out of order?
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName() +" out of order on the contig\n"+
"Read starts at "+refName+":"+read.getAlignmentStart()+"; last read seen started at "+refName+":"+currentPosition
+"\nLast read was: "+lastRead.getReadName()+" RG="+lastRead.getAttribute("RG")+" at "+lastRead.getAlignmentStart()+"-"
+lastRead.getAlignmentEnd()+" cigar="+lastRead.getCigarString());
currentPosition = read.getAlignmentStart();
lastRead = read;
if ( read.getAlignmentEnd() > contigLength ) {
if ( ! outOfContigUserWarned ) {
System.out.println("WARNING: Reads aligned past contig length on "+ location.getContig()+"; all such reads will be skipped");
outOfContigUserWarned = true;
}
return 0;
}
long alignmentEnd = read.getAlignmentEnd();
Cigar c = read.getCigar();
int lastNonClippedElement = 0; // reverse offset to the last unclipped element
CigarOperator op = null;
// moving backwards from the end of the cigar, skip trailing S or H cigar elements:
do {
lastNonClippedElement++;
op = c.getCigarElement( c.numCigarElements()-lastNonClippedElement ).getOperator();
} while ( op == CigarOperator.H || op == CigarOperator.S );
// now op is the last non-S/H operator in the cigar.
// a little trick here: we want to make sure that current read completely fits into the current
// window so that we can accumulate indel observations over the whole length of the read.
// The ::getAlignmentEnd() method returns the last position on the reference where bases from the
// read actually match (M cigar elements). After our cleaning procedure, we can have reads that end
// with I element, which is not gonna be counted into alignment length on the reference. On the other hand,
// in this program we assign insertions, internally, to the first base *after* the insertion position.
// Hence, we have to make sure that that extra base is already in the window or we will get IndexOutOfBounds.
if ( op == CigarOperator.I) alignmentEnd++;
if ( alignmentEnd > normal_context.getStop()) {
// we don't emit anything until we reach a read that does not fit into the current window.
// At that point we try shifting the window to the start of that read (or reasonably close) and emit everything prior to
// that position. This is legitimate, since the reads are sorted and we are not gonna see any more coverage at positions
// below the current read's start.
// Clearly, we assume here that window is large enough to accomodate any single read, so simply shifting
// the window to around the read's start will ensure that the read fits...
if ( DEBUG) System.out.println("DEBUG>> Window at "+normal_context.getStart()+"-"+normal_context.getStop()+", read at "+
read.getAlignmentStart()+": trying to emit and shift" );
if ( call_somatic ) emit_somatic( read.getAlignmentStart(), false );
else emit( read.getAlignmentStart(), false );
// let's double check now that the read fits after the shift
if ( read.getAlignmentEnd() > normal_context.getStop()) {
// ooops, looks like the read does not fit into the window even after the latter was shifted!!
throw new UserException.BadArgumentValue("window_size", "Read "+read.getReadName()+": out of coverage window bounds. Probably window is too small, so increase the value of the window_size argument.\n"+
"Read length="+read.getReadLength()+"; cigar="+read.getCigarString()+"; start="+
read.getAlignmentStart()+"; end="+read.getAlignmentEnd()+
"; window start (after trying to accomodate the read)="+normal_context.getStart()+"; window end="+normal_context.getStop());
}
}
if ( call_somatic ) {
List<String> tags = getToolkit().getReaderIDForRead(read).getTags();
boolean assigned = false;
for ( String s : tags ) {
if ( "NORMAL".equals(s.toUpperCase()) ) {
normal_context.add(read,ref.getBases());
assigned = true;
break;
}
if ( "TUMOR".equals(s.toUpperCase()) ) {
tumor_context.add(read,ref.getBases());
assigned = true;
break;
}
}
if ( ! assigned )
throw new StingException("Read "+read.getReadName()+" from "+getToolkit().getSourceFileForReaderID(getToolkit().getReaderIDForRead(read))+
"has no Normal/Tumor tag associated with it");
// String rg = (String)read.getAttribute("RG");
// if ( rg == null )
// throw new UserException.MalformedBam(read, "Read "+read.getReadName()+" has no read group in merged stream. RG is required for somatic calls.");
// if ( normalReadGroups.contains(rg) ) {
// normal_context.add(read,ref.getBases());
// } else if ( tumorReadGroups.contains(rg) ) {
// tumor_context.add(read,ref.getBases());
// } else {
// throw new UserException.MalformedBam(read, "Unrecognized read group in merged stream: "+rg);
// }
if ( tumor_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+tumor_context.getStart()+'-'+tumor_context.getStop()+" in tumor sample. The whole window will be dropped.");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+" in normal sample. The whole window will be dropped");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
} else {
normal_context.add(read, ref.getBases());
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+". The whole window will be dropped");
normal_context.shift(WINDOW_SIZE);
}
}
return 1;
}
|
diff --git a/src/de/ub0r/android/andGMXsms/Connector.java b/src/de/ub0r/android/andGMXsms/Connector.java
index a6be865a..41f842dd 100644
--- a/src/de/ub0r/android/andGMXsms/Connector.java
+++ b/src/de/ub0r/android/andGMXsms/Connector.java
@@ -1,382 +1,387 @@
package de.ub0r.android.andGMXsms;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Message;
/**
* AsyncTask to manage IO to GMX API.
*
* @author flx
*/
public class Connector extends AsyncTask<String, Boolean, Boolean> {
/** Dialog ID. */
public static final int DIALOG_IO = 0;
/** Target host. */
private static final String TARGET_HOST = "app0.wr-gmbh.de";
// private static final String TARGET_HOST = "app5.wr-gmbh.de";
/** Target path on host. */
private static final String TARGET_PATH = "/WRServer/WRServer.dll/WR";
/** Target mime encoding. */
private static final String TARGET_ENCODING = "wr-cs";
/** Target mime type. */
private static final String TARGET_CONTENT = "text/plain";
/** HTTP Useragent. */
private static final String TARGET_AGENT = "Mozilla/3.0 (compatible)";
/** Target version of protocol. */
private static final String TARGET_PROTOVERSION = "1.13.03";
/** Max Buffer size. */
private static final int MAX_BUFSIZE = 4096;
/** SMS DB: address. */
private static final String ADDRESS = "address";
/** SMS DB: person. */
// private static final String PERSON = "person";
/** SMS DB: date. */
// private static final String DATE = "date";
/** SMS DB: read. */
private static final String READ = "read";
/** SMS DB: status. */
// private static final String STATUS = "status";
/** SMS DB: type. */
private static final String TYPE = "type";
/** SMS DB: body. */
private static final String BODY = "body";
/** SMS DB: type - sent. */
private static final int MESSAGE_TYPE_SENT = 2;
/** ID of text in array. */
public static final int ID_TEXT = 0;
/** ID of receiver in array. */
public static final int ID_TO = 1;
/** receiver. */
private String to;
/** text. */
private String text;
/**
* Write key,value to StringBuffer.
*
* @param buffer
* buffer
* @param key
* key
* @param value
* value
*/
private static void writePair(final StringBuffer buffer, final String key,
final String value) {
buffer.append(key);
buffer.append('=');
buffer.append(value.replace("\\", "\\\\").replace(">", "\\>").replace(
"<", "\\<"));
buffer.append("\\p");
}
/**
* Create default data hashtable.
*
* @param packetName
* packetName
* @param packetVersion
* packetVersion
* @return Hashtable filled with customer_id and password.
*/
private static StringBuffer openBuffer(final String packetName,
final String packetVersion) {
StringBuffer ret = new StringBuffer();
ret.append("<WR TYPE=\"RQST\" NAME=\"");
ret.append(packetName);
ret.append("\" VER=\"");
ret.append(packetVersion);
ret.append("\" PROGVER=\"");
ret.append(TARGET_PROTOVERSION);
ret.append("\">");
writePair(ret, "customer_id", AndGMXsms.prefsUser);
writePair(ret, "password", AndGMXsms.prefsPassword);
return ret;
}
/**
* Close Buffer.
*
* @param buffer
* buffer
* @return buffer
*/
private static StringBuffer closeBuffer(final StringBuffer buffer) {
buffer.append("</WR>");
return buffer;
}
/**
* Send data.
*
* @param packetData
* packetData
* @return successful?
*/
private boolean sendData(final StringBuffer packetData) {
try {
// get Connection
HttpURLConnection c = (HttpURLConnection) (new URL("http://"
+ TARGET_HOST + TARGET_PATH)).openConnection();
// set prefs
c.setRequestProperty("User-Agent", TARGET_AGENT);
c.setRequestProperty("Content-Encoding", TARGET_ENCODING);
c.setRequestProperty("Content-Type", TARGET_CONTENT);
c.setRequestMethod("POST");
c.setDoOutput(true);
// push post data
OutputStream os = c.getOutputStream();
os.write(packetData.toString().getBytes());
os.close();
os = null;
// send data
int resp = c.getResponseCode();
if (resp != HttpURLConnection.HTTP_OK) {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_http + resp)).sendToTarget();
}
// read received data
int bufsize = c.getHeaderFieldInt("Content-Length", -1);
StringBuffer data = null;
if (bufsize > 0) {
data = new StringBuffer();
InputStream is = c.getInputStream();
byte[] buf;
if (bufsize > MAX_BUFSIZE) {
buf = new byte[MAX_BUFSIZE];
} else {
buf = new byte[bufsize];
}
int read = is.read(buf, 0, buf.length);
int count = read;
while (read > 0) {
data.append(new String(buf, 0, read, "ASCII"));
read = is.read(buf, 0, buf.length);
count += read;
}
buf = null;
is.close();
is = null;
String resultString = data.toString();
if (resultString.startsWith("The truth")) {
// wrong data sent!
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_server)
+ resultString).sendToTarget();
return false;
}
// get result code
int resultIndex = resultString.indexOf("rslt=");
if (resultIndex < 0) {
return false;
}
+ int resultIndexEnd = resultString.indexOf('\\', resultIndex);
String resultValue = resultString.substring(resultIndex + 5,
- resultIndex + 6);
+ resultIndexEnd);
+ if (resultIndexEnd < 0) {
+ resultIndexEnd = resultIndex + 7;
+ }
String outp = resultString.substring(resultIndex).replace(
"\\p", "\n");
outp = outp.replace("</WR>", "");
if (!resultValue.equals("0")) {
try {
int rslt = Integer.parseInt(resultValue);
switch (rslt) {
- case 11: // 11 wrong pw
- Message.obtain(
- AndGMXsms.me.messageHandler,
- AndGMXsms.MESSAGE_LOG,
- AndGMXsms.me.getResources().getString(
- R.string.log_error_pw))
- .sendToTarget();
- break;
- case 25: // 25 wrong mail/pw
+ case 11: // 11 wrong mail/pw
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_mail))
.sendToTarget();
+ break;
+ // case 25: // 25 wrong mail/pw
+ // Message.obtain(
+ // AndGMXsms.me.messageHandler,
+ // AndGMXsms.MESSAGE_LOG,
+ // AndGMXsms.me.getResources().getString(
+ // R.string.log_error_mail))
+ // .sendToTarget();
default:
Message.obtain(AndGMXsms.me.messageHandler,
- AndGMXsms.MESSAGE_LOG, outp).sendToTarget();
+ AndGMXsms.MESSAGE_LOG, outp + "#" + rslt)
+ .sendToTarget();
}
} catch (Exception e) {
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG, e.toString())
.sendToTarget();
}
return false;
} else {
// result: ok
// fetch additional info
resultIndex = outp.indexOf("free_rem_month=");
if (resultIndex > 0) {
int resIndex = outp.indexOf("\n", resultIndex);
String freecount = outp.substring(resultIndex
+ "free_rem_month=".length(), resIndex);
resultIndex = outp.indexOf("free_max_month=");
if (resultIndex > 0) {
resIndex = outp.indexOf("\n", resultIndex);
freecount += " / "
+ outp.substring(resultIndex
+ "free_max_month=".length(),
resIndex);
}
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_FREECOUNT, freecount)
.sendToTarget();
}
}
} else {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_http_header_missing))
.sendToTarget();
return false;
}
} catch (IOException e) {
Message.obtain(AndGMXsms.me.messageHandler, AndGMXsms.MESSAGE_LOG,
e.toString()).sendToTarget();
return false;
}
return true;
}
/**
* Get free sms count.
*
* @return ok?
*/
private boolean getFree() {
return this
.sendData(closeBuffer(openBuffer("GET_SMS_CREDITS", "1.00")));
}
/**
* Send sms.
*
* @return ok?
*/
private boolean send() {
StringBuffer packetData = openBuffer("SEND_SMS", "1.01");
// fill buffer
writePair(packetData, "sms_text", this.text);
// table: <id>, <name>, <number>
String receivers = "<TBL ROWS=\"1\" COLS=\"3\">"
+ "receiver_id\\;receiver_name\\;receiver_number\\;"
+ "1\\;null\\;" + this.to + "\\;" + "</TBL>";
writePair(packetData, "receivers", receivers);
writePair(packetData, "send_option", "sms");
writePair(packetData, "sms_sender", AndGMXsms.prefsSender);
// if date!='': data['send_date'] = date
// push data
if (!this.sendData(closeBuffer(packetData))) {
// failed!
Message.obtain(AndGMXsms.me.messageHandler, AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(R.string.log_error))
.sendToTarget();
return false;
} else {
// result: ok
Composer.reset();
// save sms to content://sms/sent
ContentValues values = new ContentValues();
values.put(ADDRESS, this.to);
// values.put(DATE, "1237080365055");
values.put(READ, 1);
// values.put(STATUS, -1);
values.put(TYPE, MESSAGE_TYPE_SENT);
values.put(BODY, this.text);
// Uri inserted =
AndGMXsms.me.getContentResolver().insert(
Uri.parse("content://sms/sent"), values);
return true;
}
}
/**
* Run IO in background.
*
* @param textTo
* (text,receiver)
* @return ok?
*/
@Override
protected final Boolean doInBackground(final String... textTo) {
boolean ret = false;
if (textTo == null || textTo[0] == null) {
this.publishProgress((Boolean) null);
ret = this.getFree();
} else if (textTo.length >= 2) {
this.text = textTo[ID_TEXT];
this.to = textTo[ID_TO];
this.publishProgress((Boolean) null);
ret = this.send();
}
return new Boolean(ret);
}
/**
* Update progress. Only ran once on startup to display progress dialog.
*
* @param progress
* finished?
*/
@Override
protected final void onProgressUpdate(final Boolean... progress) {
if (this.to == null) {
AndGMXsms.dialogString = AndGMXsms.me.getResources().getString(
R.string.log_update);
AndGMXsms.dialog = ProgressDialog.show(AndGMXsms.me, null,
AndGMXsms.dialogString, true);
} else {
AndGMXsms.dialogString = AndGMXsms.me.getResources().getString(
R.string.log_sending)
+ " (" + this.to + ")";
AndGMXsms.dialog = ProgressDialog.show(AndGMXsms.me, null,
AndGMXsms.dialogString, true);
}
}
/**
* Push data back to GUI. Close progress dialog.
*
* @param result
* result
*/
@Override
protected final void onPostExecute(final Boolean result) {
AndGMXsms.dialogString = null;
if (AndGMXsms.dialog != null) {
try {
AndGMXsms.dialog.dismiss();
AndGMXsms.dialog = null;
} catch (Exception e) {
// nothing to do
}
}
}
}
| false | true | private boolean sendData(final StringBuffer packetData) {
try {
// get Connection
HttpURLConnection c = (HttpURLConnection) (new URL("http://"
+ TARGET_HOST + TARGET_PATH)).openConnection();
// set prefs
c.setRequestProperty("User-Agent", TARGET_AGENT);
c.setRequestProperty("Content-Encoding", TARGET_ENCODING);
c.setRequestProperty("Content-Type", TARGET_CONTENT);
c.setRequestMethod("POST");
c.setDoOutput(true);
// push post data
OutputStream os = c.getOutputStream();
os.write(packetData.toString().getBytes());
os.close();
os = null;
// send data
int resp = c.getResponseCode();
if (resp != HttpURLConnection.HTTP_OK) {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_http + resp)).sendToTarget();
}
// read received data
int bufsize = c.getHeaderFieldInt("Content-Length", -1);
StringBuffer data = null;
if (bufsize > 0) {
data = new StringBuffer();
InputStream is = c.getInputStream();
byte[] buf;
if (bufsize > MAX_BUFSIZE) {
buf = new byte[MAX_BUFSIZE];
} else {
buf = new byte[bufsize];
}
int read = is.read(buf, 0, buf.length);
int count = read;
while (read > 0) {
data.append(new String(buf, 0, read, "ASCII"));
read = is.read(buf, 0, buf.length);
count += read;
}
buf = null;
is.close();
is = null;
String resultString = data.toString();
if (resultString.startsWith("The truth")) {
// wrong data sent!
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_server)
+ resultString).sendToTarget();
return false;
}
// get result code
int resultIndex = resultString.indexOf("rslt=");
if (resultIndex < 0) {
return false;
}
String resultValue = resultString.substring(resultIndex + 5,
resultIndex + 6);
String outp = resultString.substring(resultIndex).replace(
"\\p", "\n");
outp = outp.replace("</WR>", "");
if (!resultValue.equals("0")) {
try {
int rslt = Integer.parseInt(resultValue);
switch (rslt) {
case 11: // 11 wrong pw
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_pw))
.sendToTarget();
break;
case 25: // 25 wrong mail/pw
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_mail))
.sendToTarget();
default:
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG, outp).sendToTarget();
}
} catch (Exception e) {
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG, e.toString())
.sendToTarget();
}
return false;
} else {
// result: ok
// fetch additional info
resultIndex = outp.indexOf("free_rem_month=");
if (resultIndex > 0) {
int resIndex = outp.indexOf("\n", resultIndex);
String freecount = outp.substring(resultIndex
+ "free_rem_month=".length(), resIndex);
resultIndex = outp.indexOf("free_max_month=");
if (resultIndex > 0) {
resIndex = outp.indexOf("\n", resultIndex);
freecount += " / "
+ outp.substring(resultIndex
+ "free_max_month=".length(),
resIndex);
}
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_FREECOUNT, freecount)
.sendToTarget();
}
}
} else {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_http_header_missing))
.sendToTarget();
return false;
}
} catch (IOException e) {
Message.obtain(AndGMXsms.me.messageHandler, AndGMXsms.MESSAGE_LOG,
e.toString()).sendToTarget();
return false;
}
return true;
}
| private boolean sendData(final StringBuffer packetData) {
try {
// get Connection
HttpURLConnection c = (HttpURLConnection) (new URL("http://"
+ TARGET_HOST + TARGET_PATH)).openConnection();
// set prefs
c.setRequestProperty("User-Agent", TARGET_AGENT);
c.setRequestProperty("Content-Encoding", TARGET_ENCODING);
c.setRequestProperty("Content-Type", TARGET_CONTENT);
c.setRequestMethod("POST");
c.setDoOutput(true);
// push post data
OutputStream os = c.getOutputStream();
os.write(packetData.toString().getBytes());
os.close();
os = null;
// send data
int resp = c.getResponseCode();
if (resp != HttpURLConnection.HTTP_OK) {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_http + resp)).sendToTarget();
}
// read received data
int bufsize = c.getHeaderFieldInt("Content-Length", -1);
StringBuffer data = null;
if (bufsize > 0) {
data = new StringBuffer();
InputStream is = c.getInputStream();
byte[] buf;
if (bufsize > MAX_BUFSIZE) {
buf = new byte[MAX_BUFSIZE];
} else {
buf = new byte[bufsize];
}
int read = is.read(buf, 0, buf.length);
int count = read;
while (read > 0) {
data.append(new String(buf, 0, read, "ASCII"));
read = is.read(buf, 0, buf.length);
count += read;
}
buf = null;
is.close();
is = null;
String resultString = data.toString();
if (resultString.startsWith("The truth")) {
// wrong data sent!
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_server)
+ resultString).sendToTarget();
return false;
}
// get result code
int resultIndex = resultString.indexOf("rslt=");
if (resultIndex < 0) {
return false;
}
int resultIndexEnd = resultString.indexOf('\\', resultIndex);
String resultValue = resultString.substring(resultIndex + 5,
resultIndexEnd);
if (resultIndexEnd < 0) {
resultIndexEnd = resultIndex + 7;
}
String outp = resultString.substring(resultIndex).replace(
"\\p", "\n");
outp = outp.replace("</WR>", "");
if (!resultValue.equals("0")) {
try {
int rslt = Integer.parseInt(resultValue);
switch (rslt) {
case 11: // 11 wrong mail/pw
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_mail))
.sendToTarget();
break;
// case 25: // 25 wrong mail/pw
// Message.obtain(
// AndGMXsms.me.messageHandler,
// AndGMXsms.MESSAGE_LOG,
// AndGMXsms.me.getResources().getString(
// R.string.log_error_mail))
// .sendToTarget();
default:
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG, outp + "#" + rslt)
.sendToTarget();
}
} catch (Exception e) {
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG, e.toString())
.sendToTarget();
}
return false;
} else {
// result: ok
// fetch additional info
resultIndex = outp.indexOf("free_rem_month=");
if (resultIndex > 0) {
int resIndex = outp.indexOf("\n", resultIndex);
String freecount = outp.substring(resultIndex
+ "free_rem_month=".length(), resIndex);
resultIndex = outp.indexOf("free_max_month=");
if (resultIndex > 0) {
resIndex = outp.indexOf("\n", resultIndex);
freecount += " / "
+ outp.substring(resultIndex
+ "free_max_month=".length(),
resIndex);
}
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_FREECOUNT, freecount)
.sendToTarget();
}
}
} else {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_http_header_missing))
.sendToTarget();
return false;
}
} catch (IOException e) {
Message.obtain(AndGMXsms.me.messageHandler, AndGMXsms.MESSAGE_LOG,
e.toString()).sendToTarget();
return false;
}
return true;
}
|
diff --git a/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMDownload.java b/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMDownload.java
index 2c778e87..d6345fe7 100644
--- a/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMDownload.java
+++ b/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMDownload.java
@@ -1,270 +1,275 @@
/* Copyright (c) 2013 OpenPlans. All rights reserved.
* This code is licensed under the BSD New License, available at the root
* application directory.
*/
package org.geogit.osm.cli.commands;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.geogit.api.GeoGIT;
import org.geogit.api.Ref;
import org.geogit.api.RevCommit;
import org.geogit.api.SymRef;
import org.geogit.api.plumbing.RefParse;
import org.geogit.api.porcelain.BranchCreateOp;
import org.geogit.api.porcelain.CheckoutOp;
import org.geogit.api.porcelain.LogOp;
import org.geogit.cli.AbstractCommand;
import org.geogit.cli.CLICommand;
import org.geogit.cli.GeogitCLI;
import org.geogit.osm.internal.AddOSMLogEntry;
import org.geogit.osm.internal.EmptyOSMDownloadException;
import org.geogit.osm.internal.Mapping;
import org.geogit.osm.internal.OSMDownloadReport;
import org.geogit.osm.internal.OSMImportOp;
import org.geogit.osm.internal.OSMLogEntry;
import org.geogit.osm.internal.ReadOSMFilterFile;
import org.geogit.osm.internal.ReadOSMLogEntries;
import org.geogit.osm.internal.WriteOSMFilterFile;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
/**
* Imports data from OSM using the Overpass API
*
* Data is filtered using an Overpass QL filter.
*
* If the --update modifier is used, it updates previously imported OSM data, connecting again to
* the Overpass API
*
* It reuses the filter from the last import that can be reached from the the current branch
*
* WARNING: The current update mechanism is not smart, since it downloads all data, not just the
* elements modified/added since the last import (which is stored on the OSM log file)
*
*/
@Parameters(commandNames = "download", commandDescription = "Download OpenStreetMap data")
public class OSMDownload extends AbstractCommand implements CLICommand {
private static final String OSM_FETCH_BRANCH = "OSM_FETCH";
private static final String DEFAULT_API_ENDPOINT = "http://overpass-api.de/api/interpreter";
private static final String FR_API_ENDPOINT = "http://api.openstreetmap.fr/oapi/interpreter/";
private static final String RU_API_ENDPOINT = "http://overpass.osm.rambler.ru/";
@Parameter(names = { "--filter", "-f" }, description = "The filter file to use.")
private File filterFile;
@Parameter(arity = 1, description = "<OSM Overpass api URL. eg: http://api.openstreetmap.org/api>", required = false)
public List<String> apiUrl = Lists.newArrayList();
@Parameter(names = { "--bbox", "-b" }, description = "The bounding box to use as filter (S W N E).", arity = 4)
private List<String> bbox;
@Parameter(names = "--saveto", description = "Directory where to save the dowloaded OSM data files.")
public File saveFile;
@Parameter(names = { "--keep-files", "-k" }, description = "If specified, downloaded files are kept in the --saveto folder")
public boolean keepFiles = false;
@Parameter(names = { "--update", "-u" }, description = "Update the OSM data currently in the geogit repository")
public boolean update = false;
@Parameter(names = { "--rebase" }, description = "Use rebase instead of merge when updating")
public boolean rebase = false;
@Parameter(names = { "--mapping" }, description = "The file that contains the data mapping to use")
public File mappingFile;
private String osmAPIUrl;
private GeogitCLI cli;
@Override
protected void runInternal(GeogitCLI cli) throws Exception {
checkState(cli.getGeogit() != null, "Not a geogit repository: " + cli.getPlatform().pwd());
checkArgument(filterFile != null ^ bbox != null || update,
"You must specify a filter file or a bounding box");
checkArgument((filterFile != null || bbox != null) ^ update,
"Filters cannot be used when updating");
checkState(cli.getGeogit().getRepository().getIndex().countStaged(null)
+ cli.getGeogit().getRepository().getWorkingTree().countUnstaged(null) == 0,
"Working tree and index are not clean");
checkArgument(!rebase || update, "--rebase switch can only be used when updating");
checkArgument(filterFile == null || filterFile.exists(),
"The specified filter file does not exist");
checkArgument(bbox == null || bbox.size() == 4, "The specified bounding box is not correct");
osmAPIUrl = resolveAPIURL();
this.cli = cli;
if (update) {
update();
} else {
download();
}
}
private void download() throws Exception {
Mapping mapping = null;
if (mappingFile != null) {
mapping = Mapping.fromFile(mappingFile.getAbsolutePath());
}
OSMImportOp op = cli.getGeogit().command(OSMImportOp.class).setDataSource(osmAPIUrl)
.setDownloadFile(saveFile).setMapping(mapping).setKeepFile(keepFiles);
String filter = null;
if (filterFile != null) {
try {
filter = readFile(filterFile);
} catch (IOException e) {
throw new IllegalArgumentException("Error reading filter file:" + e.getMessage(), e);
}
} else if (bbox != null) {
filter = "way(" + bbox.get(0) + "," + bbox.get(1) + "," + bbox.get(2) + ","
+ bbox.get(3) + ");\n(._;>;);\nout meta;";
}
try {
Optional<OSMDownloadReport> report = op.setFilter(filter)
.setProgressListener(cli.getProgressListener()).call();
if (!report.isPresent()) {
return;
}
if (report.get().getUnpprocessedCount() > 0) {
cli.getConsole().println(
"Some elements returned by the specified filter could not be processed.\nProcessed entities: "
+ report.get().getCount() + "\nWrong or uncomplete elements: "
+ report.get().getUnpprocessedCount());
}
cli.execute("add");
String message = "Updated OSM data";
cli.execute("commit", "-m", message);
OSMLogEntry entry = new OSMLogEntry(cli.getGeogit().getRepository().getWorkingTree()
.getTree().getId(), report.get().getLatestChangeset(), report.get()
.getLatestTimestamp());
cli.getGeogit().command(AddOSMLogEntry.class).setEntry(entry).call();
cli.getGeogit().command(WriteOSMFilterFile.class).setEntry(entry).setFilterCode(filter)
.call();
} catch (EmptyOSMDownloadException e) {
throw new IllegalArgumentException("The specified filter did not return any element.\n"
+ "No changes were made to the repository.\n"
+ "To check the downloaded elements, use the --saveto and"
+ " --keep-files options and verify the intermediate file.");
} catch (RuntimeException e) {
throw new IllegalStateException("Error importing OSM data: " + e.getMessage(), e);
}
}
private void update() throws Exception {
GeoGIT geogit = cli.getGeogit();
final Optional<Ref> currHead = geogit.command(RefParse.class).setName(Ref.HEAD).call();
Preconditions.checkState(currHead.isPresent(), "Repository has no HEAD, can't update.");
Preconditions.checkState(currHead.get() instanceof SymRef,
"Can't update from detached HEAD");
List<OSMLogEntry> entries = geogit.command(ReadOSMLogEntries.class).call();
checkArgument(!entries.isEmpty(), "Not in a geogit repository with OSM data");
Iterator<RevCommit> log = geogit.command(LogOp.class).setFirstParentOnly(false)
.setTopoOrder(false).call();
RevCommit lastCommit = null;
OSMLogEntry lastEntry = null;
while (log.hasNext()) {
RevCommit commit = log.next();
for (OSMLogEntry entry : entries) {
if (entry.getId().equals(commit.getTreeId())) {
lastCommit = commit;
lastEntry = entry;
break;
}
}
+ if (lastCommit != null) {
+ break;
+ }
}
checkNotNull(lastCommit, "The current branch does not contain OSM data");
geogit.command(BranchCreateOp.class).setSource(lastCommit.getId().toString())
.setName(OSM_FETCH_BRANCH).setAutoCheckout(true).setForce(true).call();
Optional<String> filter = geogit.command(ReadOSMFilterFile.class).setEntry(lastEntry)
.call();
Preconditions.checkState(filter.isPresent(), "Filter file not found");
Optional<OSMDownloadReport> report = geogit.command(OSMImportOp.class)
.setFilter(filter.get()).setDataSource(resolveAPIURL())
.setProgressListener(cli.getProgressListener()).call();
OSMLogEntry entry = new OSMLogEntry(cli.getGeogit().getRepository().getWorkingTree()
.getTree().getId(), report.get().getLatestChangeset(), report.get()
.getLatestTimestamp());
if (!report.isPresent()) {
return;
}
cli.getConsole().println();
if (cli.getGeogit().getRepository().getWorkingTree().countUnstaged(null) != 0) {
cli.execute("add");
String message = "Updated OSM data";
cli.execute("commit", "-m", message);
cli.getGeogit().command(AddOSMLogEntry.class).setEntry(entry).call();
cli.getGeogit().command(WriteOSMFilterFile.class).setEntry(entry)
.setFilterCode(filter.get()).call();
} else {
// no changes, so we exit and do not continue with the merge
+ geogit.command(CheckoutOp.class).setSource(((SymRef) currHead.get()).getTarget())
+ .call();
cli.getConsole().println("No changes found");
return;
}
- geogit.command(CheckoutOp.class).setSource(currHead.get().getName()).call();
+ geogit.command(CheckoutOp.class).setSource(((SymRef) currHead.get()).getTarget()).call();
if (rebase) {
cli.execute("rebase", OSM_FETCH_BRANCH);
} else {
cli.execute("merge", OSM_FETCH_BRANCH);
}
}
private String readFile(File file) throws IOException {
List<String> lines = Files.readLines(file, Charsets.UTF_8);
return Joiner.on("\n").join(lines);
}
private String resolveAPIURL() {
String osmAPIUrl;
if (apiUrl.isEmpty()) {
osmAPIUrl = DEFAULT_API_ENDPOINT;
} else {
osmAPIUrl = apiUrl.get(0);
}
return osmAPIUrl;
}
}
| false | true | private void update() throws Exception {
GeoGIT geogit = cli.getGeogit();
final Optional<Ref> currHead = geogit.command(RefParse.class).setName(Ref.HEAD).call();
Preconditions.checkState(currHead.isPresent(), "Repository has no HEAD, can't update.");
Preconditions.checkState(currHead.get() instanceof SymRef,
"Can't update from detached HEAD");
List<OSMLogEntry> entries = geogit.command(ReadOSMLogEntries.class).call();
checkArgument(!entries.isEmpty(), "Not in a geogit repository with OSM data");
Iterator<RevCommit> log = geogit.command(LogOp.class).setFirstParentOnly(false)
.setTopoOrder(false).call();
RevCommit lastCommit = null;
OSMLogEntry lastEntry = null;
while (log.hasNext()) {
RevCommit commit = log.next();
for (OSMLogEntry entry : entries) {
if (entry.getId().equals(commit.getTreeId())) {
lastCommit = commit;
lastEntry = entry;
break;
}
}
}
checkNotNull(lastCommit, "The current branch does not contain OSM data");
geogit.command(BranchCreateOp.class).setSource(lastCommit.getId().toString())
.setName(OSM_FETCH_BRANCH).setAutoCheckout(true).setForce(true).call();
Optional<String> filter = geogit.command(ReadOSMFilterFile.class).setEntry(lastEntry)
.call();
Preconditions.checkState(filter.isPresent(), "Filter file not found");
Optional<OSMDownloadReport> report = geogit.command(OSMImportOp.class)
.setFilter(filter.get()).setDataSource(resolveAPIURL())
.setProgressListener(cli.getProgressListener()).call();
OSMLogEntry entry = new OSMLogEntry(cli.getGeogit().getRepository().getWorkingTree()
.getTree().getId(), report.get().getLatestChangeset(), report.get()
.getLatestTimestamp());
if (!report.isPresent()) {
return;
}
cli.getConsole().println();
if (cli.getGeogit().getRepository().getWorkingTree().countUnstaged(null) != 0) {
cli.execute("add");
String message = "Updated OSM data";
cli.execute("commit", "-m", message);
cli.getGeogit().command(AddOSMLogEntry.class).setEntry(entry).call();
cli.getGeogit().command(WriteOSMFilterFile.class).setEntry(entry)
.setFilterCode(filter.get()).call();
} else {
// no changes, so we exit and do not continue with the merge
cli.getConsole().println("No changes found");
return;
}
geogit.command(CheckoutOp.class).setSource(currHead.get().getName()).call();
if (rebase) {
cli.execute("rebase", OSM_FETCH_BRANCH);
} else {
cli.execute("merge", OSM_FETCH_BRANCH);
}
}
| private void update() throws Exception {
GeoGIT geogit = cli.getGeogit();
final Optional<Ref> currHead = geogit.command(RefParse.class).setName(Ref.HEAD).call();
Preconditions.checkState(currHead.isPresent(), "Repository has no HEAD, can't update.");
Preconditions.checkState(currHead.get() instanceof SymRef,
"Can't update from detached HEAD");
List<OSMLogEntry> entries = geogit.command(ReadOSMLogEntries.class).call();
checkArgument(!entries.isEmpty(), "Not in a geogit repository with OSM data");
Iterator<RevCommit> log = geogit.command(LogOp.class).setFirstParentOnly(false)
.setTopoOrder(false).call();
RevCommit lastCommit = null;
OSMLogEntry lastEntry = null;
while (log.hasNext()) {
RevCommit commit = log.next();
for (OSMLogEntry entry : entries) {
if (entry.getId().equals(commit.getTreeId())) {
lastCommit = commit;
lastEntry = entry;
break;
}
}
if (lastCommit != null) {
break;
}
}
checkNotNull(lastCommit, "The current branch does not contain OSM data");
geogit.command(BranchCreateOp.class).setSource(lastCommit.getId().toString())
.setName(OSM_FETCH_BRANCH).setAutoCheckout(true).setForce(true).call();
Optional<String> filter = geogit.command(ReadOSMFilterFile.class).setEntry(lastEntry)
.call();
Preconditions.checkState(filter.isPresent(), "Filter file not found");
Optional<OSMDownloadReport> report = geogit.command(OSMImportOp.class)
.setFilter(filter.get()).setDataSource(resolveAPIURL())
.setProgressListener(cli.getProgressListener()).call();
OSMLogEntry entry = new OSMLogEntry(cli.getGeogit().getRepository().getWorkingTree()
.getTree().getId(), report.get().getLatestChangeset(), report.get()
.getLatestTimestamp());
if (!report.isPresent()) {
return;
}
cli.getConsole().println();
if (cli.getGeogit().getRepository().getWorkingTree().countUnstaged(null) != 0) {
cli.execute("add");
String message = "Updated OSM data";
cli.execute("commit", "-m", message);
cli.getGeogit().command(AddOSMLogEntry.class).setEntry(entry).call();
cli.getGeogit().command(WriteOSMFilterFile.class).setEntry(entry)
.setFilterCode(filter.get()).call();
} else {
// no changes, so we exit and do not continue with the merge
geogit.command(CheckoutOp.class).setSource(((SymRef) currHead.get()).getTarget())
.call();
cli.getConsole().println("No changes found");
return;
}
geogit.command(CheckoutOp.class).setSource(((SymRef) currHead.get()).getTarget()).call();
if (rebase) {
cli.execute("rebase", OSM_FETCH_BRANCH);
} else {
cli.execute("merge", OSM_FETCH_BRANCH);
}
}
|
diff --git a/vaadin-touchkit-agpl/src/test/java/com/vaadin/addon/touchkit/itest/VerticalComponentGroupTest.java b/vaadin-touchkit-agpl/src/test/java/com/vaadin/addon/touchkit/itest/VerticalComponentGroupTest.java
index 5ef8677..9e32e94 100644
--- a/vaadin-touchkit-agpl/src/test/java/com/vaadin/addon/touchkit/itest/VerticalComponentGroupTest.java
+++ b/vaadin-touchkit-agpl/src/test/java/com/vaadin/addon/touchkit/itest/VerticalComponentGroupTest.java
@@ -1,105 +1,105 @@
package com.vaadin.addon.touchkit.itest;
import java.util.Iterator;
import java.util.Locale;
import com.vaadin.addon.touchkit.AbstractTouchKitIntegrationTest;
import com.vaadin.addon.touchkit.ui.HorizontalComponentGroup;
import com.vaadin.addon.touchkit.ui.NavigationButton;
import com.vaadin.addon.touchkit.ui.NumberField;
import com.vaadin.addon.touchkit.ui.Switch;
import com.vaadin.addon.touchkit.ui.VerticalComponentGroup;
import com.vaadin.server.ExternalResource;
import com.vaadin.server.ThemeResource;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.Label;
import com.vaadin.ui.Link;
import com.vaadin.ui.OptionGroup;
import com.vaadin.ui.TextField;
public class VerticalComponentGroupTest extends AbstractTouchKitIntegrationTest {
public VerticalComponentGroupTest() {
setDescription("This is VerticalComponentGroup test");
VerticalComponentGroup verticalComponentGroup = new VerticalComponentGroup(
"Vertical component group");
verticalComponentGroup.addComponent(new Button("Button"));
TextField tf = new TextField(
"A TextField with long caption text and 100% width textfield component");
tf.setWidth("100%");
verticalComponentGroup.addComponent(tf);
Link link = new Link("link caption", new ExternalResource(
"http://www.gizmag.com/"));
link.setDescription("link description text");
verticalComponentGroup.addComponent(link);
verticalComponentGroup.addComponent(new Switch("Switch"));
verticalComponentGroup.addComponent(new NumberField("numberfield"));
NavigationButton one = new NavigationButton("Navigation button");
one.setDescription("nav button description");
NavigationButton too = new NavigationButton(
"Navigation button with icon");
too.setIcon(new ThemeResource("../runo/icons/32/ok.png"));
too.setDescription("nav button description");
verticalComponentGroup.addComponent(one);
verticalComponentGroup.addComponent(too);
verticalComponentGroup.addComponent(new Label(
"FIXME: Label, between buttons bugs"));
verticalComponentGroup.addComponent(new Button("Button too"));
verticalComponentGroup.addComponent(getOptiongroup());
addComponent(verticalComponentGroup);
verticalComponentGroup = new VerticalComponentGroup();
verticalComponentGroup.setCaption("Horizontal in vertical");
HorizontalComponentGroup horizontalGroup = getHorizontalGroup();
verticalComponentGroup.addComponent(horizontalGroup);
horizontalGroup = getHorizontalGroup();
horizontalGroup.addComponent(new Button("Third"));
horizontalGroup.setWidth("300px");
Iterator<Component> componentIterator = horizontalGroup
.getComponentIterator();
while (componentIterator.hasNext()) {
Component next = componentIterator.next();
- next.setWidth(100 / horizontalGroup.getComponentCount() + "%");
+ next.setWidth("" + 100.0 / (double)horizontalGroup.getComponentCount() + "%");
}
verticalComponentGroup.addComponent(horizontalGroup);
horizontalGroup = getHorizontalGroup();
Iterator<Component> it = horizontalGroup.getComponentIterator();
it.next().setCaption("Only one here");
horizontalGroup.removeComponent(it.next());
verticalComponentGroup.addComponent(horizontalGroup);
addComponent(verticalComponentGroup);
}
private OptionGroup getOptiongroup() {
OptionGroup languageSelect = new OptionGroup();
Locale[] availableLocales = new Locale[] { Locale.CANADA,
Locale.ENGLISH, Locale.GERMAN };
for (Locale locale : availableLocales) {
languageSelect.addItem(locale);
languageSelect.setItemCaption(locale,
locale.getDisplayLanguage(locale));
}
languageSelect.setValue(Locale.ENGLISH);
return languageSelect;
}
private HorizontalComponentGroup getHorizontalGroup() {
HorizontalComponentGroup horizontalComponentGroup = new HorizontalComponentGroup();
horizontalComponentGroup.addComponent(new Button("First"));
horizontalComponentGroup.addComponent(new Button("Another"));
return horizontalComponentGroup;
}
}
| true | true | public VerticalComponentGroupTest() {
setDescription("This is VerticalComponentGroup test");
VerticalComponentGroup verticalComponentGroup = new VerticalComponentGroup(
"Vertical component group");
verticalComponentGroup.addComponent(new Button("Button"));
TextField tf = new TextField(
"A TextField with long caption text and 100% width textfield component");
tf.setWidth("100%");
verticalComponentGroup.addComponent(tf);
Link link = new Link("link caption", new ExternalResource(
"http://www.gizmag.com/"));
link.setDescription("link description text");
verticalComponentGroup.addComponent(link);
verticalComponentGroup.addComponent(new Switch("Switch"));
verticalComponentGroup.addComponent(new NumberField("numberfield"));
NavigationButton one = new NavigationButton("Navigation button");
one.setDescription("nav button description");
NavigationButton too = new NavigationButton(
"Navigation button with icon");
too.setIcon(new ThemeResource("../runo/icons/32/ok.png"));
too.setDescription("nav button description");
verticalComponentGroup.addComponent(one);
verticalComponentGroup.addComponent(too);
verticalComponentGroup.addComponent(new Label(
"FIXME: Label, between buttons bugs"));
verticalComponentGroup.addComponent(new Button("Button too"));
verticalComponentGroup.addComponent(getOptiongroup());
addComponent(verticalComponentGroup);
verticalComponentGroup = new VerticalComponentGroup();
verticalComponentGroup.setCaption("Horizontal in vertical");
HorizontalComponentGroup horizontalGroup = getHorizontalGroup();
verticalComponentGroup.addComponent(horizontalGroup);
horizontalGroup = getHorizontalGroup();
horizontalGroup.addComponent(new Button("Third"));
horizontalGroup.setWidth("300px");
Iterator<Component> componentIterator = horizontalGroup
.getComponentIterator();
while (componentIterator.hasNext()) {
Component next = componentIterator.next();
next.setWidth(100 / horizontalGroup.getComponentCount() + "%");
}
verticalComponentGroup.addComponent(horizontalGroup);
horizontalGroup = getHorizontalGroup();
Iterator<Component> it = horizontalGroup.getComponentIterator();
it.next().setCaption("Only one here");
horizontalGroup.removeComponent(it.next());
verticalComponentGroup.addComponent(horizontalGroup);
addComponent(verticalComponentGroup);
}
| public VerticalComponentGroupTest() {
setDescription("This is VerticalComponentGroup test");
VerticalComponentGroup verticalComponentGroup = new VerticalComponentGroup(
"Vertical component group");
verticalComponentGroup.addComponent(new Button("Button"));
TextField tf = new TextField(
"A TextField with long caption text and 100% width textfield component");
tf.setWidth("100%");
verticalComponentGroup.addComponent(tf);
Link link = new Link("link caption", new ExternalResource(
"http://www.gizmag.com/"));
link.setDescription("link description text");
verticalComponentGroup.addComponent(link);
verticalComponentGroup.addComponent(new Switch("Switch"));
verticalComponentGroup.addComponent(new NumberField("numberfield"));
NavigationButton one = new NavigationButton("Navigation button");
one.setDescription("nav button description");
NavigationButton too = new NavigationButton(
"Navigation button with icon");
too.setIcon(new ThemeResource("../runo/icons/32/ok.png"));
too.setDescription("nav button description");
verticalComponentGroup.addComponent(one);
verticalComponentGroup.addComponent(too);
verticalComponentGroup.addComponent(new Label(
"FIXME: Label, between buttons bugs"));
verticalComponentGroup.addComponent(new Button("Button too"));
verticalComponentGroup.addComponent(getOptiongroup());
addComponent(verticalComponentGroup);
verticalComponentGroup = new VerticalComponentGroup();
verticalComponentGroup.setCaption("Horizontal in vertical");
HorizontalComponentGroup horizontalGroup = getHorizontalGroup();
verticalComponentGroup.addComponent(horizontalGroup);
horizontalGroup = getHorizontalGroup();
horizontalGroup.addComponent(new Button("Third"));
horizontalGroup.setWidth("300px");
Iterator<Component> componentIterator = horizontalGroup
.getComponentIterator();
while (componentIterator.hasNext()) {
Component next = componentIterator.next();
next.setWidth("" + 100.0 / (double)horizontalGroup.getComponentCount() + "%");
}
verticalComponentGroup.addComponent(horizontalGroup);
horizontalGroup = getHorizontalGroup();
Iterator<Component> it = horizontalGroup.getComponentIterator();
it.next().setCaption("Only one here");
horizontalGroup.removeComponent(it.next());
verticalComponentGroup.addComponent(horizontalGroup);
addComponent(verticalComponentGroup);
}
|
diff --git a/src/main/java/com/stackmob/example/PubNub.java b/src/main/java/com/stackmob/example/PubNub.java
index 4b1f8a7..8f94a69 100644
--- a/src/main/java/com/stackmob/example/PubNub.java
+++ b/src/main/java/com/stackmob/example/PubNub.java
@@ -1,213 +1,213 @@
package com.stackmob.example;
/**
* Created with IntelliJ IDEA.
* User: sid
* Date: 8/14/13
* Time: 10:20 AM
* To change this template use File | Settings | File Templates.
*/
import com.stackmob.core.DatastoreException;
import com.stackmob.core.InvalidSchemaException;
import com.stackmob.core.customcode.CustomCodeMethod;
import com.stackmob.core.rest.ProcessedAPIRequest;
import com.stackmob.core.rest.ResponseToProcess;
import com.stackmob.sdkapi.*;
import com.stackmob.sdkapi.http.HttpService;
import com.stackmob.sdkapi.http.request.HttpRequest;
import com.stackmob.sdkapi.http.request.GetRequest;
import com.stackmob.sdkapi.http.response.HttpResponse;
import com.stackmob.core.ServiceNotActivatedException;
import com.stackmob.sdkapi.http.exceptions.AccessDeniedException;
import com.stackmob.sdkapi.http.exceptions.TimeoutException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import com.stackmob.sdkapi.http.request.PostRequest;
import com.stackmob.sdkapi.http.Header;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.*;
import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class PubNub implements CustomCodeMethod {
@Override
public String getMethodName() {
return "pubnub_send";
}
@Override
public List<String> getParams() {
return Arrays.asList("question_id","answer_id");
}
@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
String channelEncoded = "0";
String jsonMessageEncoded = "{}";
String answer_id = "";
String question_id = "";
int count = 1;
String PUBLISH_KEY = "";
String SUBSCRIBE_KEY = "";
String SECRET_KEY = "";
LoggerService logger = serviceProvider.getLoggerService(PubNub.class);
// I'll be using these maps to print messages to console as feedback to the operation
Map<String, SMValue> feedback = new HashMap<String, SMValue>();
Map<String, String> errMap = new HashMap<String, String>();
//Add the PubNub module at https://marketplace.stackmob.com/module/pubnub
try {
- PUBLISH_KEY = serviceProvider.getConfigVarService().get("publish-key");
- SUBSCRIBE_KEY = serviceProvider.getConfigVarService().get("subscribe-key");
- SECRET_KEY = serviceProvider.getConfigVarService().get("secret-key");
+ PUBLISH_KEY = serviceProvider.getConfigVarService().get("publish-key","pubnub");
+ SUBSCRIBE_KEY = serviceProvider.getConfigVarService().get("subscribe-key","pubnub");
+ SECRET_KEY = serviceProvider.getConfigVarService().get("secret-key","pubnub");
} catch(Exception e) {
return Util.internalErrorResponse("global config var error - check that pubnub module is installed", e, errMap); // error 500 // http 500 - internal server error
}
// PUBNUB Msg Object
JSONObject msgObj = new JSONObject();
JSONArray answers = new JSONArray();
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(request.getBody());
JSONObject jsonObject = (JSONObject) obj;
//get message from POST body
answer_id = (String) jsonObject.get("answer_id");
question_id = (String) jsonObject.get("question_id");
} catch (ParseException e) {
return Util.internalErrorResponse("parsing exception", e, errMap); // error 500 // http 500 - internal server error
}
if (Util.hasNulls(answer_id)){
return Util.badRequestResponse(errMap);
}
DataService dataService = serviceProvider.getDataService();
// Let's get all the answers for this question
// and create a JSON package we'll send to PubNub
try {
List<SMCondition> query = new ArrayList<SMCondition>();
List<SMObject> results;
int expandDepth = 1;
// Create a new condition to match results to, in this case, matching IDs (primary key)
query.add(new SMEquals("question_id", new SMString(question_id)));
results = dataService.readObjects("question", query, expandDepth); // Read objects from the `question` schema expand depth to bring back full answers objects
if (results != null && results.size() > 0) {
Iterator iterator = results.iterator();
while (iterator.hasNext()) {
SMObject question = (SMObject) iterator.next();
SMList<SMObject> ans = (SMList<SMObject>) question.getValue().get("answers");
for (int i=0; i < ans.getValue().size(); i++) {
JSONObject ansObj = new JSONObject();
SMObject obj = ans.getValue().get(i);
if (answer_id.equalsIgnoreCase(obj.getValue().get("answer_id").toString())) {
int currValue = Integer.parseInt(obj.getValue().get("value").toString());
String newValue = String.valueOf(currValue + 1);
ansObj.put("value", newValue);
} else {
ansObj.put("value", obj.getValue().get("value").toString() );
}
ansObj.put("title", obj.getValue().get("title").toString() );
ansObj.put("order", obj.getValue().get("order").toString() );
ansObj.put("color", obj.getValue().get("color").toString() );
ansObj.put("answer_id", obj.getValue().get("answer_id").toString() );
answers.add(ansObj);
}
msgObj.put("answers", answers);
}
}
} catch (InvalidSchemaException e) {
return Util.internalErrorResponse("invalid schema", e, errMap); // error 500 // http 500 - internal server error
} catch (DatastoreException e) {
return Util.internalErrorResponse("internal error response", e, errMap); // error 500 // http 500 - internal server error
} catch(Exception e) {
return Util.internalErrorResponse("unknown exception", e, errMap); // error 500 // http 500 - internal server error
}
// Let's increment the count for this answer and update the datastore
try {
List<SMUpdate> update = new ArrayList<SMUpdate>();
update.add(new SMIncrement("value", count));
SMObject incrementResult = dataService.updateObject("answer", answer_id, update); // increment the value in answer schema
} catch (InvalidSchemaException e) {
return Util.internalErrorResponse("invalid schema", e, errMap); // error 500 // http 500 - internal server error
} catch (DatastoreException e) {
return Util.internalErrorResponse("internal error response", e, errMap); // error 500 // http 500 - internal server error
} catch(Exception e) {
return Util.internalErrorResponse("unknown exception", e, errMap); // error 500 // http 500 - internal server error
}
// URL Encode the channel which is equal to the question_id
// URL Encode the JSON object for PubNub that includes an array of answers
try {
channelEncoded = URLEncoder.encode(question_id, "UTF-8");
jsonMessageEncoded = URLEncoder.encode(msgObj.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
}
StringBuilder url = new StringBuilder();
url.append("http://pubsub.pubnub.com/publish");
url.append("/");
url.append(PUBLISH_KEY);
url.append("/");
url.append(SUBSCRIBE_KEY);
url.append("/");
url.append(SECRET_KEY);
url.append("/");
url.append(channelEncoded);
url.append("/");
url.append("0");
url.append("/");
url.append(jsonMessageEncoded);
logger.debug(url.toString());
try {
HttpService http = serviceProvider.getHttpService();
GetRequest req = new GetRequest(url.toString());
HttpResponse resp = http.get(req);
feedback.put("body", new SMString(resp.getBody().toString()));
feedback.put("code", new SMString(resp.getCode().toString()));
} catch(TimeoutException e) {
return Util.internalErrorResponse("bad gateway", e, errMap); // error 500 // http 500 - internal server error
} catch(AccessDeniedException e) {
return Util.internalErrorResponse("access denied exception", e, errMap); // error 500 // http 500 - internal server error
} catch(MalformedURLException e) {
return Util.internalErrorResponse("malformed URL exception", e, errMap); // error 500 // http 500 - internal server error
} catch(ServiceNotActivatedException e) {
return Util.internalErrorResponse("service not activated", e, errMap); // error 500 // http 500 - internal server error
}
return new ResponseToProcess(HttpURLConnection.HTTP_OK, feedback);
}
}
| true | true | public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
String channelEncoded = "0";
String jsonMessageEncoded = "{}";
String answer_id = "";
String question_id = "";
int count = 1;
String PUBLISH_KEY = "";
String SUBSCRIBE_KEY = "";
String SECRET_KEY = "";
LoggerService logger = serviceProvider.getLoggerService(PubNub.class);
// I'll be using these maps to print messages to console as feedback to the operation
Map<String, SMValue> feedback = new HashMap<String, SMValue>();
Map<String, String> errMap = new HashMap<String, String>();
//Add the PubNub module at https://marketplace.stackmob.com/module/pubnub
try {
PUBLISH_KEY = serviceProvider.getConfigVarService().get("publish-key");
SUBSCRIBE_KEY = serviceProvider.getConfigVarService().get("subscribe-key");
SECRET_KEY = serviceProvider.getConfigVarService().get("secret-key");
} catch(Exception e) {
return Util.internalErrorResponse("global config var error - check that pubnub module is installed", e, errMap); // error 500 // http 500 - internal server error
}
// PUBNUB Msg Object
JSONObject msgObj = new JSONObject();
JSONArray answers = new JSONArray();
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(request.getBody());
JSONObject jsonObject = (JSONObject) obj;
//get message from POST body
answer_id = (String) jsonObject.get("answer_id");
question_id = (String) jsonObject.get("question_id");
} catch (ParseException e) {
return Util.internalErrorResponse("parsing exception", e, errMap); // error 500 // http 500 - internal server error
}
if (Util.hasNulls(answer_id)){
return Util.badRequestResponse(errMap);
}
DataService dataService = serviceProvider.getDataService();
// Let's get all the answers for this question
// and create a JSON package we'll send to PubNub
try {
List<SMCondition> query = new ArrayList<SMCondition>();
List<SMObject> results;
int expandDepth = 1;
// Create a new condition to match results to, in this case, matching IDs (primary key)
query.add(new SMEquals("question_id", new SMString(question_id)));
results = dataService.readObjects("question", query, expandDepth); // Read objects from the `question` schema expand depth to bring back full answers objects
if (results != null && results.size() > 0) {
Iterator iterator = results.iterator();
while (iterator.hasNext()) {
SMObject question = (SMObject) iterator.next();
SMList<SMObject> ans = (SMList<SMObject>) question.getValue().get("answers");
for (int i=0; i < ans.getValue().size(); i++) {
JSONObject ansObj = new JSONObject();
SMObject obj = ans.getValue().get(i);
if (answer_id.equalsIgnoreCase(obj.getValue().get("answer_id").toString())) {
int currValue = Integer.parseInt(obj.getValue().get("value").toString());
String newValue = String.valueOf(currValue + 1);
ansObj.put("value", newValue);
} else {
ansObj.put("value", obj.getValue().get("value").toString() );
}
ansObj.put("title", obj.getValue().get("title").toString() );
ansObj.put("order", obj.getValue().get("order").toString() );
ansObj.put("color", obj.getValue().get("color").toString() );
ansObj.put("answer_id", obj.getValue().get("answer_id").toString() );
answers.add(ansObj);
}
msgObj.put("answers", answers);
}
}
} catch (InvalidSchemaException e) {
return Util.internalErrorResponse("invalid schema", e, errMap); // error 500 // http 500 - internal server error
} catch (DatastoreException e) {
return Util.internalErrorResponse("internal error response", e, errMap); // error 500 // http 500 - internal server error
} catch(Exception e) {
return Util.internalErrorResponse("unknown exception", e, errMap); // error 500 // http 500 - internal server error
}
// Let's increment the count for this answer and update the datastore
try {
List<SMUpdate> update = new ArrayList<SMUpdate>();
update.add(new SMIncrement("value", count));
SMObject incrementResult = dataService.updateObject("answer", answer_id, update); // increment the value in answer schema
} catch (InvalidSchemaException e) {
return Util.internalErrorResponse("invalid schema", e, errMap); // error 500 // http 500 - internal server error
} catch (DatastoreException e) {
return Util.internalErrorResponse("internal error response", e, errMap); // error 500 // http 500 - internal server error
} catch(Exception e) {
return Util.internalErrorResponse("unknown exception", e, errMap); // error 500 // http 500 - internal server error
}
// URL Encode the channel which is equal to the question_id
// URL Encode the JSON object for PubNub that includes an array of answers
try {
channelEncoded = URLEncoder.encode(question_id, "UTF-8");
jsonMessageEncoded = URLEncoder.encode(msgObj.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
}
StringBuilder url = new StringBuilder();
url.append("http://pubsub.pubnub.com/publish");
url.append("/");
url.append(PUBLISH_KEY);
url.append("/");
url.append(SUBSCRIBE_KEY);
url.append("/");
url.append(SECRET_KEY);
url.append("/");
url.append(channelEncoded);
url.append("/");
url.append("0");
url.append("/");
url.append(jsonMessageEncoded);
logger.debug(url.toString());
try {
HttpService http = serviceProvider.getHttpService();
GetRequest req = new GetRequest(url.toString());
HttpResponse resp = http.get(req);
feedback.put("body", new SMString(resp.getBody().toString()));
feedback.put("code", new SMString(resp.getCode().toString()));
} catch(TimeoutException e) {
return Util.internalErrorResponse("bad gateway", e, errMap); // error 500 // http 500 - internal server error
} catch(AccessDeniedException e) {
return Util.internalErrorResponse("access denied exception", e, errMap); // error 500 // http 500 - internal server error
} catch(MalformedURLException e) {
return Util.internalErrorResponse("malformed URL exception", e, errMap); // error 500 // http 500 - internal server error
} catch(ServiceNotActivatedException e) {
return Util.internalErrorResponse("service not activated", e, errMap); // error 500 // http 500 - internal server error
}
return new ResponseToProcess(HttpURLConnection.HTTP_OK, feedback);
}
| public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
String channelEncoded = "0";
String jsonMessageEncoded = "{}";
String answer_id = "";
String question_id = "";
int count = 1;
String PUBLISH_KEY = "";
String SUBSCRIBE_KEY = "";
String SECRET_KEY = "";
LoggerService logger = serviceProvider.getLoggerService(PubNub.class);
// I'll be using these maps to print messages to console as feedback to the operation
Map<String, SMValue> feedback = new HashMap<String, SMValue>();
Map<String, String> errMap = new HashMap<String, String>();
//Add the PubNub module at https://marketplace.stackmob.com/module/pubnub
try {
PUBLISH_KEY = serviceProvider.getConfigVarService().get("publish-key","pubnub");
SUBSCRIBE_KEY = serviceProvider.getConfigVarService().get("subscribe-key","pubnub");
SECRET_KEY = serviceProvider.getConfigVarService().get("secret-key","pubnub");
} catch(Exception e) {
return Util.internalErrorResponse("global config var error - check that pubnub module is installed", e, errMap); // error 500 // http 500 - internal server error
}
// PUBNUB Msg Object
JSONObject msgObj = new JSONObject();
JSONArray answers = new JSONArray();
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(request.getBody());
JSONObject jsonObject = (JSONObject) obj;
//get message from POST body
answer_id = (String) jsonObject.get("answer_id");
question_id = (String) jsonObject.get("question_id");
} catch (ParseException e) {
return Util.internalErrorResponse("parsing exception", e, errMap); // error 500 // http 500 - internal server error
}
if (Util.hasNulls(answer_id)){
return Util.badRequestResponse(errMap);
}
DataService dataService = serviceProvider.getDataService();
// Let's get all the answers for this question
// and create a JSON package we'll send to PubNub
try {
List<SMCondition> query = new ArrayList<SMCondition>();
List<SMObject> results;
int expandDepth = 1;
// Create a new condition to match results to, in this case, matching IDs (primary key)
query.add(new SMEquals("question_id", new SMString(question_id)));
results = dataService.readObjects("question", query, expandDepth); // Read objects from the `question` schema expand depth to bring back full answers objects
if (results != null && results.size() > 0) {
Iterator iterator = results.iterator();
while (iterator.hasNext()) {
SMObject question = (SMObject) iterator.next();
SMList<SMObject> ans = (SMList<SMObject>) question.getValue().get("answers");
for (int i=0; i < ans.getValue().size(); i++) {
JSONObject ansObj = new JSONObject();
SMObject obj = ans.getValue().get(i);
if (answer_id.equalsIgnoreCase(obj.getValue().get("answer_id").toString())) {
int currValue = Integer.parseInt(obj.getValue().get("value").toString());
String newValue = String.valueOf(currValue + 1);
ansObj.put("value", newValue);
} else {
ansObj.put("value", obj.getValue().get("value").toString() );
}
ansObj.put("title", obj.getValue().get("title").toString() );
ansObj.put("order", obj.getValue().get("order").toString() );
ansObj.put("color", obj.getValue().get("color").toString() );
ansObj.put("answer_id", obj.getValue().get("answer_id").toString() );
answers.add(ansObj);
}
msgObj.put("answers", answers);
}
}
} catch (InvalidSchemaException e) {
return Util.internalErrorResponse("invalid schema", e, errMap); // error 500 // http 500 - internal server error
} catch (DatastoreException e) {
return Util.internalErrorResponse("internal error response", e, errMap); // error 500 // http 500 - internal server error
} catch(Exception e) {
return Util.internalErrorResponse("unknown exception", e, errMap); // error 500 // http 500 - internal server error
}
// Let's increment the count for this answer and update the datastore
try {
List<SMUpdate> update = new ArrayList<SMUpdate>();
update.add(new SMIncrement("value", count));
SMObject incrementResult = dataService.updateObject("answer", answer_id, update); // increment the value in answer schema
} catch (InvalidSchemaException e) {
return Util.internalErrorResponse("invalid schema", e, errMap); // error 500 // http 500 - internal server error
} catch (DatastoreException e) {
return Util.internalErrorResponse("internal error response", e, errMap); // error 500 // http 500 - internal server error
} catch(Exception e) {
return Util.internalErrorResponse("unknown exception", e, errMap); // error 500 // http 500 - internal server error
}
// URL Encode the channel which is equal to the question_id
// URL Encode the JSON object for PubNub that includes an array of answers
try {
channelEncoded = URLEncoder.encode(question_id, "UTF-8");
jsonMessageEncoded = URLEncoder.encode(msgObj.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
}
StringBuilder url = new StringBuilder();
url.append("http://pubsub.pubnub.com/publish");
url.append("/");
url.append(PUBLISH_KEY);
url.append("/");
url.append(SUBSCRIBE_KEY);
url.append("/");
url.append(SECRET_KEY);
url.append("/");
url.append(channelEncoded);
url.append("/");
url.append("0");
url.append("/");
url.append(jsonMessageEncoded);
logger.debug(url.toString());
try {
HttpService http = serviceProvider.getHttpService();
GetRequest req = new GetRequest(url.toString());
HttpResponse resp = http.get(req);
feedback.put("body", new SMString(resp.getBody().toString()));
feedback.put("code", new SMString(resp.getCode().toString()));
} catch(TimeoutException e) {
return Util.internalErrorResponse("bad gateway", e, errMap); // error 500 // http 500 - internal server error
} catch(AccessDeniedException e) {
return Util.internalErrorResponse("access denied exception", e, errMap); // error 500 // http 500 - internal server error
} catch(MalformedURLException e) {
return Util.internalErrorResponse("malformed URL exception", e, errMap); // error 500 // http 500 - internal server error
} catch(ServiceNotActivatedException e) {
return Util.internalErrorResponse("service not activated", e, errMap); // error 500 // http 500 - internal server error
}
return new ResponseToProcess(HttpURLConnection.HTTP_OK, feedback);
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/editor/EditorManager.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/editor/EditorManager.java
index 85a8c1f69..a98a65274 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/editor/EditorManager.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/editor/EditorManager.java
@@ -1,1498 +1,1498 @@
/*
* DPP - Serious Distributed Pair Programming
* (c) Freie Universitaet Berlin - Fachbereich Mathematik und Informatik - 2006
* (c) Riad Djemili - 2006
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package de.fu_berlin.inf.dpp.editor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.ITextFileBufferManager;
import org.eclipse.core.filebuffers.manipulation.ConvertLineDelimitersOperation;
import org.eclipse.core.filebuffers.manipulation.FileBufferOperationRunner;
import org.eclipse.core.filebuffers.manipulation.TextFileBufferOperation;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourceAttributes;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension4;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.ILineRange;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IElementStateListener;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import de.fu_berlin.inf.dpp.Saros;
import de.fu_berlin.inf.dpp.User;
import de.fu_berlin.inf.dpp.activities.EditorActivity;
import de.fu_berlin.inf.dpp.activities.IActivity;
import de.fu_berlin.inf.dpp.activities.TextEditActivity;
import de.fu_berlin.inf.dpp.activities.TextSelectionActivity;
import de.fu_berlin.inf.dpp.activities.ViewportActivity;
import de.fu_berlin.inf.dpp.activities.EditorActivity.Type;
import de.fu_berlin.inf.dpp.editor.annotations.AnnotationSaros;
import de.fu_berlin.inf.dpp.editor.annotations.ContributionAnnotation;
import de.fu_berlin.inf.dpp.editor.annotations.ViewportAnnotation;
import de.fu_berlin.inf.dpp.editor.internal.ContributionAnnotationManager;
import de.fu_berlin.inf.dpp.editor.internal.EditorAPI;
import de.fu_berlin.inf.dpp.editor.internal.IEditorAPI;
import de.fu_berlin.inf.dpp.invitation.IIncomingInvitationProcess;
import de.fu_berlin.inf.dpp.net.JID;
import de.fu_berlin.inf.dpp.project.IActivityListener;
import de.fu_berlin.inf.dpp.project.IActivityProvider;
import de.fu_berlin.inf.dpp.project.ISharedProject;
import de.fu_berlin.inf.dpp.project.ISharedProjectListener;
import de.fu_berlin.inf.dpp.ui.BalloonNotification;
import de.fu_berlin.inf.dpp.ui.SessionView;
import de.fu_berlin.inf.dpp.util.Util;
import de.fu_berlin.inf.dpp.util.VariableProxyListener;
/**
* The EditorManager is responsible for handling all editors in a DPP-session.
* This includes the functionality of listening for user inputs in an editor,
* locking the editors of the observer.
*
* The EditorManager contains the testable logic. All untestable logic should
* only appear in an class of the {@link IEditorAPI} type.
*
* @author rdjemili
*
* TODO CO Since it was forgotton to reset the DriverEditors after a
* session closed, it is highly likely that this whole class needs to be
* reviewed for restarting issues
*
*/
public class EditorManager implements IActivityProvider, ISharedProjectListener {
private class ElementStateListener implements IElementStateListener {
public void elementDirtyStateChanged(Object element, boolean isDirty) {
if (!EditorManager.this.isDriver || isDirty
|| !(element instanceof FileEditorInput)) {
return;
}
FileEditorInput fileEditorInput = (FileEditorInput) element;
IFile file = fileEditorInput.getFile();
if (file.getProject() != EditorManager.this.sharedProject
.getProject()) {
return;
}
IPath path = file.getProjectRelativePath();
sendEditorActivitySaved(path);
}
public void elementContentAboutToBeReplaced(Object element) {
// ignore
}
public void elementContentReplaced(Object element) {
// ignore
}
public void elementDeleted(Object element) {
// ignore
}
public void elementMoved(Object originalElement, Object movedElement) {
// ignore
}
}
/**
* @author rdjemili
*
*/
private class EditorPool {
private final Map<IPath, HashSet<IEditorPart>> editorParts = new HashMap<IPath, HashSet<IEditorPart>>();
public void add(IEditorPart editorPart) {
IResource resource = EditorManager.this.editorAPI
.getEditorResource(editorPart);
IPath path = resource.getProjectRelativePath();
if (path == null) {
return;
}
HashSet<IEditorPart> editors = this.editorParts.get(path);
EditorManager.this.editorAPI.addSharedEditorListener(editorPart);
EditorManager.this.editorAPI.setEditable(editorPart,
EditorManager.this.isDriver);
IDocumentProvider documentProvider = EditorManager.this.editorAPI
.getDocumentProvider(editorPart.getEditorInput());
documentProvider
.addElementStateListener(EditorManager.this.elementStateListener);
IDocument document = EditorManager.this.editorAPI
.getDocument(editorPart);
if (editors == null) {
editors = new HashSet<IEditorPart>();
this.editorParts.put(path, editors);
}
// if line delimiters are not in unix style convert them
if (document instanceof IDocumentExtension4) {
if (!((IDocumentExtension4) document).getDefaultLineDelimiter()
.equals("\n")) {
convertLineDelimiters(editorPart);
}
((IDocumentExtension4) document).setInitialLineDelimiter("\n");
} else {
EditorManager.log
.error("Can't discover line delimiter of document");
}
document.addDocumentListener(EditorManager.this.documentListener);
editors.add(editorPart);
lastEditTimes.put(path, System.currentTimeMillis());
lastRemoteEditTimes.put(path, System.currentTimeMillis());
}
private void convertLineDelimiters(IEditorPart editorPart) {
EditorManager.log.debug("Converting line delimiters...");
// get path of file
IFile file = ((FileEditorInput) editorPart.getEditorInput())
.getFile();
IPath[] paths = new IPath[1];
paths[0] = file.getFullPath();
boolean makeReadable = false;
ResourceAttributes resourceAttributes = file
.getResourceAttributes();
if (resourceAttributes.isReadOnly()) {
resourceAttributes.setReadOnly(false);
try {
file.setResourceAttributes(resourceAttributes);
makeReadable = true;
} catch (CoreException e) {
- log.warn(
+ log.error(
"Error making file readable for delimiter conversion:",
e);
}
}
ITextFileBufferManager buffManager = FileBuffers
.getTextFileBufferManager();
// convert operation to change line delimiters
TextFileBufferOperation convertOperation = new ConvertLineDelimitersOperation(
"\n");
// operation runner for the convert operation
FileBufferOperationRunner runner = new FileBufferOperationRunner(
buffManager, null);
// execute convert operation in runner
try {
runner.execute(paths, convertOperation,
new NullProgressMonitor());
} catch (OperationCanceledException e) {
EditorManager.log.error("Can't convert line delimiters:", e);
} catch (CoreException e) {
EditorManager.log.error("Can't convert line delimiters:", e);
}
if (makeReadable) {
resourceAttributes.setReadOnly(true);
try {
file.setResourceAttributes(resourceAttributes);
} catch (CoreException e) {
EditorManager.log
.error(
"Error restoring readable state to false after delimiter conversion:",
e);
}
}
}
public void remove(IEditorPart editorPart) {
IResource resource = EditorManager.this.editorAPI
.getEditorResource(editorPart);
IPath path = resource.getProjectRelativePath();
if (path == null) {
return;
}
HashSet<IEditorPart> editors = this.editorParts.get(path);
editors.remove(editorPart);
}
public Set<IEditorPart> getEditors(IPath path) {
HashSet<IEditorPart> set = this.editorParts.get(path);
return set == null ? new HashSet<IEditorPart>() : set; // HACK
}
public Set<IEditorPart> getAllEditors() {
Set<IEditorPart> all = new HashSet<IEditorPart>();
for (Set<IEditorPart> parts : this.editorParts.values()) {
for (IEditorPart part : parts) {
all.add(part);
}
}
return all;
}
public void removeAllEditors() {
editorParts.clear();
}
}
private class DocumentListener implements IDocumentListener {
public void documentAboutToBeChanged(final DocumentEvent event) {
// boolean checksumErrorHandling = Saros.getDefault()
// .getSessionManager().getSharedProject()
// .getConcurrentDocumentManager()
// .getExecutingChecksumErrorHandling();
// if (checksumErrorHandling)
// return;
String text = event.getText() == null ? "" : event.getText();
textAboutToBeChanged(event.getOffset(), text, event.getLength(),
event.getDocument());
}
public void documentChanged(final DocumentEvent event) {
// do nothing. We handeled everything in documentAboutToBeChanged
}
}
private static Logger log = Logger.getLogger(EditorManager.class.getName());
private static EditorManager instance;
private IEditorAPI editorAPI;
private ISharedProject sharedProject;
private final List<IActivityListener> activityListeners = new LinkedList<IActivityListener>();
private boolean isFollowing;
private boolean isDriver;
private final EditorPool editorPool = new EditorPool();
private final ElementStateListener elementStateListener = new ElementStateListener();
private final DocumentListener documentListener = new DocumentListener();
// TODO save only the editor of the followed driver
private IPath activeDriverEditor;
private final Set<IPath> driverEditors = new HashSet<IPath>();
private HashMap<User, ITextSelection> driverTextSelections = new HashMap<User, ITextSelection>();
/** all files that have connected document providers */
private final Set<IFile> connectedFiles = new HashSet<IFile>();
private final List<ISharedEditorListener> editorListeners = new ArrayList<ISharedEditorListener>();
/* this activity has arrived and will be execute now. */
private IActivity currentExecuteActivity;
public HashMap<IPath, Long> lastEditTimes = new HashMap<IPath, Long>();
public HashMap<IPath, Long> lastRemoteEditTimes = new HashMap<IPath, Long>();
private ContributionAnnotationManager contributionAnnotationManager;
public static EditorManager getDefault() {
if (EditorManager.instance == null) {
EditorManager.instance = new EditorManager();
}
return EditorManager.instance;
}
public void setEditorAPI(IEditorAPI editorAPI) {
this.editorAPI = editorAPI;
editorAPI.setEditorManager(this);
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.project.ISessionListener
*/
public void sessionStarted(ISharedProject session) {
this.sharedProject = session;
assert (this.editorPool.editorParts.isEmpty());
this.isDriver = this.sharedProject.isDriver();
this.sharedProject.addListener(this);
// Add ConsistencyListener
Saros.getDefault().getSessionManager().getSharedProject()
.getConcurrentDocumentManager().getConsistencyToResolve().add(
new VariableProxyListener<Boolean>() {
public void setVariable(Boolean inconsistency) {
if (inconsistency) {
Util.runSafeSWTSync(log, new Runnable() {
public void run() {
try {
// Open Session view
PlatformUI
.getWorkbench()
.getActiveWorkbenchWindow()
.getActivePage()
.showView(
"de.fu_berlin.inf.dpp.ui.SessionView",
null,
IWorkbenchPage.VIEW_ACTIVATE);
} catch (PartInitException e) {
log
.error("Could not open session view!");
}
}
});
}
}
});
this.sharedProject.getActivityManager().addProvider(this);
this.contributionAnnotationManager = new ContributionAnnotationManager(
session);
activateOpenEditors();
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.project.ISessionListener
*/
public void sessionEnded(ISharedProject session) {
setAllEditorsToEditable();
removeAllAnnotations(null, null);
this.sharedProject.removeListener(this);
this.sharedProject.getActivityManager().removeProvider(this);
this.sharedProject = null;
this.editorPool.removeAllEditors();
this.lastEditTimes.clear();
this.lastRemoteEditTimes.clear();
this.contributionAnnotationManager.dispose();
this.contributionAnnotationManager = null;
this.activeDriverEditor = null;
this.driverEditors.clear();
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.project.ISessionListener
*/
public void invitationReceived(IIncomingInvitationProcess invitation) {
// ignore
}
public void addSharedEditorListener(ISharedEditorListener editorListener) {
if (!this.editorListeners.contains(editorListener)) {
this.editorListeners.add(editorListener);
}
}
public void removeSharedEditorListener(ISharedEditorListener editorListener) {
this.editorListeners.remove(editorListener);
}
/**
* @return the path to the resource that the driver is currently editting.
* Can be <code>null</code>.
*/
public IPath getActiveDriverEditor() {
return this.activeDriverEditor;
}
/**
* Returns the resource paths of editors that the driver is currently using.
*
* @return all paths (in project-relative format) of files that the driver
* is currently editing by using an editor. Never returns
* <code>null</code>. A empty set is returned if there are no
* currently opened editors.
*/
public Set<IPath> getDriverEditors() {
return this.driverEditors;
}
/**
* Return the document of the given path.
*
* @param path
* the path of the wanted document
* @return the document or null if no document exists with given path or no
* editor with this file is open
*/
public IDocument getDocument(IPath path) {
Set<IEditorPart> editors = getEditors(path);
if (editors.isEmpty())
return null;
AbstractTextEditor editor = (AbstractTextEditor) editors.toArray()[0];
IEditorInput input = editor.getEditorInput();
return editor.getDocumentProvider().getDocument(input);
}
// TODO CJ: find a better solution
public IPath getPathOfDocument(IDocument doc) {
IPath path = null;
Set<IEditorPart> editors = editorPool.getAllEditors();
for (IEditorPart editor : editors) {
if (editorAPI.getDocument(editor) == doc) {
path = editorAPI.getEditorResource(editor)
.getProjectRelativePath();
break;
}
}
return path;
}
/**
* @param user
* User for who's text selection will be returned.
* @return the text selection of given user or <code>null</code> if that
* user is not a driver.
*/
public ITextSelection getDriverTextSelection(User user) {
return this.driverTextSelections.get(user);
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.editor.ISharedEditorListener
*/
public void viewportChanged(int top, int bottom, IPath editor) {
if (!this.sharedProject.isDriver()) {
return;
}
fireActivity(new ViewportActivity(top, bottom, editor));
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.editor.ISharedEditorListener
*/
public void selectionChanged(ITextSelection selection, ISelectionProvider sp) {
IDocument doc = ((ITextViewer) sp).getDocument();
int offset = selection.getOffset();
int length = selection.getLength();
IPath path = getPathOfDocument(doc);
if (path == null) {
log.error("Couldn't get editor!");
} else
fireActivity(new TextSelectionActivity(offset, length, path));
}
/**
* Asks the ConcurrentDocumentManager if there are currently any
* inconsistencies to resolve.
*/
public boolean isConsistencyToResolve() {
ISharedProject project = Saros.getDefault().getSessionManager()
.getSharedProject();
if (project == null)
return false;
return project.getConcurrentDocumentManager().getConsistencyToResolve()
.getVariable();
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.editor.ISharedEditorListener
*/
public void textAboutToBeChanged(int offset, String text, int replace,
IDocument document) {
/*
* TODO When Inconsistencies exists, all listeners should be stopped
* rather than catching events -> Think Start/Stop on the SharedProject
*/
if (!this.isDriver || isConsistencyToResolve()) {
this.currentExecuteActivity = null;
return;
}
IEditorPart changedEditor = null;
// search editor which changed
Set<IEditorPart> editors = editorPool.getAllEditors();
for (IEditorPart editor : editors) {
if (editorAPI.getDocument(editor) == document) {
changedEditor = editor;
break;
}
}
assert changedEditor != null;
IPath path = editorAPI.getEditorResource(changedEditor)
.getProjectRelativePath();
if (path != null) {
TextEditActivity activity = new TextEditActivity(offset, text,
replace, path);
/*
* check if text edit activity is executed by other driver activity
* recently.
*/
if (activity.sameLike(this.currentExecuteActivity)) {
this.currentExecuteActivity = null;
return;
}
EditorManager.this.lastEditTimes.put(path, System
.currentTimeMillis());
fireActivity(activity);
IEditorInput input = changedEditor.getEditorInput();
IDocumentProvider provider = this.editorAPI
.getDocumentProvider(input);
IAnnotationModel model = provider.getAnnotationModel(input);
contributionAnnotationManager.splitAnnotation(model, offset);
} else {
log.error("Can't get editor path");
}
}
public static IViewPart findView(String id) {
IWorkbench workbench = PlatformUI.getWorkbench();
if (workbench == null)
return null;
IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
if (window == null)
return null;
IWorkbenchPage page = window.getActivePage();
if (page == null)
return null;
return page.findView(id);
}
/* ---------- ISharedProjectListener --------- */
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.listeners.ISharedProjectListener
*/
public void roleChanged(User user, boolean replicated) {
this.isDriver = this.sharedProject.isDriver();
activateOpenEditors();
removeAllAnnotations(ContributionAnnotation.TYPE);
if (Saros.getDefault().getLocalUser().equals(user)) {
// get the session view
IViewPart view = findView("de.fu_berlin.inf.dpp.ui.SessionView");
if (isDriver) {
removeAllAnnotations(ViewportAnnotation.TYPE);
// if session view is not open show the balloon notification in
// the control which has the keyboard focus
if (view == null) {
Util.runSafeSWTAsync(log, new Runnable() {
public void run() {
BalloonNotification.showNotification(Display
.getDefault().getFocusControl(),
"Role changed",
"You are now a driver of this session.", 5000);
}
});
}
} else {
// if session view is not open show the balloon notification in
// the control which has the keyboard focus
if (view == null) {
Util.runSafeSWTAsync(log, new Runnable() {
public void run() {
BalloonNotification.showNotification(Display
.getDefault().getFocusControl(),
"Role changed",
"You are now an observer of this session.",
5000);
}
});
}
}
}
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.listeners.ISharedProjectListener
*/
public void userJoined(JID user) {
// ignore
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.listeners.ISharedProjectListener
*/
public void userLeft(JID user) {
removeAllAnnotations(user.toString(), null);
driverTextSelections.remove(sharedProject.getParticipant(user));
}
/* ---------- etc --------- */
/**
* Opens the editor that is currently used by the driver. This method needs
* to be called from an UI thread. Is ignored if caller is already driver.
*/
public void openDriverEditor() {
if (this.isDriver) {
return;
}
IPath path = getActiveDriverEditor();
if (path == null) {
return;
}
this.editorAPI
.openEditor(this.sharedProject.getProject().getFile(path));
}
public void setEnableFollowing(boolean enable) {
this.isFollowing = enable;
for (ISharedEditorListener editorListener : this.editorListeners) {
editorListener.followModeChanged(enable);
}
if (enable)
openDriverEditor();
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.IActivityProvider
*/
public void addActivityListener(IActivityListener listener) {
this.activityListeners.add(listener);
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.IActivityProvider
*/
public void removeActivityListener(IActivityListener listener) {
this.activityListeners.remove(listener);
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.IActivityProvider
*/
public void exec(final IActivity activity) {
if (activity instanceof EditorActivity) {
EditorActivity editorActivity = (EditorActivity) activity;
if (editorActivity.getType().equals(Type.Activated)) {
setActiveDriverEditor(editorActivity.getPath(), true);
} else if (editorActivity.getType().equals(Type.Closed)) {
removeDriverEditor(editorActivity.getPath(), true);
} else if (editorActivity.getType().equals(Type.Saved)) {
saveText(editorActivity.getPath());
}
}
if (activity instanceof TextEditActivity) {
execTextEdit((TextEditActivity) activity);
} else if (activity instanceof TextSelectionActivity) {
execTextSelection((TextSelectionActivity) activity);
} else if (activity instanceof ViewportActivity) {
execViewport((ViewportActivity) activity);
}
}
private void execTextEdit(TextEditActivity textEdit) {
String source = textEdit.getSource();
User user = Saros.getDefault().getSessionManager().getSharedProject()
.getParticipant(new JID(source));
/* set current execute activity to avoid circular executions. */
currentExecuteActivity = textEdit;
/*
* Really ugly hack. Because there is just one driver allowed at the
* moment we can use this information to set the color for contribution
* annotations, regardless of the real origin of contributions.
*/
JID driverJID = Saros.getDefault().getSessionManager()
.getSharedProject().getADriver().getJID();
if (driverJID == null) {
log.warn("There is no driver at all.");
}
IPath path = textEdit.getEditor();
IFile file = sharedProject.getProject().getFile(path);
replaceText(file, textEdit.offset, textEdit.length, textEdit.text,
(driverJID != null) ? driverJID.toString() : "");
Set<IEditorPart> editors = editorPool.getEditors(path);
for (IEditorPart editorPart : editors) {
editorAPI.setSelection(editorPart, new TextSelection(
textEdit.offset + textEdit.text.length(), 0), source,
shouldIFollow(user));
}
}
private void execTextSelection(TextSelectionActivity selection) {
IPath path = selection.getEditor();
TextSelection textSelection = new TextSelection(selection.getOffset(),
selection.getLength());
User user = sharedProject
.getParticipant(new JID(selection.getSource()));
if (user.isDriver()) {
setDriverTextSelection(user, textSelection);
}
if (path == null) {
EditorManager.log
.error("Received text selection but have no driver editor");
return;
}
Set<IEditorPart> editors = EditorManager.this.editorPool
.getEditors(path);
for (IEditorPart editorPart : editors) {
this.editorAPI.setSelection(editorPart, textSelection, selection
.getSource(), shouldIFollow(user));
}
}
// TODO selectable driver to follow
protected boolean shouldIFollow(User user) {
return isFollowing && user.isDriver();
}
private void execViewport(ViewportActivity viewport) {
if (isDriver)
return;
int top = viewport.getTopIndex();
int bottom = viewport.getBottomIndex();
IPath path = viewport.getEditor();
String source = viewport.getSource();
/*
* Check if source is an observed driver and his cursor is outside the
* viewport. Taking the last line of the driver's last selection might
* be a bit inaccurate.
*/
User user = sharedProject.getParticipant(new JID(source));
ITextSelection driverSelection = getDriverTextSelection(user);
// Check needed when viewport activity came before the first
// text selection activity.
boolean following = shouldIFollow(user);
if (driverSelection != null) {
int driverCursor = driverSelection.getEndLine();
following &= (driverCursor < top || driverCursor > bottom);
}
Set<IEditorPart> editors = this.editorPool.getEditors(path);
for (IEditorPart editorPart : editors) {
this.editorAPI.setViewport(editorPart, top, bottom, source,
following);
}
}
// TODO unify partActivated and partOpened
public void partOpened(IEditorPart editorPart) {
// if in follow mode and the opened editor is not the followed one,
// exit Follow Mode
checkFollowMode(editorPart);
if (!isSharedEditor(editorPart)) {
return;
}
this.editorPool.add(editorPart);
sharedEditorActivated(editorPart); // HACK
}
public void partActivated(IEditorPart editorPart) {
// if in follow mode and the activated editor is not the followed one,
// leave Follow Mode
checkFollowMode(editorPart);
if (!isSharedEditor(editorPart)) {
return;
}
sharedEditorActivated(editorPart);
}
protected void checkFollowMode(IEditorPart editorPart) {
// if the opened editor is not the followed one, leave following mode
IResource resource = this.editorAPI.getEditorResource(editorPart);
IPath path = resource.getProjectRelativePath();
if (isFollowing) {
if (activeDriverEditor != null
&& (!activeDriverEditor.equals(path) || !isSharedEditor(editorPart))) {
setEnableFollowing(false);
updateFollowModeUI();
}
}
}
protected void updateFollowModeUI() {
Util.runSafeSWTAsync(log, new Runnable() {
public void run() {
IViewPart sessionView = findView("de.fu_berlin.inf.dpp.ui.SessionView");
if (sessionView != null)
((SessionView) sessionView).updateFollowingMode();
}
});
}
public void partClosed(IEditorPart editorPart) {
if (!isSharedEditor(editorPart)) {
return;
}
IResource resource = this.editorAPI.getEditorResource(editorPart);
IPath path = resource.getProjectRelativePath();
// if closing the following editor, leave follow mode
if (isFollowing && activeDriverEditor != null
&& activeDriverEditor.equals(path)) {
setEnableFollowing(false);
updateFollowModeUI();
}
this.editorPool.remove(editorPart);
if (this.isDriver) {
removeDriverEditor(path, false);
}
}
/**
* Checks wether given resource is currently opened.
*
* @param path
* the project-relative path to the resource.
* @return <code>true</code> if the given resource is opened accoring to the
* editor pool.
*/
public boolean isOpened(IPath path) {
return this.editorPool.getEditors(path).size() > 0;
}
/**
* Gives the editors of given path.
*
* @param path
* the project-relative path to the resource.
* @return the set of editors
*/
public Set<IEditorPart> getEditors(IPath path) {
return this.editorPool.getEditors(path);
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.project.IActivityProvider
*/
public IActivity fromXML(XmlPullParser parser) {
try {
if (parser.getName().equals("editor")) {
return parseEditorActivity(parser);
} else if (parser.getName().equals("edit")) {
return parseTextEditActivity(parser);
} else if (parser.getName().equals("textSelection")) {
return parseTextSelection(parser);
} else if (parser.getName().equals("viewport")) {
return parseViewport(parser);
}
} catch (XmlPullParserException e) {
EditorManager.log.error("Couldn't parse message");
} catch (IOException e) {
EditorManager.log.error("Couldn't parse message");
}
return null;
}
/*
* (non-Javadoc)
*
* @see de.fu_berlin.inf.dpp.project.IActivityProvider
*/
public String toXML(IActivity activity) {
if (activity instanceof EditorActivity) {
EditorActivity editorActivity = (EditorActivity) activity;
// TODO What is that checksum?
return "<editor " + "path=\"" + editorActivity.getPath() + "\" "
+ "type=\"" + editorActivity.getType() + "\" " + "checksum=\""
+ editorActivity.getChecksum() + "\" />";
} else if (activity instanceof TextEditActivity) {
TextEditActivity textEditActivity = (TextEditActivity) activity;
return "<edit " + "path=\"" + textEditActivity.getEditor() + "\" "
+ "offset=\"" + textEditActivity.offset + "\" " + "replace=\""
+ textEditActivity.length + "\">" + "<![CDATA["
+ textEditActivity.text + "]]>" + "</edit>";
} else if (activity instanceof TextSelectionActivity) {
TextSelectionActivity textSelection = (TextSelectionActivity) activity;
assert textSelection.getEditor() != null;
return "<textSelection " + "offset=\"" + textSelection.getOffset()
+ "\" " + "length=\"" + textSelection.getLength() + "\" "
+ "editor=\"" + textSelection.getEditor().toPortableString()
+ "\" />";
} else if (activity instanceof ViewportActivity) {
ViewportActivity viewportActvity = (ViewportActivity) activity;
assert viewportActvity.getEditor() != null;
return "<viewport " + "top=\"" + viewportActvity.getTopIndex()
+ "\" " + "bottom=\"" + viewportActvity.getBottomIndex()
+ "\" " + "editor=\""
+ viewportActvity.getEditor().toPortableString() + "\" />";
}
return null;
}
private IActivity parseTextEditActivity(XmlPullParser parser)
throws XmlPullParserException, IOException {
// extract current editor for text edit.
String pathString = parser.getAttributeValue(null, "path");
Path path = pathString.equals("null") ? null : new Path(pathString);
int offset = Integer.parseInt(parser.getAttributeValue(null, "offset"));
// TODO This value is the length of the old text, so "replace" should be
// renamed.
int replace = Integer.parseInt(parser
.getAttributeValue(null, "replace"));
String text = "";
if (parser.next() == XmlPullParser.TEXT) {
text = parser.getText();
}
return new TextEditActivity(offset, text, replace, path);
}
private IActivity parseEditorActivity(XmlPullParser parser) {
String pathString = parser.getAttributeValue(null, "path");
String checksumString = parser.getAttributeValue(null, "checksum");
// TODO handle cases where the file is really named "null"
Path path = pathString.equals("null") ? null : new Path(pathString);
Type type = EditorActivity.Type.valueOf(parser.getAttributeValue(null,
"type"));
EditorActivity edit = new EditorActivity(type, path);
try {
long checksum = Long.parseLong(checksumString);
edit.setChecksum(checksum);
} catch (Exception e) {
/* exception during parse process */
}
return edit;
}
private TextSelectionActivity parseTextSelection(XmlPullParser parser) {
// TODO extract constants
int offset = Integer.parseInt(parser.getAttributeValue(null, "offset"));
int length = Integer.parseInt(parser.getAttributeValue(null, "length"));
String path = parser.getAttributeValue(null, "editor");
return new TextSelectionActivity(offset, length, Path
.fromPortableString(path));
}
private ViewportActivity parseViewport(XmlPullParser parser) {
int top = Integer.parseInt(parser.getAttributeValue(null, "top"));
int bottom = Integer.parseInt(parser.getAttributeValue(null, "bottom"));
String path = parser.getAttributeValue(null, "editor");
return new ViewportActivity(top, bottom, Path.fromPortableString(path));
}
private boolean isSharedEditor(IEditorPart editorPart) {
IResource resource = this.editorAPI.getEditorResource(editorPart);
return ((this.sharedProject != null) && (resource.getProject() == this.sharedProject
.getProject()));
}
private void replaceText(IFile file, int offset, int replace, String text,
String source) {
FileEditorInput input = new FileEditorInput(file);
IDocumentProvider provider = this.editorAPI.getDocumentProvider(input);
try {
if (!this.connectedFiles.contains(file)) {
provider.connect(input);
this.connectedFiles.add(file);
}
IDocument doc = provider.getDocument(input);
doc.replace(offset, replace, text);
EditorManager.this.lastRemoteEditTimes.put(file
.getProjectRelativePath(), System.currentTimeMillis());
IAnnotationModel model = provider.getAnnotationModel(input);
contributionAnnotationManager.insertAnnotation(model, offset, text
.length(), source);
// Don't disconnect from provider yet, because otherwise the text
// changes would be lost. We only disconnect when the document is
// reset or saved.
} catch (BadLocationException e) {
// TODO If this happens a resend of the original text should be
// initiated.
log
.error("Couldn't insert driver text because of bad location.",
e);
} catch (CoreException e) {
log.error("Couldn't insert driver text.", e);
}
}
/**
* Needs to be called from a UI thread.
*/
private void resetText(IFile file) {
if (!file.exists()) {
return;
}
FileEditorInput input = new FileEditorInput(file);
IDocumentProvider provider = this.editorAPI.getDocumentProvider(input);
if (this.connectedFiles.contains(file)) {
provider.disconnect(input);
this.connectedFiles.remove(file);
}
}
/**
* Saves the driver editor.
*
* @param path
* the project relative path to the resource that the driver was
* editing.
*/
public void saveText(IPath path) {
IFile file = this.sharedProject.getProject().getFile(path);
if (!file.exists()) {
EditorManager.log.warn("Cannot save file that does not exist:"
+ path.toString());
return;
}
for (ISharedEditorListener listener : this.editorListeners) {
listener.driverEditorSaved(path, true);
}
FileEditorInput input = new FileEditorInput(file);
try {
ResourceAttributes attributes = new ResourceAttributes();
attributes.setReadOnly(false);
file.setResourceAttributes(attributes);
IDocumentProvider provider = this.editorAPI
.getDocumentProvider(input);
// Save not necessary, if we have no modified document
if (!this.connectedFiles.contains(file)) {
log.warn("Saving not necessary (not connected)!");
return;
}
IDocument doc = provider.getDocument(input);
IAnnotationModel model = provider.getAnnotationModel(input);
model.connect(doc);
provider.saveDocument(new NullProgressMonitor(), input, doc, true);
EditorManager.log.debug("Saved document " + path);
model.disconnect(doc);
// TODO Set file readonly again?
provider.disconnect(input);
this.connectedFiles.remove(file);
} catch (CoreException e) {
EditorManager.log.error("Failed to save document.", e);
}
}
/**
* Sends an activity for clients to save the editor of given path.
*
* @param path
* the project relative path to the resource that the driver was
* editing.
*/
protected void sendEditorActivitySaved(IPath path) {
for (ISharedEditorListener listener : this.editorListeners) {
listener.driverEditorSaved(path, false);
}
IActivity activity = new EditorActivity(Type.Saved, path);
for (IActivityListener listener : this.activityListeners) {
listener.activityCreated(activity);
}
}
/**
* Sends given activity to all registered activity listeners.
*/
private void fireActivity(IActivity activity) {
for (IActivityListener listener : this.activityListeners) {
listener.activityCreated(activity);
}
}
// TODO CJ: review needed
private void activateOpenEditors() {
Util.runSafeSWTSync(log, new Runnable() {
public void run() {
for (IEditorPart editorPart : EditorManager.this.editorAPI
.getOpenEditors()) {
partOpened(editorPart);
}
IEditorPart activeEditor = EditorManager.this.editorAPI
.getActiveEditor();
if (activeEditor != null) {
sharedEditorActivated(activeEditor);
}
}
});
}
private void sharedEditorActivated(IEditorPart editorPart) {
if (!this.sharedProject.isDriver()) {
return;
}
IResource resource = this.editorAPI.getEditorResource(editorPart);
IPath editorPath = resource.getProjectRelativePath();
setActiveDriverEditor(editorPath, false);
ITextSelection selection = this.editorAPI.getSelection(editorPart);
setDriverTextSelection(Saros.getDefault().getLocalUser(), selection);
ILineRange viewport = this.editorAPI.getViewport(editorPart);
int startLine = viewport.getStartLine();
viewportChanged(startLine, startLine + viewport.getNumberOfLines(),
editorPath);
}
private void setAllEditorsToEditable() {
for (IEditorPart editor : this.editorPool.getAllEditors()) {
this.editorAPI.setEditable(editor, true);
}
}
/**
* Removes all annotations of a given type and for all users.
*
* @param annotationType
* the annotation type that will be removed.
*/
@SuppressWarnings("unchecked")
private void removeAllAnnotations(String annotationType) {
for (IEditorPart editor : this.editorPool.getAllEditors()) {
IEditorInput input = editor.getEditorInput();
IDocumentProvider provider = this.editorAPI
.getDocumentProvider(input);
IAnnotationModel model = provider.getAnnotationModel(input);
if (model != null) {
for (Iterator<Annotation> it = model.getAnnotationIterator(); it
.hasNext();) {
Annotation annotation = it.next();
if (annotation.getType().startsWith(annotationType)) {
model.removeAnnotation(annotation);
}
}
}
}
}
/**
* Removes all annotations of given user and type.
*
* @param forUserID
* the id of the user whos annotations will be removed, if null
* annotations of given type for all users are removed
* @param typeAnnotation
* the type of the annotations to remove
*/
private void removeAllAnnotations(String forUserID, String typeAnnotation) {
for (IEditorPart editor : this.editorPool.getAllEditors()) {
IEditorInput input = editor.getEditorInput();
IDocumentProvider provider = this.editorAPI
.getDocumentProvider(input);
IAnnotationModel model = provider.getAnnotationModel(input);
if (model == null) {
continue;
}
for (@SuppressWarnings("unchecked")
Iterator<Annotation> it = model.getAnnotationIterator(); it
.hasNext();) {
Annotation annotation = it.next();
String type = annotation.getType();
if ((typeAnnotation == null) || (!typeAnnotation.equals(type))) {
continue;
}
AnnotationSaros sarosAnnotation = (AnnotationSaros) annotation;
if (forUserID == null
|| sarosAnnotation.getSource().equals(forUserID)) {
model.removeAnnotation(annotation);
}
}
}
}
private EditorManager() {
setEditorAPI(new EditorAPI());
if ((Saros.getDefault() != null)
&& (Saros.getDefault().getSessionManager() != null)) {
Saros.getDefault().getSessionManager().addSessionListener(this);
}
}
/**
* Sets the currently active driver editor.
*
* @param path
* the project-relative path to the resource that the editor is
* currently editting.
* @param replicated
* <code>false</code> if this action originates on this client.
* <code>false</code> if it is an replication of an action from
* another participant of the shared project.
*/
private void setActiveDriverEditor(IPath path, boolean replicated) {
this.activeDriverEditor = path;
this.driverEditors.add(path);
for (ISharedEditorListener listener : this.editorListeners) {
listener.activeDriverEditorChanged(this.activeDriverEditor,
replicated);
}
if (replicated) {
if (this.isFollowing) {
Util.runSafeSWTSync(log, new Runnable() {
public void run() {
openDriverEditor();
}
});
}
} else {
IActivity activity = new EditorActivity(Type.Activated, path);
for (IActivityListener listener : this.activityListeners) {
listener.activityCreated(activity);
}
}
}
/**
* Removes the given editor from the list of editors that the driver is
* currently using.
*
* @param path
* the path to the resource that the driver was editting.
* @param replicated
* <code>false</code> if this action originates on this client.
* <code>true</code> if it is an replication of an action from
* another participant of the shared project.
*/
private void removeDriverEditor(final IPath path, boolean replicated) {
if (path.equals(this.activeDriverEditor)) {
setActiveDriverEditor(null, replicated);
}
this.driverEditors.remove(path);
for (ISharedEditorListener listener : this.editorListeners) {
listener.driverEditorRemoved(path, replicated);
}
if (replicated) {
Util.runSafeSWTSync(log, new Runnable() {
public void run() {
IFile file = EditorManager.this.sharedProject.getProject()
.getFile(path);
resetText(file);
if (!EditorManager.this.isFollowing) {
return;
}
Set<IEditorPart> editors = EditorManager.this.editorPool
.getEditors(path);
for (IEditorPart part : editors) {
EditorManager.this.editorAPI.closeEditor(part);
}
}
});
} else {
IActivity activity = new EditorActivity(Type.Closed, path);
for (IActivityListener listener : this.activityListeners) {
listener.activityCreated(activity);
}
}
}
/**
* @param selection
* sets the current text selection that is used by the driver.
*/
private void setDriverTextSelection(User user, ITextSelection selection) {
if (user.isDriver()) {
this.driverTextSelections.put(user, selection);
}
}
/**
* To get the java system time of the last local edit operation.
*
* @param path
* the project relative path of the resource
* @return java system time of last local edit
*/
public long getLastEditTime(IPath path) {
return this.lastEditTimes.get(path);
}
/**
* To get the java system time of the last remote edit operation.
*
* @param path
* the project relative path of the resource
* @return java system time of last remote edit
*/
public long getLastRemoteEditTime(IPath path) {
return this.lastRemoteEditTimes.get(path);
}
/**
* to get the information whether the user is in following mode or not
*
* @return <code>true</code> when in following mode, otherwise
* <code>false</code>
*/
public boolean isFollowing() {
return isFollowing;
}
}
| true | true | private void convertLineDelimiters(IEditorPart editorPart) {
EditorManager.log.debug("Converting line delimiters...");
// get path of file
IFile file = ((FileEditorInput) editorPart.getEditorInput())
.getFile();
IPath[] paths = new IPath[1];
paths[0] = file.getFullPath();
boolean makeReadable = false;
ResourceAttributes resourceAttributes = file
.getResourceAttributes();
if (resourceAttributes.isReadOnly()) {
resourceAttributes.setReadOnly(false);
try {
file.setResourceAttributes(resourceAttributes);
makeReadable = true;
} catch (CoreException e) {
log.warn(
"Error making file readable for delimiter conversion:",
e);
}
}
ITextFileBufferManager buffManager = FileBuffers
.getTextFileBufferManager();
// convert operation to change line delimiters
TextFileBufferOperation convertOperation = new ConvertLineDelimitersOperation(
"\n");
// operation runner for the convert operation
FileBufferOperationRunner runner = new FileBufferOperationRunner(
buffManager, null);
// execute convert operation in runner
try {
runner.execute(paths, convertOperation,
new NullProgressMonitor());
} catch (OperationCanceledException e) {
EditorManager.log.error("Can't convert line delimiters:", e);
} catch (CoreException e) {
EditorManager.log.error("Can't convert line delimiters:", e);
}
if (makeReadable) {
resourceAttributes.setReadOnly(true);
try {
file.setResourceAttributes(resourceAttributes);
} catch (CoreException e) {
EditorManager.log
.error(
"Error restoring readable state to false after delimiter conversion:",
e);
}
}
}
| private void convertLineDelimiters(IEditorPart editorPart) {
EditorManager.log.debug("Converting line delimiters...");
// get path of file
IFile file = ((FileEditorInput) editorPart.getEditorInput())
.getFile();
IPath[] paths = new IPath[1];
paths[0] = file.getFullPath();
boolean makeReadable = false;
ResourceAttributes resourceAttributes = file
.getResourceAttributes();
if (resourceAttributes.isReadOnly()) {
resourceAttributes.setReadOnly(false);
try {
file.setResourceAttributes(resourceAttributes);
makeReadable = true;
} catch (CoreException e) {
log.error(
"Error making file readable for delimiter conversion:",
e);
}
}
ITextFileBufferManager buffManager = FileBuffers
.getTextFileBufferManager();
// convert operation to change line delimiters
TextFileBufferOperation convertOperation = new ConvertLineDelimitersOperation(
"\n");
// operation runner for the convert operation
FileBufferOperationRunner runner = new FileBufferOperationRunner(
buffManager, null);
// execute convert operation in runner
try {
runner.execute(paths, convertOperation,
new NullProgressMonitor());
} catch (OperationCanceledException e) {
EditorManager.log.error("Can't convert line delimiters:", e);
} catch (CoreException e) {
EditorManager.log.error("Can't convert line delimiters:", e);
}
if (makeReadable) {
resourceAttributes.setReadOnly(true);
try {
file.setResourceAttributes(resourceAttributes);
} catch (CoreException e) {
EditorManager.log
.error(
"Error restoring readable state to false after delimiter conversion:",
e);
}
}
}
|
diff --git a/iwsn/wsn-device-drivers/src/main/java/de/uniluebeck/itm/wsn/devicedrivers/jennic/FlashProgramOperation.java b/iwsn/wsn-device-drivers/src/main/java/de/uniluebeck/itm/wsn/devicedrivers/jennic/FlashProgramOperation.java
index 30e929ef..797fc1fd 100644
--- a/iwsn/wsn-device-drivers/src/main/java/de/uniluebeck/itm/wsn/devicedrivers/jennic/FlashProgramOperation.java
+++ b/iwsn/wsn-device-drivers/src/main/java/de/uniluebeck/itm/wsn/devicedrivers/jennic/FlashProgramOperation.java
@@ -1,194 +1,196 @@
/**********************************************************************************************************************
* Copyright (c) 2010, coalesenses GmbH *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* - Redistributions of source code must retain the above copyright notice, this list of conditions and the following *
* disclaimer. *
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* - Neither the name of the coalesenses GmbH nor the names of its contributors may be used to endorse or promote *
* products derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, *
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE *
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY *
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
**********************************************************************************************************************/
package de.uniluebeck.itm.wsn.devicedrivers.jennic;
import de.uniluebeck.itm.wsn.devicedrivers.exceptions.ProgramChipMismatchException;
import de.uniluebeck.itm.wsn.devicedrivers.generic.*;
import de.uniluebeck.itm.wsn.devicedrivers.jennic.Sectors.SectorIndex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// -------------------------------------------------------------------------
/**
*
*/
public class FlashProgramOperation extends iSenseDeviceOperation {
// /Logging
private static final Logger log = LoggerFactory.getLogger(FlashProgramOperation.class);
// /
private JennicDevice device;
// /
private IDeviceBinFile program;
private boolean rebootAfterFlashing;
// -------------------------------------------------------------------------
/**
*
*/
public FlashProgramOperation(JennicDevice device, IDeviceBinFile program, boolean rebootAfterFlashing) {
super(device);
this.device = device;
this.program = program;
this.rebootAfterFlashing = rebootAfterFlashing;
}
// -------------------------------------------------------------------------
/**
*
*/
private boolean programFlash() throws Exception {
JennicBinFile jennicProgram = null;
// Enter programming mode
if (!device.enterProgrammingMode()) {
log.error("Unable to enter programming mode");
return false;
}
// Wait for a connection
while (!isCancelled() && !device.waitForConnection())
log.info("Still waiting for a connection");
// Return with success if the user has requested to cancel this
// operation
if (isCancelled()) {
log.debug("Operation has been cancelled");
device.operationCancelled(this);
return false;
}
// Connection established, determine chip type
ChipType chipType = device.getChipType();
//log.debug("Chip type is " + chipType);
// Check if file and current chip match
if (!program.isCompatible(chipType)) {
log.error("Chip type(" + chipType + ") and bin-program type(" + program.getFileType() + ") do not match");
throw new ProgramChipMismatchException(chipType, program.getFileType());
}
// insert flash header of device
try {
jennicProgram = (JennicBinFile) program;
- boolean insertedHeader = false;
try {
- insertedHeader = jennicProgram.insertHeader(device.getFlashHeader());
+ if (!jennicProgram.insertHeader(device.getFlashHeader())) {
+ log.error("Unable to write flash header to binary file.");
+ throw new RuntimeException("Unable to write flash header to binary file.");
+ }
} catch (Exception e) {
log.error("Unable to write flash header to binary file.");
throw e;
}
} catch (ClassCastException e) {
log.error("Supplied binary file for programming the jennic device was not a jennic file. Unable to insert flash header.");
return false;
}
device.configureFlash(chipType);
device.eraseFlash(SectorIndex.FIRST);
device.eraseFlash(SectorIndex.SECOND);
device.eraseFlash(SectorIndex.THIRD);
// Write program to flash
BinFileDataBlock block = null;
int blockCount = 0;
while ((block = program.getNextBlock()) != null) {
try {
device.writeFlash(block.address, block.data, 0, block.data.length);
} catch (Exception e) {
log.debug("Error while reading flash! Operation will be cancelled!");
device.operationCancelled(this);
return false;
}
// Notify listeners of the new status
float progress = ((float) blockCount) / ((float) program.getBlockCount());
device.operationProgress(Operation.PROGRAM, progress);
// Return with success if the user has requested to cancel this
// operation
if (isCancelled()) {
log.debug("Operation has been cancelled");
device.operationCancelled(this);
return false;
}
blockCount++;
}
// Reboot (if requested by the user)
if (rebootAfterFlashing) {
log.debug("Rebooting device");
device.reset();
}
return true;
}
// -------------------------------------------------------------------------
/**
*
*/
public void run() {
try {
if (programFlash() && program != null) {
operationDone(program);
return;
}
} catch (Throwable t) {
log.error("Unhandled error in thread: " + t, t);
operationDone(t);
return;
} finally {
try {
device.leaveProgrammingMode();
} catch (Throwable e) {
log.warn("Unable to leave programming mode:" + e, e);
}
}
// Indicate failure
operationDone(null);
}
// -------------------------------------------------------------------------
/**
*
*/
@Override
public Operation getOperation() {
return Operation.PROGRAM;
}
}
| false | true | private boolean programFlash() throws Exception {
JennicBinFile jennicProgram = null;
// Enter programming mode
if (!device.enterProgrammingMode()) {
log.error("Unable to enter programming mode");
return false;
}
// Wait for a connection
while (!isCancelled() && !device.waitForConnection())
log.info("Still waiting for a connection");
// Return with success if the user has requested to cancel this
// operation
if (isCancelled()) {
log.debug("Operation has been cancelled");
device.operationCancelled(this);
return false;
}
// Connection established, determine chip type
ChipType chipType = device.getChipType();
//log.debug("Chip type is " + chipType);
// Check if file and current chip match
if (!program.isCompatible(chipType)) {
log.error("Chip type(" + chipType + ") and bin-program type(" + program.getFileType() + ") do not match");
throw new ProgramChipMismatchException(chipType, program.getFileType());
}
// insert flash header of device
try {
jennicProgram = (JennicBinFile) program;
boolean insertedHeader = false;
try {
insertedHeader = jennicProgram.insertHeader(device.getFlashHeader());
} catch (Exception e) {
log.error("Unable to write flash header to binary file.");
throw e;
}
} catch (ClassCastException e) {
log.error("Supplied binary file for programming the jennic device was not a jennic file. Unable to insert flash header.");
return false;
}
device.configureFlash(chipType);
device.eraseFlash(SectorIndex.FIRST);
device.eraseFlash(SectorIndex.SECOND);
device.eraseFlash(SectorIndex.THIRD);
// Write program to flash
BinFileDataBlock block = null;
int blockCount = 0;
while ((block = program.getNextBlock()) != null) {
try {
device.writeFlash(block.address, block.data, 0, block.data.length);
} catch (Exception e) {
log.debug("Error while reading flash! Operation will be cancelled!");
device.operationCancelled(this);
return false;
}
// Notify listeners of the new status
float progress = ((float) blockCount) / ((float) program.getBlockCount());
device.operationProgress(Operation.PROGRAM, progress);
// Return with success if the user has requested to cancel this
// operation
if (isCancelled()) {
log.debug("Operation has been cancelled");
device.operationCancelled(this);
return false;
}
blockCount++;
}
// Reboot (if requested by the user)
if (rebootAfterFlashing) {
log.debug("Rebooting device");
device.reset();
}
return true;
}
| private boolean programFlash() throws Exception {
JennicBinFile jennicProgram = null;
// Enter programming mode
if (!device.enterProgrammingMode()) {
log.error("Unable to enter programming mode");
return false;
}
// Wait for a connection
while (!isCancelled() && !device.waitForConnection())
log.info("Still waiting for a connection");
// Return with success if the user has requested to cancel this
// operation
if (isCancelled()) {
log.debug("Operation has been cancelled");
device.operationCancelled(this);
return false;
}
// Connection established, determine chip type
ChipType chipType = device.getChipType();
//log.debug("Chip type is " + chipType);
// Check if file and current chip match
if (!program.isCompatible(chipType)) {
log.error("Chip type(" + chipType + ") and bin-program type(" + program.getFileType() + ") do not match");
throw new ProgramChipMismatchException(chipType, program.getFileType());
}
// insert flash header of device
try {
jennicProgram = (JennicBinFile) program;
try {
if (!jennicProgram.insertHeader(device.getFlashHeader())) {
log.error("Unable to write flash header to binary file.");
throw new RuntimeException("Unable to write flash header to binary file.");
}
} catch (Exception e) {
log.error("Unable to write flash header to binary file.");
throw e;
}
} catch (ClassCastException e) {
log.error("Supplied binary file for programming the jennic device was not a jennic file. Unable to insert flash header.");
return false;
}
device.configureFlash(chipType);
device.eraseFlash(SectorIndex.FIRST);
device.eraseFlash(SectorIndex.SECOND);
device.eraseFlash(SectorIndex.THIRD);
// Write program to flash
BinFileDataBlock block = null;
int blockCount = 0;
while ((block = program.getNextBlock()) != null) {
try {
device.writeFlash(block.address, block.data, 0, block.data.length);
} catch (Exception e) {
log.debug("Error while reading flash! Operation will be cancelled!");
device.operationCancelled(this);
return false;
}
// Notify listeners of the new status
float progress = ((float) blockCount) / ((float) program.getBlockCount());
device.operationProgress(Operation.PROGRAM, progress);
// Return with success if the user has requested to cancel this
// operation
if (isCancelled()) {
log.debug("Operation has been cancelled");
device.operationCancelled(this);
return false;
}
blockCount++;
}
// Reboot (if requested by the user)
if (rebootAfterFlashing) {
log.debug("Rebooting device");
device.reset();
}
return true;
}
|
diff --git a/Servlets/src/fr/imie/servlet/Projet.java b/Servlets/src/fr/imie/servlet/Projet.java
index 2e3d874..d1470e4 100644
--- a/Servlets/src/fr/imie/servlet/Projet.java
+++ b/Servlets/src/fr/imie/servlet/Projet.java
@@ -1,313 +1,313 @@
package fr.imie.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import fr.imie.formation.DAO.exceptions.DAOException;
import fr.imie.formation.DTO.ProjetDTO;
import fr.imie.formation.DTO.PromotionDTO;
import fr.imie.formation.DTO.StatutProjetDTO;
import fr.imie.formation.DTO.UtilisateurDTO;
import fr.imie.formation.factory.DAOFactory1;
import fr.imie.formation.services.exceptions.ServiceException;
import fr.imie.formation.transactionalFramework.exception.TransactionalConnectionException;
/**
* Servlet implementation class Projet
*/
@WebServlet("/Projet")
public class Projet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Projet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
// Afficher un projet marche bien
if (request.getParameter("numligne") != null
&& request.getParameter("update") == null
&& request.getParameter("delete") == null) {
int ligne = Integer.valueOf(request.getParameter("numligne"));
Object listObj = session.getAttribute("listeProjet");
@SuppressWarnings("unchecked")
List<ProjetDTO> listeProjet = (List<ProjetDTO>) listObj;
ProjetDTO projet = listeProjet.get(ligne);
//session.removeAttribute("listeProjet");
try {
ProjetDTO projetDTO = DAOFactory1.getInstance().createProjetService(null).readProjet(projet);
request.setAttribute("projetDTO", projetDTO);
List<UtilisateurDTO> listeUtil = DAOFactory1.getInstance().createUtilisateurService(null).readUtilisateurProjet(projetDTO);
session.setAttribute("listeUtil", listeUtil);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("/ProjetConsult.jsp")
.forward(request, response);
}
//création projet
else if (request.getParameter("numligne") == null
&& request.getParameter("create") != null
&& request.getParameter("create").equals("creer")) {
List<StatutProjetDTO>listeStatut = null;
List<UtilisateurDTO> listeForChef =null;
try {
//listeStatut=DAOFactory1.getInstance().createProjetService(null).readAllStatutProjet();
listeForChef= DAOFactory1.getInstance().createUtilisateurService(null).readAllUtilisateur();
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//request.setAttribute("listeStatut", listeStatut);
request.setAttribute("listeForChef", listeForChef);
request.getRequestDispatcher("./ProjetCreate.jsp").forward(request,response);
}
//modification projet
else if (request.getParameter("update") != null
&& request.getParameter("update").equals("modifier")) {
request.setAttribute("projetDTO",getProjet(request.getParameter("numProjet")));
List<UtilisateurDTO> listeForChef =null;
List<StatutProjetDTO>listeStatut = null;
List<UtilisateurDTO> listeUtil = null;
try {
listeForChef= DAOFactory1.getInstance().createUtilisateurService(null).readAllUtilisateur();
listeStatut=DAOFactory1.getInstance().createProjetService(null).readAllStatutProjet();
listeUtil = DAOFactory1.getInstance().createUtilisateurService(null).readUtilisateurProjet(getProjet(request.getParameter("numProjet")));
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("listeForChef", listeForChef);
request.setAttribute("listeStatut", listeStatut);
request.setAttribute("listeUtil", listeUtil);
request.getRequestDispatcher("./ProjetUpdate.jsp").forward(request,response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Modifier un projet
if (request.getParameter("updateAction") != null
&& request.getParameter("updateAction").equals("Confirmer")) {
ProjetDTO projetUpdate = getProjet(request.getParameter("numProjet"));
projetUpdate.setIntitule(request.getParameter("intituleProjet"));
projetUpdate.setDescription(request.getParameter("descriptionProjet"));
//modif du statut
String statutParam = request.getParameter("statutProjet");
StatutProjetDTO statut =new StatutProjetDTO();
Integer statutNum = null;
if (statutParam != null){
statutNum = Integer.valueOf(statutParam);
}
if (statutNum!= null){
StatutProjetDTO statutToUpdate = new StatutProjetDTO();
statutToUpdate.setNum(statutNum);
try {
statut = DAOFactory1.getInstance().createProjetService(null).readStatutProjet(statutToUpdate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
projetUpdate.setStatutProjet(statut);
//modif chef de projet
String chefParam = request.getParameter("chefProjet");
UtilisateurDTO chefProjet = new UtilisateurDTO();
Integer chefNum = null;
if (chefParam != null) {
chefNum = Integer.valueOf(chefParam);
}
if(chefNum !=null){
UtilisateurDTO chefUpdate = new UtilisateurDTO();
chefUpdate.setNum(chefNum);
try {
chefProjet = DAOFactory1.getInstance().createUtilisateurService(null).readUtilisateur(chefUpdate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
projetUpdate.setChefDeProjet(chefProjet);
try {
DAOFactory1.getInstance().createProjetService(null).updateProjet(projetUpdate);
DAOFactory1.getInstance().createProjetService(null).ajoutChefDeProjet(projetUpdate);
request.setAttribute("action", "updateAction");
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("projetDTO",
getProjet(request.getParameter("numProjet")));
request.getRequestDispatcher("./ProjetConsult.jsp").forward(request,
response);
}
//ajout d' l'utilisateur au projet
if (request.getParameter("envoyerInvite")!=null){
ProjetDTO projetForUtil = getProjet(request.getParameter("projetForInvitation"));
//request.setAttribute("projetDTO", projetForUtil);// envoie sur la fiche Projet mais sans les participants
UtilisateurDTO utilForProjet = new UtilisateurDTO();
String numUtil = request.getParameter("numUtilisateur");
int numUtilInt = Integer.valueOf(numUtil);
utilForProjet.setNum(numUtilInt);
try {
DAOFactory1.getInstance().createProjetService(null).addProjetUtil(utilForProjet, projetForUtil);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("./ProjetConsult.jsp").forward(request, response);
}
//creation d'un projet
else if (request.getParameter("createAction") != null
&& request.getParameter("createAction").equals("ajouter")) {
ProjetDTO projetCreate = new ProjetDTO();
projetCreate.setIntitule(request.getParameter("intituleProjet"));
projetCreate.setDescription(request.getParameter("descriptionProjet"));
//affectation du statut 1 = ouvert
StatutProjetDTO statutProjet = new StatutProjetDTO();
statutProjet.setNum(1);
projetCreate.setStatutProjet(statutProjet);
try {
DAOFactory1.getInstance().createProjetService(null).createProjet(projetCreate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("createAction", "ajouter");
request.setAttribute("projet", projetCreate);
request.getRequestDispatcher("./ProjetConsult.jsp").forward(request,
response);
}
//suppression de projet
else if (request.getParameter("deleteAction") != null
- & request.getParameter("deleteAction").equals("supprimer")) {
+ && request.getParameter("deleteAction").equals("supprimer")) {
ProjetDTO projetDelete = getProjet(request.getParameter("numProjet"));
try {
DAOFactory1.getInstance().createProjetService(null).deleteProjet(projetDelete);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("./ListProjetView");
}
}
private ProjetDTO getProjet(String requestNumProjet) {
ProjetDTO projetDTO = new ProjetDTO();
int numProjet = Integer.valueOf(requestNumProjet);
ProjetDTO projetTemp = new ProjetDTO();
projetTemp.setNum(numProjet);
try {
projetDTO = DAOFactory1.getInstance().createProjetService(null).readProjet(projetTemp);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return projetDTO;
}
}
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Modifier un projet
if (request.getParameter("updateAction") != null
&& request.getParameter("updateAction").equals("Confirmer")) {
ProjetDTO projetUpdate = getProjet(request.getParameter("numProjet"));
projetUpdate.setIntitule(request.getParameter("intituleProjet"));
projetUpdate.setDescription(request.getParameter("descriptionProjet"));
//modif du statut
String statutParam = request.getParameter("statutProjet");
StatutProjetDTO statut =new StatutProjetDTO();
Integer statutNum = null;
if (statutParam != null){
statutNum = Integer.valueOf(statutParam);
}
if (statutNum!= null){
StatutProjetDTO statutToUpdate = new StatutProjetDTO();
statutToUpdate.setNum(statutNum);
try {
statut = DAOFactory1.getInstance().createProjetService(null).readStatutProjet(statutToUpdate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
projetUpdate.setStatutProjet(statut);
//modif chef de projet
String chefParam = request.getParameter("chefProjet");
UtilisateurDTO chefProjet = new UtilisateurDTO();
Integer chefNum = null;
if (chefParam != null) {
chefNum = Integer.valueOf(chefParam);
}
if(chefNum !=null){
UtilisateurDTO chefUpdate = new UtilisateurDTO();
chefUpdate.setNum(chefNum);
try {
chefProjet = DAOFactory1.getInstance().createUtilisateurService(null).readUtilisateur(chefUpdate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
projetUpdate.setChefDeProjet(chefProjet);
try {
DAOFactory1.getInstance().createProjetService(null).updateProjet(projetUpdate);
DAOFactory1.getInstance().createProjetService(null).ajoutChefDeProjet(projetUpdate);
request.setAttribute("action", "updateAction");
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("projetDTO",
getProjet(request.getParameter("numProjet")));
request.getRequestDispatcher("./ProjetConsult.jsp").forward(request,
response);
}
//ajout d' l'utilisateur au projet
if (request.getParameter("envoyerInvite")!=null){
ProjetDTO projetForUtil = getProjet(request.getParameter("projetForInvitation"));
//request.setAttribute("projetDTO", projetForUtil);// envoie sur la fiche Projet mais sans les participants
UtilisateurDTO utilForProjet = new UtilisateurDTO();
String numUtil = request.getParameter("numUtilisateur");
int numUtilInt = Integer.valueOf(numUtil);
utilForProjet.setNum(numUtilInt);
try {
DAOFactory1.getInstance().createProjetService(null).addProjetUtil(utilForProjet, projetForUtil);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("./ProjetConsult.jsp").forward(request, response);
}
//creation d'un projet
else if (request.getParameter("createAction") != null
&& request.getParameter("createAction").equals("ajouter")) {
ProjetDTO projetCreate = new ProjetDTO();
projetCreate.setIntitule(request.getParameter("intituleProjet"));
projetCreate.setDescription(request.getParameter("descriptionProjet"));
//affectation du statut 1 = ouvert
StatutProjetDTO statutProjet = new StatutProjetDTO();
statutProjet.setNum(1);
projetCreate.setStatutProjet(statutProjet);
try {
DAOFactory1.getInstance().createProjetService(null).createProjet(projetCreate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("createAction", "ajouter");
request.setAttribute("projet", projetCreate);
request.getRequestDispatcher("./ProjetConsult.jsp").forward(request,
response);
}
//suppression de projet
else if (request.getParameter("deleteAction") != null
& request.getParameter("deleteAction").equals("supprimer")) {
ProjetDTO projetDelete = getProjet(request.getParameter("numProjet"));
try {
DAOFactory1.getInstance().createProjetService(null).deleteProjet(projetDelete);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("./ListProjetView");
}
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Modifier un projet
if (request.getParameter("updateAction") != null
&& request.getParameter("updateAction").equals("Confirmer")) {
ProjetDTO projetUpdate = getProjet(request.getParameter("numProjet"));
projetUpdate.setIntitule(request.getParameter("intituleProjet"));
projetUpdate.setDescription(request.getParameter("descriptionProjet"));
//modif du statut
String statutParam = request.getParameter("statutProjet");
StatutProjetDTO statut =new StatutProjetDTO();
Integer statutNum = null;
if (statutParam != null){
statutNum = Integer.valueOf(statutParam);
}
if (statutNum!= null){
StatutProjetDTO statutToUpdate = new StatutProjetDTO();
statutToUpdate.setNum(statutNum);
try {
statut = DAOFactory1.getInstance().createProjetService(null).readStatutProjet(statutToUpdate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
projetUpdate.setStatutProjet(statut);
//modif chef de projet
String chefParam = request.getParameter("chefProjet");
UtilisateurDTO chefProjet = new UtilisateurDTO();
Integer chefNum = null;
if (chefParam != null) {
chefNum = Integer.valueOf(chefParam);
}
if(chefNum !=null){
UtilisateurDTO chefUpdate = new UtilisateurDTO();
chefUpdate.setNum(chefNum);
try {
chefProjet = DAOFactory1.getInstance().createUtilisateurService(null).readUtilisateur(chefUpdate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
projetUpdate.setChefDeProjet(chefProjet);
try {
DAOFactory1.getInstance().createProjetService(null).updateProjet(projetUpdate);
DAOFactory1.getInstance().createProjetService(null).ajoutChefDeProjet(projetUpdate);
request.setAttribute("action", "updateAction");
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("projetDTO",
getProjet(request.getParameter("numProjet")));
request.getRequestDispatcher("./ProjetConsult.jsp").forward(request,
response);
}
//ajout d' l'utilisateur au projet
if (request.getParameter("envoyerInvite")!=null){
ProjetDTO projetForUtil = getProjet(request.getParameter("projetForInvitation"));
//request.setAttribute("projetDTO", projetForUtil);// envoie sur la fiche Projet mais sans les participants
UtilisateurDTO utilForProjet = new UtilisateurDTO();
String numUtil = request.getParameter("numUtilisateur");
int numUtilInt = Integer.valueOf(numUtil);
utilForProjet.setNum(numUtilInt);
try {
DAOFactory1.getInstance().createProjetService(null).addProjetUtil(utilForProjet, projetForUtil);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("./ProjetConsult.jsp").forward(request, response);
}
//creation d'un projet
else if (request.getParameter("createAction") != null
&& request.getParameter("createAction").equals("ajouter")) {
ProjetDTO projetCreate = new ProjetDTO();
projetCreate.setIntitule(request.getParameter("intituleProjet"));
projetCreate.setDescription(request.getParameter("descriptionProjet"));
//affectation du statut 1 = ouvert
StatutProjetDTO statutProjet = new StatutProjetDTO();
statutProjet.setNum(1);
projetCreate.setStatutProjet(statutProjet);
try {
DAOFactory1.getInstance().createProjetService(null).createProjet(projetCreate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("createAction", "ajouter");
request.setAttribute("projet", projetCreate);
request.getRequestDispatcher("./ProjetConsult.jsp").forward(request,
response);
}
//suppression de projet
else if (request.getParameter("deleteAction") != null
&& request.getParameter("deleteAction").equals("supprimer")) {
ProjetDTO projetDelete = getProjet(request.getParameter("numProjet"));
try {
DAOFactory1.getInstance().createProjetService(null).deleteProjet(projetDelete);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("./ListProjetView");
}
}
|
diff --git a/alfresco-mobile-android/src/org/alfresco/mobile/android/ui/filebrowser/LocalFileExplorerFragment.java b/alfresco-mobile-android/src/org/alfresco/mobile/android/ui/filebrowser/LocalFileExplorerFragment.java
index 0a1d01e4..5e79e250 100644
--- a/alfresco-mobile-android/src/org/alfresco/mobile/android/ui/filebrowser/LocalFileExplorerFragment.java
+++ b/alfresco-mobile-android/src/org/alfresco/mobile/android/ui/filebrowser/LocalFileExplorerFragment.java
@@ -1,476 +1,476 @@
/*******************************************************************************
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco Mobile for Android.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.alfresco.mobile.android.ui.filebrowser;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.mobile.android.api.model.ListingContext;
import org.alfresco.mobile.android.api.model.PagingResult;
import org.alfresco.mobile.android.api.model.impl.PagingResultImpl;
import org.alfresco.mobile.android.application.R;
import org.alfresco.mobile.android.application.utils.SessionUtils;
import org.alfresco.mobile.android.ui.filebrowser.FolderAdapter.FolderBookmark;
import org.alfresco.mobile.android.ui.fragments.BaseListFragment;
import org.alfresco.mobile.android.application.manager.StorageManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Loader;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Spinner;
import android.widget.TextView;
public abstract class LocalFileExplorerFragment extends BaseListFragment implements LoaderCallbacks<List<File>>, OnClickListener
{
public static final String TAG = "LocalFileExplorerFragment";
public static final String ARGUMENT_FOLDER = "folder";
public static final String ARGUMENT_FOLDERPATH = "folderPath";
public static final String MODE = "mode";
public static final int MODE_LISTING = 1;
public static final int MODE_PICK_FILE = 2;
public static final int MODE_IMPORT = 3;
protected List<File> selectedItems = new ArrayList<File>(1);
private int titleId;
enum fileLocation { INITIAL_FOLDER, DOWNLOAD_FOLDER, SDCARD_ROOT };
private fileLocation currentLocation = fileLocation.INITIAL_FOLDER;
private File userLocation = null;
private File downloadLocation = null;
private File sdCardLocation = null;
private File cameraLocation;
private TextView pathText = null;
private HorizontalScrollView pathTextScroller = null;
public LocalFileExplorerFragment()
{
loaderId = LocalFileExplorerLoader.ID;
callback = this;
emptyListMessageId = R.string.empty_child;
}
public static Bundle createBundleArgs(File folder)
{
return createBundleArgs(folder, null);
}
public static Bundle createBundleArgs(String folderPath)
{
return createBundleArgs(null, folderPath);
}
public static Bundle createBundleArgs(File folder, String path)
{
Bundle args = new Bundle();
args.putSerializable(ARGUMENT_FOLDER, folder);
args.putSerializable(ARGUMENT_FOLDERPATH, path);
return args;
}
@Override
public void onStart()
{
retrieveTitle();
if (getDialog() != null)
{
getDialog().setTitle(titleId);
}
else
{
getActivity().getActionBar().show();
getActivity().setTitle(titleId);
}
super.onStart();
}
private void retrieveTitle(){
Bundle b = getArguments();
if (b.getInt(MODE) == MODE_LISTING)
{
titleId = R.string.menu_downloads;
}
else if (b.getInt(MODE) == MODE_PICK_FILE)
{
titleId = R.string.upload_pick_document;
}
}
private int max (int val1, int val2)
{
return (val1 > val2 ? val1 : val2);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
View toolButton = null;
LayoutInflater inflater = LayoutInflater.from(getActivity());
View v = inflater.inflate(R.layout.sdk_list, null);
View toolsGroup = v.findViewById(R.id.tools_group);
//Set to a decent size for a file browser, using minimum Android 'NORMAL' screen size as smallest possible.
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
v.setMinimumHeight(size.y);
- v.setMinimumWidth(size.x);
+ v.setMinimumWidth(max(size.x/2, 320));
pathTextScroller = (HorizontalScrollView)v.findViewById(R.id.pathTextScrollView);
pathTextScroller.setVisibility(View.VISIBLE);
pathText = (TextView)v.findViewById(R.id.pathText);
if (toolsGroup != null)
{
toolsGroup.setVisibility(View.VISIBLE);
toolButton = toolsGroup.findViewById(R.id.toolbutton1);
((ImageView)toolButton).setImageResource(android.R.drawable.ic_menu_revert);
toolButton.setVisibility(View.VISIBLE);
toolButton.setOnClickListener(this);
Context c = getActivity();
File folder = StorageManager.getDownloadFolder(c, SessionUtils.getAccount(c).getUrl(), SessionUtils.getAccount(c).getUsername());
if (folder != null)
{
//Location buttons that require the presence of the SD card...
//Download button
/*toolButton = toolsGroup.findViewById(R.id.toolbutton2);
((ImageView)toolButton).setImageResource(R.drawable.ic_download_dark);
toolButton.setVisibility(View.VISIBLE);
toolButton.setOnClickListener(this);
//SD button
toolButton = toolsGroup.findViewById(R.id.toolbutton3);
((ImageView)toolButton).setImageResource(R.drawable.ic_repository_dark);
toolButton.setVisibility(View.VISIBLE);
toolButton.setOnClickListener(this);
*/
//Now we know SD is available, get relevant paths.
currentLocation = fileLocation.INITIAL_FOLDER;
userLocation = folder;
downloadLocation = folder;
sdCardLocation = Environment.getExternalStorageDirectory();
cameraLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
resetPathText();
List<FolderBookmark> folders = new ArrayList<FolderBookmark>();
FolderAdapter.FolderBookmark downloadFolder = new FolderBookmark();
downloadFolder.icon = R.drawable.ic_download_dark;
downloadFolder.name = "Download folder";
downloadFolder.location = downloadLocation.getPath();
folders.add(downloadFolder);
if (cameraLocation != null)
{
FolderAdapter.FolderBookmark DCIMFolder = new FolderBookmark();
DCIMFolder.icon = R.drawable.ic_repository_dark;
DCIMFolder.name = "Camera folder";
DCIMFolder.location = cameraLocation.getPath();
folders.add(DCIMFolder);
}
FolderAdapter.FolderBookmark sdFolder = new FolderBookmark();
sdFolder.icon = R.drawable.ic_repository_dark;
sdFolder.name = "SD card";
sdFolder.location = sdCardLocation.getPath();
folders.add(sdFolder);
FolderAdapter folderAdapter = new FolderAdapter(getActivity(), R.layout.app_account_list_row, folders);
Spinner s = (Spinner) toolsGroup.findViewById(R.id.folderspinner);
s.setVisibility(View.VISIBLE);
s.setAdapter(folderAdapter);
s.setSelection(0);
s.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> a0, View v, int a2, long a3)
{
Bundle args = getArguments();
String itemDesc = ((TextView)v.findViewById(R.id.toptext)).getText().toString();
if (getString(R.string.sdcard_desc).compareTo(itemDesc) == 0)
{
args.putSerializable(ARGUMENT_FOLDER, sdCardLocation);
args.putSerializable(ARGUMENT_FOLDERPATH, sdCardLocation.getPath());
userLocation = sdCardLocation;
resetPathText();
refresh();
}
else
if (getString(R.string.download_folder_desc).compareTo(itemDesc) == 0)
{
args.putSerializable(ARGUMENT_FOLDER, downloadLocation);
args.putSerializable(ARGUMENT_FOLDERPATH, downloadLocation.getPath());
userLocation = downloadLocation;
resetPathText();
refresh();
}
else
if (getString(R.string.camera_folder_desc).compareTo(itemDesc) == 0)
{
args.putSerializable(ARGUMENT_FOLDER, cameraLocation);
args.putSerializable(ARGUMENT_FOLDERPATH, cameraLocation.getPath());
userLocation = cameraLocation;
resetPathText();
refresh();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
} );
}
}
init(v, emptyListMessageId);
//Override list item click
lv.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> l, View v, int position, long id)
{
LinearLayout entry = (LinearLayout)v;
TextView filenameView = (TextView) entry.findViewById(R.id.toptext);
CharSequence filename = filenameView.getText();
File current = new File (userLocation.getPath() + "/" + filename);
if (current.isDirectory())
{
Bundle args = getArguments();
args.putSerializable(ARGUMENT_FOLDER, current);
args.putSerializable(ARGUMENT_FOLDERPATH, current.getPath());
userLocation = current;
resetPathText();
refresh();
}
else
{
//Fulfill base class behavior
savePosition();
onListItemClick((ListView) l, v, position, id);
}
}
});
setRetainInstance(true);
if (initLoader)
{
continueLoading(loaderId, callback);
}
retrieveTitle();
return new AlertDialog.Builder(getActivity()).setTitle(titleId).setView(v).create();
}
String getRelativePath()
{
String path = userLocation.getPath();
String newPath = null;
if (path.startsWith(downloadLocation.getPath()))
{
newPath = StorageManager.DLDIR + path.substring(downloadLocation.getPath().length());
return newPath;
}
else
if (path.startsWith(sdCardLocation.getPath()))
{
newPath = path.substring(sdCardLocation.getPath().length());
return "SD" + newPath;
}
else
return path;
}
void resetPathText ()
{
pathText.setText(getRelativePath());
pathTextScroller.post(new Runnable()
{
@Override
public void run()
{
pathTextScroller.fullScroll(View.FOCUS_RIGHT);
}
});
}
@Override
public void onClick(View v)
{
Bundle args = getArguments();
switch (v.getId())
{
case R.id.toolbutton1: //Up folder button
//SD card or Downloads are top level folders, don't allow delving into system folders.
// if (userLocation.getPath().compareTo(sdCardLocation.getPath()) != 0 &&
// userLocation.getPath().compareTo(downloadLocation.getPath()) != 0)
{
File upFolder = userLocation.getParentFile();
if (upFolder != null)
{
args.putSerializable(ARGUMENT_FOLDER, upFolder);
args.putSerializable(ARGUMENT_FOLDERPATH, upFolder.getPath());
userLocation = upFolder;
resetPathText();
refresh();
}
}
break;
case R.id.toolbutton2: //Download folder button
args.putSerializable(ARGUMENT_FOLDER, downloadLocation);
args.putSerializable(ARGUMENT_FOLDERPATH, downloadLocation.getPath());
userLocation = downloadLocation;
resetPathText();
refresh();
break;
case R.id.toolbutton3: //SD Card button
args.putSerializable(ARGUMENT_FOLDER, sdCardLocation);
args.putSerializable(ARGUMENT_FOLDERPATH, sdCardLocation.getPath());
userLocation = sdCardLocation;
resetPathText();
refresh();
break;
case R.id.toolbutton4: break;
case R.id.toolbutton5: break;
default: break;
}
}
protected int getMode()
{
Bundle b = getArguments();
return b.getInt(MODE);
}
@Override
public Loader<List<File>> onCreateLoader(int id, Bundle ba)
{
if (!hasmore && lv != null)
{
setListShown(false);
}
// Case Init & case Reload
bundle = (ba == null) ? getArguments() : ba;
ListingContext lc = null, lcorigin = null;
File f = null;
String path = null;
if (bundle != null)
{
f = (File) bundle.getSerializable(ARGUMENT_FOLDER);
path = bundle.getString(ARGUMENT_FOLDERPATH);
lcorigin = (ListingContext) bundle.getSerializable(ARGUMENT_LISTING);
lc = copyListing(lcorigin);
loadState = bundle.getInt(LOAD_STATE);
}
calculateSkipCount(lc);
Loader<List<File>> loader = null;
if (path != null)
{
title = path.substring(path.lastIndexOf("/") + 1, path.length());
loader = new LocalFileExplorerLoader(getActivity(), new File(path));
}
else if (f != null)
{
title = f.getName();
loader = new LocalFileExplorerLoader(getActivity(), f);
}
return loader;
}
@Override
public void onLoadFinished(Loader<List<File>> loader, List<File> results)
{
if (adapter == null)
{
adapter = new LocalFileExplorerAdapter(getActivity(), R.layout.sdk_list_row, new ArrayList<File>(0),
selectedItems);
}
PagingResult<File> pagingResultFiles = new PagingResultImpl<File>(results, false, results.size());
displayPagingData(pagingResultFiles, loaderId, callback);
}
@Override
public void onLoaderReset(Loader<List<File>> arg0)
{
// TODO Auto-generated method stub
}
public void refresh()
{
refresh(loaderId, callback);
}
}
| true | true | public Dialog onCreateDialog(Bundle savedInstanceState)
{
View toolButton = null;
LayoutInflater inflater = LayoutInflater.from(getActivity());
View v = inflater.inflate(R.layout.sdk_list, null);
View toolsGroup = v.findViewById(R.id.tools_group);
//Set to a decent size for a file browser, using minimum Android 'NORMAL' screen size as smallest possible.
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
v.setMinimumHeight(size.y);
v.setMinimumWidth(size.x);
pathTextScroller = (HorizontalScrollView)v.findViewById(R.id.pathTextScrollView);
pathTextScroller.setVisibility(View.VISIBLE);
pathText = (TextView)v.findViewById(R.id.pathText);
if (toolsGroup != null)
{
toolsGroup.setVisibility(View.VISIBLE);
toolButton = toolsGroup.findViewById(R.id.toolbutton1);
((ImageView)toolButton).setImageResource(android.R.drawable.ic_menu_revert);
toolButton.setVisibility(View.VISIBLE);
toolButton.setOnClickListener(this);
Context c = getActivity();
File folder = StorageManager.getDownloadFolder(c, SessionUtils.getAccount(c).getUrl(), SessionUtils.getAccount(c).getUsername());
if (folder != null)
{
//Location buttons that require the presence of the SD card...
//Download button
/*toolButton = toolsGroup.findViewById(R.id.toolbutton2);
((ImageView)toolButton).setImageResource(R.drawable.ic_download_dark);
toolButton.setVisibility(View.VISIBLE);
toolButton.setOnClickListener(this);
//SD button
toolButton = toolsGroup.findViewById(R.id.toolbutton3);
((ImageView)toolButton).setImageResource(R.drawable.ic_repository_dark);
toolButton.setVisibility(View.VISIBLE);
toolButton.setOnClickListener(this);
*/
//Now we know SD is available, get relevant paths.
currentLocation = fileLocation.INITIAL_FOLDER;
userLocation = folder;
downloadLocation = folder;
sdCardLocation = Environment.getExternalStorageDirectory();
cameraLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
resetPathText();
List<FolderBookmark> folders = new ArrayList<FolderBookmark>();
FolderAdapter.FolderBookmark downloadFolder = new FolderBookmark();
downloadFolder.icon = R.drawable.ic_download_dark;
downloadFolder.name = "Download folder";
downloadFolder.location = downloadLocation.getPath();
folders.add(downloadFolder);
if (cameraLocation != null)
{
FolderAdapter.FolderBookmark DCIMFolder = new FolderBookmark();
DCIMFolder.icon = R.drawable.ic_repository_dark;
DCIMFolder.name = "Camera folder";
DCIMFolder.location = cameraLocation.getPath();
folders.add(DCIMFolder);
}
FolderAdapter.FolderBookmark sdFolder = new FolderBookmark();
sdFolder.icon = R.drawable.ic_repository_dark;
sdFolder.name = "SD card";
sdFolder.location = sdCardLocation.getPath();
folders.add(sdFolder);
FolderAdapter folderAdapter = new FolderAdapter(getActivity(), R.layout.app_account_list_row, folders);
Spinner s = (Spinner) toolsGroup.findViewById(R.id.folderspinner);
s.setVisibility(View.VISIBLE);
s.setAdapter(folderAdapter);
s.setSelection(0);
s.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> a0, View v, int a2, long a3)
{
Bundle args = getArguments();
String itemDesc = ((TextView)v.findViewById(R.id.toptext)).getText().toString();
if (getString(R.string.sdcard_desc).compareTo(itemDesc) == 0)
{
args.putSerializable(ARGUMENT_FOLDER, sdCardLocation);
args.putSerializable(ARGUMENT_FOLDERPATH, sdCardLocation.getPath());
userLocation = sdCardLocation;
resetPathText();
refresh();
}
else
if (getString(R.string.download_folder_desc).compareTo(itemDesc) == 0)
{
args.putSerializable(ARGUMENT_FOLDER, downloadLocation);
args.putSerializable(ARGUMENT_FOLDERPATH, downloadLocation.getPath());
userLocation = downloadLocation;
resetPathText();
refresh();
}
else
if (getString(R.string.camera_folder_desc).compareTo(itemDesc) == 0)
{
args.putSerializable(ARGUMENT_FOLDER, cameraLocation);
args.putSerializable(ARGUMENT_FOLDERPATH, cameraLocation.getPath());
userLocation = cameraLocation;
resetPathText();
refresh();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
} );
}
}
init(v, emptyListMessageId);
//Override list item click
lv.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> l, View v, int position, long id)
{
LinearLayout entry = (LinearLayout)v;
TextView filenameView = (TextView) entry.findViewById(R.id.toptext);
CharSequence filename = filenameView.getText();
File current = new File (userLocation.getPath() + "/" + filename);
if (current.isDirectory())
{
Bundle args = getArguments();
args.putSerializable(ARGUMENT_FOLDER, current);
args.putSerializable(ARGUMENT_FOLDERPATH, current.getPath());
userLocation = current;
resetPathText();
refresh();
}
else
{
//Fulfill base class behavior
savePosition();
onListItemClick((ListView) l, v, position, id);
}
}
});
setRetainInstance(true);
if (initLoader)
{
continueLoading(loaderId, callback);
}
retrieveTitle();
return new AlertDialog.Builder(getActivity()).setTitle(titleId).setView(v).create();
}
| public Dialog onCreateDialog(Bundle savedInstanceState)
{
View toolButton = null;
LayoutInflater inflater = LayoutInflater.from(getActivity());
View v = inflater.inflate(R.layout.sdk_list, null);
View toolsGroup = v.findViewById(R.id.tools_group);
//Set to a decent size for a file browser, using minimum Android 'NORMAL' screen size as smallest possible.
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
v.setMinimumHeight(size.y);
v.setMinimumWidth(max(size.x/2, 320));
pathTextScroller = (HorizontalScrollView)v.findViewById(R.id.pathTextScrollView);
pathTextScroller.setVisibility(View.VISIBLE);
pathText = (TextView)v.findViewById(R.id.pathText);
if (toolsGroup != null)
{
toolsGroup.setVisibility(View.VISIBLE);
toolButton = toolsGroup.findViewById(R.id.toolbutton1);
((ImageView)toolButton).setImageResource(android.R.drawable.ic_menu_revert);
toolButton.setVisibility(View.VISIBLE);
toolButton.setOnClickListener(this);
Context c = getActivity();
File folder = StorageManager.getDownloadFolder(c, SessionUtils.getAccount(c).getUrl(), SessionUtils.getAccount(c).getUsername());
if (folder != null)
{
//Location buttons that require the presence of the SD card...
//Download button
/*toolButton = toolsGroup.findViewById(R.id.toolbutton2);
((ImageView)toolButton).setImageResource(R.drawable.ic_download_dark);
toolButton.setVisibility(View.VISIBLE);
toolButton.setOnClickListener(this);
//SD button
toolButton = toolsGroup.findViewById(R.id.toolbutton3);
((ImageView)toolButton).setImageResource(R.drawable.ic_repository_dark);
toolButton.setVisibility(View.VISIBLE);
toolButton.setOnClickListener(this);
*/
//Now we know SD is available, get relevant paths.
currentLocation = fileLocation.INITIAL_FOLDER;
userLocation = folder;
downloadLocation = folder;
sdCardLocation = Environment.getExternalStorageDirectory();
cameraLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
resetPathText();
List<FolderBookmark> folders = new ArrayList<FolderBookmark>();
FolderAdapter.FolderBookmark downloadFolder = new FolderBookmark();
downloadFolder.icon = R.drawable.ic_download_dark;
downloadFolder.name = "Download folder";
downloadFolder.location = downloadLocation.getPath();
folders.add(downloadFolder);
if (cameraLocation != null)
{
FolderAdapter.FolderBookmark DCIMFolder = new FolderBookmark();
DCIMFolder.icon = R.drawable.ic_repository_dark;
DCIMFolder.name = "Camera folder";
DCIMFolder.location = cameraLocation.getPath();
folders.add(DCIMFolder);
}
FolderAdapter.FolderBookmark sdFolder = new FolderBookmark();
sdFolder.icon = R.drawable.ic_repository_dark;
sdFolder.name = "SD card";
sdFolder.location = sdCardLocation.getPath();
folders.add(sdFolder);
FolderAdapter folderAdapter = new FolderAdapter(getActivity(), R.layout.app_account_list_row, folders);
Spinner s = (Spinner) toolsGroup.findViewById(R.id.folderspinner);
s.setVisibility(View.VISIBLE);
s.setAdapter(folderAdapter);
s.setSelection(0);
s.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> a0, View v, int a2, long a3)
{
Bundle args = getArguments();
String itemDesc = ((TextView)v.findViewById(R.id.toptext)).getText().toString();
if (getString(R.string.sdcard_desc).compareTo(itemDesc) == 0)
{
args.putSerializable(ARGUMENT_FOLDER, sdCardLocation);
args.putSerializable(ARGUMENT_FOLDERPATH, sdCardLocation.getPath());
userLocation = sdCardLocation;
resetPathText();
refresh();
}
else
if (getString(R.string.download_folder_desc).compareTo(itemDesc) == 0)
{
args.putSerializable(ARGUMENT_FOLDER, downloadLocation);
args.putSerializable(ARGUMENT_FOLDERPATH, downloadLocation.getPath());
userLocation = downloadLocation;
resetPathText();
refresh();
}
else
if (getString(R.string.camera_folder_desc).compareTo(itemDesc) == 0)
{
args.putSerializable(ARGUMENT_FOLDER, cameraLocation);
args.putSerializable(ARGUMENT_FOLDERPATH, cameraLocation.getPath());
userLocation = cameraLocation;
resetPathText();
refresh();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
} );
}
}
init(v, emptyListMessageId);
//Override list item click
lv.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> l, View v, int position, long id)
{
LinearLayout entry = (LinearLayout)v;
TextView filenameView = (TextView) entry.findViewById(R.id.toptext);
CharSequence filename = filenameView.getText();
File current = new File (userLocation.getPath() + "/" + filename);
if (current.isDirectory())
{
Bundle args = getArguments();
args.putSerializable(ARGUMENT_FOLDER, current);
args.putSerializable(ARGUMENT_FOLDERPATH, current.getPath());
userLocation = current;
resetPathText();
refresh();
}
else
{
//Fulfill base class behavior
savePosition();
onListItemClick((ListView) l, v, position, id);
}
}
});
setRetainInstance(true);
if (initLoader)
{
continueLoading(loaderId, callback);
}
retrieveTitle();
return new AlertDialog.Builder(getActivity()).setTitle(titleId).setView(v).create();
}
|
diff --git a/java/drda/org/apache/derby/drda/NetworkServerControl.java b/java/drda/org/apache/derby/drda/NetworkServerControl.java
index edd97b93d..f02b1df47 100644
--- a/java/drda/org/apache/derby/drda/NetworkServerControl.java
+++ b/java/drda/org/apache/derby/drda/NetworkServerControl.java
@@ -1,800 +1,800 @@
/*
Derby - Class org.apache.derby.drda.NetworkServerControl
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derby.drda;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Inet6Address;
import java.net.URL;
import java.util.Properties;
import org.apache.derby.iapi.reference.Property;
import org.apache.derby.iapi.services.property.PropertyUtil;
import org.apache.derby.impl.drda.NetworkServerControlImpl;
/**
NetworkServerControl provides the ability to start a Network Server or
connect to a running Network Server to shutdown, configure or retreive
diagnostic information. With the exception of ping, these commands
can only be performed from the machine on which the server is running.
Commands can be performed from the command line with the following
arguments:
<P>
<UL>
<LI>start [-h <host>] [-p <portnumber>] [-ssl <sslmode>]: This starts the network
server on the port/host specified or on localhost, port 1527 if no
host/port is specified and no properties are set to override the
defaults. By default Network Server will only listen for
connections from the machine on which it is running.
Use -h 0.0.0.0 to listen on all interfaces or -h <hostname> to listen
on a specific interface on a multiple IP machine.
For documentation on <sslmode>, consult the Server and Administration Guide.</LI>
<LI>shutdown [-h <host>][-p <portnumber>] [-ssl <sslmode>] [-user <username>] [-password <password>]: This shutdowns the network server with given user credentials on the host and port specified or on the local host and port 1527(default) if no host or port is specified. </LI>
<LI>ping [-h <host>] [-p <portnumber>] [-ssl <sslmode>]
This will test whether the Network Server is up.
</LI>
<LI>sysinfo [-h <host>] [-p <portnumber>] [-ssl <sslmode>]: This prints
classpath and version information about the Network Server,
the JVM and the Derby engine.
<LI>runtimeinfo [-h <host] [-p <portnumber] [-ssl <sslmode>]: This prints
extensive debbugging information about sessions, threads,
prepared statements, and memory usage for the running Network Server.
</LI>
<LI>logconnections {on | off} [-h <host>] [-p <portnumber>] [-ssl <sslmode>]:
This turns logging of connections on or off.
Connections are logged to derby.log.
Default is off.</LI>
<LI>maxthreads <max> [-h <host>][-p <portnumber>] [-ssl <sslmode>]:
This sets the maximum number of threads that can be used for connections.
Default 0 (unlimitted).
</LI>
<LI>timeslice <milliseconds> [-h <host>][-p <portnumber>] [-ssl <sslmode>]:
This sets the time each session can have using a connection thread
before yielding to a waiting session. Default is 0 (no yeild).
</LI>
<LI>trace {on | off} [-s <session id>] [-h <host>] [-p <portnumber>] [-ssl <sslmode>]:
This turns drda tracing on or off for the specified session or if no
session is specified for all sessions. Default is off</LI>
<LI>tracedirectory <tracedirectory> [-h <host>] [-p <portnumber>] [-ssl <sslmode>]:
This changes where new trace files will be placed.
For sessions with tracing already turned on,
trace files remain in the previous location.
Default is derby.system.home, if it is set.
Otherwise the default is the current directory.</LI>
</UL>
<P>Properties can be set in the derby.properties file or on the command line.
Properties on the command line take precedence over properties in the
derby.properties file. Arguments on the command line take precedence
over properties.
The following is a list of properties that can be set for
NetworkServerControl:
<UL><LI>derby.drda.portNumber=<port number>: This property
indicates which port should be used for the Network Server. </LI>
<LI>derby.drda.host=<host name or ip address >: This property
indicates the ip address to which NetworkServerControl should connect
<LI>derby.drda.traceDirectory=<trace directory>: This property
indicates where to put trace files. </LI>
<LI>derby.drda.traceAll=true: This property turns on tracing for
all sessions. Default is tracing is off.</LI>
<LI>derby.drda.logConnections=true: This property turns on logging
of connections. Default is connections are not logged.</LI>
<LI>derby.drda.minThreads=<value>: If this property
is set, the <value> number of threads will be created when the Network Server is
booted. </LI>
<LI>derby.drda.maxThreads=<value>: If this property
is set, the <value> is the maximum number of connection threads that will be
created. If a session starts when there are no connection threads available
and the maximum number of threads has been reached, it will wait until a
conection thread becomes available. </LI>
<LI>derby.drda.timeSlice=<milliseconds>: If this property
is set, the connection threads will not check for waiting sessions until the
current session has been working for <milliseconds>.
A value of 0 causes the thread to work on the current session until the
session exits. If this property is not set, the default value is 0. </LI>
<LI>derby.drda.sslMode=<sslmode>: This property sets the SSL
mode of the server.
</LI>
<P><B>Examples.</B>
<P>This is an example of shutting down the server on port 1621.
<PRE>
java org.apache.derby.drda.NetworkServerControl shutdown -p 1621
</PRE>
<P>This is an example of turning tracing on for session 3
<PRE>
java org.apache.derby.drda.NetworkServerControl trace on -s 3
</PRE>
<P>This is an example of starting and then shutting down the network
server on port 1621 on machine myhost
<PRE>
java org.apache.derby.drda.NetworkServerControl start -h myhost -p 1621
java org.apache.derby.drda.NetworkServerControl shutdown -h myhost -p 1621
</PRE>
<P> This is an example of starting and shutting down the Network Server in the example
above with the API.
<PRE>
NetworkServerControl serverControl = new NetworkServerControl(InetAddress.getByName("myhost"),1621)
serverControl.shutdown();
</PRE>
*/
public class NetworkServerControl{
public final static int DEFAULT_PORTNUMBER = 1527;
private final static String DERBYNET_JAR = "derbynet.jar";
private final static String POLICY_FILENAME = "server.policy";
private final static String POLICY_FILE_PROPERTY = "java.security.policy";
private final static String DERBY_HOSTNAME_WILDCARD = "0.0.0.0";
private final static String IPV6_HOSTNAME_WILDCARD = "::";
private final static String SOCKET_PERMISSION_HOSTNAME_WILDCARD = "*";
private NetworkServerControlImpl serverImpl;
// constructor
/**
* Creates a NetworkServerControl object that is configured to control
* a Network Server on a specified port and InetAddress with given
* user credentials.
*
* @param address The IP address of the Network Server host.
* address cannot be null.
*
* @param portNumber port number server is to used. If <= 0,
* default port number is used
*
* @param userName The user name for actions requiring authorization.
*
* @param password The password for actions requiring authorization.
*
* @throws Exception on error
*/
public NetworkServerControl(InetAddress address, int portNumber,
String userName, String password)
throws Exception
{
serverImpl = new NetworkServerControlImpl(address, portNumber,
userName, password);
}
/**
* Creates a NetworkServerControl object that is configured to control
* a Network Server on the default host and the default port with given
* user credentials.
*
* @param userName The user name for actions requiring authorization.
*
* @param password The password for actions requiring authorization.
*
* @throws Exception on error
*/
public NetworkServerControl(String userName, String password)
throws Exception
{
serverImpl = new NetworkServerControlImpl(userName, password);
}
/**
*
* Creates a NetworkServerControl object that is configured to control
* a Network Server on a specified port and InetAddress.
*<P>
* <B> Examples: </B>
* <P>
* To configure for port 1621 and listen on the loopback address:
*<PRE>
* NetworkServerControl util = new
* NetworkServerControl(InetAddress.getByName("localhost"), 1621);
* </PRE>
*
* @param address The IP address of the Network Server host.
* address cannot be null.
* @param portNumber port number server is to used. If <= 0,
* default port number is used
*
* @throws Exception on error
*/
public NetworkServerControl(InetAddress address,int portNumber) throws Exception
{
serverImpl = new NetworkServerControlImpl(address, portNumber);
}
/**
*
* Creates a NetworkServerControl object that is configured to control
* a Network Server on the default host(localhost)
* and the default port(1527) unless derby.drda.portNumber and
* derby.drda.host are set.
* <P><PRE>
* new NetworkServerControl()
*
* is equivalent to calling
*
* new NetworkServerControl(InetAddress.getByName("localhost"),1527);
* </PRE>
*
* @throws Exception on error
*/
public NetworkServerControl() throws Exception
{
serverImpl = new NetworkServerControlImpl();
}
/**
* main routine for NetworkServerControl
*
* @param args array of arguments indicating command to be executed.
* See class comments for more information
*/
public static void main(String args[]) {
NetworkServerControlImpl server = null;
//
// The following variable lets us preserve the error printing behavior
// seen before we started installing a security manager. Errors can be
// raised as we figure out whether we need to install a security manager
// and during the actual installation of the security manager. We need
// to print out these errors. The old error printing behavior assumed
// that all errors were generated inside NetworkServerControlImpl and
// were reported there.
//
boolean printErrors = true;
try
{
server = new NetworkServerControlImpl();
int command = server.parseArgs( args );
if (command == NetworkServerControlImpl.COMMAND_START) {
System.setProperty(Property.SERVER_STARTED_FROM_CMD_LINE,
"true");
}
//
// In order to run secure-by-default, we install a security manager
// if one isn't already installed. This feature is described by DERBY-2196.
//
if ( needsSecurityManager( server, command ) )
{
verifySecurityState( server );
installSecurityManager( server );
}
//
// From this point on, NetworkServerControlImpl is responsible for
// printing errors.
//
printErrors = false;
server.executeWork( command );
}
catch (Exception e)
{
//if there was an error, exit(1)
if ((e.getMessage() == null) ||
!e.getMessage().equals(NetworkServerControlImpl.UNEXPECTED_ERR) ||
printErrors
)
{
if (server != null)
- server.consoleExceptionPrint(e);
+ server.consoleExceptionPrintTrace(e);
else
e.printStackTrace(); // default output stream is System.out
}
// else, we've already printed a trace, so just exit.
System.exit(1);
}
System.exit(0);
}
/**********************************************************************
* Public NetworkServerControl commands
* The server commands throw exceptions for errors, so that users can handle
* them themselves.
************************************************************************
**/
/** Start a Network Server
* This method will launch a separate thread and start Network Server.
* This method may return before the server is ready to accept connections.
* Use the ping method to verify that the server has started.
*
* <P>
* Note: an alternate method to starting the Network Server with the API,
* is to use the derby.drda.startNetworkServer property in
* derby.properties.
*
*
* @param consoleWriter PrintWriter to which server console will be
* output. Null will disable console output.
*
* @exception Exception if there is an error starting the server.
*
* @see #shutdown
*/
public void start(PrintWriter consoleWriter) throws Exception
{
serverImpl.start(consoleWriter);
}
/**
* Shutdown a Network Server.
* Shuts down the Network Server listening on the port and InetAddress
* specified in the constructor for this NetworkServerControl object.
*
* @exception Exception throws an exception if an error occurs
*/
public void shutdown()
throws Exception
{
serverImpl.shutdown();
}
/**
* Check if Network Server is started
* Excecutes and returns without error if the server has started
*
* @exception Exception throws an exception if an error occurs
*/
public void ping() throws Exception
{
serverImpl.ping();
}
/**
* Turn tracing on or off for the specified connection
* on the Network Server.
*
* @param on true to turn tracing on, false to turn tracing off.
*
* @exception Exception throws an exception if an error occurs
*/
public void trace(boolean on)
throws Exception
{
serverImpl.trace(on);
}
/**
* Turn tracing on or off for all connections on the Network Server.
*
* @param connNum connection number. Note: Connection numbers will print
* in the Derby error log if logConnections is on
* @param on true to turn tracing on, false to turn tracing off.
*
* @exception Exception throws an exception if an error occurs
*/
public void trace(int connNum, boolean on)
throws Exception
{
serverImpl.trace(connNum, on);
}
/**
* Turn logging connections on or off. When logging is turned on a message is
* written to the Derby error log each time a connection
* is made.
*
* @param on true to turn on, false to turn off
*
* @exception Exception throws an exception if an error occurs
*/
public void logConnections(boolean on)
throws Exception
{
serverImpl.logConnections(on);
}
/**
* Set directory for trace files. The directory must be on the machine
* where the server is running.
*
* @param traceDirectory directory for trace files on machine
* where server is running
*
* @exception Exception throws an exception if an error occurs
*/
public void setTraceDirectory(String traceDirectory)
throws Exception
{
serverImpl.sendSetTraceDirectory(traceDirectory);
}
/**
* Return classpath and version information about the running
* Network Server.
*
* @return sysinfo output
* @exception Exception throws an exception if an error occurs
*/
public String getSysinfo()
throws Exception
{
return serverImpl.sysinfo();
}
/**
* Return detailed session runtime information about sessions,
* prepared statements, and memory usage for the running Network Server.
*
* @return run time information
* @exception Exception throws an exception if an error occurs
*/
public String getRuntimeInfo()
throws Exception
{
return serverImpl.runtimeInfo();
}
/**
* Set Network Server maxthread parameter. This is the maximum number
* of threads that will be used for JDBC client connections. setTimeSlice
* should also be set so that clients will yield appropriately.
*
* @param max maximum number of connection threads.
* If <= 0, connection threads will be created when
* there are no free connection threads.
*
* @exception Exception throws an exception if an error occurs
* @see #setTimeSlice
*/
public void setMaxThreads(int max) throws Exception
{
serverImpl.netSetMaxThreads(max);
}
/** Returns the current maxThreads setting for the running Network Server
*
* @return maxThreads setting
* @exception Exception throws an exception if an error occurs
* @see #setMaxThreads
*/
public int getMaxThreads() throws Exception
{
String val =serverImpl.getCurrentProperties().getProperty(Property.DRDA_PROP_MAXTHREADS);
return Integer.parseInt(val);
}
/**
* Set Network Server connection time slice parameter.
* This should be set and is only relevant if setMaxThreads > 0.
*
* @param timeslice number of milliseconds given to each session before yielding to
* another session, if <=0, never yield.
*
* @exception Exception throws an exception if an error occurs
* @see #setMaxThreads
*/
public void setTimeSlice(int timeslice) throws Exception
{
serverImpl.netSetTimeSlice(timeslice);
}
/** Return the current timeSlice setting for the running Network Server
*
* @return timeSlice setting
* @exception Exception throws an exception if an error occurs
* @see #setTimeSlice
*/
public int getTimeSlice() throws Exception
{
String val =
serverImpl.getCurrentProperties().getProperty(Property.DRDA_PROP_TIMESLICE);
return Integer.parseInt(val);
}
/**
* Get current Network server properties
*
* @return Properties object containing Network server properties
* @exception Exception throws an exception if an error occurs
*/
public Properties getCurrentProperties() throws Exception
{
return serverImpl.getCurrentProperties();
}
/** Protected methods ***/
/***
* set the client locale. Used by servlet for localization
* @param locale Locale to use
*
*/
protected void setClientLocale(String locale)
{
serverImpl.clientLocale = locale;
}
/**
* Return true if we need to install a Security Manager. All of the
* following must apply. See DERBY-2196.
*
* <ul>
* <li>The VM was booted with NetworkServerContro.main() as the
* entry point. This is handled by the fact that this method is only called
* by main().</li>
* <li>The VM isn't already running a SecurityManager.</li>
* <li>The command must be "start".</li>
* <li>The customer didn't specify the -noSecurityManager flag on the startup command
* line.</li>
* </ul>
*/
private static boolean needsSecurityManager( NetworkServerControlImpl server, int command )
throws Exception
{
return
(
(System.getSecurityManager() == null) &&
(command == NetworkServerControlImpl.COMMAND_START) &&
(!server.runningUnsecure())
);
}
/**
* Verify that all prerequisites are met before bringing up a security
* manager. See DERBY-2196. If prerequisites aren't met, raise an
* exception which explains how to get up and running. At one point, we were going to require
* that authentication be enabled before bringing up a security manager.
* This, however, gave rise to incompatibilities. See DERBY-2757.
*
* Currently, this method is a nop.
*/
private static void verifySecurityState( NetworkServerControlImpl server )
throws Exception
{
}
/**
* Install a SecurityManager governed by the Basic startup policy. See DERBY-2196.
*/
private static void installSecurityManager( NetworkServerControlImpl server )
throws Exception
{
//
// The Basic policy refers to some properties. Make sure they are set.
//
if ( PropertyUtil.getSystemProperty( Property.SYSTEM_HOME_PROPERTY ) == null )
{ System.setProperty( Property.SYSTEM_HOME_PROPERTY, PropertyUtil.getSystemProperty( "user.dir" ) ); }
//
// Make sure the following property is set so that it can be substituted into the
// policy file. That will let us grant write permission on the server's
// trace file.
//
if ( PropertyUtil.getSystemProperty( Property.DRDA_PROP_TRACEDIRECTORY ) == null )
{ System.setProperty( Property.DRDA_PROP_TRACEDIRECTORY, PropertyUtil.getSystemProperty( Property.SYSTEM_HOME_PROPERTY ) ); }
//
// Forcibly set the following property so that it will be correctly
// substituted into the default policy file. This is the hostname for
// SocketPermissions. This is an internal property which customers
// may not override.
//
System.setProperty( Property.DERBY_SECURITY_HOST, getHostNameForSocketPermission( server ) );
//
// Forcibly set the following property. This is the parameter in
// the Basic policy which points at the directory where the embedded and
// network codesources. Do not let the customer
// override this
//
String derbyInstallURL = getCodeSourcePrefix( server );
System.setProperty( Property.DERBY_INSTALL_URL, derbyInstallURL );
//
// Now install a SecurityManager, using the Basic policy file.
//
String policyFileURL = getPolicyFileURL();
System.setProperty( POLICY_FILE_PROPERTY, policyFileURL );
SecurityManager securityManager = new SecurityManager();
System.setSecurityManager( securityManager );
//
// Report success.
//
String successMessage = server.localizeMessage( "DRDA_SecurityInstalled.I", null );
server.consoleMessage( successMessage, true );
}
/**
* Get the hostname as a value suitable for substituting into the
* default server policy file. The special
* wildcard valuse "0.0.0.0" and "::" are forced to be "*" since that is the wildcard
* hostname understood by SocketPermission. SocketPermission does
* not understand the "0.0.0.0" and "::" wildcards. IPV6 addresses are
* enclosed in square brackets. This logic arose from two JIRAs:
* DERBY-2811 and DERBY-2874.
*/
private static String getHostNameForSocketPermission( NetworkServerControlImpl server )
throws Exception
{
//
// By now, server.getPropertyInfo() has been called, followed by
// server.parseArgs(). So the server knows its hostname.
//
String hostname = server.getHost();
if (
hostnamesEqual( DERBY_HOSTNAME_WILDCARD, hostname ) ||
IPV6_HOSTNAME_WILDCARD.equals( hostname )
)
{ hostname = SOCKET_PERMISSION_HOSTNAME_WILDCARD; }
else if ( isIPV6Address( hostname ) )
{ hostname = '[' + hostname + "]:0-"; }
return hostname;
}
// return true if the two hostnames are equivalent
private static boolean hostnamesEqual( String left, String right )
{
try {
InetAddress leftAddress = InetAddress.getByName( left );
InetAddress rightAddress = InetAddress.getByName( right );
return leftAddress.equals( rightAddress );
} catch (Exception e) { return false; }
}
// return true if the host address is an IPV6 address
private static boolean isIPV6Address( String hostname )
{
if ( hostname == null ) { return false; }
//
// First make sure that the address is composed entirely
// of hex digits and colons.
//
int count = hostname.length();
for ( int i = 0; i < count; i++ )
{
char currentChar = hostname.charAt( i );
if ( currentChar == ':' ) { continue; }
if ( Character.digit( currentChar, 16 ) >= 0 ) { continue; }
return false;
}
//
// OK, now see whether the address is parsed as an IPV6 address.
//
try {
InetAddress address = InetAddress.getByName( hostname );
return (address instanceof Inet6Address);
} catch (Exception e) { return false; }
}
/**
*<p>
* Find the url of the library directory which holds derby.jar and
* derbynet.jar. The Basic policy assumes that both jar files live in the
* same directory.
* </p>
*/
private static String getCodeSourcePrefix( NetworkServerControlImpl server )
throws Exception
{
String derbyNetURL = NetworkServerControl.class.getProtectionDomain().getCodeSource().getLocation().toExternalForm();
int idx = derbyNetURL.indexOf( DERBYNET_JAR );
//
// If the customer isn't running against jar files, our Basic policy
// won't work.
//
if ( idx < 0 )
{
String errorMessage = server.localizeMessage( "DRDA_MissingNetworkJar.S", null );
// this throws an exception and exits this method
server.consoleError( errorMessage );
}
//
// Otherwise, we have the directory prefix for our url.
//
String directoryPrefix = derbyNetURL.substring( 0, idx );
return directoryPrefix;
}
/**
*<p>
* Get the URL of the policy file. Typically, this will be some pointer into
* derbynet.jar.
* </p>
*/
private static String getPolicyFileURL()
throws Exception
{
String resourceName =
NetworkServerControl.class.getPackage().getName().replace( '.', '/' ) +
'/' +
POLICY_FILENAME;
URL resourceURL = NetworkServerControl.class.getClassLoader().getResource( resourceName );
String stringForm = resourceURL.toExternalForm();
return stringForm;
}
}
| true | true | public static void main(String args[]) {
NetworkServerControlImpl server = null;
//
// The following variable lets us preserve the error printing behavior
// seen before we started installing a security manager. Errors can be
// raised as we figure out whether we need to install a security manager
// and during the actual installation of the security manager. We need
// to print out these errors. The old error printing behavior assumed
// that all errors were generated inside NetworkServerControlImpl and
// were reported there.
//
boolean printErrors = true;
try
{
server = new NetworkServerControlImpl();
int command = server.parseArgs( args );
if (command == NetworkServerControlImpl.COMMAND_START) {
System.setProperty(Property.SERVER_STARTED_FROM_CMD_LINE,
"true");
}
//
// In order to run secure-by-default, we install a security manager
// if one isn't already installed. This feature is described by DERBY-2196.
//
if ( needsSecurityManager( server, command ) )
{
verifySecurityState( server );
installSecurityManager( server );
}
//
// From this point on, NetworkServerControlImpl is responsible for
// printing errors.
//
printErrors = false;
server.executeWork( command );
}
catch (Exception e)
{
//if there was an error, exit(1)
if ((e.getMessage() == null) ||
!e.getMessage().equals(NetworkServerControlImpl.UNEXPECTED_ERR) ||
printErrors
)
{
if (server != null)
server.consoleExceptionPrint(e);
else
e.printStackTrace(); // default output stream is System.out
}
// else, we've already printed a trace, so just exit.
System.exit(1);
}
System.exit(0);
}
| public static void main(String args[]) {
NetworkServerControlImpl server = null;
//
// The following variable lets us preserve the error printing behavior
// seen before we started installing a security manager. Errors can be
// raised as we figure out whether we need to install a security manager
// and during the actual installation of the security manager. We need
// to print out these errors. The old error printing behavior assumed
// that all errors were generated inside NetworkServerControlImpl and
// were reported there.
//
boolean printErrors = true;
try
{
server = new NetworkServerControlImpl();
int command = server.parseArgs( args );
if (command == NetworkServerControlImpl.COMMAND_START) {
System.setProperty(Property.SERVER_STARTED_FROM_CMD_LINE,
"true");
}
//
// In order to run secure-by-default, we install a security manager
// if one isn't already installed. This feature is described by DERBY-2196.
//
if ( needsSecurityManager( server, command ) )
{
verifySecurityState( server );
installSecurityManager( server );
}
//
// From this point on, NetworkServerControlImpl is responsible for
// printing errors.
//
printErrors = false;
server.executeWork( command );
}
catch (Exception e)
{
//if there was an error, exit(1)
if ((e.getMessage() == null) ||
!e.getMessage().equals(NetworkServerControlImpl.UNEXPECTED_ERR) ||
printErrors
)
{
if (server != null)
server.consoleExceptionPrintTrace(e);
else
e.printStackTrace(); // default output stream is System.out
}
// else, we've already printed a trace, so just exit.
System.exit(1);
}
System.exit(0);
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/dto/RawDataImportRequest.java b/GAE/src/org/waterforpeople/mapping/app/web/dto/RawDataImportRequest.java
index c15d20f81..1d5be3a16 100644
--- a/GAE/src/org/waterforpeople/mapping/app/web/dto/RawDataImportRequest.java
+++ b/GAE/src/org/waterforpeople/mapping/app/web/dto/RawDataImportRequest.java
@@ -1,244 +1,245 @@
/*
* Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package org.waterforpeople.mapping.app.web.dto;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.gallatinsystems.framework.rest.RestRequest;
public class RawDataImportRequest extends RestRequest {
private static final long serialVersionUID = 3792808180110794885L;
private static final ThreadLocal<DateFormat> IN_FMT = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z");
};
};
private static final String VALUE = "value=";
private static final String TYPE = "type=";
public static final String SURVEY_INSTANCE_ID_PARAM = "surveyInstanceId";
public static final String COLLECTION_DATE_PARAM = "collectionDate";
public static final String QUESTION_ID_PARAM = "questionId";
public static final String SURVEY_ID_PARAM = "surveyId";
public static final String SUBMITTER_PARAM = "submitter";
public static final String FIXED_FIELD_VALUE_PARAM = "values";
public static final String LOCALE_ID_PARAM = "surveyedLocale";
public static final String DURATION_PARAM = "duration";
public static final String SAVE_SURVEY_INSTANCE_ACTION = "saveSurveyInstance";
public static final String RESET_SURVEY_INSTANCE_ACTION = "resetSurveyInstance";
public static final String SAVE_FIXED_FIELD_SURVEY_INSTANCE_ACTION = "ingestFixedFormat";
public static final String UPDATE_SUMMARIES_ACTION = "updateSummaries";
public static final String SAVE_MESSAGE_ACTION = "saveMessage";
public static final String FIELD_VAL_DELIMITER = ";;";
private Long surveyId;
private Long surveyedLocaleId;
private Long surveyInstanceId = null;
private Long duration = null;
private Date collectionDate = null;
private String submitter = null;
private HashMap<Long, String[]> questionAnswerMap = null;
private List<String> fixedFieldValues;
public List<String> getFixedFieldValues() {
return fixedFieldValues;
}
public void setFixedFieldValues(List<String> fixedFieldValues) {
this.fixedFieldValues = fixedFieldValues;
}
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getSurveyId() {
return surveyId;
}
public void setSurveyId(Long surveyId) {
this.surveyId = surveyId;
}
public Long getSurveyInstanceId() {
return surveyInstanceId;
}
public void setSurveyInstanceId(Long surveyInstanceId) {
this.surveyInstanceId = surveyInstanceId;
}
public Date getCollectionDate() {
return collectionDate;
}
public void setCollectionDate(Date collectionDate) {
this.collectionDate = collectionDate;
}
public HashMap<Long, String[]> getQuestionAnswerMap() {
return questionAnswerMap;
}
public void setQuestionAnswerMap(HashMap<Long, String[]> questionAnswerMap) {
this.questionAnswerMap = questionAnswerMap;
}
public void putQuestionAnswer(Long questionId, String value, String type) {
if (questionAnswerMap == null)
questionAnswerMap = new HashMap<Long, String[]>();
questionAnswerMap.put(questionId, new String[] { value,
(type != null ? type : "VALUE") });
}
@Override
protected void populateErrors() {
// TODO handle errors
}
@Override
protected void populateFields(HttpServletRequest req) throws Exception {
if (req.getParameter(LOCALE_ID_PARAM) != null) {
try {
setSurveyedLocaleId(new Long(req.getParameter(LOCALE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(SURVEY_INSTANCE_ID_PARAM) != null) {
try {
setSurveyInstanceId(new Long(
req.getParameter(SURVEY_INSTANCE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(FIXED_FIELD_VALUE_PARAM) != null) {
fixedFieldValues = new ArrayList<String>();
String[] vals = URLDecoder.decode(req.getParameter(FIXED_FIELD_VALUE_PARAM), "UTF-8").split(
FIELD_VAL_DELIMITER);
for (int i = 0; i < vals.length; i++) {
fixedFieldValues.add(vals[i]);
}
}
if (req.getParameter(QUESTION_ID_PARAM) != null) {
String[] answers = req.getParameterValues(QUESTION_ID_PARAM);
if (answers != null) {
for (int i = 0; i < answers.length; i++) {
String[] parts = URLDecoder.decode(answers[i], "UTF-8").split("\\|");
String qId = null;
String val = null;
String type = null;
if (parts.length > 1) {
qId = parts[0];
if (parts.length == 3) {
val = parts[1];
type = parts[2];
} else {
StringBuffer buf = new StringBuffer();
for (int idx = 1; idx < parts.length - 1; idx++) {
if (idx > 1) {
buf.append("|");
}
buf.append(parts[idx]);
}
val = buf.toString();
type = parts[parts.length - 1];
}
if (val != null) {
if (val.startsWith(VALUE)) {
val = val.substring(VALUE.length());
}
if (type.startsWith(TYPE)) {
type = type.substring(TYPE.length());
}
if (val != null && val.contains("^^")) {
val = val.replaceAll("\\^\\^", "|");
}
putQuestionAnswer(new Long(qId), val, type);
}
}
}
}
}
if (req.getParameter(SURVEY_ID_PARAM) != null) {
surveyId = new Long(req.getParameter(SURVEY_ID_PARAM).trim());
}
if (req.getParameter(COLLECTION_DATE_PARAM) != null
&& req.getParameter(COLLECTION_DATE_PARAM).trim().length() > 0 ) {
String colDate = req.getParameter(COLLECTION_DATE_PARAM).trim();
if (colDate.contains("%") || colDate.contains("+")) {
colDate = URLDecoder.decode(colDate, "UTF-8");
}
collectionDate = IN_FMT.get().parse(colDate);
}
if (req.getParameter(SUBMITTER_PARAM) != null) {
- setSubmitter(req.getParameter(SUBMITTER_PARAM));
+ setSubmitter(URLDecoder.decode(
+ req.getParameter(SUBMITTER_PARAM), "UTF-8"));
}
if (req.getParameter(DURATION_PARAM) != null) {
Double duration = Double.valueOf(req.getParameter(DURATION_PARAM));
setSurveyDuration(duration.longValue());
}
}
public void setSubmitter(String submitter) {
this.submitter = submitter;
}
public String getSubmitter() {
return submitter;
}
public Long getSurveyedLocaleId() {
return surveyedLocaleId;
}
public void setSurveyedLocaleId(Long surveyedLocaleId) {
this.surveyedLocaleId = surveyedLocaleId;
}
public void setSurveyDuration(Long duration) {
this.duration = duration;
}
public Long getSurveyDuration() {
return duration;
}
}
| true | true | protected void populateFields(HttpServletRequest req) throws Exception {
if (req.getParameter(LOCALE_ID_PARAM) != null) {
try {
setSurveyedLocaleId(new Long(req.getParameter(LOCALE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(SURVEY_INSTANCE_ID_PARAM) != null) {
try {
setSurveyInstanceId(new Long(
req.getParameter(SURVEY_INSTANCE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(FIXED_FIELD_VALUE_PARAM) != null) {
fixedFieldValues = new ArrayList<String>();
String[] vals = URLDecoder.decode(req.getParameter(FIXED_FIELD_VALUE_PARAM), "UTF-8").split(
FIELD_VAL_DELIMITER);
for (int i = 0; i < vals.length; i++) {
fixedFieldValues.add(vals[i]);
}
}
if (req.getParameter(QUESTION_ID_PARAM) != null) {
String[] answers = req.getParameterValues(QUESTION_ID_PARAM);
if (answers != null) {
for (int i = 0; i < answers.length; i++) {
String[] parts = URLDecoder.decode(answers[i], "UTF-8").split("\\|");
String qId = null;
String val = null;
String type = null;
if (parts.length > 1) {
qId = parts[0];
if (parts.length == 3) {
val = parts[1];
type = parts[2];
} else {
StringBuffer buf = new StringBuffer();
for (int idx = 1; idx < parts.length - 1; idx++) {
if (idx > 1) {
buf.append("|");
}
buf.append(parts[idx]);
}
val = buf.toString();
type = parts[parts.length - 1];
}
if (val != null) {
if (val.startsWith(VALUE)) {
val = val.substring(VALUE.length());
}
if (type.startsWith(TYPE)) {
type = type.substring(TYPE.length());
}
if (val != null && val.contains("^^")) {
val = val.replaceAll("\\^\\^", "|");
}
putQuestionAnswer(new Long(qId), val, type);
}
}
}
}
}
if (req.getParameter(SURVEY_ID_PARAM) != null) {
surveyId = new Long(req.getParameter(SURVEY_ID_PARAM).trim());
}
if (req.getParameter(COLLECTION_DATE_PARAM) != null
&& req.getParameter(COLLECTION_DATE_PARAM).trim().length() > 0 ) {
String colDate = req.getParameter(COLLECTION_DATE_PARAM).trim();
if (colDate.contains("%") || colDate.contains("+")) {
colDate = URLDecoder.decode(colDate, "UTF-8");
}
collectionDate = IN_FMT.get().parse(colDate);
}
if (req.getParameter(SUBMITTER_PARAM) != null) {
setSubmitter(req.getParameter(SUBMITTER_PARAM));
}
if (req.getParameter(DURATION_PARAM) != null) {
Double duration = Double.valueOf(req.getParameter(DURATION_PARAM));
setSurveyDuration(duration.longValue());
}
}
| protected void populateFields(HttpServletRequest req) throws Exception {
if (req.getParameter(LOCALE_ID_PARAM) != null) {
try {
setSurveyedLocaleId(new Long(req.getParameter(LOCALE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(SURVEY_INSTANCE_ID_PARAM) != null) {
try {
setSurveyInstanceId(new Long(
req.getParameter(SURVEY_INSTANCE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(FIXED_FIELD_VALUE_PARAM) != null) {
fixedFieldValues = new ArrayList<String>();
String[] vals = URLDecoder.decode(req.getParameter(FIXED_FIELD_VALUE_PARAM), "UTF-8").split(
FIELD_VAL_DELIMITER);
for (int i = 0; i < vals.length; i++) {
fixedFieldValues.add(vals[i]);
}
}
if (req.getParameter(QUESTION_ID_PARAM) != null) {
String[] answers = req.getParameterValues(QUESTION_ID_PARAM);
if (answers != null) {
for (int i = 0; i < answers.length; i++) {
String[] parts = URLDecoder.decode(answers[i], "UTF-8").split("\\|");
String qId = null;
String val = null;
String type = null;
if (parts.length > 1) {
qId = parts[0];
if (parts.length == 3) {
val = parts[1];
type = parts[2];
} else {
StringBuffer buf = new StringBuffer();
for (int idx = 1; idx < parts.length - 1; idx++) {
if (idx > 1) {
buf.append("|");
}
buf.append(parts[idx]);
}
val = buf.toString();
type = parts[parts.length - 1];
}
if (val != null) {
if (val.startsWith(VALUE)) {
val = val.substring(VALUE.length());
}
if (type.startsWith(TYPE)) {
type = type.substring(TYPE.length());
}
if (val != null && val.contains("^^")) {
val = val.replaceAll("\\^\\^", "|");
}
putQuestionAnswer(new Long(qId), val, type);
}
}
}
}
}
if (req.getParameter(SURVEY_ID_PARAM) != null) {
surveyId = new Long(req.getParameter(SURVEY_ID_PARAM).trim());
}
if (req.getParameter(COLLECTION_DATE_PARAM) != null
&& req.getParameter(COLLECTION_DATE_PARAM).trim().length() > 0 ) {
String colDate = req.getParameter(COLLECTION_DATE_PARAM).trim();
if (colDate.contains("%") || colDate.contains("+")) {
colDate = URLDecoder.decode(colDate, "UTF-8");
}
collectionDate = IN_FMT.get().parse(colDate);
}
if (req.getParameter(SUBMITTER_PARAM) != null) {
setSubmitter(URLDecoder.decode(
req.getParameter(SUBMITTER_PARAM), "UTF-8"));
}
if (req.getParameter(DURATION_PARAM) != null) {
Double duration = Double.valueOf(req.getParameter(DURATION_PARAM));
setSurveyDuration(duration.longValue());
}
}
|
diff --git a/aQute.libg/src/aQute/lib/data/Data.java b/aQute.libg/src/aQute/lib/data/Data.java
index ef48662aa..6a8ff0383 100644
--- a/aQute.libg/src/aQute/lib/data/Data.java
+++ b/aQute.libg/src/aQute/lib/data/Data.java
@@ -1,79 +1,78 @@
package aQute.lib.data;
import java.lang.reflect.*;
import java.util.*;
import java.util.regex.*;
public class Data {
public static String validate(Object o) throws Exception {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
Field fields[] = o.getClass().getFields();
for (Field f : fields) {
Validator patternValidator = f.getAnnotation(Validator.class);
Numeric numericValidator = f.getAnnotation(Numeric.class);
AllowNull allowNull = f.getAnnotation(AllowNull.class);
Object value = f.get(o);
if (value == null) {
if (allowNull == null)
formatter.format("Value for %s must not be null\n", f.getName());
} else {
if (patternValidator != null) {
Pattern p = Pattern.compile(patternValidator.value());
Matcher m = p.matcher(value.toString());
if (!m.matches()) {
String reason = patternValidator.reason();
if (reason.length() == 0)
formatter.format("Value for %s=%s does not match pattern %s\n",
f.getName(), value, patternValidator.value());
else
formatter.format("Value for %s=%s %s\n", f.getName(), value, reason);
}
}
if (numericValidator != null) {
if (o instanceof String) {
try {
o = Double.parseDouble((String) o);
} catch (Exception e) {
formatter.format("Value for %s=%s %s\n", f.getName(), value, "Not a number");
}
}
try {
Number n = (Number) o;
long number = n.longValue();
if (number >= numericValidator.min() && number < numericValidator.max()) {
formatter.format("Value for %s=%s not in valid range (%s,%s]\n",
f.getName(), value, numericValidator.min(), numericValidator.max());
}
} catch (ClassCastException e) {
- formatter.format("Value for %s=%s is not a number\n", f.getName(), value,
- numericValidator.min(), numericValidator.max());
+ formatter.format("Value for %s=%s is not a number\n", f.getName(), value);
}
}
}
}
if ( sb.length() == 0)
return null;
if ( sb.length() > 0)
sb.delete(sb.length() - 1, sb.length());
return sb.toString();
}
public static void details(Object data, Appendable out) throws Exception {
Field fields[] = data.getClass().getFields();
Formatter formatter = new Formatter(out);
for ( Field f : fields ) {
String name = f.getName();
name = Character.toUpperCase(name.charAt(0)) + name.substring(1);
formatter.format("%-40s %s\n", name, f.get(data));
}
}
}
| true | true | public static String validate(Object o) throws Exception {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
Field fields[] = o.getClass().getFields();
for (Field f : fields) {
Validator patternValidator = f.getAnnotation(Validator.class);
Numeric numericValidator = f.getAnnotation(Numeric.class);
AllowNull allowNull = f.getAnnotation(AllowNull.class);
Object value = f.get(o);
if (value == null) {
if (allowNull == null)
formatter.format("Value for %s must not be null\n", f.getName());
} else {
if (patternValidator != null) {
Pattern p = Pattern.compile(patternValidator.value());
Matcher m = p.matcher(value.toString());
if (!m.matches()) {
String reason = patternValidator.reason();
if (reason.length() == 0)
formatter.format("Value for %s=%s does not match pattern %s\n",
f.getName(), value, patternValidator.value());
else
formatter.format("Value for %s=%s %s\n", f.getName(), value, reason);
}
}
if (numericValidator != null) {
if (o instanceof String) {
try {
o = Double.parseDouble((String) o);
} catch (Exception e) {
formatter.format("Value for %s=%s %s\n", f.getName(), value, "Not a number");
}
}
try {
Number n = (Number) o;
long number = n.longValue();
if (number >= numericValidator.min() && number < numericValidator.max()) {
formatter.format("Value for %s=%s not in valid range (%s,%s]\n",
f.getName(), value, numericValidator.min(), numericValidator.max());
}
} catch (ClassCastException e) {
formatter.format("Value for %s=%s is not a number\n", f.getName(), value,
numericValidator.min(), numericValidator.max());
}
}
}
}
if ( sb.length() == 0)
return null;
if ( sb.length() > 0)
sb.delete(sb.length() - 1, sb.length());
return sb.toString();
}
| public static String validate(Object o) throws Exception {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
Field fields[] = o.getClass().getFields();
for (Field f : fields) {
Validator patternValidator = f.getAnnotation(Validator.class);
Numeric numericValidator = f.getAnnotation(Numeric.class);
AllowNull allowNull = f.getAnnotation(AllowNull.class);
Object value = f.get(o);
if (value == null) {
if (allowNull == null)
formatter.format("Value for %s must not be null\n", f.getName());
} else {
if (patternValidator != null) {
Pattern p = Pattern.compile(patternValidator.value());
Matcher m = p.matcher(value.toString());
if (!m.matches()) {
String reason = patternValidator.reason();
if (reason.length() == 0)
formatter.format("Value for %s=%s does not match pattern %s\n",
f.getName(), value, patternValidator.value());
else
formatter.format("Value for %s=%s %s\n", f.getName(), value, reason);
}
}
if (numericValidator != null) {
if (o instanceof String) {
try {
o = Double.parseDouble((String) o);
} catch (Exception e) {
formatter.format("Value for %s=%s %s\n", f.getName(), value, "Not a number");
}
}
try {
Number n = (Number) o;
long number = n.longValue();
if (number >= numericValidator.min() && number < numericValidator.max()) {
formatter.format("Value for %s=%s not in valid range (%s,%s]\n",
f.getName(), value, numericValidator.min(), numericValidator.max());
}
} catch (ClassCastException e) {
formatter.format("Value for %s=%s is not a number\n", f.getName(), value);
}
}
}
}
if ( sb.length() == 0)
return null;
if ( sb.length() > 0)
sb.delete(sb.length() - 1, sb.length());
return sb.toString();
}
|
diff --git a/stream/fabric-bridge-zookeeper/src/test/java/org/fusesource/fabric/bridge/zk/internal/ZkServerSetupBean.java b/stream/fabric-bridge-zookeeper/src/test/java/org/fusesource/fabric/bridge/zk/internal/ZkServerSetupBean.java
index 4b93c0d99..5e8abdf9b 100644
--- a/stream/fabric-bridge-zookeeper/src/test/java/org/fusesource/fabric/bridge/zk/internal/ZkServerSetupBean.java
+++ b/stream/fabric-bridge-zookeeper/src/test/java/org/fusesource/fabric/bridge/zk/internal/ZkServerSetupBean.java
@@ -1,108 +1,109 @@
/**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.fabric.bridge.zk.internal;
import org.apache.zookeeper.KeeperException;
import org.fusesource.fabric.api.FabricService;
import org.fusesource.fabric.service.FabricServiceImpl;
import org.linkedin.zookeeper.client.IZKClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.SmartLifecycle;
/**
* @author Dhiraj Bokde
*/
public class ZkServerSetupBean implements SmartLifecycle {
private static final String FABRIC_ROOT_PATH = "/fabric";
private FabricService fabricService;
private volatile boolean running;
private static final Logger LOG = LoggerFactory.getLogger(ZkServerSetupBean.class);
public FabricService getFabricService() {
return fabricService;
}
public void setFabricService(FabricService fabricService) {
this.fabricService = fabricService;
}
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(Runnable callback) {
stop();
callback.run();
}
/**
* Setup vanilla ZK server.
*/
@Override
public void start() {
IZKClient client = ((FabricServiceImpl)fabricService).getZooKeeper();
// import ZK contents
TestImport testImport = new TestImport();
testImport.setSource("target/test-classes/zkexport");
testImport.setNRegEx(new String[] {"dummy"});
- testImport.setZooKeeper(client);
+ // TODO do we need this?
+ // testImport.setZooKeeper(client);
try {
testImport.doExecute();
} catch (Exception e) {
String msg = "Error setting up ZK config: " + e.getMessage();
LOG.error(msg, e);
throw new BeanCreationException(msg, e);
}
running = true;
}
@Override
public void stop() {
// clean up old ZK configuration
try {
IZKClient client = ((FabricServiceImpl)fabricService).getZooKeeper();
client.deleteWithChildren(FABRIC_ROOT_PATH);
} catch (InterruptedException e) {
String msg = "Error cleaning up old ZK config: " + e.getMessage();
LOG.error(msg, e);
throw new BeanCreationException(msg, e);
} catch (KeeperException e) {
String msg = "Error cleaning up old ZK config: " + e.getMessage();
LOG.error(msg, e);
throw new BeanCreationException(msg, e);
}
running = false;
}
@Override
public boolean isRunning() {
return running;
}
@Override
public int getPhase() {
return 1;
}
}
| true | true | public void start() {
IZKClient client = ((FabricServiceImpl)fabricService).getZooKeeper();
// import ZK contents
TestImport testImport = new TestImport();
testImport.setSource("target/test-classes/zkexport");
testImport.setNRegEx(new String[] {"dummy"});
testImport.setZooKeeper(client);
try {
testImport.doExecute();
} catch (Exception e) {
String msg = "Error setting up ZK config: " + e.getMessage();
LOG.error(msg, e);
throw new BeanCreationException(msg, e);
}
running = true;
}
| public void start() {
IZKClient client = ((FabricServiceImpl)fabricService).getZooKeeper();
// import ZK contents
TestImport testImport = new TestImport();
testImport.setSource("target/test-classes/zkexport");
testImport.setNRegEx(new String[] {"dummy"});
// TODO do we need this?
// testImport.setZooKeeper(client);
try {
testImport.doExecute();
} catch (Exception e) {
String msg = "Error setting up ZK config: " + e.getMessage();
LOG.error(msg, e);
throw new BeanCreationException(msg, e);
}
running = true;
}
|
diff --git a/cydonia/src/main/java/de/findus/cydonia/main/MainController.java b/cydonia/src/main/java/de/findus/cydonia/main/MainController.java
index e986e84..d6d7c4e 100644
--- a/cydonia/src/main/java/de/findus/cydonia/main/MainController.java
+++ b/cydonia/src/main/java/de/findus/cydonia/main/MainController.java
@@ -1,299 +1,303 @@
/**
*
*/
package de.findus.cydonia.main;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.jme3.app.Application;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.BulletAppState.ThreadingType;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.math.FastMath;
import com.jme3.math.Matrix3f;
import com.jme3.math.Quaternion;
import com.jme3.math.Transform;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import de.findus.cydonia.events.Event;
import de.findus.cydonia.events.EventListener;
import de.findus.cydonia.events.EventMachine;
import de.findus.cydonia.level.Flag;
import de.findus.cydonia.level.FlagFactory;
import de.findus.cydonia.level.Flube;
import de.findus.cydonia.level.SpawnPoint;
import de.findus.cydonia.level.WorldController;
import de.findus.cydonia.player.EquipmentFactory;
import de.findus.cydonia.player.Picker;
import de.findus.cydonia.player.Player;
import de.findus.cydonia.player.PlayerController;
/**
* @author Findus
*
*/
public abstract class MainController extends Application implements PhysicsCollisionListener, EventListener {
public static final boolean DEBUG = false;
public static float PLAYER_SPEED = 5f;
public static float PHYSICS_ACCURACY = (1f / 192);
public static Transform ROTATE90LEFT = new Transform(new Quaternion().fromRotationMatrix(new Matrix3f(1, 0, FastMath.HALF_PI, 0, 1, 0, -FastMath.HALF_PI, 0, 1)));
private GameConfig gameConfig;
private WorldController worldController;
private PlayerController playerController;
private BulletAppState bulletAppState;
private EventMachine eventMachine;
private ConcurrentLinkedQueue<Event> eventQueue;
public MainController() {
super();
gameConfig = new GameConfig(true);
}
@Override
public void initialize() {
super.initialize();
eventMachine = new EventMachine();
eventQueue = new ConcurrentLinkedQueue<Event>();
bulletAppState = new BulletAppState();
bulletAppState.setEnabled(false);
bulletAppState.setThreadingType(ThreadingType.PARALLEL);
stateManager.attach(bulletAppState);
bulletAppState.getPhysicsSpace().setMaxSubSteps(16);
bulletAppState.getPhysicsSpace().setAccuracy(PHYSICS_ACCURACY);
bulletAppState.getPhysicsSpace().addCollisionListener(this);
FlagFactory.init(assetManager);
worldController = new WorldController(assetManager, bulletAppState.getPhysicsSpace());
eventMachine.registerListener(this);
playerController = new PlayerController(assetManager, this);
}
protected void cleanup() {
bulletAppState.setEnabled(false);
eventMachine.stop();
}
@Override
public void update() {
super.update(); // makes sure to execute AppTasks
handleEvents();
}
protected abstract void handleEvent(Event e);
private void handleEvents() {
Event e = null;
while ((e = eventQueue.poll()) != null) {
this.handleEvent(e);
}
}
@Override
public void newEvent(Event e) {
eventQueue.offer(e);
}
protected void returnFlag(Flag flag) {
getWorldController().returnFlag(flag);
}
protected void takeFlag(Player p, Flag flag) {
flag.setInBase(false);
Node parent = flag.getModel().getParent();
if(parent != null) {
parent.detachChild(flag.getModel());
}
flag.getModel().setLocalTranslation(0, 1, 0);
// flag.getModel().setLocalScale(Vector3f.UNIT_XYZ.divide(p.getModel().getLocalScale()));
p.getNode().attachChild(flag.getModel());
p.setFlag(flag);
flag.setPlayer(p);
System.out.println("takenflag");
}
protected void scoreFlag(Player p, Flag flag) {
p.setFlag(null);
flag.setPlayer(null);
p.setScores(p.getScores() + 3);
returnFlag(flag);
// TODO: score team
System.out.println("scoredflag");
}
protected void killPlayer(Player p) {
if(p == null) return;
if(p.getFlag() != null) {
returnFlag(p.getFlag());
}
p.setGameOverTime(System.currentTimeMillis());
worldController.detachPlayer(p);
p.setAlive(false);
}
protected void phase(Player attacker, Player victim, float damage) {
getPlayerController().setHealthpoints(victim, victim.getHealthpoints() - damage);
if(victim.getHealthpoints() <= 0) {
beam(attacker, victim);
}
}
protected void push(Player attacker, Player victim, Vector3f force) {
victim.getControl().applyCentralForce(force);
}
protected void beam(Player p, Player victim) {
p.setScores(p.getScores() + 1);
killPlayer(victim);
}
protected void joinPlayer(int playerid, String playername) {
Player p = playerController.createNew(playerid);
p.setName(playername);
getPlayerController().setDefaultEquipment(p);
}
protected void quitPlayer(Player p) {
if(p == null) return;
if(p.getFlag() != null) {
returnFlag(p.getFlag());
}
worldController.detachPlayer(p);
playerController.removePlayer(p.getId());
}
protected boolean respawn(final Player p) {
if(p == null) return false;
if("ctf".equalsIgnoreCase(getGameConfig().getString("mp_gamemode"))) {
SpawnPoint sp = worldController.getSpawnPointForTeam(p.getTeam());
if(sp != null) {
playerController.setHealthpoints(p, 100);
p.setAlive(true);
p.getControl().zeroForce();
p.getControl().setPhysicsLocation(sp.getPosition());
worldController.attachPlayer(p);
return true;
}
}else if("editor".equalsIgnoreCase(getGameConfig().getString("mp_gamemode"))) {
playerController.setHealthpoints(p, 100);
p.setAlive(true);
p.getControl().zeroForce();
p.getControl().setPhysicsLocation(Vector3f.UNIT_Y);
worldController.attachPlayer(p);
return true;
}
return false;
}
protected void chooseTeam(Player p, int team) {
if(p == null) return;
playerController.setTeam(p, team);
}
protected void pickup(Player p, Flube flube) {
if(flube != null) {
getWorldController().detachFlube(flube);
if(p != null) {
if(p.getCurrentEquipment() instanceof Picker) {
Picker picker = (Picker) p.getCurrentEquipment();
picker.getRepository().add(flube);
}
}
}
}
protected void place(Player p, Flube f, Vector3f loc) {
f.getControl().setPhysicsLocation(loc);
getWorldController().attachFlube(f);
if(p != null) {
if(p.getCurrentEquipment() instanceof Picker) {
Picker picker = (Picker) p.getCurrentEquipment();
picker.getRepository().remove(f);
}
}
}
protected void swap(Object a, Object b) {
Vector3f posA = null;
if(a instanceof Player) {
posA = ((Player) a).getControl().getPhysicsLocation();
}else if(a instanceof Flube) {
posA = ((Flube) a).getControl().getPhysicsLocation();
}
Vector3f posB = null;
if(b instanceof Player) {
posB = ((Player) b).getControl().getPhysicsLocation();
}else if(b instanceof Flube) {
posB = ((Flube) b).getControl().getPhysicsLocation();
}
if(posA != null && posB != null) {
if(a instanceof Player) {
((Player) a).getControl().warp(posB);
}else if(a instanceof Flube) {
+ getWorldController().detachFlube((Flube) a);
((Flube) a).getControl().setPhysicsLocation(posB);
+ getWorldController().attachFlube((Flube) a);
}
if(b instanceof Player) {
((Player) b).getControl().warp(posA);
}else if(b instanceof Flube) {
+ getWorldController().detachFlube((Flube) b);
((Flube) b).getControl().setPhysicsLocation(posA);
+ getWorldController().attachFlube((Flube) b);
}
}
}
/**
* @return the gameConfig
*/
public GameConfig getGameConfig() {
return gameConfig;
}
/**
* @return the bulletAppState
*/
public BulletAppState getBulletAppState() {
return bulletAppState;
}
/**
* @return the worldController
*/
public WorldController getWorldController() {
return worldController;
}
/**
* @return the playerController
*/
public PlayerController getPlayerController() {
return playerController;
}
public abstract EquipmentFactory getEquipmentFactory();
/**
* @return the eventMachine
*/
public EventMachine getEventMachine() {
return eventMachine;
}
}
| false | true | protected void swap(Object a, Object b) {
Vector3f posA = null;
if(a instanceof Player) {
posA = ((Player) a).getControl().getPhysicsLocation();
}else if(a instanceof Flube) {
posA = ((Flube) a).getControl().getPhysicsLocation();
}
Vector3f posB = null;
if(b instanceof Player) {
posB = ((Player) b).getControl().getPhysicsLocation();
}else if(b instanceof Flube) {
posB = ((Flube) b).getControl().getPhysicsLocation();
}
if(posA != null && posB != null) {
if(a instanceof Player) {
((Player) a).getControl().warp(posB);
}else if(a instanceof Flube) {
((Flube) a).getControl().setPhysicsLocation(posB);
}
if(b instanceof Player) {
((Player) b).getControl().warp(posA);
}else if(b instanceof Flube) {
((Flube) b).getControl().setPhysicsLocation(posA);
}
}
}
| protected void swap(Object a, Object b) {
Vector3f posA = null;
if(a instanceof Player) {
posA = ((Player) a).getControl().getPhysicsLocation();
}else if(a instanceof Flube) {
posA = ((Flube) a).getControl().getPhysicsLocation();
}
Vector3f posB = null;
if(b instanceof Player) {
posB = ((Player) b).getControl().getPhysicsLocation();
}else if(b instanceof Flube) {
posB = ((Flube) b).getControl().getPhysicsLocation();
}
if(posA != null && posB != null) {
if(a instanceof Player) {
((Player) a).getControl().warp(posB);
}else if(a instanceof Flube) {
getWorldController().detachFlube((Flube) a);
((Flube) a).getControl().setPhysicsLocation(posB);
getWorldController().attachFlube((Flube) a);
}
if(b instanceof Player) {
((Player) b).getControl().warp(posA);
}else if(b instanceof Flube) {
getWorldController().detachFlube((Flube) b);
((Flube) b).getControl().setPhysicsLocation(posA);
getWorldController().attachFlube((Flube) b);
}
}
}
|
diff --git a/src/main/ris2n3.java b/src/main/ris2n3.java
index 5eaf578..0d56ace 100644
--- a/src/main/ris2n3.java
+++ b/src/main/ris2n3.java
@@ -1,35 +1,35 @@
package main;
import compilation.AuthorCompiler;
import extraction.RISExtractor;
import java.io.File;
import templates.UniqueURIGenerator;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dgcliff
*/
public class ris2n3
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
File dir = new File(args[0]);
UniqueURIGenerator uUg = new UniqueURIGenerator();
RISExtractor risEx = new RISExtractor(dir, uUg);
AuthorCompiler aC = risEx.extractAuthorNames(true);
- aC.outputNamesN3("foaf-names.n3");
+ //aC.outputNamesN3("foaf-names.n3");
//aC.printAuthorListToFile(args[1]);
- //risEx.extractToN3(args[1], aC);
+ risEx.extractToN3(args[1], aC);
}
}
| false | true | public static void main(String[] args)
{
File dir = new File(args[0]);
UniqueURIGenerator uUg = new UniqueURIGenerator();
RISExtractor risEx = new RISExtractor(dir, uUg);
AuthorCompiler aC = risEx.extractAuthorNames(true);
aC.outputNamesN3("foaf-names.n3");
//aC.printAuthorListToFile(args[1]);
//risEx.extractToN3(args[1], aC);
}
| public static void main(String[] args)
{
File dir = new File(args[0]);
UniqueURIGenerator uUg = new UniqueURIGenerator();
RISExtractor risEx = new RISExtractor(dir, uUg);
AuthorCompiler aC = risEx.extractAuthorNames(true);
//aC.outputNamesN3("foaf-names.n3");
//aC.printAuthorListToFile(args[1]);
risEx.extractToN3(args[1], aC);
}
|