diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/org/openstreetmap/josm/gui/SplashScreen.java b/src/org/openstreetmap/josm/gui/SplashScreen.java
index 12b86740..61b5fb41 100644
--- a/src/org/openstreetmap/josm/gui/SplashScreen.java
+++ b/src/org/openstreetmap/josm/gui/SplashScreen.java
@@ -1,144 +1,144 @@
// License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.gui;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import org.openstreetmap.josm.actions.AboutAction;
/**
* Show a splash screen so the user knows what is happening during startup.
*
* @author cbrill
*/
public class SplashScreen extends JWindow {
private JLabel status;
private Runnable closerRunner;
public SplashScreen() {
super();
// Add a nice border to the main splash screen
JPanel contentPane = (JPanel)this.getContentPane();
Border margin = new EtchedBorder(1, Color.white, Color.gray);
contentPane.setBorder(margin);
// Add a margin from the border to the content
JPanel innerContentPane = new JPanel();
innerContentPane.setBorder(new EmptyBorder(10, 10, 2, 10));
contentPane.add(innerContentPane);
innerContentPane.setLayout(new GridBagLayout());
// Add the logo
JLabel logo = new JLabel(new ImageIcon("images/logo.png"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = 2;
innerContentPane.add(logo, gbc);
// Add the name of this application
JLabel caption = new JLabel(tr("JOSM - Java OpenStreetMap Editor"));
caption.setFont(new Font("Helvetica", Font.BOLD, 20));
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.insets = new Insets(30, 0, 0, 0);
innerContentPane.add(caption, gbc);
// Add the version number
JLabel version = new JLabel(tr("Version {0}", AboutAction.version));
gbc.gridy = 1;
gbc.insets = new Insets(0, 0, 0, 0);
innerContentPane.add(version, gbc);
// Add a separator to the status text
JSeparator separator = new JSeparator(JSeparator.HORIZONTAL);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(15, 0, 5, 0);
innerContentPane.add(separator, gbc);
// Add a status message
status = new JLabel();
gbc.gridy = 3;
gbc.insets = new Insets(0, 0, 0, 0);
innerContentPane.add(status, gbc);
setStatus(tr("Initializing"));
pack();
// Center the splash screen
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension labelSize = contentPane.getPreferredSize();
setLocation(screenSize.width / 2 - (labelSize.width / 2),
screenSize.height / 2 - (labelSize.height / 2));
// Method to close the splash screen when being clicked or when closeSplash is called
closerRunner = new Runnable() {
public void run() {
setVisible(false);
dispose();
}
};
// Add ability to hide splash screen by clicking it
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent event) {
try {
- SwingUtilities.invokeAndWait(closerRunner);
+ closerRunner.run();
} catch (Exception e) {
e.printStackTrace();
// can catch InvocationTargetException
// can catch InterruptedException
}
}
});
setVisible(true);
}
/**
* This method sets the status message. It should be called prior to
* actually doing the action.
*
* @param message
* the message to be displayed
*/
public void setStatus(String message) {
status.setText(message + " ...");
}
/**
* Closes the splashscreen. Call once you are done starting.
*/
public void closeSplash() {
try {
SwingUtilities.invokeAndWait(closerRunner);
} catch (Exception e) {
e.printStackTrace();
// can catch InvocationTargetException
// can catch InterruptedException
}
}
}
| true | true | public SplashScreen() {
super();
// Add a nice border to the main splash screen
JPanel contentPane = (JPanel)this.getContentPane();
Border margin = new EtchedBorder(1, Color.white, Color.gray);
contentPane.setBorder(margin);
// Add a margin from the border to the content
JPanel innerContentPane = new JPanel();
innerContentPane.setBorder(new EmptyBorder(10, 10, 2, 10));
contentPane.add(innerContentPane);
innerContentPane.setLayout(new GridBagLayout());
// Add the logo
JLabel logo = new JLabel(new ImageIcon("images/logo.png"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = 2;
innerContentPane.add(logo, gbc);
// Add the name of this application
JLabel caption = new JLabel(tr("JOSM - Java OpenStreetMap Editor"));
caption.setFont(new Font("Helvetica", Font.BOLD, 20));
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.insets = new Insets(30, 0, 0, 0);
innerContentPane.add(caption, gbc);
// Add the version number
JLabel version = new JLabel(tr("Version {0}", AboutAction.version));
gbc.gridy = 1;
gbc.insets = new Insets(0, 0, 0, 0);
innerContentPane.add(version, gbc);
// Add a separator to the status text
JSeparator separator = new JSeparator(JSeparator.HORIZONTAL);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(15, 0, 5, 0);
innerContentPane.add(separator, gbc);
// Add a status message
status = new JLabel();
gbc.gridy = 3;
gbc.insets = new Insets(0, 0, 0, 0);
innerContentPane.add(status, gbc);
setStatus(tr("Initializing"));
pack();
// Center the splash screen
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension labelSize = contentPane.getPreferredSize();
setLocation(screenSize.width / 2 - (labelSize.width / 2),
screenSize.height / 2 - (labelSize.height / 2));
// Method to close the splash screen when being clicked or when closeSplash is called
closerRunner = new Runnable() {
public void run() {
setVisible(false);
dispose();
}
};
// Add ability to hide splash screen by clicking it
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent event) {
try {
SwingUtilities.invokeAndWait(closerRunner);
} catch (Exception e) {
e.printStackTrace();
// can catch InvocationTargetException
// can catch InterruptedException
}
}
});
setVisible(true);
}
| public SplashScreen() {
super();
// Add a nice border to the main splash screen
JPanel contentPane = (JPanel)this.getContentPane();
Border margin = new EtchedBorder(1, Color.white, Color.gray);
contentPane.setBorder(margin);
// Add a margin from the border to the content
JPanel innerContentPane = new JPanel();
innerContentPane.setBorder(new EmptyBorder(10, 10, 2, 10));
contentPane.add(innerContentPane);
innerContentPane.setLayout(new GridBagLayout());
// Add the logo
JLabel logo = new JLabel(new ImageIcon("images/logo.png"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = 2;
innerContentPane.add(logo, gbc);
// Add the name of this application
JLabel caption = new JLabel(tr("JOSM - Java OpenStreetMap Editor"));
caption.setFont(new Font("Helvetica", Font.BOLD, 20));
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.insets = new Insets(30, 0, 0, 0);
innerContentPane.add(caption, gbc);
// Add the version number
JLabel version = new JLabel(tr("Version {0}", AboutAction.version));
gbc.gridy = 1;
gbc.insets = new Insets(0, 0, 0, 0);
innerContentPane.add(version, gbc);
// Add a separator to the status text
JSeparator separator = new JSeparator(JSeparator.HORIZONTAL);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(15, 0, 5, 0);
innerContentPane.add(separator, gbc);
// Add a status message
status = new JLabel();
gbc.gridy = 3;
gbc.insets = new Insets(0, 0, 0, 0);
innerContentPane.add(status, gbc);
setStatus(tr("Initializing"));
pack();
// Center the splash screen
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension labelSize = contentPane.getPreferredSize();
setLocation(screenSize.width / 2 - (labelSize.width / 2),
screenSize.height / 2 - (labelSize.height / 2));
// Method to close the splash screen when being clicked or when closeSplash is called
closerRunner = new Runnable() {
public void run() {
setVisible(false);
dispose();
}
};
// Add ability to hide splash screen by clicking it
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent event) {
try {
closerRunner.run();
} catch (Exception e) {
e.printStackTrace();
// can catch InvocationTargetException
// can catch InterruptedException
}
}
});
setVisible(true);
}
|
diff --git a/src/backends/gdx-cpp-backend-android/android_support/src/com/aevumlab/gdxcpp/ApplicationManager.java b/src/backends/gdx-cpp-backend-android/android_support/src/com/aevumlab/gdxcpp/ApplicationManager.java
index c3a65f2..3d42381 100644
--- a/src/backends/gdx-cpp-backend-android/android_support/src/com/aevumlab/gdxcpp/ApplicationManager.java
+++ b/src/backends/gdx-cpp-backend-android/android_support/src/com/aevumlab/gdxcpp/ApplicationManager.java
@@ -1,192 +1,192 @@
package com.aevumlab.gdxcpp;
import java.util.HashMap;
import java.util.Stack;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.opengl.GLSurfaceView;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.backends.android.AndroidAudio;
import com.badlogic.gdx.backends.android.AndroidFiles;
import com.badlogic.gdx.files.FileHandle;
public class ApplicationManager {
static HashMap<Integer, Integer> pointerIdToButton = new HashMap<Integer, Integer>();
static Stack<Integer> pendingIds = new Stack<Integer>();
static {
for (int i = 20; i > 0; --i) {
pendingIds.push(i);
}
}
static native void nativeInitSystem();
static native void nativeInitialize(AssetManager manager, int width, int height);
static native void nativeCreate();
static native void nativeUpdate();
static native void nativePause();
static native void nativeResume();
static native void nativeResize(int widht, int height);
static native void nativeTouchDownEvent(float x, float y, int button);
static native void nativeTouchUpEvent(float x, float y, int button);
static native void nativeTouchDragEvent(float x, float y, int button);
static native void nativeBackPressed();
InputHandler handler = new InputHandler();
Activity activity;
Runnable onBeforeCreate;
static AndroidFiles files;
private AndroidAudio audio;
class NativeSurfaceRenderer implements GLSurfaceView.Renderer {
boolean created;
@Override
public void onDrawFrame(GL10 gl) {
ApplicationManager.nativeUpdate();
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
ApplicationManager.nativeResize(width, height);
if (!created) {
if (onBeforeCreate != null) {
onBeforeCreate.run();
}
ApplicationManager.nativeCreate();
created = true;
}
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Display display = activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
ApplicationManager.nativeInitialize(null, width, height);
audio = new AndroidAudio(activity);
audio.registerAudioEngine(audio);
}
}
class NativeSurfaceView extends GLSurfaceView {
public NativeSurfaceView(Context context) {
super(context);
handler.setup(this);
setFocusable(true);
setFocusableInTouchMode(true);
setRenderer(new NativeSurfaceRenderer());
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = View.MeasureSpec.getSize(widthMeasureSpec);
final int height = View.MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
}
}
public GLSurfaceView createView(Context context) {
return new NativeSurfaceView(context);
}
public void initializeWithSharedLib(String library, AssetManager assetManager) {
files = new AndroidFiles(assetManager);
System.loadLibrary(library);
nativeInitSystem();
}
public void initialize(Activity activity, Runnable beforeCreate) {
this.activity = activity;
this.onBeforeCreate = beforeCreate;
}
public void update() {
}
public void pause() {
nativePause();
audio.pause();
}
public void resume() {
nativeResume();
audio.resume();
}
public void unload() {
audio.dispose();
}
public void backPressed() {
nativeBackPressed();
}
public static void onTouchEvent(MotionEvent evt) {
final int action = evt.getAction() & MotionEvent.ACTION_MASK;
int pointerIndex = (evt.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;
synchronized (pointerIdToButton) {
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:{
int pointerId = evt.getPointerId(pointerIndex);
pointerIdToButton.put(pointerId, pendingIds.pop());
- nativeTouchDownEvent(evt.getX(), evt.getY(), pointerIdToButton.get(pointerId));
+ nativeTouchDownEvent(evt.getX(pointerIndex), evt.getY(pointerIndex), pointerIdToButton.get(pointerId));
}
break;
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
int pointerId = evt.getPointerId(pointerIndex);
int button = pointerIdToButton.get(pointerId);
- nativeTouchUpEvent(evt.getX(), evt.getY(), button);
+ nativeTouchUpEvent(evt.getX(pointerIndex), evt.getY(pointerIndex), button);
pendingIds.push(button);
pointerIdToButton.remove(pointerId);
break;
case MotionEvent.ACTION_MOVE:
for (int i = 0; i < evt.getPointerCount(); i++) {
nativeTouchDragEvent(evt.getX(i), evt.getY(i), pointerIdToButton.get(evt.getPointerId(i)));
}
break;
}
}
}
static byte[] readFile(String filename, int fileType) {
FileHandle handle = files.getFileHandle(filename, FileType.values()[fileType]);
if (handle != null) {
return handle.readBytes();
}
return null;
}
}
| false | true | public static void onTouchEvent(MotionEvent evt) {
final int action = evt.getAction() & MotionEvent.ACTION_MASK;
int pointerIndex = (evt.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;
synchronized (pointerIdToButton) {
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:{
int pointerId = evt.getPointerId(pointerIndex);
pointerIdToButton.put(pointerId, pendingIds.pop());
nativeTouchDownEvent(evt.getX(), evt.getY(), pointerIdToButton.get(pointerId));
}
break;
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
int pointerId = evt.getPointerId(pointerIndex);
int button = pointerIdToButton.get(pointerId);
nativeTouchUpEvent(evt.getX(), evt.getY(), button);
pendingIds.push(button);
pointerIdToButton.remove(pointerId);
break;
case MotionEvent.ACTION_MOVE:
for (int i = 0; i < evt.getPointerCount(); i++) {
nativeTouchDragEvent(evt.getX(i), evt.getY(i), pointerIdToButton.get(evt.getPointerId(i)));
}
break;
}
}
}
| public static void onTouchEvent(MotionEvent evt) {
final int action = evt.getAction() & MotionEvent.ACTION_MASK;
int pointerIndex = (evt.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;
synchronized (pointerIdToButton) {
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:{
int pointerId = evt.getPointerId(pointerIndex);
pointerIdToButton.put(pointerId, pendingIds.pop());
nativeTouchDownEvent(evt.getX(pointerIndex), evt.getY(pointerIndex), pointerIdToButton.get(pointerId));
}
break;
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
int pointerId = evt.getPointerId(pointerIndex);
int button = pointerIdToButton.get(pointerId);
nativeTouchUpEvent(evt.getX(pointerIndex), evt.getY(pointerIndex), button);
pendingIds.push(button);
pointerIdToButton.remove(pointerId);
break;
case MotionEvent.ACTION_MOVE:
for (int i = 0; i < evt.getPointerCount(); i++) {
nativeTouchDragEvent(evt.getX(i), evt.getY(i), pointerIdToButton.get(evt.getPointerId(i)));
}
break;
}
}
}
|
diff --git a/signserver/modules/SignServer-ejb/src/java/org/signserver/ejb/WorkerSessionBean.java b/signserver/modules/SignServer-ejb/src/java/org/signserver/ejb/WorkerSessionBean.java
index f8fc71f2d..6b71f50a8 100644
--- a/signserver/modules/SignServer-ejb/src/java/org/signserver/ejb/WorkerSessionBean.java
+++ b/signserver/modules/SignServer-ejb/src/java/org/signserver/ejb/WorkerSessionBean.java
@@ -1,1345 +1,1347 @@
/*************************************************************************
* *
* SignServer: The OpenSource Automated Signing Server *
* *
* This software is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.signserver.ejb;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyStoreException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.apache.log4j.Logger;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.x509.PrivateKeyUsagePeriod;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.ejbca.util.CertTools;
import org.signserver.common.ArchiveDataVO;
import org.signserver.common.AuthorizationRequiredException;
import org.signserver.common.AuthorizedClient;
import org.signserver.common.CryptoTokenAuthenticationFailureException;
import org.signserver.common.CryptoTokenOfflineException;
import org.signserver.common.GlobalConfiguration;
import org.signserver.common.IArchivableProcessResponse;
import org.signserver.common.ICertReqData;
import org.signserver.common.ISignResponse;
import org.signserver.common.ISignerCertReqInfo;
import org.signserver.common.IllegalRequestException;
import org.signserver.common.InvalidWorkerIdException;
import org.signserver.common.KeyTestResult;
import org.signserver.common.NoSuchWorkerException;
import org.signserver.common.ProcessRequest;
import org.signserver.common.ProcessResponse;
import org.signserver.common.ProcessableConfig;
import org.signserver.common.RequestContext;
import org.signserver.common.SignServerConstants;
import org.signserver.common.SignServerException;
import org.signserver.common.WorkerConfig;
import org.signserver.common.WorkerStatus;
import org.signserver.ejb.interfaces.IGlobalConfigurationSession;
import org.signserver.ejb.interfaces.IServiceTimerSession;
import org.signserver.ejb.interfaces.IWorkerSession;
import org.signserver.server.AccounterException;
import org.signserver.server.BaseProcessable;
import org.signserver.server.IClientCredential;
import org.signserver.server.IProcessable;
import org.signserver.server.IWorker;
import org.signserver.server.KeyUsageCounter;
import org.signserver.server.NotGrantedException;
import org.signserver.server.SignServerContext;
import org.signserver.server.WorkerFactory;
import org.signserver.server.archive.Archivable;
import org.signserver.server.archive.ArchiveException;
import org.signserver.server.archive.Archiver;
import org.signserver.server.archive.olddbarchiver.ArchiveDataArchivable;
import org.signserver.server.archive.olddbarchiver.ArchiveDataBean;
import org.signserver.server.archive.olddbarchiver.ArchiveDataService;
import org.signserver.server.log.ISystemLogger;
import org.signserver.server.log.IWorkerLogger;
import org.signserver.server.log.SystemLoggerException;
import org.signserver.server.log.SystemLoggerFactory;
import org.signserver.server.log.WorkerLoggerException;
import org.signserver.server.statistics.Event;
import org.signserver.server.statistics.StatisticsManager;
/**
* The main worker session bean.
*
* @version $Id$
*/
@Stateless
public class WorkerSessionBean implements IWorkerSession.ILocal,
IWorkerSession.IRemote {
/** Log4j instance for this class. */
private static final Logger LOG = Logger.getLogger(WorkerSessionBean.class);
/** Audit logger. */
private static final ISystemLogger AUDITLOG = SystemLoggerFactory
.getInstance().getLogger(WorkerSessionBean.class);
/** The local home interface of Worker Config entity bean. */
private WorkerConfigDataService workerConfigService;
/** The local home interface of archive entity bean. */
private ArchiveDataService archiveDataService;
@EJB
private IGlobalConfigurationSession.ILocal globalConfigurationSession;
@EJB
private IServiceTimerSession.ILocal serviceTimerSession;
@PersistenceContext(unitName = "SignServerJPA")
EntityManager em;
@PostConstruct
public void create() {
workerConfigService = new WorkerConfigDataService(em);
archiveDataService = new ArchiveDataService(em);
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#process(int,
* org.signserver.common.ISignRequest, java.security.cert.X509Certificate,
* java.lang.String)
*/
public ProcessResponse process(final int workerId,
final ProcessRequest request, final RequestContext requestContext)
throws IllegalRequestException, CryptoTokenOfflineException,
SignServerException {
if (LOG.isDebugEnabled()) {
LOG.debug(">process: " + workerId);
}
// Start time
final long startTime = System.currentTimeMillis();
// Map of log entries
final Map<String, String> logMap = getLogMap(requestContext);
// Get transaction ID or create new if not created yet
final String transactionID;
if (requestContext.get(RequestContext.TRANSACTION_ID) == null) {
transactionID = generateTransactionID();
} else {
transactionID = (String) requestContext.get(
RequestContext.TRANSACTION_ID);
}
// Store values for request context and logging
requestContext.put(RequestContext.WORKER_ID, Integer.valueOf(workerId));
requestContext.put(RequestContext.TRANSACTION_ID, transactionID);
logMap.put(IWorkerLogger.LOG_TIME, String.valueOf(startTime));
logMap.put(IWorkerLogger.LOG_ID, transactionID);
logMap.put(IWorkerLogger.LOG_WORKER_ID, String.valueOf(workerId));
logMap.put(IWorkerLogger.LOG_CLIENT_IP,
(String) requestContext.get(RequestContext.REMOTE_IP));
// Get worker instance
final IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker == null) {
final IllegalRequestException ex =
new NoSuchWorkerException(String.valueOf(workerId));
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
try {
AUDITLOG.log(logMap);
} catch (SystemLoggerException ex2) {
LOG.error("Audit log failure", ex2);
}
throw ex;
}
// Get worker log instance
final IWorkerLogger workerLogger = WorkerFactory.getInstance().
getWorkerLogger(workerId,
worker.getStatus().getActiveSignerConfig(), em);
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId + "]: " + "WorkerLogger: "
+ workerLogger);
}
try {
// Get processable
if (!(worker instanceof IProcessable)) {
final IllegalRequestException ex = new IllegalRequestException(
"Worker exists but isn't a processable: " + workerId);
// auditLog(startTime, workerId, false, requestContext, ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw ex;
}
final IProcessable processable = (IProcessable) worker;
// Check authorization
logMap.put(IWorkerLogger.LOG_WORKER_AUTHTYPE,
processable.getAuthenticationType());
try {
WorkerFactory.getInstance()
.getAuthenticator(workerId,
processable.getAuthenticationType(),
worker.getStatus().getActiveSignerConfig(),
em).isAuthorized(request, requestContext);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(true));
} catch (AuthorizationRequiredException ex) {
throw ex;
} catch (IllegalRequestException ex) {
final IllegalRequestException exception =
new IllegalRequestException("Authorization failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(false));
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
} catch (SignServerException ex) {
final SignServerException exception =
new SignServerException("Authorization failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(false));
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Log client certificate (if any)
final Certificate clientCertificate = (Certificate)
requestContext.get(RequestContext.CLIENT_CERTIFICATE);
if (clientCertificate instanceof X509Certificate) {
final X509Certificate cert = (X509Certificate) clientCertificate;
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_SUBJECTDN,
cert.getSubjectDN().getName());
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_ISSUERDN,
cert.getIssuerDN().getName());
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_SERIALNUMBER,
cert.getSerialNumber().toString(16));
}
// Check activation
final WorkerConfig awc =
processable.getStatus().getActiveSignerConfig();
if (awc.getProperties().getProperty(SignServerConstants.DISABLED,
"FALSE").equalsIgnoreCase("TRUE")) {
final CryptoTokenOfflineException exception =
new CryptoTokenOfflineException("Error Signer : "
+ workerId
+ " is disabled and cannot perform any signature operations");
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Check signer certificate
try {
// Check if the signer has a signer certificate and if that
// certificate have ok validity and private key usage periods.
checkSignerValidity(workerId, awc, logMap);
// Check key usage limit (preliminary check only)
checkSignerKeyUsageCounter(processable, workerId, awc, em,
false);
} catch (CryptoTokenOfflineException ex) {
final CryptoTokenOfflineException exception =
new CryptoTokenOfflineException(ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Statistics: start event
final Event event = StatisticsManager.startEvent(workerId, awc, em);
requestContext.put(RequestContext.STATISTICS_EVENT, event);
// Process the request
final ProcessResponse res;
try {
res = processable.processData(request, requestContext);
} catch (AuthorizationRequiredException ex) {
throw ex; // This can happen in dispatching workers
} catch (SignServerException e) {
final SignServerException exception = new SignServerException(
"SignServerException calling signer with id " + workerId
+ " : " + e.getMessage(), e);
LOG.error(exception.getMessage(), exception);
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
} catch (IllegalRequestException ex) {
final IllegalRequestException exception =
new IllegalRequestException(ex.getMessage());
- LOG.error("Error calling signer with id " + workerId
- + " : " + ex.getMessage(), exception);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Illegal request calling signer with id " + workerId
+ + " : " + ex.getMessage());
+ }
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Charge the client if the request was successfull
if (Boolean.TRUE.equals(requestContext.get(
RequestContext.WORKER_FULFILLED_REQUEST))) {
// Billing time
boolean purchased = false;
try {
IClientCredential credential =
(IClientCredential) requestContext.get(
RequestContext.CLIENT_CREDENTIAL);
purchased = WorkerFactory.getInstance().getAccounter(workerId,
worker.getStatus().getActiveSignerConfig(),
em).purchase(credential, request, res,
requestContext);
logMap.put(IWorkerLogger.LOG_PURCHASED, "true");
} catch (AccounterException ex) {
logMap.put(IWorkerLogger.LOG_PURCHASED, "false");
final SignServerException exception =
new SignServerException("Accounter failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
if (!purchased) {
final String error = "Purchase not granted";
logMap.put(IWorkerLogger.LOG_EXCEPTION, error);
workerLogger.log(logMap);
throw new NotGrantedException(error);
}
} else {
logMap.put(IWorkerLogger.LOG_PURCHASED, "false");
}
// Archiving
if (res instanceof IArchivableProcessResponse) {
final IArchivableProcessResponse arres =
(IArchivableProcessResponse) res;
if (arres.getArchiveData() != null) {
// The IArchivableProcessResponse only supports a single
// item to archive. In the future we might get multiple
// Archivables from a worker.
final Archivable archivableResponse
= new ArchiveDataArchivable(arres.getArchiveId(),
arres.getArchiveData(), Archivable.TYPE_RESPONSE);
final Collection<Archivable> archivables
= Collections.singleton(archivableResponse);
// Archive all Archivables using all ArchiverS
final List<Archiver> archivers = WorkerFactory
.getInstance().getArchivers(workerId, awc, em);
if (archivers != null) {
try {
for (Archiver archiver : archivers) {
for (Archivable archivable : archivables) {
final boolean archived = archiver.archive(
archivable, requestContext);
if (LOG.isDebugEnabled()) {
final StringBuilder buff = new StringBuilder();
buff.append("Archiver ");
buff.append(archiver);
buff.append(" archived request: ");
buff.append(archived);
LOG.debug(buff.toString());
}
}
}
} catch (ArchiveException ex) {
LOG.error("Archiving failed", ex);
throw new SignServerException(
"Archiving failed. See server log.");
}
}
}
}
// Statistics: end event
StatisticsManager.endEvent(workerId, awc, em, event);
// Check key usage limit
checkSignerKeyUsageCounter(processable, workerId, awc, em, true);
// Output successfully
if (res instanceof ISignResponse) {
LOG.info("Worker " + workerId + " Processed request "
+ ((ISignResponse) res).getRequestID()
+ " successfully");
} else {
LOG.info("Worker " + workerId
+ " Processed request successfully");
}
// Old log entries (SignServer 3.1) added for backward compatibility
// Log: REQUESTID
if (res instanceof ISignResponse) {
logMap.put("REQUESTID",
String.valueOf(((ISignResponse) res).getRequestID()));
}
// Log
logMap.put(IWorkerLogger.LOG_PROCESS_SUCCESS, String.valueOf(true));
workerLogger.log(logMap);
LOG.debug("<process");
return res;
} catch (WorkerLoggerException ex) {
final SignServerException exception =
new SignServerException("Logging failed", ex);
LOG.error(exception.getMessage(), exception);
throw exception;
}
}
/**
* Verify the certificate validity times, the PrivateKeyUsagePeriod and
* that the minremaining validity is ok.
*
* @param workerId
* @param awc
* @throws CryptoTokenOfflineException
*/
private void checkSignerValidity(final int workerId,
final WorkerConfig awc, final Map<String, String> logMap)
throws CryptoTokenOfflineException {
// If the signer have a certificate, check that it is usable
final Certificate signerCert = getSignerCertificate(workerId);
if (signerCert instanceof X509Certificate) {
final X509Certificate cert = (X509Certificate) signerCert;
// Log client certificate
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_SUBJECTDN,
cert.getSubjectDN().getName());
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_ISSUERDN,
cert.getIssuerDN().getName());
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_SERIALNUMBER,
cert.getSerialNumber().toString(16));
// Check certificate, privatekey and minremaining validities
final Date notBefore =
getSigningValidity(false, workerId, awc, cert);
final Date notAfter =
getSigningValidity(true, workerId, awc, cert);
if (LOG.isDebugEnabled()) {
LOG.debug("The signer validity is from '"
+ notBefore + "' until '" + notAfter + "'");
}
// Compare with current date
final Date now = new Date();
if (notBefore != null && now.before(notBefore)) {
final String msg = "Error Signer " + workerId
+ " is not valid until " + notBefore;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
if (notAfter != null && now.after(notAfter)) {
String msg = "Error Signer " + workerId
+ " expired at " + notAfter;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
} else { // if (cert != null)
if (LOG.isDebugEnabled()) {
LOG.debug("Worker does not have a signing certificate. Worker: "
+ workerId);
}
}
} // checkCertificateValidity
private static PrivateKeyUsagePeriod getPrivateKeyUsagePeriod(
final X509Certificate cert) throws IOException {
PrivateKeyUsagePeriod res = null;
final byte[] extvalue = cert.getExtensionValue(
X509Extensions.PrivateKeyUsagePeriod.getId());
if ((extvalue != null) && (extvalue.length > 0)) {
if (LOG.isDebugEnabled()) {
LOG.debug(
"Found a PrivateKeyUsagePeriod in the signer certificate.");
}
final DEROctetString oct = (DEROctetString) (new ASN1InputStream(
new ByteArrayInputStream(extvalue)).readObject());
res = PrivateKeyUsagePeriod.
getInstance((ASN1Sequence) new ASN1InputStream(
new ByteArrayInputStream(oct.getOctets())).
readObject());
}
return res;
}
/**
* Gets the last date the specified worker can do signings.
* @param workerId Id of worker to check.
* @return The last date or null if no last date (=unlimited).
* @throws CryptoTokenOfflineException In case the cryptotoken is offline
* for some reason.
*/
public Date getSigningValidityNotAfter(final int workerId)
throws CryptoTokenOfflineException {
Date date = null;
final Certificate signerCert = getSignerCertificate(workerId);
if (signerCert instanceof X509Certificate) {
final X509Certificate cert = (X509Certificate) signerCert;
date = getSigningValidity(true, workerId,
getWorkerConfig(workerId), cert);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Worker does not have a signing certificate. Worker: "
+ workerId);
}
}
return date;
}
/**
* Gets the first date the specified worker can do signings.
* @param workerId Id of worker to check.
* @return The first date or null if no last date (=unlimited).
* @throws CryptoTokenOfflineException In case the cryptotoken is offline
* for some reason.
*/
public Date getSigningValidityNotBefore(final int workerId)
throws CryptoTokenOfflineException {
Date date = null;
final Certificate signerCert = getSignerCertificate(workerId);
if (signerCert instanceof X509Certificate) {
final X509Certificate cert = (X509Certificate) signerCert;
date = getSigningValidity(false, workerId,
getWorkerConfig(workerId), cert);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Worker does not have a signing certificate. Worker: "
+ workerId);
}
}
return date;
}
private Date getSigningValidity(final boolean notAfter, final int workerId,
final WorkerConfig awc, final X509Certificate cert)
throws CryptoTokenOfflineException {
Date certDate = null;
Date privatekeyDate = null;
Date minreimainingDate = null;
boolean checkcertvalidity = awc.getProperties().getProperty(
SignServerConstants.CHECKCERTVALIDITY, "TRUE").equalsIgnoreCase(
"TRUE");
boolean checkprivatekeyvalidity = awc.getProperties().getProperty(
SignServerConstants.CHECKCERTPRIVATEKEYVALIDITY, "TRUE").
equalsIgnoreCase("TRUE");
int minremainingcertvalidity = Integer.valueOf(awc.getProperties().
getProperty(SignServerConstants.MINREMAININGCERTVALIDITY, "0"));
if (LOG.isDebugEnabled()) {
LOG.debug("checkcertvalidity: " + checkcertvalidity);
LOG.debug("checkprivatekeyvalidity: " + checkprivatekeyvalidity);
LOG.debug("minremainingcertvalidity: " + minremainingcertvalidity);
}
// Certificate validity period. Cert must not be expired.
if (checkcertvalidity) {
certDate = notAfter ? cert.getNotAfter() : cert.getNotBefore();
}
// Private key usage period. Private key must not be expired
if (checkprivatekeyvalidity) {
// Check privateKeyUsagePeriod of it exists
try {
final PrivateKeyUsagePeriod p = getPrivateKeyUsagePeriod(cert);
if (p != null) {
privatekeyDate = notAfter ? p.getNotAfter().getDate()
: p.getNotBefore().getDate();
}
} catch (IOException e) {
LOG.error(e);
CryptoTokenOfflineException newe =
new CryptoTokenOfflineException(
"Error Signer " + workerId
+ " have a problem with PrivateKeyUsagePeriod, check server log.");
newe.initCause(e);
throw newe;
} catch (ParseException e) {
LOG.error(e);
CryptoTokenOfflineException newe =
new CryptoTokenOfflineException(
"Error Signer " + workerId
+ " have a problem with PrivateKeyUsagePeriod, check server log.");
newe.initCause(e);
throw newe;
}
}
// Check remaining validity of certificate. Must not be too short.
if (notAfter && minremainingcertvalidity > 0) {
final Date certNotAfter = cert.getNotAfter();
final Calendar cal = Calendar.getInstance();
cal.setTime(certNotAfter);
cal.add(Calendar.DAY_OF_MONTH, -minremainingcertvalidity);
minreimainingDate = cal.getTime();
}
Date res = null;
res = certDate;
res = max(notAfter, res, privatekeyDate);
res = max(notAfter, res, minreimainingDate);
if (LOG.isDebugEnabled()) {
LOG.debug((notAfter ? "min(" : "max(") + certDate + ", "
+ privatekeyDate + ", " + minreimainingDate + ") = "
+ res);
}
return res;
}
/**
* Returns the value of the KeyUsageCounter for the given workerId. If no
* certificate is configured for the worker or the current key does not yet
* have a counter in the database -1 is returned.
* @param workerId
* @return Value of the key usage counter or -1
* @throws CryptoTokenOfflineException
*/
public long getKeyUsageCounterValue(final int workerId)
throws CryptoTokenOfflineException {
long result;
try {
final Certificate cert = getSignerCertificate(workerId);
if (cert == null) {
result = -1;
} else {
final String pk
= KeyUsageCounter.createKeyHash(cert.getPublicKey());
final KeyUsageCounter signings
= em.find(KeyUsageCounter.class, pk);
if (signings == null) {
result = -1;
} else {
result = signings.getCounter();
}
}
return result;
} catch (IllegalArgumentException ex) {
LOG.error(ex, ex);
throw new CryptoTokenOfflineException(ex);
}
}
/**
* @param inv If the max function should be inverrted (min).
* @param date1 Operand 1
* @param date2 Operand 2
* @return The last of the two dates unless inv is true in which case it
* returns the first of the two.
*/
private static Date max(final boolean inv, final Date date1,
final Date date2) {
if (date1 == null) {
return date2;
} else if (date2 == null) {
return date1;
}
return inv && date1.before(date2) ? date1 : date2;
}
/**
* Checks that if this worker has a certificate (ie the worker is a Signer)
* the counter of the usages of the key has not reached the configured
* limit.
* @param workerId
* @param awc
* @param em
* @throws CryptoTokenOfflineException
*/
private void checkSignerKeyUsageCounter(final IProcessable worker,
final int workerId, final WorkerConfig awc, EntityManager em,
final boolean increment)
throws CryptoTokenOfflineException {
// If the signer have a certificate, check that the usage of the key
// has not reached the limit
Certificate cert = null;
if (worker instanceof BaseProcessable) {
cert = ((BaseProcessable) worker).getSigningCertificate();
} else {
// The following will not work for keystores where the SIGNSERCERT
// property is not set
cert = (new ProcessableConfig(awc)).getSignerCertificate();
}
if (cert != null) {
final long keyUsageLimit
= Long.valueOf(awc.getProperty(SignServerConstants.KEYUSAGELIMIT, "-1"));
final String keyHash
= KeyUsageCounter.createKeyHash(cert.getPublicKey());
if(LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId +"]: "
+ "Key usage limit: " + keyUsageLimit);
LOG.debug("Worker[" + workerId +"]: "
+ "Key hash: " + keyHash);
}
if (increment) {
final Query updateQuery;
if (keyUsageLimit < 0) {
updateQuery = em.createQuery("UPDATE KeyUsageCounter w SET w.counter = w.counter + 1 WHERE w.keyHash = :keyhash");
} else {
updateQuery = em.createQuery("UPDATE KeyUsageCounter w SET w.counter = w.counter + 1 WHERE w.keyHash = :keyhash AND w.counter < :limit");
updateQuery.setParameter("limit", keyUsageLimit);
}
updateQuery.setParameter("keyhash", keyHash);
if (updateQuery.executeUpdate() < 1) {
final String message
= "Key usage limit exceeded or not initialized for worker "
+ workerId;
LOG.debug(message);
throw new CryptoTokenOfflineException(message);
}
} else {
// Just check the value without updating
if (keyUsageLimit > -1) {
final Query selectQuery;
selectQuery = em.createQuery("SELECT COUNT(w) FROM KeyUsageCounter w WHERE w.keyHash = :keyhash AND w.counter < :limit");
selectQuery.setParameter("limit", keyUsageLimit);
selectQuery.setParameter("keyhash", keyHash);
if (selectQuery.getResultList().size() < 1) {
final String message
= "Key usage limit exceeded or not initialized for worker "
+ workerId;
LOG.debug(message);
throw new CryptoTokenOfflineException(message);
}
}
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId + "]: "
+ "No certificate so not checking signing key usage counter");
}
}
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getStatus(int)
*/
public WorkerStatus getStatus(int workerId) throws InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + workerId
+ " doesn't exist");
}
return worker.getStatus();
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getWorkerId(java.lang.String)
*/
public int getWorkerId(String signerName) {
return WorkerFactory.getInstance().getWorkerIdFromName(signerName.
toUpperCase(), workerConfigService, globalConfigurationSession, new SignServerContext(
em));
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#reloadConfiguration(int)
*/
public void reloadConfiguration(int workerId) {
if (workerId == 0) {
globalConfigurationSession.reload();
} else {
WorkerFactory.getInstance().reloadWorker(workerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
// Try to insert a key usage counter entry for this worker's public
// key
// Get worker instance
final IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
try {
final Certificate cert = ((BaseProcessable)worker)
.getSigningCertificate();
if (cert != null) {
final String keyHash = KeyUsageCounter
.createKeyHash(cert.getPublicKey());
KeyUsageCounter counter
= em.find(KeyUsageCounter.class, keyHash);
if (counter == null) {
counter = new KeyUsageCounter(keyHash);
em.persist(counter);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId + "]: "
+ "key usage counter: " + counter.getCounter());
}
}
} catch (CryptoTokenOfflineException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[ " + workerId + "]: "
+ "Crypto token offline trying to create key usage counter");
}
}
}
}
if (workerId == 0 || globalConfigurationSession.getWorkers(
GlobalConfiguration.WORKERTYPE_SERVICES).contains(new Integer(
workerId))) {
serviceTimerSession.unload(workerId);
serviceTimerSession.load(workerId);
}
StatisticsManager.flush(workerId);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#activateSigner(int, java.lang.String)
*/
public void activateSigner(int signerId, String authenticationCode)
throws CryptoTokenAuthenticationFailureException,
CryptoTokenOfflineException, InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
signer.activateSigner(authenticationCode);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#deactivateSigner(int)
*/
public boolean deactivateSigner(int signerId)
throws CryptoTokenOfflineException, InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
return signer.deactivateSigner();
}
/**
* @see IWorkerSession#generateSignerKey(int, java.lang.String,
* java.lang.String, java.lang.String, char[])
*/
public String generateSignerKey(final int signerId, String keyAlgorithm,
String keySpec, String alias, final char[] authCode)
throws CryptoTokenOfflineException, InvalidWorkerIdException,
IllegalArgumentException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
final IProcessable signer = (IProcessable) worker;
final WorkerConfig config = worker.getStatus().getActiveSignerConfig();
if (keyAlgorithm == null) {
keyAlgorithm = config.getProperty("KEYALG");
}
if (keySpec == null) {
keySpec = config.getProperty("KEYSPEC");
}
if (alias == null) {
final String currentAlias = config.getProperty("DEFAULTKEY");
if (currentAlias == null) {
throw new IllegalArgumentException("No key alias specified");
} else {
alias = nextAliasInSequence(currentAlias);
}
}
signer.generateKey(keyAlgorithm, keySpec, alias,
authCode);
return alias;
}
static String nextAliasInSequence(final String currentAlias) {
String prefix = currentAlias;
String nextSequence = "2";
final String[] entry = currentAlias.split("[0-9]+$");
if (entry.length == 1) {
prefix = entry[0];
final String currentSequence
= currentAlias.substring(prefix.length());
final int sequenceChars = currentSequence.length();
if (sequenceChars > 0) {
final long nextSequenceNumber = Long.parseLong(currentSequence) + 1;
final String nextSequenceNumberString
= String.valueOf(nextSequenceNumber);
if (sequenceChars > nextSequenceNumberString.length()) {
nextSequence = currentSequence.substring(0,
sequenceChars - nextSequenceNumberString.length())
+ nextSequenceNumberString;
} else {
nextSequence = nextSequenceNumberString;
}
}
}
return prefix + nextSequence;
}
/**
* @see IWorkerSession#testKey(int, java.lang.String, char[])
*/
public Collection<KeyTestResult> testKey(final int signerId, String alias,
char[] authCode)
throws CryptoTokenOfflineException, InvalidWorkerIdException,
KeyStoreException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
final IProcessable signer = (IProcessable) worker;
// if (worker.getStatus().isOK() != null) {
// throw new CryptoTokenOfflineException(
// "Testing key can not be performed on offline cryptotoken");
// }
final WorkerConfig config = worker.getStatus().getActiveSignerConfig();
if (alias == null) {
alias = config.getProperty("DEFAULTKEY");
}
return signer.testKey(alias, authCode);
}
/* (non-Javadoc)
* @see org.signserver.ejb.IWorkerSession#getCurrentSignerConfig(int)
*/
public WorkerConfig getCurrentWorkerConfig(int signerId) {
return getWorkerConfig(signerId);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#setWorkerProperty(int, java.lang.String, java.lang.String)
*/
public void setWorkerProperty(int workerId, String key, String value) {
WorkerConfig config = getWorkerConfig(workerId);
config.setProperty(key.toUpperCase(), value);
workerConfigService.setWorkerConfig(workerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#removeWorkerProperty(int, java.lang.String)
*/
public boolean removeWorkerProperty(int workerId, String key) {
boolean result = false;
WorkerConfig config = getWorkerConfig(workerId);
result = config.removeProperty(key.toUpperCase());
if (config.getProperties().size() == 0) {
workerConfigService.removeWorkerConfig(workerId);
LOG.debug("WorkerConfig is empty and therefore removed.");
} else {
workerConfigService.setWorkerConfig(workerId, config);
}
return result;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getAuthorizedClients(int)
*/
public Collection<AuthorizedClient> getAuthorizedClients(int signerId) {
return new ProcessableConfig(getWorkerConfig(signerId)).
getAuthorizedClients();
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#addAuthorizedClient(int, org.signserver.common.AuthorizedClient)
*/
public void addAuthorizedClient(int signerId, AuthorizedClient authClient) {
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig(config)).addAuthorizedClient(authClient);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#removeAuthorizedClient(int, org.signserver.common.AuthorizedClient)
*/
public boolean removeAuthorizedClient(int signerId,
AuthorizedClient authClient) {
boolean result = false;
WorkerConfig config = getWorkerConfig(signerId);
result = (new ProcessableConfig(config)).removeAuthorizedClient(
authClient);
workerConfigService.setWorkerConfig(signerId, config);
return result;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getCertificateRequest(int, org.signserver.common.ISignerCertReqInfo)
*/
public ICertReqData getCertificateRequest(final int signerId,
final ISignerCertReqInfo certReqInfo,
final boolean explicitEccParameters) throws
CryptoTokenOfflineException, InvalidWorkerIdException {
return getCertificateRequest(signerId, certReqInfo,
explicitEccParameters, true);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getCertificateRequest(int, org.signserver.common.ISignerCertReqInfo)
*/
public ICertReqData getCertificateRequest(int signerId,
ISignerCertReqInfo certReqInfo,
final boolean explicitEccParameters,
final boolean defaultKey) throws
CryptoTokenOfflineException, InvalidWorkerIdException {
if (LOG.isTraceEnabled()) {
LOG.trace(">getCertificateRequest: signerId=" + signerId);
}
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable processable = (IProcessable) worker;
if (LOG.isDebugEnabled()) {
LOG.debug("Found processable worker of type: " + processable.
getClass().getName());
}
ICertReqData ret = processable.genCertificateRequest(certReqInfo,
explicitEccParameters, defaultKey);
if (LOG.isTraceEnabled()) {
LOG.trace("<getCertificateRequest: signerId=" + signerId);
}
return ret;
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#getSigningCertificate(int)
*/
public Certificate getSignerCertificate(final int signerId) throws CryptoTokenOfflineException {
Certificate ret = null;
final IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
ret = ((BaseProcessable) worker).getSigningCertificate();
}
return ret;
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#getSigningCertificateChain(int)
*/
public List<Certificate> getSignerCertificateChain(final int signerId)
throws CryptoTokenOfflineException {
List<Certificate> ret = null;
final IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
Collection<Certificate> certs = ((BaseProcessable) worker)
.getSigningCertificateChain();
if (certs instanceof List) {
ret = (List) certs;
} else if( certs != null) {
ret = new LinkedList<Certificate>(certs);
}
}
return ret;
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#getSigningCertificateBytes(int)
*/
@Override
public byte[] getSignerCertificateBytes(final int signerId)
throws CryptoTokenOfflineException {
try {
final Certificate cert = getSignerCertificate(signerId);
return cert == null ? null : cert.getEncoded();
} catch (CertificateEncodingException ex) {
throw new CryptoTokenOfflineException(ex);
}
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#getSigningCertificateChain(int)
*/
@Override
public List<byte[]> getSignerCertificateChainBytes(final int signerId)
throws CryptoTokenOfflineException {
final List<Certificate> certs = getSignerCertificateChain(signerId);
final List<byte[]> res = new LinkedList<byte[]>();
try {
for (Certificate cert : certs) {
res.add(cert.getEncoded());
}
} catch (CertificateEncodingException ex) {
throw new CryptoTokenOfflineException(ex);
}
return res;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#destroyKey(int, int)
*/
public boolean destroyKey(int signerId, int purpose) throws
InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
return signer.destroyKey(purpose);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#uploadSignerCertificate(int, java.security.cert.X509Certificate, java.lang.String)
*/
public void uploadSignerCertificate(int signerId, byte[] signerCert,
String scope) throws CertificateException {
WorkerConfig config = getWorkerConfig(signerId);
final Certificate cert = CertTools.getCertfromByteArray(signerCert);
( new ProcessableConfig(config)).setSignerCertificate((X509Certificate)cert,scope);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#uploadSignerCertificateChain(int, java.util.Collection, java.lang.String)
*/
public void uploadSignerCertificateChain(int signerId,
Collection<byte[]> signerCerts, String scope)
throws CertificateException {
WorkerConfig config = getWorkerConfig(signerId);
ArrayList<Certificate> certs = new ArrayList<Certificate>();
Iterator<byte[]> iter = signerCerts.iterator();
while(iter.hasNext()){
X509Certificate cert;
cert = (X509Certificate) CertTools.getCertfromByteArray(iter.next());
certs.add(cert);
}
// Collections.reverse(certs); // TODO: Why?
(new ProcessableConfig( config)).setSignerCertificateChain(certs, scope);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#genFreeWorkerId()
*/
public int genFreeWorkerId() {
Collection<Integer> ids = globalConfigurationSession.getWorkers(
GlobalConfiguration.WORKERTYPE_ALL);
int max = 0;
Iterator<Integer> iter = ids.iterator();
while (iter.hasNext()) {
Integer id = iter.next();
if (id.intValue() > max) {
max = id.intValue();
}
}
return max + 1;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDataFromArchiveId(int, java.lang.String)
*/
public ArchiveDataVO findArchiveDataFromArchiveId(int signerId,
String archiveId) {
ArchiveDataVO retval = null;
ArchiveDataBean adb = archiveDataService.findByArchiveId(
ArchiveDataVO.TYPE_RESPONSE, signerId, archiveId);
if (adb != null) {
retval = adb.getArchiveDataVO();
}
return retval;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDatasFromRequestIP(int, java.lang.String)
*/
public List<ArchiveDataVO> findArchiveDatasFromRequestIP(int signerId,
String requestIP) {
ArrayList<ArchiveDataVO> retval = new ArrayList<ArchiveDataVO>();
Collection<ArchiveDataBean> result = archiveDataService.findByRequestIP(
ArchiveDataVO.TYPE_RESPONSE, signerId, requestIP);
Iterator<ArchiveDataBean> iter = result.iterator();
while (iter.hasNext()) {
ArchiveDataBean next = iter.next();
retval.add(next.getArchiveDataVO());
}
return retval;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDatasFromRequestCertificate(int, java.math.BigInteger, java.lang.String)
*/
public List<ArchiveDataVO> findArchiveDatasFromRequestCertificate(
int signerId, BigInteger requestCertSerialnumber,
String requestCertIssuerDN) {
ArrayList<ArchiveDataVO> retval = new ArrayList<ArchiveDataVO>();
Collection<ArchiveDataBean> result = archiveDataService.
findByRequestCertificate(ArchiveDataVO.TYPE_RESPONSE, signerId, CertTools.
stringToBCDNString(requestCertIssuerDN), requestCertSerialnumber.
toString(16));
Iterator<ArchiveDataBean> iter = result.iterator();
while (iter.hasNext()) {
ArchiveDataBean next = iter.next();
retval.add(next.getArchiveDataVO());
}
return retval;
}
private WorkerConfig getWorkerConfig(int workerId) {
WorkerConfig workerConfig =
workerConfigService.getWorkerConfig(workerId);
if (workerConfig == null) {
workerConfigService.create(workerId, WorkerConfig.class.getName());
workerConfig = workerConfigService.getWorkerConfig(workerId);
}
return workerConfig;
}
private String generateTransactionID() {
return UUID.randomUUID().toString();
}
private Map<String, String> getLogMap(final RequestContext requestContext) {
Map<String, String> logMap = (Map)
requestContext.get(RequestContext.LOGMAP);
if (logMap == null) {
logMap = new HashMap<String, String>();
requestContext.put(RequestContext.LOGMAP, logMap);
}
return logMap;
}
}
| true | true | public ProcessResponse process(final int workerId,
final ProcessRequest request, final RequestContext requestContext)
throws IllegalRequestException, CryptoTokenOfflineException,
SignServerException {
if (LOG.isDebugEnabled()) {
LOG.debug(">process: " + workerId);
}
// Start time
final long startTime = System.currentTimeMillis();
// Map of log entries
final Map<String, String> logMap = getLogMap(requestContext);
// Get transaction ID or create new if not created yet
final String transactionID;
if (requestContext.get(RequestContext.TRANSACTION_ID) == null) {
transactionID = generateTransactionID();
} else {
transactionID = (String) requestContext.get(
RequestContext.TRANSACTION_ID);
}
// Store values for request context and logging
requestContext.put(RequestContext.WORKER_ID, Integer.valueOf(workerId));
requestContext.put(RequestContext.TRANSACTION_ID, transactionID);
logMap.put(IWorkerLogger.LOG_TIME, String.valueOf(startTime));
logMap.put(IWorkerLogger.LOG_ID, transactionID);
logMap.put(IWorkerLogger.LOG_WORKER_ID, String.valueOf(workerId));
logMap.put(IWorkerLogger.LOG_CLIENT_IP,
(String) requestContext.get(RequestContext.REMOTE_IP));
// Get worker instance
final IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker == null) {
final IllegalRequestException ex =
new NoSuchWorkerException(String.valueOf(workerId));
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
try {
AUDITLOG.log(logMap);
} catch (SystemLoggerException ex2) {
LOG.error("Audit log failure", ex2);
}
throw ex;
}
// Get worker log instance
final IWorkerLogger workerLogger = WorkerFactory.getInstance().
getWorkerLogger(workerId,
worker.getStatus().getActiveSignerConfig(), em);
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId + "]: " + "WorkerLogger: "
+ workerLogger);
}
try {
// Get processable
if (!(worker instanceof IProcessable)) {
final IllegalRequestException ex = new IllegalRequestException(
"Worker exists but isn't a processable: " + workerId);
// auditLog(startTime, workerId, false, requestContext, ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw ex;
}
final IProcessable processable = (IProcessable) worker;
// Check authorization
logMap.put(IWorkerLogger.LOG_WORKER_AUTHTYPE,
processable.getAuthenticationType());
try {
WorkerFactory.getInstance()
.getAuthenticator(workerId,
processable.getAuthenticationType(),
worker.getStatus().getActiveSignerConfig(),
em).isAuthorized(request, requestContext);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(true));
} catch (AuthorizationRequiredException ex) {
throw ex;
} catch (IllegalRequestException ex) {
final IllegalRequestException exception =
new IllegalRequestException("Authorization failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(false));
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
} catch (SignServerException ex) {
final SignServerException exception =
new SignServerException("Authorization failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(false));
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Log client certificate (if any)
final Certificate clientCertificate = (Certificate)
requestContext.get(RequestContext.CLIENT_CERTIFICATE);
if (clientCertificate instanceof X509Certificate) {
final X509Certificate cert = (X509Certificate) clientCertificate;
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_SUBJECTDN,
cert.getSubjectDN().getName());
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_ISSUERDN,
cert.getIssuerDN().getName());
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_SERIALNUMBER,
cert.getSerialNumber().toString(16));
}
// Check activation
final WorkerConfig awc =
processable.getStatus().getActiveSignerConfig();
if (awc.getProperties().getProperty(SignServerConstants.DISABLED,
"FALSE").equalsIgnoreCase("TRUE")) {
final CryptoTokenOfflineException exception =
new CryptoTokenOfflineException("Error Signer : "
+ workerId
+ " is disabled and cannot perform any signature operations");
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Check signer certificate
try {
// Check if the signer has a signer certificate and if that
// certificate have ok validity and private key usage periods.
checkSignerValidity(workerId, awc, logMap);
// Check key usage limit (preliminary check only)
checkSignerKeyUsageCounter(processable, workerId, awc, em,
false);
} catch (CryptoTokenOfflineException ex) {
final CryptoTokenOfflineException exception =
new CryptoTokenOfflineException(ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Statistics: start event
final Event event = StatisticsManager.startEvent(workerId, awc, em);
requestContext.put(RequestContext.STATISTICS_EVENT, event);
// Process the request
final ProcessResponse res;
try {
res = processable.processData(request, requestContext);
} catch (AuthorizationRequiredException ex) {
throw ex; // This can happen in dispatching workers
} catch (SignServerException e) {
final SignServerException exception = new SignServerException(
"SignServerException calling signer with id " + workerId
+ " : " + e.getMessage(), e);
LOG.error(exception.getMessage(), exception);
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
} catch (IllegalRequestException ex) {
final IllegalRequestException exception =
new IllegalRequestException(ex.getMessage());
LOG.error("Error calling signer with id " + workerId
+ " : " + ex.getMessage(), exception);
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Charge the client if the request was successfull
if (Boolean.TRUE.equals(requestContext.get(
RequestContext.WORKER_FULFILLED_REQUEST))) {
// Billing time
boolean purchased = false;
try {
IClientCredential credential =
(IClientCredential) requestContext.get(
RequestContext.CLIENT_CREDENTIAL);
purchased = WorkerFactory.getInstance().getAccounter(workerId,
worker.getStatus().getActiveSignerConfig(),
em).purchase(credential, request, res,
requestContext);
logMap.put(IWorkerLogger.LOG_PURCHASED, "true");
} catch (AccounterException ex) {
logMap.put(IWorkerLogger.LOG_PURCHASED, "false");
final SignServerException exception =
new SignServerException("Accounter failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
if (!purchased) {
final String error = "Purchase not granted";
logMap.put(IWorkerLogger.LOG_EXCEPTION, error);
workerLogger.log(logMap);
throw new NotGrantedException(error);
}
} else {
logMap.put(IWorkerLogger.LOG_PURCHASED, "false");
}
// Archiving
if (res instanceof IArchivableProcessResponse) {
final IArchivableProcessResponse arres =
(IArchivableProcessResponse) res;
if (arres.getArchiveData() != null) {
// The IArchivableProcessResponse only supports a single
// item to archive. In the future we might get multiple
// Archivables from a worker.
final Archivable archivableResponse
= new ArchiveDataArchivable(arres.getArchiveId(),
arres.getArchiveData(), Archivable.TYPE_RESPONSE);
final Collection<Archivable> archivables
= Collections.singleton(archivableResponse);
// Archive all Archivables using all ArchiverS
final List<Archiver> archivers = WorkerFactory
.getInstance().getArchivers(workerId, awc, em);
if (archivers != null) {
try {
for (Archiver archiver : archivers) {
for (Archivable archivable : archivables) {
final boolean archived = archiver.archive(
archivable, requestContext);
if (LOG.isDebugEnabled()) {
final StringBuilder buff = new StringBuilder();
buff.append("Archiver ");
buff.append(archiver);
buff.append(" archived request: ");
buff.append(archived);
LOG.debug(buff.toString());
}
}
}
} catch (ArchiveException ex) {
LOG.error("Archiving failed", ex);
throw new SignServerException(
"Archiving failed. See server log.");
}
}
}
}
// Statistics: end event
StatisticsManager.endEvent(workerId, awc, em, event);
// Check key usage limit
checkSignerKeyUsageCounter(processable, workerId, awc, em, true);
// Output successfully
if (res instanceof ISignResponse) {
LOG.info("Worker " + workerId + " Processed request "
+ ((ISignResponse) res).getRequestID()
+ " successfully");
} else {
LOG.info("Worker " + workerId
+ " Processed request successfully");
}
// Old log entries (SignServer 3.1) added for backward compatibility
// Log: REQUESTID
if (res instanceof ISignResponse) {
logMap.put("REQUESTID",
String.valueOf(((ISignResponse) res).getRequestID()));
}
// Log
logMap.put(IWorkerLogger.LOG_PROCESS_SUCCESS, String.valueOf(true));
workerLogger.log(logMap);
LOG.debug("<process");
return res;
} catch (WorkerLoggerException ex) {
final SignServerException exception =
new SignServerException("Logging failed", ex);
LOG.error(exception.getMessage(), exception);
throw exception;
}
}
| public ProcessResponse process(final int workerId,
final ProcessRequest request, final RequestContext requestContext)
throws IllegalRequestException, CryptoTokenOfflineException,
SignServerException {
if (LOG.isDebugEnabled()) {
LOG.debug(">process: " + workerId);
}
// Start time
final long startTime = System.currentTimeMillis();
// Map of log entries
final Map<String, String> logMap = getLogMap(requestContext);
// Get transaction ID or create new if not created yet
final String transactionID;
if (requestContext.get(RequestContext.TRANSACTION_ID) == null) {
transactionID = generateTransactionID();
} else {
transactionID = (String) requestContext.get(
RequestContext.TRANSACTION_ID);
}
// Store values for request context and logging
requestContext.put(RequestContext.WORKER_ID, Integer.valueOf(workerId));
requestContext.put(RequestContext.TRANSACTION_ID, transactionID);
logMap.put(IWorkerLogger.LOG_TIME, String.valueOf(startTime));
logMap.put(IWorkerLogger.LOG_ID, transactionID);
logMap.put(IWorkerLogger.LOG_WORKER_ID, String.valueOf(workerId));
logMap.put(IWorkerLogger.LOG_CLIENT_IP,
(String) requestContext.get(RequestContext.REMOTE_IP));
// Get worker instance
final IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker == null) {
final IllegalRequestException ex =
new NoSuchWorkerException(String.valueOf(workerId));
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
try {
AUDITLOG.log(logMap);
} catch (SystemLoggerException ex2) {
LOG.error("Audit log failure", ex2);
}
throw ex;
}
// Get worker log instance
final IWorkerLogger workerLogger = WorkerFactory.getInstance().
getWorkerLogger(workerId,
worker.getStatus().getActiveSignerConfig(), em);
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId + "]: " + "WorkerLogger: "
+ workerLogger);
}
try {
// Get processable
if (!(worker instanceof IProcessable)) {
final IllegalRequestException ex = new IllegalRequestException(
"Worker exists but isn't a processable: " + workerId);
// auditLog(startTime, workerId, false, requestContext, ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw ex;
}
final IProcessable processable = (IProcessable) worker;
// Check authorization
logMap.put(IWorkerLogger.LOG_WORKER_AUTHTYPE,
processable.getAuthenticationType());
try {
WorkerFactory.getInstance()
.getAuthenticator(workerId,
processable.getAuthenticationType(),
worker.getStatus().getActiveSignerConfig(),
em).isAuthorized(request, requestContext);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(true));
} catch (AuthorizationRequiredException ex) {
throw ex;
} catch (IllegalRequestException ex) {
final IllegalRequestException exception =
new IllegalRequestException("Authorization failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(false));
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
} catch (SignServerException ex) {
final SignServerException exception =
new SignServerException("Authorization failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(false));
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Log client certificate (if any)
final Certificate clientCertificate = (Certificate)
requestContext.get(RequestContext.CLIENT_CERTIFICATE);
if (clientCertificate instanceof X509Certificate) {
final X509Certificate cert = (X509Certificate) clientCertificate;
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_SUBJECTDN,
cert.getSubjectDN().getName());
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_ISSUERDN,
cert.getIssuerDN().getName());
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_SERIALNUMBER,
cert.getSerialNumber().toString(16));
}
// Check activation
final WorkerConfig awc =
processable.getStatus().getActiveSignerConfig();
if (awc.getProperties().getProperty(SignServerConstants.DISABLED,
"FALSE").equalsIgnoreCase("TRUE")) {
final CryptoTokenOfflineException exception =
new CryptoTokenOfflineException("Error Signer : "
+ workerId
+ " is disabled and cannot perform any signature operations");
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Check signer certificate
try {
// Check if the signer has a signer certificate and if that
// certificate have ok validity and private key usage periods.
checkSignerValidity(workerId, awc, logMap);
// Check key usage limit (preliminary check only)
checkSignerKeyUsageCounter(processable, workerId, awc, em,
false);
} catch (CryptoTokenOfflineException ex) {
final CryptoTokenOfflineException exception =
new CryptoTokenOfflineException(ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Statistics: start event
final Event event = StatisticsManager.startEvent(workerId, awc, em);
requestContext.put(RequestContext.STATISTICS_EVENT, event);
// Process the request
final ProcessResponse res;
try {
res = processable.processData(request, requestContext);
} catch (AuthorizationRequiredException ex) {
throw ex; // This can happen in dispatching workers
} catch (SignServerException e) {
final SignServerException exception = new SignServerException(
"SignServerException calling signer with id " + workerId
+ " : " + e.getMessage(), e);
LOG.error(exception.getMessage(), exception);
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
} catch (IllegalRequestException ex) {
final IllegalRequestException exception =
new IllegalRequestException(ex.getMessage());
if (LOG.isInfoEnabled()) {
LOG.info("Illegal request calling signer with id " + workerId
+ " : " + ex.getMessage());
}
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Charge the client if the request was successfull
if (Boolean.TRUE.equals(requestContext.get(
RequestContext.WORKER_FULFILLED_REQUEST))) {
// Billing time
boolean purchased = false;
try {
IClientCredential credential =
(IClientCredential) requestContext.get(
RequestContext.CLIENT_CREDENTIAL);
purchased = WorkerFactory.getInstance().getAccounter(workerId,
worker.getStatus().getActiveSignerConfig(),
em).purchase(credential, request, res,
requestContext);
logMap.put(IWorkerLogger.LOG_PURCHASED, "true");
} catch (AccounterException ex) {
logMap.put(IWorkerLogger.LOG_PURCHASED, "false");
final SignServerException exception =
new SignServerException("Accounter failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
if (!purchased) {
final String error = "Purchase not granted";
logMap.put(IWorkerLogger.LOG_EXCEPTION, error);
workerLogger.log(logMap);
throw new NotGrantedException(error);
}
} else {
logMap.put(IWorkerLogger.LOG_PURCHASED, "false");
}
// Archiving
if (res instanceof IArchivableProcessResponse) {
final IArchivableProcessResponse arres =
(IArchivableProcessResponse) res;
if (arres.getArchiveData() != null) {
// The IArchivableProcessResponse only supports a single
// item to archive. In the future we might get multiple
// Archivables from a worker.
final Archivable archivableResponse
= new ArchiveDataArchivable(arres.getArchiveId(),
arres.getArchiveData(), Archivable.TYPE_RESPONSE);
final Collection<Archivable> archivables
= Collections.singleton(archivableResponse);
// Archive all Archivables using all ArchiverS
final List<Archiver> archivers = WorkerFactory
.getInstance().getArchivers(workerId, awc, em);
if (archivers != null) {
try {
for (Archiver archiver : archivers) {
for (Archivable archivable : archivables) {
final boolean archived = archiver.archive(
archivable, requestContext);
if (LOG.isDebugEnabled()) {
final StringBuilder buff = new StringBuilder();
buff.append("Archiver ");
buff.append(archiver);
buff.append(" archived request: ");
buff.append(archived);
LOG.debug(buff.toString());
}
}
}
} catch (ArchiveException ex) {
LOG.error("Archiving failed", ex);
throw new SignServerException(
"Archiving failed. See server log.");
}
}
}
}
// Statistics: end event
StatisticsManager.endEvent(workerId, awc, em, event);
// Check key usage limit
checkSignerKeyUsageCounter(processable, workerId, awc, em, true);
// Output successfully
if (res instanceof ISignResponse) {
LOG.info("Worker " + workerId + " Processed request "
+ ((ISignResponse) res).getRequestID()
+ " successfully");
} else {
LOG.info("Worker " + workerId
+ " Processed request successfully");
}
// Old log entries (SignServer 3.1) added for backward compatibility
// Log: REQUESTID
if (res instanceof ISignResponse) {
logMap.put("REQUESTID",
String.valueOf(((ISignResponse) res).getRequestID()));
}
// Log
logMap.put(IWorkerLogger.LOG_PROCESS_SUCCESS, String.valueOf(true));
workerLogger.log(logMap);
LOG.debug("<process");
return res;
} catch (WorkerLoggerException ex) {
final SignServerException exception =
new SignServerException("Logging failed", ex);
LOG.error(exception.getMessage(), exception);
throw exception;
}
}
|
diff --git a/src/com/android/settings/CryptKeeper.java b/src/com/android/settings/CryptKeeper.java
index d58dddb93..655d8ad26 100644
--- a/src/com/android/settings/CryptKeeper.java
+++ b/src/com/android/settings/CryptKeeper.java
@@ -1,598 +1,594 @@
/*
* 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.settings;
import android.app.Activity;
import android.app.StatusBarManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.os.storage.IMountService;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.inputmethod.InputMethodSubtype;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.internal.telephony.ITelephony;
import java.util.List;
/**
* Settings screens to show the UI flows for encrypting/decrypting the device.
*
* This may be started via adb for debugging the UI layout, without having to go through
* encryption flows everytime. It should be noted that starting the activity in this manner
* is only useful for verifying UI-correctness - the behavior will not be identical.
* <pre>
* $ adb shell pm enable com.android.settings/.CryptKeeper
* $ adb shell am start \
* -e "com.android.settings.CryptKeeper.DEBUG_FORCE_VIEW" "progress" \
* -n com.android.settings/.CryptKeeper
* </pre>
*/
public class CryptKeeper extends Activity implements TextView.OnEditorActionListener {
private static final String TAG = "CryptKeeper";
private static final String DECRYPT_STATE = "trigger_restart_framework";
private static final int UPDATE_PROGRESS = 1;
private static final int COOLDOWN = 2;
private static final int MAX_FAILED_ATTEMPTS = 30;
private static final int COOL_DOWN_ATTEMPTS = 10;
private static final int COOL_DOWN_INTERVAL = 30; // 30 seconds
// Intent action for launching the Emergency Dialer activity.
static final String ACTION_EMERGENCY_DIAL = "com.android.phone.EmergencyDialer.DIAL";
// Debug Intent extras so that this Activity may be started via adb for debugging UI layouts
private static final String EXTRA_FORCE_VIEW =
"com.android.settings.CryptKeeper.DEBUG_FORCE_VIEW";
private static final String FORCE_VIEW_PROGRESS = "progress";
private static final String FORCE_VIEW_ENTRY = "entry";
private static final String FORCE_VIEW_ERROR = "error";
/** When encryption is detected, this flag indivates whether or not we've checked for erros. */
private boolean mValidationComplete;
private boolean mValidationRequested;
/** A flag to indicate that the volume is in a bad state (e.g. partially encrypted). */
private boolean mEncryptionGoneBad;
private int mCooldown;
PowerManager.WakeLock mWakeLock;
private EditText mPasswordEntry;
/**
* Used to propagate state through configuration changes (e.g. screen rotation)
*/
private static class NonConfigurationInstanceState {
final PowerManager.WakeLock wakelock;
NonConfigurationInstanceState(PowerManager.WakeLock _wakelock) {
wakelock = _wakelock;
}
}
// This activity is used to fade the screen to black after the password is entered.
public static class Blank extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.crypt_keeper_blank);
}
}
private class DecryptTask extends AsyncTask<String, Void, Integer> {
@Override
protected Integer doInBackground(String... params) {
IMountService service = getMountService();
try {
return service.decryptStorage(params[0]);
} catch (Exception e) {
Log.e(TAG, "Error while decrypting...", e);
return -1;
}
}
@Override
protected void onPostExecute(Integer failedAttempts) {
if (failedAttempts == 0) {
// The password was entered successfully. Start the Blank activity
// so this activity animates to black before the devices starts. Note
// It has 1 second to complete the animation or it will be frozen
// until the boot animation comes back up.
Intent intent = new Intent(CryptKeeper.this, Blank.class);
finish();
startActivity(intent);
} else if (failedAttempts == MAX_FAILED_ATTEMPTS) {
// Factory reset the device.
sendBroadcast(new Intent("android.intent.action.MASTER_CLEAR"));
} else if ((failedAttempts % COOL_DOWN_ATTEMPTS) == 0) {
mCooldown = COOL_DOWN_INTERVAL;
cooldown();
} else {
TextView tv = (TextView) findViewById(R.id.status);
tv.setText(R.string.try_again);
tv.setVisibility(View.VISIBLE);
// Reenable the password entry
mPasswordEntry.setEnabled(true);
}
}
}
private class ValidationTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
IMountService service = getMountService();
try {
Log.d(TAG, "Validating encryption state.");
int state = service.getEncryptionState();
if (state == IMountService.ENCRYPTION_STATE_NONE) {
Log.w(TAG, "Unexpectedly in CryptKeeper even though there is no encryption.");
return true; // Unexpected, but fine, I guess...
}
return state == IMountService.ENCRYPTION_STATE_OK;
} catch (RemoteException e) {
Log.w(TAG, "Unable to get encryption state properly");
return true;
}
}
@Override
protected void onPostExecute(Boolean result) {
mValidationComplete = true;
if (Boolean.FALSE.equals(result)) {
Log.w(TAG, "Incomplete, or corrupted encryption detected. Prompting user to wipe.");
mEncryptionGoneBad = true;
} else {
Log.d(TAG, "Encryption state validated. Proceeding to configure UI");
}
setupUi();
}
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_PROGRESS:
updateProgress();
break;
case COOLDOWN:
cooldown();
break;
}
}
};
/** @return whether or not this Activity was started for debugging the UI only. */
private boolean isDebugView() {
return getIntent().hasExtra(EXTRA_FORCE_VIEW);
}
/** @return whether or not this Activity was started for debugging the specific UI view only. */
private boolean isDebugView(String viewType /* non-nullable */) {
return viewType.equals(getIntent().getStringExtra(EXTRA_FORCE_VIEW));
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// If we are not encrypted or encrypting, get out quickly.
String state = SystemProperties.get("vold.decrypt");
if (!isDebugView() && ("".equals(state) || DECRYPT_STATE.equals(state))) {
// Disable the crypt keeper.
PackageManager pm = getPackageManager();
ComponentName name = new ComponentName(this, CryptKeeper.class);
pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
// Typically CryptKeeper is launched as the home app. We didn't
- // want to be running, so need to finish this activity and re-launch
- // its intent now that we are not in the way of doing what is really
- // supposed to happen.
+ // want to be running, so need to finish this activity. We can count
+ // on the activity manager re-launching the new home app upon finishing
+ // this one, since this will leave the activity stack empty.
// NOTE: This is really grungy. I think it would be better for the
// activity manager to explicitly launch the crypt keeper instead of
// home in the situation where we need to decrypt the device
finish();
- Intent intent = getIntent();
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.setComponent(null);
- startActivity(intent);
return;
}
// Disable the status bar
StatusBarManager sbm = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE);
sbm.disable(StatusBarManager.DISABLE_EXPAND
| StatusBarManager.DISABLE_NOTIFICATION_ICONS
| StatusBarManager.DISABLE_NOTIFICATION_ALERTS
| StatusBarManager.DISABLE_SYSTEM_INFO
| StatusBarManager.DISABLE_HOME
| StatusBarManager.DISABLE_RECENT
| StatusBarManager.DISABLE_BACK);
// Check for (and recover) retained instance data
Object lastInstance = getLastNonConfigurationInstance();
if (lastInstance instanceof NonConfigurationInstanceState) {
NonConfigurationInstanceState retained = (NonConfigurationInstanceState) lastInstance;
mWakeLock = retained.wakelock;
Log.d(TAG, "Restoring wakelock from NonConfigurationInstanceState");
}
}
/**
* Note, we defer the state check and screen setup to onStart() because this will be
* re-run if the user clicks the power button (sleeping/waking the screen), and this is
* especially important if we were to lose the wakelock for any reason.
*/
@Override
public void onStart() {
super.onStart();
setupUi();
}
/**
* Initializes the UI based on the current state of encryption.
* This is idempotent - calling repeatedly will simply re-initialize the UI.
*/
private void setupUi() {
if (mEncryptionGoneBad || isDebugView(FORCE_VIEW_ERROR)) {
setContentView(R.layout.crypt_keeper_progress);
showFactoryReset();
return;
}
String progress = SystemProperties.get("vold.encrypt_progress");
if (!"".equals(progress) || isDebugView(FORCE_VIEW_PROGRESS)) {
setContentView(R.layout.crypt_keeper_progress);
encryptionProgressInit();
} else if (mValidationComplete) {
setContentView(R.layout.crypt_keeper_password_entry);
passwordEntryInit();
} else if (!mValidationRequested) {
// We're supposed to be encrypted, but no validation has been done.
new ValidationTask().execute((Void[]) null);
mValidationRequested = true;
}
}
@Override
public void onStop() {
super.onStop();
mHandler.removeMessages(COOLDOWN);
mHandler.removeMessages(UPDATE_PROGRESS);
}
/**
* Reconfiguring, so propagate the wakelock to the next instance. This runs between onStop()
* and onDestroy() and only if we are changing configuration (e.g. rotation). Also clears
* mWakeLock so the subsequent call to onDestroy does not release it.
*/
@Override
public Object onRetainNonConfigurationInstance() {
NonConfigurationInstanceState state = new NonConfigurationInstanceState(mWakeLock);
Log.d(TAG, "Handing wakelock off to NonConfigurationInstanceState");
mWakeLock = null;
return state;
}
@Override
public void onDestroy() {
super.onDestroy();
if (mWakeLock != null) {
Log.d(TAG, "Releasing and destroying wakelock");
mWakeLock.release();
mWakeLock = null;
}
}
private void encryptionProgressInit() {
// Accquire a partial wakelock to prevent the device from sleeping. Note
// we never release this wakelock as we will be restarted after the device
// is encrypted.
Log.d(TAG, "Encryption progress screen initializing.");
if (mWakeLock == null) {
Log.d(TAG, "Acquiring wakelock.");
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
mWakeLock.acquire();
}
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setIndeterminate(true);
updateProgress();
}
private void showFactoryReset() {
// Hide the encryption-bot to make room for the "factory reset" button
findViewById(R.id.encroid).setVisibility(View.GONE);
// Show the reset button, failure text, and a divider
Button button = (Button) findViewById(R.id.factory_reset);
button.setVisibility(View.VISIBLE);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Factory reset the device.
sendBroadcast(new Intent("android.intent.action.MASTER_CLEAR"));
}
});
TextView tv = (TextView) findViewById(R.id.title);
tv.setText(R.string.crypt_keeper_failed_title);
tv = (TextView) findViewById(R.id.status);
tv.setText(R.string.crypt_keeper_failed_summary);
View view = findViewById(R.id.bottom_divider);
if (view != null) {
view.setVisibility(View.VISIBLE);
}
}
private void updateProgress() {
String state = SystemProperties.get("vold.encrypt_progress");
if ("error_partially_encrypted".equals(state)) {
showFactoryReset();
return;
}
int progress = 0;
try {
// Force a 50% progress state when debugging the view.
progress = isDebugView() ? 50 : Integer.parseInt(state);
} catch (Exception e) {
Log.w(TAG, "Error parsing progress: " + e.toString());
}
CharSequence status = getText(R.string.crypt_keeper_setup_description);
Log.v(TAG, "Encryption progress: " + progress);
TextView tv = (TextView) findViewById(R.id.status);
tv.setText(TextUtils.expandTemplate(status, Integer.toString(progress)));
// Check the progress every 5 seconds
mHandler.removeMessages(UPDATE_PROGRESS);
mHandler.sendEmptyMessageDelayed(UPDATE_PROGRESS, 5000);
}
private void cooldown() {
TextView tv = (TextView) findViewById(R.id.status);
if (mCooldown <= 0) {
// Re-enable the password entry
mPasswordEntry.setEnabled(true);
tv.setVisibility(View.GONE);
} else {
CharSequence template = getText(R.string.crypt_keeper_cooldown);
tv.setText(TextUtils.expandTemplate(template, Integer.toString(mCooldown)));
tv.setVisibility(View.VISIBLE);
mCooldown--;
mHandler.removeMessages(COOLDOWN);
mHandler.sendEmptyMessageDelayed(COOLDOWN, 1000); // Tick every second
}
}
private void passwordEntryInit() {
mPasswordEntry = (EditText) findViewById(R.id.passwordEntry);
mPasswordEntry.setOnEditorActionListener(this);
mPasswordEntry.requestFocus();
View imeSwitcher = findViewById(R.id.switch_ime_button);
final InputMethodManager imm = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
if (imeSwitcher != null && hasMultipleEnabledIMEsOrSubtypes(imm, false)) {
imeSwitcher.setVisibility(View.VISIBLE);
imeSwitcher.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
imm.showInputMethodPicker();
}
});
}
// Asynchronously throw up the IME, since there are issues with requesting it to be shown
// immediately.
mHandler.postDelayed(new Runnable() {
@Override public void run() {
imm.showSoftInputUnchecked(0, null);
}
}, 0);
updateEmergencyCallButtonState();
}
/**
* Method adapted from com.android.inputmethod.latin.Utils
*
* @param imm The input method manager
* @param shouldIncludeAuxiliarySubtypes
* @return true if we have multiple IMEs to choose from
*/
private boolean hasMultipleEnabledIMEsOrSubtypes(InputMethodManager imm,
final boolean shouldIncludeAuxiliarySubtypes) {
final List<InputMethodInfo> enabledImis = imm.getEnabledInputMethodList();
// Number of the filtered IMEs
int filteredImisCount = 0;
for (InputMethodInfo imi : enabledImis) {
// We can return true immediately after we find two or more filtered IMEs.
if (filteredImisCount > 1) return true;
final List<InputMethodSubtype> subtypes =
imm.getEnabledInputMethodSubtypeList(imi, true);
// IMEs that have no subtypes should be counted.
if (subtypes.isEmpty()) {
++filteredImisCount;
continue;
}
int auxCount = 0;
for (InputMethodSubtype subtype : subtypes) {
if (subtype.isAuxiliary()) {
++auxCount;
}
}
final int nonAuxCount = subtypes.size() - auxCount;
// IMEs that have one or more non-auxiliary subtypes should be counted.
// If shouldIncludeAuxiliarySubtypes is true, IMEs that have two or more auxiliary
// subtypes should be counted as well.
if (nonAuxCount > 0 || (shouldIncludeAuxiliarySubtypes && auxCount > 1)) {
++filteredImisCount;
continue;
}
}
return filteredImisCount > 1
// imm.getEnabledInputMethodSubtypeList(null, false) will return the current IME's enabled
// input method subtype (The current IME should be LatinIME.)
|| imm.getEnabledInputMethodSubtypeList(null, false).size() > 1;
}
private IMountService getMountService() {
IBinder service = ServiceManager.getService("mount");
if (service != null) {
return IMountService.Stub.asInterface(service);
}
return null;
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL || actionId == EditorInfo.IME_ACTION_DONE) {
// Get the password
String password = v.getText().toString();
if (TextUtils.isEmpty(password)) {
return true;
}
// Now that we have the password clear the password field.
v.setText(null);
// Disable the password entry while checking the password. This
// we either be reenabled if the password was wrong or after the
// cooldown period.
mPasswordEntry.setEnabled(false);
Log.d(TAG, "Attempting to send command to decrypt");
new DecryptTask().execute(password);
return true;
}
return false;
}
//
// Code to update the state of, and handle clicks from, the "Emergency call" button.
//
// This code is mostly duplicated from the corresponding code in
// LockPatternUtils and LockPatternKeyguardView under frameworks/base.
//
private void updateEmergencyCallButtonState() {
Button button = (Button) findViewById(R.id.emergencyCallButton);
// The button isn't present at all in some configurations.
if (button == null) return;
if (isEmergencyCallCapable()) {
button.setVisibility(View.VISIBLE);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
takeEmergencyCallAction();
}
});
} else {
button.setVisibility(View.GONE);
return;
}
int newState = TelephonyManager.getDefault().getCallState();
int textId;
if (newState == TelephonyManager.CALL_STATE_OFFHOOK) {
// show "return to call" text and show phone icon
textId = R.string.cryptkeeper_return_to_call;
int phoneCallIcon = R.drawable.stat_sys_phone_call;
button.setCompoundDrawablesWithIntrinsicBounds(phoneCallIcon, 0, 0, 0);
} else {
textId = R.string.cryptkeeper_emergency_call;
int emergencyIcon = R.drawable.ic_emergency;
button.setCompoundDrawablesWithIntrinsicBounds(emergencyIcon, 0, 0, 0);
}
button.setText(textId);
}
private boolean isEmergencyCallCapable() {
return getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
}
private void takeEmergencyCallAction() {
if (TelephonyManager.getDefault().getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
resumeCall();
} else {
launchEmergencyDialer();
}
}
private void resumeCall() {
ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
if (phone != null) {
try {
phone.showCallScreen();
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelephony service: " + e);
}
}
}
private void launchEmergencyDialer() {
Intent intent = new Intent(ACTION_EMERGENCY_DIAL);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// If we are not encrypted or encrypting, get out quickly.
String state = SystemProperties.get("vold.decrypt");
if (!isDebugView() && ("".equals(state) || DECRYPT_STATE.equals(state))) {
// Disable the crypt keeper.
PackageManager pm = getPackageManager();
ComponentName name = new ComponentName(this, CryptKeeper.class);
pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
// Typically CryptKeeper is launched as the home app. We didn't
// want to be running, so need to finish this activity and re-launch
// its intent now that we are not in the way of doing what is really
// supposed to happen.
// NOTE: This is really grungy. I think it would be better for the
// activity manager to explicitly launch the crypt keeper instead of
// home in the situation where we need to decrypt the device
finish();
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(null);
startActivity(intent);
return;
}
// Disable the status bar
StatusBarManager sbm = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE);
sbm.disable(StatusBarManager.DISABLE_EXPAND
| StatusBarManager.DISABLE_NOTIFICATION_ICONS
| StatusBarManager.DISABLE_NOTIFICATION_ALERTS
| StatusBarManager.DISABLE_SYSTEM_INFO
| StatusBarManager.DISABLE_HOME
| StatusBarManager.DISABLE_RECENT
| StatusBarManager.DISABLE_BACK);
// Check for (and recover) retained instance data
Object lastInstance = getLastNonConfigurationInstance();
if (lastInstance instanceof NonConfigurationInstanceState) {
NonConfigurationInstanceState retained = (NonConfigurationInstanceState) lastInstance;
mWakeLock = retained.wakelock;
Log.d(TAG, "Restoring wakelock from NonConfigurationInstanceState");
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// If we are not encrypted or encrypting, get out quickly.
String state = SystemProperties.get("vold.decrypt");
if (!isDebugView() && ("".equals(state) || DECRYPT_STATE.equals(state))) {
// Disable the crypt keeper.
PackageManager pm = getPackageManager();
ComponentName name = new ComponentName(this, CryptKeeper.class);
pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
// Typically CryptKeeper is launched as the home app. We didn't
// want to be running, so need to finish this activity. We can count
// on the activity manager re-launching the new home app upon finishing
// this one, since this will leave the activity stack empty.
// NOTE: This is really grungy. I think it would be better for the
// activity manager to explicitly launch the crypt keeper instead of
// home in the situation where we need to decrypt the device
finish();
return;
}
// Disable the status bar
StatusBarManager sbm = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE);
sbm.disable(StatusBarManager.DISABLE_EXPAND
| StatusBarManager.DISABLE_NOTIFICATION_ICONS
| StatusBarManager.DISABLE_NOTIFICATION_ALERTS
| StatusBarManager.DISABLE_SYSTEM_INFO
| StatusBarManager.DISABLE_HOME
| StatusBarManager.DISABLE_RECENT
| StatusBarManager.DISABLE_BACK);
// Check for (and recover) retained instance data
Object lastInstance = getLastNonConfigurationInstance();
if (lastInstance instanceof NonConfigurationInstanceState) {
NonConfigurationInstanceState retained = (NonConfigurationInstanceState) lastInstance;
mWakeLock = retained.wakelock;
Log.d(TAG, "Restoring wakelock from NonConfigurationInstanceState");
}
}
|
diff --git a/saiku-bi-platform-plugin-p5/src/main/java/org/saiku/plugin/PentahoDatasourceManager.java b/saiku-bi-platform-plugin-p5/src/main/java/org/saiku/plugin/PentahoDatasourceManager.java
index 0827d27f..61be99e2 100644
--- a/saiku-bi-platform-plugin-p5/src/main/java/org/saiku/plugin/PentahoDatasourceManager.java
+++ b/saiku-bi-platform-plugin-p5/src/main/java/org/saiku/plugin/PentahoDatasourceManager.java
@@ -1,200 +1,202 @@
/*
* Copyright 2012 OSBI Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.saiku.plugin;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import mondrian.olap.MondrianProperties;
import mondrian.olap.Util;
import mondrian.rolap.RolapConnectionProperties;
import mondrian.util.Pair;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.plugin.action.mondrian.catalog.IMondrianCatalogService;
import org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalog;
import org.pentaho.platform.util.messages.LocaleHelper;
import org.saiku.datasources.connection.ISaikuConnection;
import org.saiku.datasources.datasource.SaikuDatasource;
import org.saiku.service.datasource.IDatasourceManager;
public class PentahoDatasourceManager implements IDatasourceManager {
private static final Log LOG = LogFactory.getLog(PentahoDatasourceManager.class);
private Map<String,SaikuDatasource> datasources = Collections.synchronizedMap(new HashMap<String,SaikuDatasource>());
private String saikuDatasourceProcessor;
private String saikuConnectionProcessor;
private String dynamicSchemaProcessor;
private IPentahoSession session;
private IMondrianCatalogService catalogService;
private String datasourceResolver;
public void setDatasourceResolverClass(String datasourceResolverClass) {
this.datasourceResolver = datasourceResolverClass;
}
public void setSaikuDatasourceProcessor(String datasourceProcessor) {
this.saikuDatasourceProcessor = datasourceProcessor;
}
public void setSaikuConnectionProcessor(String connectionProcessor) {
this.saikuConnectionProcessor = connectionProcessor;
}
public void setDynamicSchemaProcessor(String dynamicSchemaProcessor) {
this.dynamicSchemaProcessor = dynamicSchemaProcessor;
}
public PentahoDatasourceManager() {
}
public void init() {
load();
}
public void load() {
datasources.clear();
loadDatasources();
}
private Map<String, SaikuDatasource> loadDatasources() {
try {
this.session = PentahoSessionHolder.getSession();
ClassLoader cl = this.getClass().getClassLoader();
ClassLoader cl2 = this.getClass().getClassLoader().getParent();
Thread.currentThread().setContextClassLoader(cl2);
this.catalogService = PentahoSystem.get(IMondrianCatalogService.class,
session);
List<MondrianCatalog> catalogs = catalogService.listCatalogs(session, true);
Thread.currentThread().setContextClassLoader(cl);
- MondrianProperties.instance().DataSourceResolverClass.setString(this.datasourceResolver);
+ if (StringUtils.isNotBlank(this.datasourceResolver)) {
+ MondrianProperties.instance().DataSourceResolverClass.setString(this.datasourceResolver);
+ }
for (MondrianCatalog catalog : catalogs) {
String name = catalog.getName();
Util.PropertyList parsedProperties = Util.parseConnectString(catalog
.getDataSourceInfo());
String dynProcName = parsedProperties.get(
RolapConnectionProperties.DynamicSchemaProcessor.name());
if (StringUtils.isNotBlank(dynamicSchemaProcessor) && StringUtils.isBlank(dynProcName)) {
parsedProperties.put(RolapConnectionProperties.DynamicSchemaProcessor.name(), dynamicSchemaProcessor);
}
StringBuilder builder = new StringBuilder();
builder.append("jdbc:mondrian:");
builder.append("Catalog=");
builder.append(catalog.getDefinition());
builder.append("; ");
Iterator<Pair<String, String>> it = parsedProperties.iterator();
while (it.hasNext()) {
Pair<String, String> pair = it.next();
builder.append(pair.getKey());
builder.append("=");
builder.append(pair.getValue());
builder.append("; ");
}
// builder.append("PoolNeeded=false; ");
builder.append("Locale=");
if (session != null) {
builder.append(session.getLocale().toString());
} else {
builder.append(LocaleHelper.getLocale().toString());
}
builder.append(";");
String url = builder.toString();
LOG.debug("NAME: " + catalog.getName() + " DSINFO: " + url + " ###CATALOG: " + catalog.getName());
Properties props = new Properties();
props.put("driver", "mondrian.olap4j.MondrianOlap4jDriver");
props.put("location",url);
if (saikuDatasourceProcessor != null) {
props.put(ISaikuConnection.DATASOURCE_PROCESSORS, saikuDatasourceProcessor);
}
if (saikuConnectionProcessor != null) {
props.put(ISaikuConnection.CONNECTION_PROCESSORS, saikuConnectionProcessor);
}
props.list(System.out);
SaikuDatasource sd = new SaikuDatasource(name, SaikuDatasource.Type.OLAP, props);
datasources.put(name, sd);
}
return datasources;
} catch(Exception e) {
e.printStackTrace();
LOG.error(e);
}
return new HashMap<String, SaikuDatasource>();
}
public SaikuDatasource addDatasource(SaikuDatasource datasource) {
throw new UnsupportedOperationException();
}
public SaikuDatasource setDatasource(SaikuDatasource datasource) {
throw new UnsupportedOperationException();
}
public List<SaikuDatasource> addDatasources(List<SaikuDatasource> datasources) {
throw new UnsupportedOperationException();
}
public boolean removeDatasource(String datasourceName) {
throw new UnsupportedOperationException();
}
public Map<String,SaikuDatasource> getDatasources() {
return loadDatasources();
}
public SaikuDatasource getDatasource(String datasourceName) {
return loadDatasources().get(datasourceName);
}
}
| true | true | private Map<String, SaikuDatasource> loadDatasources() {
try {
this.session = PentahoSessionHolder.getSession();
ClassLoader cl = this.getClass().getClassLoader();
ClassLoader cl2 = this.getClass().getClassLoader().getParent();
Thread.currentThread().setContextClassLoader(cl2);
this.catalogService = PentahoSystem.get(IMondrianCatalogService.class,
session);
List<MondrianCatalog> catalogs = catalogService.listCatalogs(session, true);
Thread.currentThread().setContextClassLoader(cl);
MondrianProperties.instance().DataSourceResolverClass.setString(this.datasourceResolver);
for (MondrianCatalog catalog : catalogs) {
String name = catalog.getName();
Util.PropertyList parsedProperties = Util.parseConnectString(catalog
.getDataSourceInfo());
String dynProcName = parsedProperties.get(
RolapConnectionProperties.DynamicSchemaProcessor.name());
if (StringUtils.isNotBlank(dynamicSchemaProcessor) && StringUtils.isBlank(dynProcName)) {
parsedProperties.put(RolapConnectionProperties.DynamicSchemaProcessor.name(), dynamicSchemaProcessor);
}
StringBuilder builder = new StringBuilder();
builder.append("jdbc:mondrian:");
builder.append("Catalog=");
builder.append(catalog.getDefinition());
builder.append("; ");
Iterator<Pair<String, String>> it = parsedProperties.iterator();
while (it.hasNext()) {
Pair<String, String> pair = it.next();
builder.append(pair.getKey());
builder.append("=");
builder.append(pair.getValue());
builder.append("; ");
}
// builder.append("PoolNeeded=false; ");
builder.append("Locale=");
if (session != null) {
builder.append(session.getLocale().toString());
} else {
builder.append(LocaleHelper.getLocale().toString());
}
builder.append(";");
String url = builder.toString();
LOG.debug("NAME: " + catalog.getName() + " DSINFO: " + url + " ###CATALOG: " + catalog.getName());
Properties props = new Properties();
props.put("driver", "mondrian.olap4j.MondrianOlap4jDriver");
props.put("location",url);
if (saikuDatasourceProcessor != null) {
props.put(ISaikuConnection.DATASOURCE_PROCESSORS, saikuDatasourceProcessor);
}
if (saikuConnectionProcessor != null) {
props.put(ISaikuConnection.CONNECTION_PROCESSORS, saikuConnectionProcessor);
}
props.list(System.out);
SaikuDatasource sd = new SaikuDatasource(name, SaikuDatasource.Type.OLAP, props);
datasources.put(name, sd);
}
return datasources;
} catch(Exception e) {
e.printStackTrace();
LOG.error(e);
}
return new HashMap<String, SaikuDatasource>();
}
| private Map<String, SaikuDatasource> loadDatasources() {
try {
this.session = PentahoSessionHolder.getSession();
ClassLoader cl = this.getClass().getClassLoader();
ClassLoader cl2 = this.getClass().getClassLoader().getParent();
Thread.currentThread().setContextClassLoader(cl2);
this.catalogService = PentahoSystem.get(IMondrianCatalogService.class,
session);
List<MondrianCatalog> catalogs = catalogService.listCatalogs(session, true);
Thread.currentThread().setContextClassLoader(cl);
if (StringUtils.isNotBlank(this.datasourceResolver)) {
MondrianProperties.instance().DataSourceResolverClass.setString(this.datasourceResolver);
}
for (MondrianCatalog catalog : catalogs) {
String name = catalog.getName();
Util.PropertyList parsedProperties = Util.parseConnectString(catalog
.getDataSourceInfo());
String dynProcName = parsedProperties.get(
RolapConnectionProperties.DynamicSchemaProcessor.name());
if (StringUtils.isNotBlank(dynamicSchemaProcessor) && StringUtils.isBlank(dynProcName)) {
parsedProperties.put(RolapConnectionProperties.DynamicSchemaProcessor.name(), dynamicSchemaProcessor);
}
StringBuilder builder = new StringBuilder();
builder.append("jdbc:mondrian:");
builder.append("Catalog=");
builder.append(catalog.getDefinition());
builder.append("; ");
Iterator<Pair<String, String>> it = parsedProperties.iterator();
while (it.hasNext()) {
Pair<String, String> pair = it.next();
builder.append(pair.getKey());
builder.append("=");
builder.append(pair.getValue());
builder.append("; ");
}
// builder.append("PoolNeeded=false; ");
builder.append("Locale=");
if (session != null) {
builder.append(session.getLocale().toString());
} else {
builder.append(LocaleHelper.getLocale().toString());
}
builder.append(";");
String url = builder.toString();
LOG.debug("NAME: " + catalog.getName() + " DSINFO: " + url + " ###CATALOG: " + catalog.getName());
Properties props = new Properties();
props.put("driver", "mondrian.olap4j.MondrianOlap4jDriver");
props.put("location",url);
if (saikuDatasourceProcessor != null) {
props.put(ISaikuConnection.DATASOURCE_PROCESSORS, saikuDatasourceProcessor);
}
if (saikuConnectionProcessor != null) {
props.put(ISaikuConnection.CONNECTION_PROCESSORS, saikuConnectionProcessor);
}
props.list(System.out);
SaikuDatasource sd = new SaikuDatasource(name, SaikuDatasource.Type.OLAP, props);
datasources.put(name, sd);
}
return datasources;
} catch(Exception e) {
e.printStackTrace();
LOG.error(e);
}
return new HashMap<String, SaikuDatasource>();
}
|
diff --git a/src/hamhamdash/PlayerCharacter.java b/src/hamhamdash/PlayerCharacter.java
index bd4ff5d..4fc8ce7 100755
--- a/src/hamhamdash/PlayerCharacter.java
+++ b/src/hamhamdash/PlayerCharacter.java
@@ -1,114 +1,114 @@
package hamhamdash;
import jgame.*;
import jgame.platform.*;
/**
*
* @author Cornel Alders
*/
public class PlayerCharacter extends GCharacter
{
private JGEngine game;
//private GCharacter GCharacter;
public PlayerCharacter(int x, int y)
{
super("player", true, x, y, 1, "hidle");
}
@Override
public void move()
{
xspeed = 0;
yspeed = 0;
xdir = 0;
ydir = 0;
if (eng.getKey(eng.KeyUp) && !(eng.getKey(eng.KeyLeft) || eng.getKey(eng.KeyRight)))
{
if (y < game.pfHeight() - 230)
{
setGraphic("hrunup");
yspeed = 0;
ydir = 0;
System.out.println(x);
System.out.println(y);
System.out.println(game.pfHeight());
}
else
{
setGraphic("hrunup");
yspeed = -6;
ydir = 1;
System.out.println(x);
}
}
else if (eng.getKey(eng.KeyDown) && !(eng.getKey(eng.KeyLeft) || eng.getKey(eng.KeyRight)))
{
if (y > game.pfHeight() - 56)
{
setGraphic("hrundown");
yspeed = 0;
ydir = 0;
}
else
{
setGraphic("hrundown");
yspeed = 6;
ydir = 1;
}
}
else if (eng.getKey(eng.KeyLeft) && !(eng.getKey(eng.KeyUp) || eng.getKey(eng.KeyDown)))
{
if (x < game.pfWidth() - 300)
{
setGraphic("hrunleft");
xspeed = 0;
xdir = 0;
}
else
{
setGraphic("hrunleft");
xspeed = -6;
xdir = 1;
}
}
else if (eng.getKey(eng.KeyRight) && !(eng.getKey(eng.KeyUp) || eng.getKey(eng.KeyDown)))
{
if (x > game.pfWidth() - 60)
{
setGraphic("hrunright");
xspeed = 0;
xdir = 0;
}
else
{
setGraphic("hrunright");
xspeed = 6;
xdir = 1;
}
}
else
{
- setGraphic("hstandstill");
+ setGraphic("hidle");
xspeed = 0;
yspeed = 0;
xdir = 0;
ydir = 0;
}
}
@Override
public void hit_bg(int tilecid)
{
}
;
@Override
public void hit(JGObject obj)
{
}
;
}
| true | true | public void move()
{
xspeed = 0;
yspeed = 0;
xdir = 0;
ydir = 0;
if (eng.getKey(eng.KeyUp) && !(eng.getKey(eng.KeyLeft) || eng.getKey(eng.KeyRight)))
{
if (y < game.pfHeight() - 230)
{
setGraphic("hrunup");
yspeed = 0;
ydir = 0;
System.out.println(x);
System.out.println(y);
System.out.println(game.pfHeight());
}
else
{
setGraphic("hrunup");
yspeed = -6;
ydir = 1;
System.out.println(x);
}
}
else if (eng.getKey(eng.KeyDown) && !(eng.getKey(eng.KeyLeft) || eng.getKey(eng.KeyRight)))
{
if (y > game.pfHeight() - 56)
{
setGraphic("hrundown");
yspeed = 0;
ydir = 0;
}
else
{
setGraphic("hrundown");
yspeed = 6;
ydir = 1;
}
}
else if (eng.getKey(eng.KeyLeft) && !(eng.getKey(eng.KeyUp) || eng.getKey(eng.KeyDown)))
{
if (x < game.pfWidth() - 300)
{
setGraphic("hrunleft");
xspeed = 0;
xdir = 0;
}
else
{
setGraphic("hrunleft");
xspeed = -6;
xdir = 1;
}
}
else if (eng.getKey(eng.KeyRight) && !(eng.getKey(eng.KeyUp) || eng.getKey(eng.KeyDown)))
{
if (x > game.pfWidth() - 60)
{
setGraphic("hrunright");
xspeed = 0;
xdir = 0;
}
else
{
setGraphic("hrunright");
xspeed = 6;
xdir = 1;
}
}
else
{
setGraphic("hstandstill");
xspeed = 0;
yspeed = 0;
xdir = 0;
ydir = 0;
}
}
| public void move()
{
xspeed = 0;
yspeed = 0;
xdir = 0;
ydir = 0;
if (eng.getKey(eng.KeyUp) && !(eng.getKey(eng.KeyLeft) || eng.getKey(eng.KeyRight)))
{
if (y < game.pfHeight() - 230)
{
setGraphic("hrunup");
yspeed = 0;
ydir = 0;
System.out.println(x);
System.out.println(y);
System.out.println(game.pfHeight());
}
else
{
setGraphic("hrunup");
yspeed = -6;
ydir = 1;
System.out.println(x);
}
}
else if (eng.getKey(eng.KeyDown) && !(eng.getKey(eng.KeyLeft) || eng.getKey(eng.KeyRight)))
{
if (y > game.pfHeight() - 56)
{
setGraphic("hrundown");
yspeed = 0;
ydir = 0;
}
else
{
setGraphic("hrundown");
yspeed = 6;
ydir = 1;
}
}
else if (eng.getKey(eng.KeyLeft) && !(eng.getKey(eng.KeyUp) || eng.getKey(eng.KeyDown)))
{
if (x < game.pfWidth() - 300)
{
setGraphic("hrunleft");
xspeed = 0;
xdir = 0;
}
else
{
setGraphic("hrunleft");
xspeed = -6;
xdir = 1;
}
}
else if (eng.getKey(eng.KeyRight) && !(eng.getKey(eng.KeyUp) || eng.getKey(eng.KeyDown)))
{
if (x > game.pfWidth() - 60)
{
setGraphic("hrunright");
xspeed = 0;
xdir = 0;
}
else
{
setGraphic("hrunright");
xspeed = 6;
xdir = 1;
}
}
else
{
setGraphic("hidle");
xspeed = 0;
yspeed = 0;
xdir = 0;
ydir = 0;
}
}
|
diff --git a/src/java/com/rapleaf/jack/BaseDatabaseConnection.java b/src/java/com/rapleaf/jack/BaseDatabaseConnection.java
index 25db775d..dcfb9fda 100644
--- a/src/java/com/rapleaf/jack/BaseDatabaseConnection.java
+++ b/src/java/com/rapleaf/jack/BaseDatabaseConnection.java
@@ -1,129 +1,129 @@
package com.rapleaf.jack;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public abstract class BaseDatabaseConnection implements Serializable {
protected transient Connection conn = null;
/**
* Get a Connection to a MySQL database.
* If there is no connection, create a new one.
*/
public abstract Connection getConnection();
/**
* Re-establish the connection in case it has been sitting idle for too
* long and has been claimed by the server
*/
public Connection resetConnection() {
if (conn != null) {
try {
- if (getAutoCommit()) {
+ if (!getAutoCommit()) {
conn.commit();
}
conn.close();
} catch (Exception e) {
// do nothing
}
}
conn = null;
return getConnection();
}
/**
* Creates a connection using the argument credentials. Useful for when
* MapReduce workers machines need to make database connections, as they
* don't have access to the local config file. Returns true if the new
* connection is made and false if a connection already exists.
*/
public boolean connect() {
if (conn == null) {
conn = getConnection();
return true;
} else
return false;
}
/**
* Creates a Statement object that can be used to send SQL queries to the RapLeaf
* database.
*/
public Statement getStatement() {
try {
return getConnection().createStatement();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* Creates a PreparedStatement object that can be used to send SQL queries to the
* RapLeaf database.
*/
public PreparedStatement getPreparedStatement(String statement) {
try {
return getConnection().prepareStatement(statement);
} catch(SQLException e) {
throw new RuntimeException(e);
}
}
/**
* Sets this connection's auto-commit mode to the given state. If a connection
* is in auto-commit mode, then all its SQL statements will be executed and
* committed as individual transactions. Otherwise, its SQL statements are
* grouped into transactions that are terminated by a call to either the
* method commit or the method rollback. By default, new connections are in
* auto-commit mode.
* @param autoCommit
*/
public void setAutoCommit(boolean autoCommit) {
try {
getConnection().setAutoCommit(autoCommit);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* Retrieves the current auto-commit mode
*/
public boolean getAutoCommit() {
try {
return getConnection().getAutoCommit();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* Makes all changes made since the previous commit/rollback permanent and
* releases any database locks currently held by this Connection object.
* This method should be used only when auto-commit mode has been disabled.
*/
public void commit() {
try {
getConnection().commit();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* Undoes all changes made in the current transaction and releases any
* database locks currently held by this Connection object. This method should
* be used only when auto-commit mode has been disabled.
*/
public void rollback() {
try {
getConnection().rollback();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
| true | true | public Connection resetConnection() {
if (conn != null) {
try {
if (getAutoCommit()) {
conn.commit();
}
conn.close();
} catch (Exception e) {
// do nothing
}
}
conn = null;
return getConnection();
}
| public Connection resetConnection() {
if (conn != null) {
try {
if (!getAutoCommit()) {
conn.commit();
}
conn.close();
} catch (Exception e) {
// do nothing
}
}
conn = null;
return getConnection();
}
|
diff --git a/src/uk/co/sticksoft/adce/cpu/CPU_1_7.java b/src/uk/co/sticksoft/adce/cpu/CPU_1_7.java
index bb1ceab..1549f4d 100644
--- a/src/uk/co/sticksoft/adce/cpu/CPU_1_7.java
+++ b/src/uk/co/sticksoft/adce/cpu/CPU_1_7.java
@@ -1,566 +1,566 @@
package uk.co.sticksoft.adce.cpu;
import java.util.LinkedList;
import java.util.Queue;
import android.widget.Toast;
import uk.co.sticksoft.adce.MainActivity;
import uk.co.sticksoft.adce.asm._1_7.*;
import uk.co.sticksoft.adce.hardware.Device;
import uk.co.sticksoft.adce.hardware.HardwareManager;
/*
* Half-baked 1.7 version of the CPU
*/
public class CPU_1_7 extends CPU
{
public static final int A = 0, B = 1, C = 2, X = 3, Y = 4, Z = 5, I = 6, J = 7;
public char[] register = new char[J+1];
public char PC, SP, EX, IA;
// Flags
private boolean onFire, skipping, interruptQueueing;
// Temporary cache for SP and PC
private char tSP, tPC;
// Interrupt queue
private Queue<Character> interruptQueue = new LinkedList<Character>();
@Override
public void reset()
{
for (int i = 0; i < register.length; i++)
register[i] = 0;
for (int i = 0; i < 0x10000; i++)
RAM[i] = 0;
PC = SP = EX = IA = 0;
cycleCount = 0;
onFire = skipping = interruptQueueing = false;
interruptQueue.clear();
}
private enum AddressType
{
REGISTER,
RAM,
PC,
SP,
EX,
IA,
LITERAL
}
private AddressType addressType(char value)
{
if (value < 0x08)
return AddressType.REGISTER;
if (value < 0x10)
return AddressType.RAM;
if (value < 0x18)
return AddressType.RAM;
if (value == 0x18)
return AddressType.RAM;
if (value == 0x19)
return AddressType.RAM;
if (value == 0x1a)
return AddressType.RAM;
if (value == 0x1b)
return AddressType.SP;
if (value == 0x1c)
return AddressType.PC;
if (value == 0x1d)
return AddressType.EX;
if (value == 0x1e)
return AddressType.RAM;
if (value == 0x1f)
return AddressType.RAM;
return AddressType.LITERAL;
}
private char addressA(char value)
{
if (value < 0x08)
return value;
if (value < 0x10)
return register[value-0x08];
if (value < 0x18)
return (char)(RAM[tPC++]+register[value-0x10]);
if (value == 0x18)
return tSP++;
if (value == 0x19)
return tSP;
if (value == 0x1a)
return (char)(RAM[tPC++] + tSP);
if (value == 0x1b)
return 0;
if (value == 0x1c)
return 0;
if (value == 0x1d)
return 0;
if (value == 0x1e)
return RAM[tPC++];
if (value == 0x1f)
return tPC++;
return (char)(value - 0x20);
}
private char addressB(char value)
{
if (value < 0x08)
return value;
if (value < 0x10)
return register[value-0x08];
if (value < 0x18)
return (char)(RAM[tPC++]+register[value-0x10]);
if (value == 0x18)
return --tSP;
if (value == 0x19)
return tSP;
if (value == 0x1a)
return (char)(RAM[tPC++] + tSP);
if (value == 0x1b)
return 0;
if (value == 0x1c)
return 0;
if (value == 0x1d)
return 0;
if (value == 0x1e)
return RAM[tPC++];
if (value == 0x1f)
return tPC++;
return (char)(value - 0x20);
}
private char read(AddressType type, char address)
{
switch (type)
{
case REGISTER:
return register[address];
case RAM:
return RAM[address];
case PC:
return PC;
case SP:
return SP;
case EX:
return EX;
default:
if (address == 0)
return 0xFFFF;
else
return (char)(address-1);
}
}
private void write(AddressType type, char address, char word)
{
switch (type)
{
case REGISTER:
register[address] = word;
break;
case RAM:
RAM[address] = word;
break;
case PC:
tPC = word;
break;
case SP:
tSP = word;
break;
case EX:
EX = word;
break;
default:
// What yo playin' at?!
}
}
private static int unsignedCharAsSignedInt(char c)
{
return c < 0x8000 ? c : c - 0x10000;
}
@Override
public synchronized void execute()
{
cycleCount++;
tSP = SP; // Cache SP
tPC = (char)(PC+1); // Pre-increment tPC
boolean error = false; // Not sure what to do with this yet (maybe set on fire?)
// Fetch
char instr = RAM[PC];
if (instr == 0) // Invalid instruction; stop.
{
notifyObservers();
return;
}
// Decode
int opcode = instr & 0x1f;
char b = (char)((instr >> 5) & 0x1f);
char a = (char)(instr >> 10);
if (opcode != 0)
{
if (skipping)
{
// Skip reading next words
if ((b >= 0x10 && b < 0x18) || b == 0x1a || b == 0x1e || b == 0x1f) // [register + next word], [SP + next word], [next word], next word
tPC++;
if ((a >= 0x10 && a < 0x18) || a == 0x1a || a == 0x1e || a == 0x1f) // [register + next word], [SP + next word], [next word], next word
tPC++;
PC = tPC;
if (opcode < 0x10 || opcode > 0x17) // Keep skipping over conditionals
skipping = false;
}
else
{
// Work out address type and location before instruction
// These will only modify tSP or tPC, not the actual SP or PC
// until after the instruction completes.
AddressType aType = addressType(a), bType = addressType(b);
char aAddr = addressA(a), bAddr = addressB(b);
// Grab the actual values
char aVal = read(aType, aAddr), bVal = read(bType, bAddr);
int res = 0; // Result
switch (opcode)
{
case 0x01: // SET
res = aVal;
break;
case 0x02: // ADD
res = bVal + aVal;
EX = (res <= 0xffff) ? (char)0 : (char)1;
break;
case 0x03: // SUB
res = bVal - aVal;
EX = (res >= 0) ? 0 : (char)0xffff;
break;
case 0x04: // MUL
res = bVal * aVal;
EX = (char)(res >> 16);
break;
case 0x05: // MLI
res = unsignedCharAsSignedInt(bVal) * unsignedCharAsSignedInt(aVal);
EX = (char)(res >> 16);
break;
case 0x06: // DIV
res = bVal / aVal;
EX = (char)(((bVal << 16) / aVal) & 0xffff);
break;
case 0x07: // DVI
res = unsignedCharAsSignedInt(bVal) / unsignedCharAsSignedInt(aVal);
EX = (char)(((unsignedCharAsSignedInt(bVal) << 16) / unsignedCharAsSignedInt(aVal)) & 0xffff);
break;
case 0x08: // MOD
if (aVal == 0)
res = 0;
else
res = bVal % aVal;
break;
case 0x09: // MDI
if (aVal == 0)
res = 0;
else
res = unsignedCharAsSignedInt(bVal) % unsignedCharAsSignedInt(aVal);
break;
case 0x0a: // AND
res = bVal & aVal;
break;
case 0x0b: // BOR
res = bVal | aVal;
break;
case 0x0c: // XOR
res = bVal ^ aVal;
break;
case 0x0d: // SHR
res = bVal >>> aVal;
EX = (char)(((bVal << 16) >>> a) & 0xffff);
break;
case 0x0e: // ASR
- res = bVal >> aVal;
- EX = (char)(((bVal << 16) >> a) & 0xffff);
+ res = unsignedCharAsSignedInt(bVal) >> unsignedCharAsSignedInt(aVal);
+ EX = (char)(((unsignedCharAsSignedInt(bVal) << 16) >> unsignedCharAsSignedInt(aVal)) & 0xffff);
break;
case 0x0f: // SHL
res = bVal << aVal;
EX = (char)(((bVal << aVal) >> 16) & 0xffff);
break;
case 0x10: // IFB
skipping = (bVal & aVal) == 0;
break;
case 0x11: // IFC
skipping = (bVal & aVal) != 0;
break;
case 0x12: // IFE
skipping = (bVal != aVal);
break;
case 0x13: // IFN
skipping = (bVal == aVal);
break;
case 0x14: // IFG
skipping = (bVal <= aVal);
break;
case 0x15: // IFA
skipping = (unsignedCharAsSignedInt(bVal) <= unsignedCharAsSignedInt(aVal));
break;
case 0x16: // IFL
skipping = (bVal >= aVal);
break;
case 0x17: // IFU
skipping = (unsignedCharAsSignedInt(bVal) >= unsignedCharAsSignedInt(bVal));
break;
case 0x18: // -
case 0x19: // -
error = true;
break;
case 0x1a: // ADX
res = bVal + aVal + EX;
EX = (char)((res <= 0xFFFF) ? 0 : 1);
break;
case 0x1b: // SBX
res = bVal - aVal - EX;
EX = (char)((res >= 0) ? 0 : 1);
break;
case 0x1c: // -
case 0x1d: // -
error = true;
break;
case 0x1e: // STI
res = aVal;
register[I]++;
register[J]++;
break;
case 0x1f: // STD
res = aVal;
register[I]--;
register[J]--;
break;
}
if (opcode < 0x10 || opcode > 0x17)
write(bType, bAddr, (char)(res & 0xffff));
}
}
else
{
if (skipping)
{
// Skip reading next word
if ((a >= 0x10 && a < 0x18) || a == 0x1a || a == 0x1e || a == 0x1f) // [register + next word], [SP + next word], [next word], next word
tPC++;
skipping = false;
PC = tPC;
}
else
{
switch (b) // b becomes the special opcode
{
case 0x00: // Reserved
error = true;
break;
case 0x01: // JSR
// Get jump address
char jmp = read(addressType(a), addressA(a));
// Push PC
RAM[--tSP] = tPC;
// Set PC to jump address (after increment)
tPC = jmp;
break;
case 0x02: // -
case 0x03: // -
case 0x04: // -
case 0x05: // -
case 0x06: // -
case 0x07: // -
error = true;
break;
case 0x08: // INT
interrupt(read(addressType(a), addressA(a)));
break;
case 0x09: // IAG
write(addressType(a), addressA(a), IA);
break;
case 0x0a: // IAS
IA = read(addressType(a), addressA(a));
break;
case 0x0b: // RFI
interruptQueueing = false;
register[A] = RAM[tSP++];
tPC = RAM[tSP++];
break;
case 0x0c: // IAQ
interruptQueueing = (read(addressType(a), addressA(a)) == 0);
break;
case 0x0d: // -
case 0x0e: // -
case 0x0f: // -
error = true;
break;
case 0x10: // HWN
write(addressType(a), addressA(a), (char)HardwareManager.instance().getCount());
break;
case 0x11: // HWQ
{
Device device = HardwareManager.instance().getDevice(read(addressType(a), addressA(a)));
if (device != null)
{
register[A] = device.GetIDLo();
register[B] = device.GetIDHi();
register[C] = device.GetVersion();
register[X] = device.GetManuLo();
register[Y] = device.GetManuHi();
}
else
error = true;
break;
}
case 0x12: // HWI
{
Device device = HardwareManager.instance().getDevice(read(addressType(a), addressA(a)));
if (device != null)
device.HWI_1_7(this);
else
error = true;
break;
}
case 0x13: // -
case 0x14: // -
case 0x15: // -
case 0x16: // -
case 0x17: // -
case 0x18: // -
case 0x19: // -
case 0x1a: // -
case 0x1b: // -
case 0x1c: // -
case 0x1d: // -
case 0x1e: // -
case 0x1f: // -
error = true;
break;
}
}
}
if (!skipping && !interruptQueueing && !interruptQueue.isEmpty())
{
interruptQueueing = true;
RAM[tSP--] = tPC;
RAM[tSP--] = register[A];
tPC = IA;
register[A] = interruptQueue.remove().charValue();
}
PC = tPC;
SP = tSP;
notifyObservers();
}
public synchronized void interrupt(char interrupt)
{
if (interruptQueueing)
interruptQueue.add(Character.valueOf(interrupt));
else if (IA != 0)
{
interruptQueueing = true;
RAM[--tSP] = tPC;
RAM[--tSP] = register[A];
tPC = IA;
register[A] = interrupt;
}
PC = tPC;
SP = tSP;
}
public char[] getStateInfo()
{
int size = 1 /* version */ + register.length /* registers */ + 4 /* PC, SP, EX, IA */ + 3 /* on fire, skipping, interrupt queueing */ + 2 /* cyclecount */ + 1 /* interrupt queue size*/ + interruptQueue.size() /* interrupt queue */;
char[] out = new char[size];
int cursor = 0;
out[cursor++] = 0x0107; // Version 1.7
System.arraycopy(register, 0, out, cursor, register.length); cursor += register.length;
out[cursor++] = PC;
out[cursor++] = SP;
out[cursor++] = EX;
out[cursor++] = IA;
out[cursor++] = (char) (onFire ? 0xFFFF : 0x0000);
out[cursor++] = (char) (skipping ? 0xFFFF : 0x0000);
out[cursor++] = (char) (interruptQueueing ? 0xFFFF : 0x0000);
intToLittleEndian((int)cycleCount, out, cursor); cursor += 2;
out[cursor++] = (char) interruptQueue.size();
for (Character c : interruptQueue)
out[cursor++] = c;
return out;
}
public void setStateInfo(char[] state)
{
try
{
//int size = 1 /* version */ + register.length /* registers */ + 4 /* PC, SP, EX, IA */ + 3 /* on fire, skipping, interrupt queueing */ + 2 /* cyclecount */ + 1 /* interrupt queue size*/ + interruptQueue.size() /* interrupt queue */;
char version = state[0];
if (version != 0x0107)
{
MainActivity.showToast("State info doesn't match this processor version!", Toast.LENGTH_LONG);
return;
}
int cursor = 0;
System.arraycopy(state, 0, register, 0, cursor = register.length);
PC = state[cursor++];
SP = state[cursor++];
EX = state[cursor++];
IA = state[cursor++];
onFire = (state[cursor++] == 0xFFFF);
skipping = (state[cursor++] == 0xFFFF);
interruptQueueing = (state[cursor++] == 0xFFFF);
cycleCount = intFromLittleEndian(state, cursor); cursor += 2;
char iqSize = state[cursor++];
interruptQueue.clear();
for (int i = cursor; i < iqSize + cursor; i++)
interruptQueue.add(state[cursor]);
}
catch (Exception ex)
{
MainActivity.showToast("Unable to retreive CPU state!", Toast.LENGTH_LONG);
}
}
@Override
public String getStatusText()
{
return String.format(" A:%04x B:%04x C:%04x\n X:%04x Y:%04x Z:%04x\n I:%04x J:%04x\n PC:%04x SP:%04x EX:%04x IA:%04x\n%s\n%s",
(int)register[A], (int)register[B], (int)register[C],
(int)register[X], (int)register[Y], (int)register[Z],
(int)register[I], (int)register[J],
(int)PC, (int)SP, (int)EX, (int)IA,
skipping ? "SKIPPING" : "",
Disasm.disasm(RAM, PC));
}
}
| true | true | public synchronized void execute()
{
cycleCount++;
tSP = SP; // Cache SP
tPC = (char)(PC+1); // Pre-increment tPC
boolean error = false; // Not sure what to do with this yet (maybe set on fire?)
// Fetch
char instr = RAM[PC];
if (instr == 0) // Invalid instruction; stop.
{
notifyObservers();
return;
}
// Decode
int opcode = instr & 0x1f;
char b = (char)((instr >> 5) & 0x1f);
char a = (char)(instr >> 10);
if (opcode != 0)
{
if (skipping)
{
// Skip reading next words
if ((b >= 0x10 && b < 0x18) || b == 0x1a || b == 0x1e || b == 0x1f) // [register + next word], [SP + next word], [next word], next word
tPC++;
if ((a >= 0x10 && a < 0x18) || a == 0x1a || a == 0x1e || a == 0x1f) // [register + next word], [SP + next word], [next word], next word
tPC++;
PC = tPC;
if (opcode < 0x10 || opcode > 0x17) // Keep skipping over conditionals
skipping = false;
}
else
{
// Work out address type and location before instruction
// These will only modify tSP or tPC, not the actual SP or PC
// until after the instruction completes.
AddressType aType = addressType(a), bType = addressType(b);
char aAddr = addressA(a), bAddr = addressB(b);
// Grab the actual values
char aVal = read(aType, aAddr), bVal = read(bType, bAddr);
int res = 0; // Result
switch (opcode)
{
case 0x01: // SET
res = aVal;
break;
case 0x02: // ADD
res = bVal + aVal;
EX = (res <= 0xffff) ? (char)0 : (char)1;
break;
case 0x03: // SUB
res = bVal - aVal;
EX = (res >= 0) ? 0 : (char)0xffff;
break;
case 0x04: // MUL
res = bVal * aVal;
EX = (char)(res >> 16);
break;
case 0x05: // MLI
res = unsignedCharAsSignedInt(bVal) * unsignedCharAsSignedInt(aVal);
EX = (char)(res >> 16);
break;
case 0x06: // DIV
res = bVal / aVal;
EX = (char)(((bVal << 16) / aVal) & 0xffff);
break;
case 0x07: // DVI
res = unsignedCharAsSignedInt(bVal) / unsignedCharAsSignedInt(aVal);
EX = (char)(((unsignedCharAsSignedInt(bVal) << 16) / unsignedCharAsSignedInt(aVal)) & 0xffff);
break;
case 0x08: // MOD
if (aVal == 0)
res = 0;
else
res = bVal % aVal;
break;
case 0x09: // MDI
if (aVal == 0)
res = 0;
else
res = unsignedCharAsSignedInt(bVal) % unsignedCharAsSignedInt(aVal);
break;
case 0x0a: // AND
res = bVal & aVal;
break;
case 0x0b: // BOR
res = bVal | aVal;
break;
case 0x0c: // XOR
res = bVal ^ aVal;
break;
case 0x0d: // SHR
res = bVal >>> aVal;
EX = (char)(((bVal << 16) >>> a) & 0xffff);
break;
case 0x0e: // ASR
res = bVal >> aVal;
EX = (char)(((bVal << 16) >> a) & 0xffff);
break;
case 0x0f: // SHL
res = bVal << aVal;
EX = (char)(((bVal << aVal) >> 16) & 0xffff);
break;
case 0x10: // IFB
skipping = (bVal & aVal) == 0;
break;
case 0x11: // IFC
skipping = (bVal & aVal) != 0;
break;
case 0x12: // IFE
skipping = (bVal != aVal);
break;
case 0x13: // IFN
skipping = (bVal == aVal);
break;
case 0x14: // IFG
skipping = (bVal <= aVal);
break;
case 0x15: // IFA
skipping = (unsignedCharAsSignedInt(bVal) <= unsignedCharAsSignedInt(aVal));
break;
case 0x16: // IFL
skipping = (bVal >= aVal);
break;
case 0x17: // IFU
skipping = (unsignedCharAsSignedInt(bVal) >= unsignedCharAsSignedInt(bVal));
break;
case 0x18: // -
case 0x19: // -
error = true;
break;
case 0x1a: // ADX
res = bVal + aVal + EX;
EX = (char)((res <= 0xFFFF) ? 0 : 1);
break;
case 0x1b: // SBX
res = bVal - aVal - EX;
EX = (char)((res >= 0) ? 0 : 1);
break;
case 0x1c: // -
case 0x1d: // -
error = true;
break;
case 0x1e: // STI
res = aVal;
register[I]++;
register[J]++;
break;
case 0x1f: // STD
res = aVal;
register[I]--;
register[J]--;
break;
}
if (opcode < 0x10 || opcode > 0x17)
write(bType, bAddr, (char)(res & 0xffff));
}
}
else
{
if (skipping)
{
// Skip reading next word
if ((a >= 0x10 && a < 0x18) || a == 0x1a || a == 0x1e || a == 0x1f) // [register + next word], [SP + next word], [next word], next word
tPC++;
skipping = false;
PC = tPC;
}
else
{
switch (b) // b becomes the special opcode
{
case 0x00: // Reserved
error = true;
break;
case 0x01: // JSR
// Get jump address
char jmp = read(addressType(a), addressA(a));
// Push PC
RAM[--tSP] = tPC;
// Set PC to jump address (after increment)
tPC = jmp;
break;
case 0x02: // -
case 0x03: // -
case 0x04: // -
case 0x05: // -
case 0x06: // -
case 0x07: // -
error = true;
break;
case 0x08: // INT
interrupt(read(addressType(a), addressA(a)));
break;
case 0x09: // IAG
write(addressType(a), addressA(a), IA);
break;
case 0x0a: // IAS
IA = read(addressType(a), addressA(a));
break;
case 0x0b: // RFI
interruptQueueing = false;
register[A] = RAM[tSP++];
tPC = RAM[tSP++];
break;
case 0x0c: // IAQ
interruptQueueing = (read(addressType(a), addressA(a)) == 0);
break;
case 0x0d: // -
case 0x0e: // -
case 0x0f: // -
error = true;
break;
case 0x10: // HWN
write(addressType(a), addressA(a), (char)HardwareManager.instance().getCount());
break;
case 0x11: // HWQ
{
Device device = HardwareManager.instance().getDevice(read(addressType(a), addressA(a)));
if (device != null)
{
register[A] = device.GetIDLo();
register[B] = device.GetIDHi();
register[C] = device.GetVersion();
register[X] = device.GetManuLo();
register[Y] = device.GetManuHi();
}
else
error = true;
break;
}
case 0x12: // HWI
{
Device device = HardwareManager.instance().getDevice(read(addressType(a), addressA(a)));
if (device != null)
device.HWI_1_7(this);
else
error = true;
break;
}
case 0x13: // -
case 0x14: // -
case 0x15: // -
case 0x16: // -
case 0x17: // -
case 0x18: // -
case 0x19: // -
case 0x1a: // -
case 0x1b: // -
case 0x1c: // -
case 0x1d: // -
case 0x1e: // -
case 0x1f: // -
error = true;
break;
}
}
}
if (!skipping && !interruptQueueing && !interruptQueue.isEmpty())
{
interruptQueueing = true;
RAM[tSP--] = tPC;
RAM[tSP--] = register[A];
tPC = IA;
register[A] = interruptQueue.remove().charValue();
}
PC = tPC;
SP = tSP;
notifyObservers();
}
| public synchronized void execute()
{
cycleCount++;
tSP = SP; // Cache SP
tPC = (char)(PC+1); // Pre-increment tPC
boolean error = false; // Not sure what to do with this yet (maybe set on fire?)
// Fetch
char instr = RAM[PC];
if (instr == 0) // Invalid instruction; stop.
{
notifyObservers();
return;
}
// Decode
int opcode = instr & 0x1f;
char b = (char)((instr >> 5) & 0x1f);
char a = (char)(instr >> 10);
if (opcode != 0)
{
if (skipping)
{
// Skip reading next words
if ((b >= 0x10 && b < 0x18) || b == 0x1a || b == 0x1e || b == 0x1f) // [register + next word], [SP + next word], [next word], next word
tPC++;
if ((a >= 0x10 && a < 0x18) || a == 0x1a || a == 0x1e || a == 0x1f) // [register + next word], [SP + next word], [next word], next word
tPC++;
PC = tPC;
if (opcode < 0x10 || opcode > 0x17) // Keep skipping over conditionals
skipping = false;
}
else
{
// Work out address type and location before instruction
// These will only modify tSP or tPC, not the actual SP or PC
// until after the instruction completes.
AddressType aType = addressType(a), bType = addressType(b);
char aAddr = addressA(a), bAddr = addressB(b);
// Grab the actual values
char aVal = read(aType, aAddr), bVal = read(bType, bAddr);
int res = 0; // Result
switch (opcode)
{
case 0x01: // SET
res = aVal;
break;
case 0x02: // ADD
res = bVal + aVal;
EX = (res <= 0xffff) ? (char)0 : (char)1;
break;
case 0x03: // SUB
res = bVal - aVal;
EX = (res >= 0) ? 0 : (char)0xffff;
break;
case 0x04: // MUL
res = bVal * aVal;
EX = (char)(res >> 16);
break;
case 0x05: // MLI
res = unsignedCharAsSignedInt(bVal) * unsignedCharAsSignedInt(aVal);
EX = (char)(res >> 16);
break;
case 0x06: // DIV
res = bVal / aVal;
EX = (char)(((bVal << 16) / aVal) & 0xffff);
break;
case 0x07: // DVI
res = unsignedCharAsSignedInt(bVal) / unsignedCharAsSignedInt(aVal);
EX = (char)(((unsignedCharAsSignedInt(bVal) << 16) / unsignedCharAsSignedInt(aVal)) & 0xffff);
break;
case 0x08: // MOD
if (aVal == 0)
res = 0;
else
res = bVal % aVal;
break;
case 0x09: // MDI
if (aVal == 0)
res = 0;
else
res = unsignedCharAsSignedInt(bVal) % unsignedCharAsSignedInt(aVal);
break;
case 0x0a: // AND
res = bVal & aVal;
break;
case 0x0b: // BOR
res = bVal | aVal;
break;
case 0x0c: // XOR
res = bVal ^ aVal;
break;
case 0x0d: // SHR
res = bVal >>> aVal;
EX = (char)(((bVal << 16) >>> a) & 0xffff);
break;
case 0x0e: // ASR
res = unsignedCharAsSignedInt(bVal) >> unsignedCharAsSignedInt(aVal);
EX = (char)(((unsignedCharAsSignedInt(bVal) << 16) >> unsignedCharAsSignedInt(aVal)) & 0xffff);
break;
case 0x0f: // SHL
res = bVal << aVal;
EX = (char)(((bVal << aVal) >> 16) & 0xffff);
break;
case 0x10: // IFB
skipping = (bVal & aVal) == 0;
break;
case 0x11: // IFC
skipping = (bVal & aVal) != 0;
break;
case 0x12: // IFE
skipping = (bVal != aVal);
break;
case 0x13: // IFN
skipping = (bVal == aVal);
break;
case 0x14: // IFG
skipping = (bVal <= aVal);
break;
case 0x15: // IFA
skipping = (unsignedCharAsSignedInt(bVal) <= unsignedCharAsSignedInt(aVal));
break;
case 0x16: // IFL
skipping = (bVal >= aVal);
break;
case 0x17: // IFU
skipping = (unsignedCharAsSignedInt(bVal) >= unsignedCharAsSignedInt(bVal));
break;
case 0x18: // -
case 0x19: // -
error = true;
break;
case 0x1a: // ADX
res = bVal + aVal + EX;
EX = (char)((res <= 0xFFFF) ? 0 : 1);
break;
case 0x1b: // SBX
res = bVal - aVal - EX;
EX = (char)((res >= 0) ? 0 : 1);
break;
case 0x1c: // -
case 0x1d: // -
error = true;
break;
case 0x1e: // STI
res = aVal;
register[I]++;
register[J]++;
break;
case 0x1f: // STD
res = aVal;
register[I]--;
register[J]--;
break;
}
if (opcode < 0x10 || opcode > 0x17)
write(bType, bAddr, (char)(res & 0xffff));
}
}
else
{
if (skipping)
{
// Skip reading next word
if ((a >= 0x10 && a < 0x18) || a == 0x1a || a == 0x1e || a == 0x1f) // [register + next word], [SP + next word], [next word], next word
tPC++;
skipping = false;
PC = tPC;
}
else
{
switch (b) // b becomes the special opcode
{
case 0x00: // Reserved
error = true;
break;
case 0x01: // JSR
// Get jump address
char jmp = read(addressType(a), addressA(a));
// Push PC
RAM[--tSP] = tPC;
// Set PC to jump address (after increment)
tPC = jmp;
break;
case 0x02: // -
case 0x03: // -
case 0x04: // -
case 0x05: // -
case 0x06: // -
case 0x07: // -
error = true;
break;
case 0x08: // INT
interrupt(read(addressType(a), addressA(a)));
break;
case 0x09: // IAG
write(addressType(a), addressA(a), IA);
break;
case 0x0a: // IAS
IA = read(addressType(a), addressA(a));
break;
case 0x0b: // RFI
interruptQueueing = false;
register[A] = RAM[tSP++];
tPC = RAM[tSP++];
break;
case 0x0c: // IAQ
interruptQueueing = (read(addressType(a), addressA(a)) == 0);
break;
case 0x0d: // -
case 0x0e: // -
case 0x0f: // -
error = true;
break;
case 0x10: // HWN
write(addressType(a), addressA(a), (char)HardwareManager.instance().getCount());
break;
case 0x11: // HWQ
{
Device device = HardwareManager.instance().getDevice(read(addressType(a), addressA(a)));
if (device != null)
{
register[A] = device.GetIDLo();
register[B] = device.GetIDHi();
register[C] = device.GetVersion();
register[X] = device.GetManuLo();
register[Y] = device.GetManuHi();
}
else
error = true;
break;
}
case 0x12: // HWI
{
Device device = HardwareManager.instance().getDevice(read(addressType(a), addressA(a)));
if (device != null)
device.HWI_1_7(this);
else
error = true;
break;
}
case 0x13: // -
case 0x14: // -
case 0x15: // -
case 0x16: // -
case 0x17: // -
case 0x18: // -
case 0x19: // -
case 0x1a: // -
case 0x1b: // -
case 0x1c: // -
case 0x1d: // -
case 0x1e: // -
case 0x1f: // -
error = true;
break;
}
}
}
if (!skipping && !interruptQueueing && !interruptQueue.isEmpty())
{
interruptQueueing = true;
RAM[tSP--] = tPC;
RAM[tSP--] = register[A];
tPC = IA;
register[A] = interruptQueue.remove().charValue();
}
PC = tPC;
SP = tSP;
notifyObservers();
}
|
diff --git a/fuj1n/modjam2_src/block/BlockSecureCore.java b/fuj1n/modjam2_src/block/BlockSecureCore.java
index bf49fa1..89d847a 100644
--- a/fuj1n/modjam2_src/block/BlockSecureCore.java
+++ b/fuj1n/modjam2_src/block/BlockSecureCore.java
@@ -1,184 +1,184 @@
package fuj1n.modjam2_src.block;
import java.util.Random;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import fuj1n.modjam2_src.SecureMod;
import fuj1n.modjam2_src.client.gui.GuiHandler.GuiIdReference;
import fuj1n.modjam2_src.client.particle.EntityElectricityFX;
import fuj1n.modjam2_src.item.SecureModItems;
import fuj1n.modjam2_src.tileentity.TileEntitySecurityCore;
public class BlockSecureCore extends BlockContainer implements ISecure {
private Icon[] icons = new Icon[3];
public BlockSecureCore(int par1) {
super(par1, Material.tnt);
this.setStepSound(this.soundMetalFootstep);
}
@Override
public boolean isOpaqueCube() {
return true;
//return false;
}
@Override
public boolean canProvidePower() {
return true;
}
@Override
public int isProvidingWeakPower(IBlockAccess par1IBlockAccess, int par2, int par3, int par4, int par5) {
TileEntitySecurityCore te = (TileEntitySecurityCore)par1IBlockAccess.getBlockTileEntity(par2, par3, par4);
return te.redstoneSignalsOut[par5] > 0 ? te.redstoneSignalsOut[par5] : te.redstoneSignalsRet[par5];
}
@Override
public boolean isBlockSolidOnSide(World world, int x, int y, int z, ForgeDirection side) {
return true;
}
@Override
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) {
TileEntitySecurityCore te = (TileEntitySecurityCore) par1World.getBlockTileEntity(par2, par3, par4);
switch (te.inputMode) {
case 1:
par5EntityPlayer.openGui(SecureMod.instance, GuiIdReference.GUI_SECURECOREPASS, par1World, par2, par3, par4);
return true;
case 2:
if (par5EntityPlayer.getHeldItem() != null && par5EntityPlayer.getHeldItem().itemID == SecureModItems.securityPass.itemID && par5EntityPlayer.getHeldItem().getTagCompound() != null) {
if (Integer.toString(par5EntityPlayer.getHeldItem().getTagCompound().getInteger("cardID")).equals(te.passcode)) {
te.setOutput();
+ return true;
}
- return true;
}
break;
case 3:
if (par5EntityPlayer.username.equals(te.playerName)) {
te.setOutput();
return true;
}
break;
case 4:
break;
}
te.setRetaliate(par5EntityPlayer);
return false;
}
@Override
public void onBlockClicked(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer) {
TileEntitySecurityCore te = (TileEntitySecurityCore) par1World.getBlockTileEntity(par2, par3, par4);
te.setRetaliate(par5EntityPlayer);
}
@Override
public void onBlockPlacedBy(World par1World, int par2, int par3, int par4, EntityLivingBase par5EntityLivingBase, ItemStack par6ItemStack) {
int l = MathHelper.floor_double((double) (par5EntityLivingBase.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
if (l == 0) {
par1World.setBlockMetadataWithNotify(par2, par3, par4, 2, 2);
}
if (l == 1) {
par1World.setBlockMetadataWithNotify(par2, par3, par4, 5, 2);
}
if (l == 2) {
par1World.setBlockMetadataWithNotify(par2, par3, par4, 3, 2);
}
if (l == 3) {
par1World.setBlockMetadataWithNotify(par2, par3, par4, 4, 2);
}
if (par5EntityLivingBase instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer) par5EntityLivingBase;
TileEntitySecurityCore te = (TileEntitySecurityCore)par1World.getBlockTileEntity(par2, par3, par4);
te.playerName = player.username;
player.openGui(SecureMod.instance, GuiIdReference.GUI_SECURECORE, par1World, par2, par3, par4);
}
}
@Override
public Icon getBlockTexture(IBlockAccess par1World, int par2, int par3, int par4, int par5) {
int meta = par1World.getBlockMetadata(par2, par3, par4);
return par5 == 1 ? this.icons[1] : (par5 == 0 ? this.icons[1] : (par5 != meta ? this.icons[0] : this.icons[2]));
}
@Override
public Icon getIcon(int par1, int par2) {
if (par1 == 0 || par1 == 1) {
return icons[1];
} else if (par1 == 4) {
return icons[2];
}
return icons[0];
}
@Override
public void onNeighborBlockChange(World par1World, int par2, int par3, int par4, int par5) {
TileEntitySecurityCore te = (TileEntitySecurityCore)par1World.getBlockTileEntity(par2, par3, par4);
if(te.inputMode == 4 && par1World.isBlockIndirectlyGettingPowered(par2, par3, par4)){
te.setOutput();
}
}
@Override
public void registerIcons(IconRegister par1IconRegister) {
icons[0] = par1IconRegister.registerIcon("securemod:secure_block_base");
icons[1] = par1IconRegister.registerIcon("securemod:secure_block_axisY");
icons[2] = par1IconRegister.registerIcon("securemod:secure_core_front");
}
@Override
public TileEntity createNewTileEntity(World world) {
return new TileEntitySecurityCore();
}
@Override
public boolean canBreak(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer) {
TileEntitySecurityCore te = (TileEntitySecurityCore)par1World.getBlockTileEntity(par2, par3, par4);
if(par5EntityPlayer.username.equals(te.playerName) || te.playerName == null){
return true;
}
return false;
}
@Override
public boolean canEntityDestroy(World world, int x, int y, int z, Entity entity) {
return false;
}
@Override
public int getMobilityFlag(){
return 2;
}
// @SideOnly(Side.CLIENT)
// @Override
// public void randomDisplayTick(World par1World, int par2, int par3, int par4, Random par5Random){
//
// }
}
| false | true | public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) {
TileEntitySecurityCore te = (TileEntitySecurityCore) par1World.getBlockTileEntity(par2, par3, par4);
switch (te.inputMode) {
case 1:
par5EntityPlayer.openGui(SecureMod.instance, GuiIdReference.GUI_SECURECOREPASS, par1World, par2, par3, par4);
return true;
case 2:
if (par5EntityPlayer.getHeldItem() != null && par5EntityPlayer.getHeldItem().itemID == SecureModItems.securityPass.itemID && par5EntityPlayer.getHeldItem().getTagCompound() != null) {
if (Integer.toString(par5EntityPlayer.getHeldItem().getTagCompound().getInteger("cardID")).equals(te.passcode)) {
te.setOutput();
}
return true;
}
break;
case 3:
if (par5EntityPlayer.username.equals(te.playerName)) {
te.setOutput();
return true;
}
break;
case 4:
break;
}
te.setRetaliate(par5EntityPlayer);
return false;
}
| public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) {
TileEntitySecurityCore te = (TileEntitySecurityCore) par1World.getBlockTileEntity(par2, par3, par4);
switch (te.inputMode) {
case 1:
par5EntityPlayer.openGui(SecureMod.instance, GuiIdReference.GUI_SECURECOREPASS, par1World, par2, par3, par4);
return true;
case 2:
if (par5EntityPlayer.getHeldItem() != null && par5EntityPlayer.getHeldItem().itemID == SecureModItems.securityPass.itemID && par5EntityPlayer.getHeldItem().getTagCompound() != null) {
if (Integer.toString(par5EntityPlayer.getHeldItem().getTagCompound().getInteger("cardID")).equals(te.passcode)) {
te.setOutput();
return true;
}
}
break;
case 3:
if (par5EntityPlayer.username.equals(te.playerName)) {
te.setOutput();
return true;
}
break;
case 4:
break;
}
te.setRetaliate(par5EntityPlayer);
return false;
}
|
diff --git a/imap2/src/com/android/imap2/Imap2SyncService.java b/imap2/src/com/android/imap2/Imap2SyncService.java
index 8f069d9c2..82a5ffa95 100644
--- a/imap2/src/com/android/imap2/Imap2SyncService.java
+++ b/imap2/src/com/android/imap2/Imap2SyncService.java
@@ -1,2469 +1,2469 @@
/* Copyright (C) 2012 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.imap2;
import android.content.ContentProviderOperation;
import android.content.ContentProviderOperation.Builder;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import com.android.emailcommon.Logging;
import com.android.emailcommon.TrafficFlags;
import com.android.emailcommon.internet.MimeUtility;
import com.android.emailcommon.internet.Rfc822Output;
import com.android.emailcommon.mail.Address;
import com.android.emailcommon.mail.CertificateValidationException;
import com.android.emailcommon.mail.MessagingException;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.AccountColumns;
import com.android.emailcommon.provider.EmailContent.Attachment;
import com.android.emailcommon.provider.EmailContent.Body;
import com.android.emailcommon.provider.EmailContent.MailboxColumns;
import com.android.emailcommon.provider.EmailContent.Message;
import com.android.emailcommon.provider.EmailContent.MessageColumns;
import com.android.emailcommon.provider.EmailContent.SyncColumns;
import com.android.emailcommon.provider.HostAuth;
import com.android.emailcommon.provider.Mailbox;
import com.android.emailcommon.provider.MailboxUtilities;
import com.android.emailcommon.service.EmailServiceProxy;
import com.android.emailcommon.service.EmailServiceStatus;
import com.android.emailcommon.service.SearchParams;
import com.android.emailcommon.service.SyncWindow;
import com.android.emailcommon.utility.CountingOutputStream;
import com.android.emailcommon.utility.EOLConvertingOutputStream;
import com.android.emailcommon.utility.SSLUtils;
import com.android.emailcommon.utility.TextUtilities;
import com.android.emailcommon.utility.Utility;
import com.android.emailsync.AbstractSyncService;
import com.android.emailsync.PartRequest;
import com.android.emailsync.Request;
import com.android.emailsync.SyncManager;
import com.android.imap2.smtp.SmtpSender;
import com.android.mail.providers.UIProvider;
import com.beetstra.jutf7.CharsetProvider;
import com.google.common.annotations.VisibleForTesting;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
public class Imap2SyncService extends AbstractSyncService {
private static final String IMAP_OK = "OK";
private static final SimpleDateFormat GMAIL_INTERNALDATE_FORMAT =
new SimpleDateFormat("EEE, dd MMM yy HH:mm:ss z");
private static final String IMAP_ERR = "ERR";
private static final String IMAP_NO = "NO";
private static final String IMAP_BAD = "BAD";
private static final SimpleDateFormat IMAP_DATE_FORMAT =
new SimpleDateFormat("dd-MMM-yyyy");
private static final SimpleDateFormat INTERNALDATE_FORMAT =
new SimpleDateFormat("dd-MMM-yy HH:mm:ss z");
private static final Charset MODIFIED_UTF_7_CHARSET =
new CharsetProvider().charsetForName("X-RFC-3501");
public static final String IMAP_DELETED_MESSAGES_FOLDER_NAME = "AndroidMail Trash";
public static final String GMAIL_TRASH_FOLDER = "[Gmail]/Trash";
private static Pattern IMAP_RESPONSE_PATTERN = Pattern.compile("\\*(\\s(\\d+))?\\s(\\w+).*");
private static final int HEADER_BATCH_COUNT = 20;
private static final int SECONDS = 1000;
private static final int MINS = 60*SECONDS;
private static final int IDLE_ASLEEP_MILLIS = 11*MINS;
private static final int IDLE_FALLBACK_SYNC_INTERVAL = 10;
private static final int SOCKET_CONNECT_TIMEOUT = 10*SECONDS;
private static final int SOCKET_TIMEOUT = 20*SECONDS;
private static final int SEARCH_TIMEOUT = 60*SECONDS;
private static final int AUTOMATIC_SYNC_WINDOW_MAX_MESSAGES = 250;
private static final int AUTOMATIC_SYNC_WINDOW_LARGE_MAILBOX = 1000;
private ContentResolver mResolver;
private int mWriterTag = 1;
private boolean mIsGmail = false;
private boolean mIsIdle = false;
private int mLastExists = -1;
private ArrayList<String> mImapResponse = null;
private String mImapResult;
private String mImapErrorLine = null;
private String mImapSuccessLine = null;
private Socket mSocket = null;
private boolean mStop = false;
public int mServiceResult = 0;
private boolean mIsServiceRequestPending = false;
private final String[] MAILBOX_SERVER_ID_ARGS = new String[2];
public Imap2SyncService() {
this("Imap2 Validation");
}
private final ArrayList<Integer> SERVER_DELETES = new ArrayList<Integer>();
private static final String INBOX_SERVER_NAME = "Inbox"; // Per RFC3501
private BufferedWriter mWriter;
private ImapInputStream mReader;
private HostAuth mHostAuth;
private String mPrefix;
private long mTrashMailboxId = Mailbox.NO_MAILBOX;
private long mAccountId;
private final ArrayList<Long> mUpdatedIds = new ArrayList<Long>();
private final ArrayList<Long> mDeletedIds = new ArrayList<Long>();
private final Stack<Integer> mDeletes = new Stack<Integer>();
private final Stack<Integer> mReadUpdates = new Stack<Integer>();
private final Stack<Integer> mUnreadUpdates = new Stack<Integer>();
private final Stack<Integer> mFlaggedUpdates = new Stack<Integer>();
private final Stack<Integer> mUnflaggedUpdates = new Stack<Integer>();
public Imap2SyncService(Context _context, Mailbox _mailbox) {
super(_context, _mailbox);
mResolver = _context.getContentResolver();
if (mAccount != null) {
mAccountId = mAccount.mId;
}
MAILBOX_SERVER_ID_ARGS[0] = Long.toString(mMailboxId);
}
private Imap2SyncService(String prefix) {
super(prefix);
}
public Imap2SyncService(Context _context, Account _account) {
this("Imap2 Account");
mContext = _context;
mResolver = _context.getContentResolver();
mAccount = _account;
mAccountId = _account.mId;
mHostAuth = HostAuth.restoreHostAuthWithId(_context, mAccount.mHostAuthKeyRecv);
mPrefix = mHostAuth.mDomain;
mTrashMailboxId = Mailbox.findMailboxOfType(_context, _account.mId, Mailbox.TYPE_TRASH);
}
@Override
public boolean alarm() {
// See if we've got anything to do...
Cursor updates = getUpdatesCursor();
Cursor deletes = getDeletesCursor();
try {
if (mRequestQueue.isEmpty() && updates == null && deletes == null) {
userLog("Ping: nothing to do");
} else {
int cnt = mRequestQueue.size();
if (updates != null) {
cnt += updates.getCount();
}
if (deletes != null) {
cnt += deletes.getCount();
}
userLog("Ping: " + cnt + " tasks");
ping();
}
} finally {
if (updates != null) {
updates.close();
}
if (deletes != null) {
deletes.close();
}
}
return true;
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
public void addRequest(Request req) {
super.addRequest(req);
if (req instanceof PartRequest) {
userLog("Request for attachment " + ((PartRequest)req).mAttachment.mId);
}
ping();
}
@Override
public Bundle validateAccount(HostAuth hostAuth, Context context) {
Bundle bundle = new Bundle();
int resultCode = MessagingException.IOERROR;
Connection conn = connectAndLogin(hostAuth, "main");
if (conn.status == EXIT_DONE) {
resultCode = MessagingException.NO_ERROR;
} else if (conn.status == EXIT_LOGIN_FAILURE) {
resultCode = MessagingException.AUTHENTICATION_FAILED;
}
bundle.putInt(EmailServiceProxy.VALIDATE_BUNDLE_RESULT_CODE, resultCode);
return bundle;
}
public void loadFolderList() throws IOException {
HostAuth hostAuth =
HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv);
if (hostAuth == null) return;
Connection conn = connectAndLogin(hostAuth, "folderList");
if (conn.status == EXIT_DONE) {
setConnection(conn);
readFolderList();
conn.socket.close();
}
}
private void setConnection(Connection conn) {
mConnection = conn;
mWriter = conn.writer;
mReader = conn.reader;
mSocket = conn.socket;
}
@Override
public void resetCalendarSyncKey() {
// Not used by Imap2
}
public void ping() {
mIsServiceRequestPending = true;
Imap2SyncManager.runAwake(mMailbox.mId);
if (mSocket != null) {
try {
if (mIsIdle) {
userLog("breakIdle; sending DONE...");
mWriter.write("DONE\r\n");
mWriter.flush();
}
} catch (SocketException e) {
} catch (IOException e) {
}
}
}
public void stop () {
if (mSocket != null)
try {
if (mIsIdle)
ping();
mSocket.close();
} catch (IOException e) {
}
mStop = true;
}
public String writeCommand (Writer out, String cmd) throws IOException {
Integer t = mWriterTag++;
String tag = "@@a" + t + ' ';
if (!cmd.startsWith("login")) {
userLog(tag + cmd);
}
out.write(tag);
out.write(cmd);
out.write("\r\n");
out.flush();
return tag;
}
private void writeContinuation(Writer out, String cmd) {
try {
out.write(cmd);
out.write("\r\n");
out.flush();
userLog(cmd);
} catch (IOException e) {
userLog("IOException in writeCommand");
}
}
private long readLong (String str, int idx) {
char ch = str.charAt(idx);
long num = 0;
while (ch >= '0' && ch <= '9') {
num = (num * 10) + (ch - '0');
ch = str.charAt(++idx);
}
return num;
}
private void readUntagged(String str) {
// Skip the "* "
Parser p = new Parser(str, 2);
String type = p.parseAtom();
int val = -1;
if (type != null) {
char c = type.charAt(0);
if (c >= '0' && c <= '9')
try {
val = Integer.parseInt(type);
type = p.parseAtom();
if (p != null) {
if (type.toLowerCase().equals("exists"))
mLastExists = val;
}
} catch (NumberFormatException e) {
}
else if (mMailbox != null && (mMailbox.mSyncKey == null || mMailbox.mSyncKey == "0")) {
str = str.toLowerCase();
int idx = str.indexOf("uidvalidity");
if (idx > 0) {
// 12 = length of "uidvalidity" + 1
long num = readLong(str, idx + 12);
mMailbox.mSyncKey = Long.toString(num);
ContentValues cv = new ContentValues();
cv.put(MailboxColumns.SYNC_KEY, mMailbox.mSyncKey);
mContext.getContentResolver().update(
ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailbox.mId), cv,
null, null);
}
}
}
userLog("Untagged: " + type);
}
private boolean caseInsensitiveStartsWith(String str, String tag) {
return str.toLowerCase().startsWith(tag.toLowerCase());
}
private String readResponse (ImapInputStream r, String tag) throws IOException {
return readResponse(r, tag, null);
}
private String readResponse (ImapInputStream r, String tag, String command) throws IOException {
mImapResult = IMAP_ERR;
String str = null;
if (command != null)
mImapResponse = new ArrayList<String>();
while (true) {
str = r.readLine();
userLog("< " + str);
if (caseInsensitiveStartsWith(str, tag)) {
// This is the response from the command named 'tag'
Parser p = new Parser(str, tag.length() - 1);
mImapResult = p.parseAtom();
break;
} else if (str.charAt(0) == '*') {
if (command != null) {
Matcher m = IMAP_RESPONSE_PATTERN.matcher(str);
if (m.matches() && m.group(3).equals(command)) {
mImapResponse.add(str);
} else
readUntagged(str);
} else
readUntagged(str);
} else if (str.charAt(0) == '+') {
mImapResult = str;
return str;
} else if (!mImapResponse.isEmpty()) {
// Continuation with string literal, perhaps?
int off = mImapResponse.size() - 1;
mImapResponse.set(off, mImapResponse.get(off) + "\r\n" + str);
}
}
if (mImapResult.equals(IMAP_OK)) {
mImapSuccessLine = str;
} else {
userLog("$$$ Error result = " + mImapResult);
mImapErrorLine = str;
}
return mImapResult;
}
String parseRecipientList (String str) {
if (str == null)
return null;
ArrayList<Address> list = new ArrayList<Address>();
String r;
Parser p = new Parser(str);
while ((r = p.parseList()) != null) {
Parser rp = new Parser(r);
String displayName = rp.parseString();
rp.parseString();
String emailAddress = rp.parseString() + "@" + rp.parseString();
list.add(new Address(emailAddress, displayName));
}
return Address.pack(list.toArray(new Address[list.size()]));
}
String parseRecipients (Parser p, Message msg) {
msg.mFrom = parseRecipientList(p.parseListOrNil());
@SuppressWarnings("unused")
String senderList = parseRecipientList(p.parseListOrNil());
msg.mReplyTo = parseRecipientList(p.parseListOrNil());
msg.mTo = parseRecipientList(p.parseListOrNil());
msg.mCc = parseRecipientList(p.parseListOrNil());
msg.mBcc = parseRecipientList(p.parseListOrNil());
return Address.toFriendly(Address.unpack(msg.mFrom));
}
private Message createMessage (String str, long mailboxId) {
Parser p = new Parser(str, str.indexOf('(') + 1);
Date date = null;
String subject = null;
String sender = null;
boolean read = false;
int flag = 0;
String flags = null;
int uid = 0;
Message msg = new Message();
msg.mMailboxKey = mailboxId;
try {
while (true) {
String atm = p.parseAtom();
// Not sure if this case is possible
if (atm == null)
break;
if (atm.equalsIgnoreCase("UID")) {
uid = p.parseInteger();
//userLog("UID=" + uid);
} else if (atm.equalsIgnoreCase("ENVELOPE")) {
String envelope = p.parseList();
Parser ep = new Parser(envelope);
ep.skipWhite();
//date = parseDate(ep.parseString());
ep.parseString();
subject = ep.parseString();
sender = parseRecipients(ep, msg);
} else if (atm.equalsIgnoreCase("FLAGS")) {
flags = p.parseList().toLowerCase();
if (flags.indexOf("\\seen") >=0)
read = true;
if (flags.indexOf("\\flagged") >=0)
flag = 1;
} else if (atm.equalsIgnoreCase("BODYSTRUCTURE")) {
msg.mSyncData = p.parseList();
} else if (atm.equalsIgnoreCase("INTERNALDATE")) {
date = parseInternaldate(p.parseString());
}
}
} catch (Exception e) {
// Parsing error here. We've got one known one from EON
// in which BODYSTRUCTURE is ( "MIXED" (....) )
if (sender == null)
sender = "Unknown sender";
if (subject == null)
subject = "No subject";
e.printStackTrace();
}
if (subject != null && subject.startsWith("=?"))
subject = MimeUtility.decode(subject);
msg.mSubject = subject;
//msg.bodyId = 0;
//msg.parts = parts.toString();
msg.mAccountKey = mAccountId;
msg.mFlagLoaded = Message.FLAG_LOADED_UNLOADED;
msg.mFlags = flag;
if (read)
msg.mFlagRead = true;
msg.mTimeStamp = ((date != null) ? date : new Date()).getTime();
msg.mServerId = Long.toString(uid);
// If we're not storing to the same mailbox (search), save away our mailbox name
if (mailboxId != mMailboxId) {
msg.mProtocolSearchInfo = mMailboxName;
}
return msg;
}
private Date parseInternaldate (String str) {
if (str != null) {
SimpleDateFormat f = INTERNALDATE_FORMAT;
if (str.charAt(3) == ',')
f = GMAIL_INTERNALDATE_FORMAT;
try {
return f.parse(str);
} catch (ParseException e) {
userLog("Unparseable date: " + str);
}
}
return new Date();
}
private long getIdForUid(int uid) {
// TODO: Rename this
MAILBOX_SERVER_ID_ARGS[1] = Integer.toString(uid);
Cursor c = mResolver.query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION,
MessageColumns.MAILBOX_KEY + "=? AND " + SyncColumns.SERVER_ID + "=?",
MAILBOX_SERVER_ID_ARGS, null);
try {
if (c != null && c.moveToFirst()) {
return c.getLong(Message.ID_COLUMNS_ID_COLUMN);
}
} finally {
if (c != null) {
c.close();
}
}
return Message.NO_MESSAGE;
}
private void processDelete(int uid) {
SERVER_DELETES.clear();
SERVER_DELETES.add(uid);
processServerDeletes(SERVER_DELETES);
}
/**
* Handle a single untagged line
* TODO: Perhaps batch operations for multiple lines into a single transaction
*/
private boolean handleUntagged (String line) {
line = line.toLowerCase();
Matcher m = IMAP_RESPONSE_PATTERN.matcher(line);
boolean res = false;
if (m.matches()) {
// What kind of thing is this?
String type = m.group(3);
if (type.equals("fetch") || type.equals("expunge")) {
// This is a flag change or an expunge. First, find the UID
int uid = 0;
// TODO Get rid of hack to avoid uid...
int uidPos = line.indexOf("uid");
if (uidPos > 0) {
Parser p = new Parser(line, uidPos + 3);
uid = p.parseInteger();
}
if (uid == 0) {
// This will be very inefficient
// Have to 1) break idle, 2) query the server for uid
return false;
}
long id = getIdForUid(uid);
if (id == Message.NO_MESSAGE) {
// Nothing to do; log
userLog("? No message found for uid " + uid);
return true;
}
if (type.equals("fetch")) {
if (line.indexOf("\\deleted") > 0) {
processDelete(uid);
} else {
boolean read = line.indexOf("\\seen") > 0;
boolean flagged = line.indexOf("\\flagged") > 0;
// TODO: Reuse
ContentValues values = new ContentValues();
values.put(MessageColumns.FLAG_READ, read);
values.put(MessageColumns.FLAG_FAVORITE, flagged);
mResolver.update(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, id),
values, null, null);
}
userLog("<<< FLAGS " + uid);
} else {
userLog("<<< EXPUNGE " + uid);
processDelete(uid);
}
} else if (type.equals("exists")) {
int num = Integer.parseInt(m.group(2));
if (mIsGmail && (num == mLastExists)) {
userLog("Gmail: nothing new...");
return false;
}
else if (mIsGmail)
mLastExists = num;
res = true;
userLog("<<< EXISTS tag; new SEARCH");
}
}
return res;
}
/**
* Prepends the folder name with the given prefix and UTF-7 encodes it.
*/
private String encodeFolderName(String name) {
// do NOT add the prefix to the special name "INBOX"
if ("inbox".equalsIgnoreCase(name)) return name;
// Prepend prefix
if (mPrefix != null) {
name = mPrefix + name;
}
// TODO bypass the conversion if name doesn't have special char.
ByteBuffer bb = MODIFIED_UTF_7_CHARSET.encode(name);
byte[] b = new byte[bb.limit()];
bb.get(b);
return Utility.fromAscii(b);
}
/**
* UTF-7 decodes the folder name and removes the given path prefix.
*/
static String decodeFolderName(String name, String prefix) {
// TODO bypass the conversion if name doesn't have special char.
String folder;
folder = MODIFIED_UTF_7_CHARSET.decode(ByteBuffer.wrap(Utility.toAscii(name))).toString();
if ((prefix != null) && folder.startsWith(prefix)) {
folder = folder.substring(prefix.length());
}
return folder;
}
private Cursor getUpdatesCursor() {
Cursor c = mResolver.query(Message.UPDATED_CONTENT_URI, UPDATE_DELETE_PROJECTION,
MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null);
if (c == null || c.getCount() == 0) {
c.close();
return null;
}
return c;
}
private static final String[] UPDATE_DELETE_PROJECTION =
new String[] {MessageColumns.ID, SyncColumns.SERVER_ID, MessageColumns.MAILBOX_KEY,
MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE};
private static final int UPDATE_DELETE_ID_COLUMN = 0;
private static final int UPDATE_DELETE_SERVER_ID_COLUMN = 1;
private static final int UPDATE_DELETE_MAILBOX_KEY_COLUMN = 2;
private static final int UPDATE_DELETE_READ_COLUMN = 3;
private static final int UPDATE_DELETE_FAVORITE_COLUMN = 4;
private Cursor getDeletesCursor() {
Cursor c = mResolver.query(Message.DELETED_CONTENT_URI, UPDATE_DELETE_PROJECTION,
MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null);
if (c == null || c.getCount() == 0) {
c.close();
return null;
}
return c;
}
private void handleLocalDeletes() throws IOException {
Cursor c = getDeletesCursor();
if (c == null) return;
mDeletes.clear();
mDeletedIds.clear();
try {
while (c.moveToNext()) {
long id = c.getLong(UPDATE_DELETE_ID_COLUMN);
mDeletes.add(c.getInt(UPDATE_DELETE_SERVER_ID_COLUMN));
mDeletedIds.add(id);
}
sendUpdate(mDeletes, "+FLAGS (\\Deleted)");
String tag = writeCommand(mConnection.writer, "expunge");
readResponse(mConnection.reader, tag, "expunge");
// Delete the deletions now (we must go deeper!)
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
for (long id: mDeletedIds) {
ops.add(ContentProviderOperation.newDelete(
ContentUris.withAppendedId(
Message.DELETED_CONTENT_URI, id)).build());
}
applyBatch(ops);
} finally {
c.close();
}
}
private void handleLocalUpdates() throws IOException {
Cursor updatesCursor = getUpdatesCursor();
if (updatesCursor == null) return;
mUpdatedIds.clear();
mReadUpdates.clear();
mUnreadUpdates.clear();
mFlaggedUpdates.clear();
mUnflaggedUpdates.clear();
try {
while (updatesCursor.moveToNext()) {
long id = updatesCursor.getLong(UPDATE_DELETE_ID_COLUMN);
// Keep going if there's no serverId
int serverId = updatesCursor.getInt(UPDATE_DELETE_SERVER_ID_COLUMN);
if (serverId == 0) {
continue;
}
// Say we've handled this update
mUpdatedIds.add(id);
// We have the id of the changed item. But first, we have to find out its current
// state, since the updated table saves the opriginal state
Cursor currentCursor = mResolver.query(
ContentUris.withAppendedId(Message.CONTENT_URI, id),
UPDATE_DELETE_PROJECTION, null, null, null);
try {
// If this item no longer exists (shouldn't be possible), just move along
if (!currentCursor.moveToFirst()) {
continue;
}
boolean flagChange = false;
boolean readChange = false;
long mailboxId = currentCursor.getLong(UPDATE_DELETE_MAILBOX_KEY_COLUMN);
// If the message is now in the trash folder, it has been deleted by the user
if (mailboxId != updatesCursor.getLong(UPDATE_DELETE_MAILBOX_KEY_COLUMN)) {
// The message has been moved to another mailbox
Mailbox newMailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId);
if (newMailbox == null) {
continue;
}
copyMessage(serverId, newMailbox);
}
// We can only send flag changes to the server in 12.0 or later
int flag = currentCursor.getInt(UPDATE_DELETE_FAVORITE_COLUMN);
if (flag != updatesCursor.getInt(UPDATE_DELETE_FAVORITE_COLUMN)) {
flagChange = true;
}
int read = currentCursor.getInt(UPDATE_DELETE_READ_COLUMN);
if (read != updatesCursor.getInt(UPDATE_DELETE_READ_COLUMN)) {
readChange = true;
}
if (!flagChange && !readChange) {
// In this case, we've got nothing to send to the server
continue;
}
Integer update = serverId;
if (readChange) {
if (read == 1) {
mReadUpdates.add(update);
} else {
mUnreadUpdates.add(update);
}
}
if (flagChange) {
if (flag == 1) {
mFlaggedUpdates.add(update);
} else {
mUnflaggedUpdates.add(update);
}
}
} finally {
currentCursor.close();
}
}
} finally {
updatesCursor.close();
}
if (!mUpdatedIds.isEmpty()) {
sendUpdate(mReadUpdates, "+FLAGS (\\Seen)");
sendUpdate(mUnreadUpdates, "-FLAGS (\\Seen)");
sendUpdate(mFlaggedUpdates, "+FLAGS (\\Flagged)");
sendUpdate(mUnflaggedUpdates, "-FLAGS (\\Flagged)");
// Delete the updates now
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
for (Long id: mUpdatedIds) {
ops.add(ContentProviderOperation.newDelete(
ContentUris.withAppendedId(Message.UPDATED_CONTENT_URI, id)).build());
}
applyBatch(ops);
}
}
private void sendUpdate(Stack<Integer> updates, String command) throws IOException {
// First, generate the appropriate String
while (!updates.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < HEADER_BATCH_COUNT && !updates.empty(); i++) {
Integer update = updates.pop();
if (i != 0) {
sb.append(',');
}
sb.append(update);
}
String tag =
writeCommand(mConnection.writer, "uid store " + sb.toString() + " " + command);
if (!readResponse(mConnection.reader, tag, "STORE").equals(IMAP_OK)) {
errorLog("Server flag update failed?");
return;
}
}
}
private void copyMessage(int serverId, Mailbox mailbox) throws IOException {
String tag = writeCommand(mConnection.writer, "uid copy " + serverId + " \"" +
encodeFolderName(mailbox.mServerId) + "\"");
if (readResponse(mConnection.reader, tag, "COPY").equals(IMAP_OK)) {
tag = writeCommand(mConnection.writer, "uid store " + serverId + " +FLAGS(\\Deleted)");
if (readResponse(mConnection.reader, tag, "STORE").equals(IMAP_OK)) {
tag = writeCommand(mConnection.writer, "expunge");
readResponse(mConnection.reader, tag, "expunge");
}
} else {
errorLog("Server copy failed?");
}
}
private void saveNewMessages (ArrayList<Message> msgList) {
// Get the ids of updated messages in this mailbox (usually there won't be any)
Cursor c = getUpdatesCursor();
ArrayList<Integer> updatedIds = new ArrayList<Integer>();
boolean newUpdates = false;
if (c != null) {
try {
if (c.moveToFirst()) {
do {
updatedIds.add(c.getInt(UPDATE_DELETE_SERVER_ID_COLUMN));
newUpdates = true;
} while (c.moveToNext());
}
} finally {
c.close();
}
}
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
for (Message msg: msgList) {
// If the message is updated, make sure it's not deleted (we don't want to reload it)
if (newUpdates && updatedIds.contains(msg.mServerId)) {
Message currentMsg = Message.restoreMessageWithId(mContext, msg.mId);
if (currentMsg.mMailboxKey == mTrashMailboxId) {
userLog("PHEW! Didn't save deleted message with uid: " + msg.mServerId);
continue;
}
}
// Add the CPO's for this message
msg.addSaveOps(ops);
}
// Commit these messages
applyBatch(ops);
}
private String readTextPart (ImapInputStream in, String tag, Attachment att, boolean lastPart)
throws IOException {
String res = in.readLine();
int bstart = res.indexOf("body[");
if (bstart < 0)
bstart = res.indexOf("BODY[");
if (bstart < 0)
return "";
int bend = res.indexOf(']', bstart);
if (bend < 0)
return "";
//String charset = getCharset(thisLoc);
boolean qp = att.mEncoding.equalsIgnoreCase("quoted-printable");
int br = res.indexOf('{');
if (br > 0) {
Parser p = new Parser(res, br + 1);
int length = p.parseInteger();
int len = length;
byte[] buf = new byte[len];
int offs = 0;
while (len > 0) {
int rd = in.read(buf, offs, len);
offs += rd;
len -= rd;
}
if (qp) {
length = QuotedPrintable.decode(buf, length);
}
if (lastPart) {
String line = in.readLine();
if (!line.endsWith(")")) {
userLog("Bad text part?");
throw new IOException();
}
line = in.readLine();
if (!line.startsWith(tag)) {
userLog("Bad text part?");
throw new IOException();
}
}
return new String(buf, 0, length, Charset.forName("UTF8"));
} else {
return "";
}
}
private BodyThread mBodyThread;
private Connection mConnection;
private void parseBodystructure (Message msg, Parser p, String level, int cnt,
ArrayList<Attachment> viewables, ArrayList<Attachment> attachments) {
if (p.peekChar() == '(') {
// Multipart variant
while (true) {
String ps = p.parseList();
if (ps == null)
break;
parseBodystructure(msg,
new Parser(ps), level + ((level.length() > 0) ? '.' : "") + cnt, 1,
viewables, attachments);
cnt++;
}
// Multipart type (MIXED/ALTERNATIVE/RELATED)
String mp = p.parseString();
userLog("Multipart: " + mp);
} else {
boolean attachment = true;
String fileName = "";
// Here's an actual part...
// mime type
String type = p.parseString().toLowerCase();
// mime subtype
String sub = p.parseString().toLowerCase();
// parameter list or NIL
String paramList = p.parseList();
if (paramList == null)
p.parseAtom();
else {
Parser pp = new Parser(paramList);
String param;
while ((param = pp.parseString()) != null) {
String val = pp.parseString();
if (param.equalsIgnoreCase("name")) {
fileName = val;
} else if (param.equalsIgnoreCase("charset")) {
// TODO: Do we need to handle this?
}
}
}
// contentId
String contentId = p.parseString();
if (contentId != null) {
// Must remove the angle-bracket pair
contentId = contentId.substring(1, contentId.length() - 1);
fileName = "";
}
// contentName
p.parseString();
// encoding
String encoding = p.parseString().toLowerCase();
// length
Integer length = p.parseInteger();
String lvl = level.length() > 0 ? level : String.valueOf(cnt);
// body MD5
p.parseStringOrAtom();
// disposition
paramList = p.parseList();
if (paramList != null) {
//A parenthesized list, consisting of a disposition type
//string, followed by a parenthesized list of disposition
//attribute/value pairs as defined in [DISPOSITION].
Parser pp = new Parser(paramList);
String param;
while ((param = pp.parseString()) != null) {
String val = pp.parseString();
if (param.equalsIgnoreCase("name") || param.equalsIgnoreCase("filename")) {
fileName = val;
}
}
}
// Don't waste time with Microsoft foolishness
if (!sub.equals("ms-tnef")) {
Attachment att = new Attachment();
att.mLocation = lvl;
att.mMimeType = type + "/" + sub;
att.mSize = length;
att.mFileName = fileName;
att.mEncoding = encoding;
att.mContentId = contentId;
// TODO: charset?
if ((!type.startsWith("text")) && attachment) {
//msg.encoding |= Email.ENCODING_HAS_ATTACHMENTS;
attachments.add(att);
} else {
viewables.add(att);
}
userLog("Part " + lvl + ": " + type + "/" + sub);
}
}
}
private void fetchMessageData(Connection conn, Cursor c) throws IOException {
for (;;) {
try {
if (c == null) {
c = mResolver.query(Message.CONTENT_URI, Message.CONTENT_PROJECTION,
MessageColumns.FLAG_LOADED + "=" + Message.FLAG_LOADED_UNLOADED, null,
MessageColumns.TIMESTAMP + " desc");
if (c == null || c.getCount() == 0) {
return;
}
}
while (c.moveToNext()) {
// Parse the message's bodystructure
Message msg = new Message();
msg.restore(c);
ArrayList<Attachment> viewables = new ArrayList<Attachment>();
ArrayList<Attachment> attachments = new ArrayList<Attachment>();
parseBodystructure(msg, new Parser(msg.mSyncData), "", 1, viewables,
attachments);
ContentValues values = new ContentValues();
values.put(MessageColumns.FLAG_LOADED, Message.FLAG_LOADED_COMPLETE);
// Save the attachments...
for (Attachment att: attachments) {
att.mAccountKey = mAccountId;
att.mMessageKey = msg.mId;
att.save(mContext);
}
// Whether or not we have attachments
values.put(MessageColumns.FLAG_ATTACHMENT, !attachments.isEmpty());
// Get the viewables
Attachment textViewable = null;
for (Attachment viewable: viewables) {
String mimeType = viewable.mMimeType;
if ("text/html".equalsIgnoreCase(mimeType)) {
textViewable = viewable;
} else if ("text/plain".equalsIgnoreCase(mimeType) &&
textViewable == null) {
textViewable = viewable;
}
}
if (textViewable != null) {
// For now, just get single viewable
String tag = writeCommand(conn.writer,
"uid fetch " + msg.mServerId + " body.peek[" +
textViewable.mLocation + "]<0.200000>");
String text = readTextPart(conn.reader, tag, textViewable, true);
userLog("Viewable " + textViewable.mMimeType + ", len = " + text.length());
// Save it away
Body body = new Body();
if (textViewable.mMimeType.equalsIgnoreCase("text/html")) {
body.mHtmlContent = text;
} else {
body.mTextContent = text;
}
body.mMessageKey = msg.mId;
body.save(mContext);
values.put(MessageColumns.SNIPPET,
TextUtilities.makeSnippetFromHtmlText(text));
} else {
userLog("No viewable?");
values.putNull(MessageColumns.SNIPPET);
}
mResolver.update(ContentUris.withAppendedId(
Message.CONTENT_URI, msg.mId), values, null, null);
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
}
}
/**
* Class that loads message bodies in its own thread
*/
private class BodyThread extends Thread {
final Connection mConnection;
final Cursor mCursor;
BodyThread(Connection conn, Cursor cursor) {
super();
mConnection = conn;
mCursor = cursor;
}
public void run() {
try {
fetchMessageData(mConnection, mCursor);
} catch (IOException e) {
userLog("IOException in body thread; closing...");
} finally {
mConnection.close();
mBodyThread = null;
}
}
void close() {
mConnection.close();
}
}
private void fetchMessageData () throws IOException {
// If we're already loading messages on another thread, there's nothing to do
if (mBodyThread != null) {
return;
}
HostAuth hostAuth =
HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv);
if (hostAuth == null) return;
// Find messages to load, if any
final Cursor unloaded = mResolver.query(Message.CONTENT_URI, Message.CONTENT_PROJECTION,
MessageColumns.FLAG_LOADED + "=" + Message.FLAG_LOADED_UNLOADED, null,
MessageColumns.TIMESTAMP + " desc");
int cnt = unloaded.getCount();
// If there aren't any, we're done
if (cnt > 0) {
userLog("Found " + unloaded.getCount() + " messages requiring fetch");
// If we have more than one, try a second thread
// Some servers may not allow this, so we fall back to loading text on the main thread
if (cnt > 1) {
final Connection conn = connectAndLogin(hostAuth, "body");
if (conn.status == EXIT_DONE) {
mBodyThread = new BodyThread(conn, unloaded);
mBodyThread.start();
userLog("***** Starting mBodyThread " + mBodyThread.getId());
} else {
fetchMessageData(mConnection, unloaded);
}
} else {
fetchMessageData(mConnection, unloaded);
}
}
}
void readFolderList () throws IOException {
String tag = writeCommand(mWriter, "list \"\" *");
String line;
char dchar = '/';
userLog("Loading folder list...");
ArrayList<String> parentList = new ArrayList<String>();
ArrayList<Mailbox> mailboxList = new ArrayList<Mailbox>();
while (true) {
line = mReader.readLine();
userLog(line);
if (line.startsWith(tag)) {
// Done reading folder list
break;
} else {
Parser p = new Parser(line, 2);
String cmd = p.parseAtom();
if (cmd.equalsIgnoreCase("list")) {
@SuppressWarnings("unused")
String props = p.parseListOrNil();
String delim = p.parseString();
if (delim == null)
delim = "~";
if (delim.length() == 1)
dchar = delim.charAt(0);
String serverId = p.parseStringOrAtom();
int lastDelim = serverId.lastIndexOf(delim);
String displayName;
String parentName;
if (lastDelim > 0) {
displayName = serverId.substring(lastDelim + 1);
parentName = serverId.substring(0, lastDelim);
} else {
displayName = serverId;
parentName = null;
}
Mailbox m = new Mailbox();
- m.mDisplayName = displayName;
+ m.mDisplayName = decodeFolderName(displayName, null);
m.mAccountKey = mAccountId;
- m.mServerId = serverId;
+ m.mServerId = decodeFolderName(serverId, null);
if (parentName != null && !parentList.contains(parentName)) {
parentList.add(parentName);
}
m.mFlagVisible = true;
m.mParentServerId = parentName;
m.mDelimiter = dchar;
m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER;
mailboxList.add(m);
} else {
// WTF
}
}
}
// TODO: Use narrower projection
Cursor c = mResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
Mailbox.ACCOUNT_KEY + "=?", new String[] {Long.toString(mAccountId)},
MailboxColumns.SERVER_ID + " asc");
if (c == null) return;
int cnt = c.getCount();
String[] serverIds = new String[cnt];
long[] uidvals = new long[cnt];
long[] ids = new long[cnt];
int i = 0;
try {
if (c.moveToFirst()) {
// Get arrays of information about existing mailboxes in account
do {
serverIds[i] = c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN);
uidvals[i] = c.getLong(Mailbox.CONTENT_SYNC_KEY_COLUMN);
ids[i] = c.getLong(Mailbox.CONTENT_ID_COLUMN);
i++;
} while (c.moveToNext());
}
} finally {
c.close();
}
ArrayList<Mailbox> addList = new ArrayList<Mailbox>();
for (Mailbox m: mailboxList) {
int loc = Arrays.binarySearch(serverIds, m.mServerId);
if (loc >= 0) {
// It exists
if (uidvals[loc] == 0) {
// Good enough; a match that we've never visited!
// Mark this as touched (-1)...
uidvals[loc] = -1;
} else {
// Ok, now we need to see if this is the SAME mailbox...
// For now, assume it is; move on
// TODO: There's a problem if you've 1) visited this box and 2) another box now
// has its name, but how likely is that??
uidvals[loc] = -1;
}
} else {
// We don't know about this mailbox, so we'll add it...
// BUT must see if it's a rename of one we've visited!
addList.add(m);
}
}
// TODO: Flush this list every N (100?) in case there are zillions
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
try {
for (i = 0; i < cnt; i++) {
String name = serverIds[i];
long uidval = uidvals[i];
// -1 means matched; ignore
// 0 means unmatched and never before seen
// > 0 means unmatched and HAS been seen. must find mWriter why
// TODO: Get rid of "Outbox"
if (uidval == 0 && !name.equals("Outbox") &&
!name.equalsIgnoreCase(INBOX_SERVER_NAME)) {
// Ok, here's one we've never visited and it's not in the new list
ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(
Mailbox.CONTENT_URI, ids[i])).build());
userLog("Deleting unseen mailbox; no match: " + name);
} else if (uidval > 0 && !name.equalsIgnoreCase(INBOX_SERVER_NAME)) {
boolean found = false;
for (Mailbox m : addList) {
tag = writeCommand(mWriter, "status \"" + m.mServerId + "\" (UIDVALIDITY)");
if (readResponse(mReader, tag, "STATUS").equals(IMAP_OK)) {
String str = mImapResponse.get(0).toLowerCase();
int idx = str.indexOf("uidvalidity");
long num = readLong(str, idx + 12);
if (uidval == num) {
// try {
// // This is a renamed mailbox...
// c = Mailbox.getCursorWhere(mDatabase, "account=" + mAccount.id + " and serverName=?", name);
// if (c != null && c.moveToFirst()) {
// Mailbox existing = Mailbox.restoreFromCursor(c);
// userLog("Renaming existing mailbox: " + existing.mServerId + " to: " + m.mServerId);
// existing.mDisplayName = m.mDisplayName;
// existing.mServerId = m.mServerId;
// m.mHierarchicalName = m.mServerId;
// existing.mParentServerId = m.mParentServerId;
// existing.mFlags = m.mFlags;
// existing.save(mDatabase);
// // Mark this so that we don't save it below
// m.mServerId = null;
// }
// } finally {
// if (c != null) {
// c.close();
// }
// }
found = true;
break;
}
}
}
if (!found) {
// There's no current mailbox with this uidval, so delete.
ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(
Mailbox.CONTENT_URI, ids[i])).build());
userLog("Deleting uidval mailbox; no match: " + name);
}
}
}
for (Mailbox m : addList) {
String serverId = m.mServerId;
if (serverId == null)
continue;
if (!serverId.equalsIgnoreCase(INBOX_SERVER_NAME)
&& !serverId.equalsIgnoreCase("Outbox")) {
m.mHierarchicalName = m.mServerId;
//*** For now, use Mail. We need a way to select the others...
m.mType = Mailbox.TYPE_MAIL;
ops.add(ContentProviderOperation.newInsert(
Mailbox.CONTENT_URI).withValues(m.toContentValues()).build());
userLog("Adding new mailbox: " + m.mServerId);
}
}
applyBatch(ops);
// Fixup parent stuff, flags...
MailboxUtilities.fixupUninitializedParentKeys(mContext,
Mailbox.ACCOUNT_KEY + "=" + mAccountId);
} finally {
SyncManager.kick("folder list");
}
}
public int getDepth (String name, char delim) {
int depth = 0;
int last = -1;
while (true) {
last = name.indexOf(delim, last + 1);
if (last < 0)
return depth;
depth++;
}
}
private static final int BATCH_SIZE = 100;
private void applyBatch(ArrayList<ContentProviderOperation> ops) {
try {
int len = ops.size();
if (len == 0) {
return;
} else if (len < BATCH_SIZE) {
mResolver.applyBatch(EmailContent.AUTHORITY, ops);
} else {
ArrayList<ContentProviderOperation> batchOps =
new ArrayList<ContentProviderOperation>();
for (int i = 0; i < len; i+=BATCH_SIZE) {
batchOps.clear();
for (int j = 0; (j < BATCH_SIZE) && ((i+j) < len); j++) {
batchOps.add(ops.get(i+j));
}
mResolver.applyBatch(EmailContent.AUTHORITY, batchOps);
}
}
} catch (RemoteException e) {
// Nothing to be done
} catch (OperationApplicationException e) {
// These operations are legal; this can't really happen
}
}
private void processServerDeletes(ArrayList<Integer> deleteList) {
int cnt = deleteList.size();
if (cnt > 0) {
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
for (int i = 0; i < cnt; i++) {
MAILBOX_SERVER_ID_ARGS[1] = Long.toString(deleteList.get(i));
Builder b = ContentProviderOperation.newDelete(
Message.SELECTED_MESSAGE_CONTENT_URI);
b.withSelection(MessageColumns.MAILBOX_KEY + "=? AND " +
SyncColumns.SERVER_ID + "=?", MAILBOX_SERVER_ID_ARGS);
ops.add(b.build());
}
applyBatch(ops);
}
}
private void processIntegers(ArrayList<Integer> deleteList, ContentValues values) {
int cnt = deleteList.size();
if (cnt > 0) {
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
for (int i = 0; i < cnt; i++) {
MAILBOX_SERVER_ID_ARGS[1] = Long.toString(deleteList.get(i));
Builder b = ContentProviderOperation.newUpdate(
Message.SELECTED_MESSAGE_CONTENT_URI);
b.withSelection(MessageColumns.MAILBOX_KEY + "=? AND " +
SyncColumns.SERVER_ID + "=?", MAILBOX_SERVER_ID_ARGS);
b.withValues(values);
ops.add(b.build());
}
applyBatch(ops);
}
}
private static class Reconciled {
ArrayList<Integer> insert;
ArrayList<Integer> delete;
Reconciled (ArrayList<Integer> ins, ArrayList<Integer> del) {
insert = ins;
delete = del;
}
}
// Arrays must be sorted beforehand
public Reconciled reconcile (String name, int[] deviceList, int[] serverList) {
ArrayList<Integer> loadList = new ArrayList<Integer>();
ArrayList<Integer> deleteList = new ArrayList<Integer>();
int soff = 0;
int doff = 0;
int scnt = serverList.length;
int dcnt = deviceList.length;
while (scnt > 0 || dcnt > 0) {
if (scnt == 0) {
for (; dcnt > 0; dcnt--)
deleteList.add(deviceList[doff++]);
break;
} else if (dcnt == 0) {
for (; scnt > 0; scnt--)
loadList.add(serverList[soff++]);
break;
}
int s = serverList[soff++];
int d = deviceList[doff++];
scnt--;
dcnt--;
if (s == d) {
continue;
} else if (s > d) {
deleteList.add(d);
scnt++;
soff--;
} else if (d > s) {
loadList.add(s);
dcnt++;
doff--;
}
}
userLog("Reconciler " + name + "-> Insert: " + loadList.size() +
", Delete: " + deleteList.size());
return new Reconciled(loadList, deleteList);
}
private static final String[] UID_PROJECTION = new String[] {SyncColumns.SERVER_ID};
public int[] getUidList (String andClause) {
int offs = 0;
String ac = MessageColumns.MAILBOX_KEY + "=?";
if (andClause != null) {
ac = ac + andClause;
}
Cursor c = mResolver.query(Message.CONTENT_URI, UID_PROJECTION,
ac, new String[] {Long.toString(mMailboxId)}, SyncColumns.SERVER_ID);
if (c != null) {
try {
int[] uids = new int[c.getCount()];
if (c.moveToFirst()) {
do {
uids[offs++] = c.getInt(0);
} while (c.moveToNext());
return uids;
}
} finally {
c.close();
}
}
return new int[0];
}
public int[] getUnreadUidList () {
return getUidList(" and " + Message.FLAG_READ + "=0");
}
public int[] getFlaggedUidList () {
return getUidList(" and " + Message.FLAG_FAVORITE + "!=0");
}
private void reconcileState(int[] deviceList, String since, String flag, String search,
String column, boolean sense) throws IOException {
int[] serverList;
Parser p;
String msgs;
String tag = writeCommand(mWriter, "uid search undeleted " + search + " since " + since);
if (readResponse(mReader, tag, "SEARCH").equals(IMAP_OK)) {
if (mImapResponse.isEmpty()) {
serverList = new int[0];
} else {
msgs = mImapResponse.get(0);
p = new Parser(msgs, 8);
serverList = p.gatherInts();
Arrays.sort(serverList);
}
Reconciled r = reconcile(flag, deviceList, serverList);
ContentValues values = new ContentValues();
values.put(column, sense);
processIntegers(r.delete, values);
values.put(column, !sense);
processIntegers(r.insert, values);
}
}
private ArrayList<String> getTokens(String str) {
ArrayList<String> tokens = new ArrayList<String>();
Parser p = new Parser(str);
while(true) {
String capa = p.parseAtom();
if (capa == null) {
break;
}
tokens.add(capa);
}
return tokens;
}
/**
* Convenience class to hold state for a single IMAP connection
*/
public static class Connection {
Socket socket;
int status;
String reason;
ImapInputStream reader;
BufferedWriter writer;
void close() {
try {
socket.close();
} catch (IOException e) {
// It's all good
}
}
}
private String mUserAgent;
private Connection connectAndLogin(HostAuth hostAuth, String name) {
return connectAndLogin(hostAuth, name, null);
}
private Connection connectAndLogin(HostAuth hostAuth, String name, Socket tlsSocket) {
Connection conn = new Connection();
Socket socket;
try {
if (tlsSocket != null) {
// Start secure connection on top of existing one
boolean trust = (hostAuth.mFlags & HostAuth.FLAG_TRUST_ALL) != 0;
socket = SSLUtils.getSSLSocketFactory(mContext, hostAuth, trust)
.createSocket(tlsSocket, hostAuth.mAddress, hostAuth.mPort, true);
} else {
socket = getSocket(hostAuth);
}
socket.setSoTimeout(SOCKET_TIMEOUT);
userLog(">>> IMAP CONNECTION SUCCESSFUL: " + name +
((socket != null) ? " [STARTTLS]" : ""));
ImapInputStream reader = new ImapInputStream(socket.getInputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
// Get welcome string
if (tlsSocket == null) {
reader.readLine();
}
String tag = writeCommand(writer, "CAPABILITY");
if (readResponse(reader, tag, "CAPABILITY").equals(IMAP_OK)) {
// If CAPABILITY
if (!mImapResponse.isEmpty()) {
String capa = mImapResponse.get(0).toLowerCase();
ArrayList<String> tokens = getTokens(capa);
if (tokens.contains("starttls") && tlsSocket == null &&
((hostAuth.mFlags & HostAuth.FLAG_SSL) == 0)) {
userLog("[Use STARTTLS]");
tag = writeCommand(writer, "STARTTLS");
readResponse(reader, tag, "STARTTLS");
return connectAndLogin(hostAuth, name, socket);
}
if (tokens.contains("id")) {
String hostAddress = hostAuth.mAddress;
// Never send ID to *.secureserver.net
// Hackish, yes, but we've been doing this for years... :-(
if (!hostAddress.toLowerCase().endsWith(".secureserver.net")) {
// Assign user-agent string (for RFC2971 ID command)
if (mUserAgent == null) {
mUserAgent = ImapId.getImapId(mContext, hostAuth.mLogin,
hostAddress, null);
}
tag = writeCommand(writer, "ID (" + mUserAgent + ")");
// We learn nothing useful from the response
readResponse(reader, tag);
}
}
}
}
tag = writeCommand(writer,
"login " + hostAuth.mLogin + ' ' + hostAuth.mPassword);
if (!IMAP_OK.equals(readResponse(reader, tag))) {
if (IMAP_NO.equals(mImapResult)) {
int alertPos = mImapErrorLine.indexOf("[ALERT]");
if (alertPos > 0) {
conn.reason = mImapErrorLine.substring(alertPos + 7);
}
}
conn.status = EXIT_LOGIN_FAILURE;
} else {
conn.socket = socket;
conn.reader = reader;
conn.writer = writer;
conn.status = EXIT_DONE;
userLog(">>> LOGGED IN: " + name);
if (mMailboxName != null) {
tag = writeCommand(conn.writer, "select \"" + encodeFolderName(mMailboxName) +
'\"');
if (!readResponse(conn.reader, tag).equals(IMAP_OK)) {
// Select failed
userLog("Select failed?");
conn.status = EXIT_EXCEPTION;
} else {
userLog(">>> SELECTED");
}
}
}
} catch (CertificateValidationException e) {
conn.status = EXIT_LOGIN_FAILURE;
} catch (IOException e) {
conn.status = EXIT_IO_ERROR;
}
return conn;
}
private void setMailboxSyncStatus(long id, int status) {
ContentValues values = new ContentValues();
values.put(Mailbox.UI_SYNC_STATUS, status);
// Make sure we're always showing a "success" value. A failure wouldn't get set here, but
// rather via SyncService.done()
values.put(Mailbox.UI_LAST_SYNC_RESULT, Mailbox.LAST_SYNC_RESULT_SUCCESS);
mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, id), values, null, null);
}
/**
* Reset the sync interval for this mailbox (account if it's Inbox)
*/
private void resetSyncInterval(int minutes) {
ContentValues values = new ContentValues();
Uri uri;
if (mMailbox.mType == Mailbox.TYPE_INBOX) {
values.put(AccountColumns.SYNC_INTERVAL, minutes);
uri = ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId);
} else {
values.put(MailboxColumns.SYNC_INTERVAL, minutes);
uri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailboxId);
}
// Reset this so that we won't loop
mMailbox.mSyncInterval = minutes;
// Update the mailbox/account with new sync interval
mResolver.update(uri, values, null, null);
}
private void idle() throws IOException {
mIsIdle = true;
mThread.setName(mMailboxName + ":IDLE[" + mAccount.mDisplayName + "]");
userLog("Entering idle...");
String tag = writeCommand(mWriter, "idle");
try {
while (true) {
String resp = mReader.readLine();
if (resp.startsWith("+"))
break;
// Remember to handle untagged responses here (sigh, and elsewhere)
if (resp.startsWith("* "))
handleUntagged(resp);
else {
userLog("Error in IDLE response: " + resp);
if (resp.contains(IMAP_BAD)) {
// Fatal error (server doesn't support this command)
userLog("IDLE not supported; falling back to scheduled sync");
resetSyncInterval(IDLE_FALLBACK_SYNC_INTERVAL);
}
return;
}
}
// Server has accepted IDLE
long idleStartTime = System.currentTimeMillis();
// Let the socket time out a minute after we expect to terminate it ourselves
mSocket.setSoTimeout(IDLE_ASLEEP_MILLIS + (1*MINS));
// Say we're no longer syncing (turn off indeterminate progress in the UI)
setMailboxSyncStatus(mMailboxId, UIProvider.SyncStatus.NO_SYNC);
// Set an alarm for one minute before our timeout our expected IDLE time
Imap2SyncManager.runAsleep(mMailboxId, IDLE_ASLEEP_MILLIS);
while (true) {
String line = null;
try {
line = mReader.readLine();
userLog(line);
} catch (SocketTimeoutException e) {
userLog("Socket timeout");
} finally {
Imap2SyncManager.runAwake(mMailboxId);
// Say we're syncing again
setMailboxSyncStatus(mMailboxId, UIProvider.SyncStatus.BACKGROUND_SYNC);
}
if (line == null || line.startsWith("* ")) {
boolean finish = (line == null) ? true : handleUntagged(line);
if (!finish) {
long timeSinceIdle =
System.currentTimeMillis() - idleStartTime;
// If we're nearing the end of IDLE time, let's just reset the IDLE while
// we've got the processor awake
if (timeSinceIdle > IDLE_ASLEEP_MILLIS - (2*MINS)) {
userLog("Time to reset IDLE...");
finish = true;
}
}
if (finish) {
mWriter.write("DONE\r\n");
mWriter.flush();
}
} else if (line.startsWith(tag)) {
Parser p = new Parser(line, tag.length() - 1);
mImapResult = p.parseAtom();
mIsIdle = false;
break;
}
}
} finally {
// We might have left IDLE due to an exception
if (mSocket != null) {
// Reset the standard timeout
mSocket.setSoTimeout(SOCKET_TIMEOUT);
}
mIsIdle = false;
mThread.setName(mMailboxName + "[" + mAccount.mDisplayName + "]");
}
}
private void doUpload(long messageId, String mailboxServerId) throws IOException,
MessagingException {
ContentValues values = new ContentValues();
CountingOutputStream out = new CountingOutputStream();
EOLConvertingOutputStream eolOut = new EOLConvertingOutputStream(out);
Rfc822Output.writeTo(mContext,
messageId,
eolOut,
false /* do not use smart reply */,
false /* do not send BCC */);
eolOut.flush();
long len = out.getCount();
try {
String tag = writeCommand(mWriter, "append \"" +
encodeFolderName(mailboxServerId) +
"\" (\\seen) {" + len + '}');
String line = mReader.readLine();
if (line.startsWith("+")) {
userLog("append response: " + line);
eolOut = new EOLConvertingOutputStream(mSocket.getOutputStream());
Rfc822Output.writeTo(mContext,
messageId,
eolOut,
false /* do not use smart reply */,
false /* do not send BCC */);
eolOut.flush();
mWriter.write("\r\n");
mWriter.flush();
if (readResponse(mConnection.reader, tag).equals(IMAP_OK)) {
int serverId = 0;
String lc = mImapSuccessLine.toLowerCase();
int appendUid = lc.indexOf("appenduid");
if (appendUid > 0) {
Parser p = new Parser(lc, appendUid + 11);
// UIDVALIDITY (we don't need it)
p.parseInteger();
serverId = p.parseInteger();
}
values.put(SyncColumns.SERVER_ID, serverId);
mResolver.update(ContentUris.withAppendedId(Message.CONTENT_URI,
messageId), values, null, null);
} else {
userLog("Append failed: " + mImapErrorLine);
}
} else {
userLog("Append failed: " + line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void processUploads() {
Mailbox sentMailbox = Mailbox.restoreMailboxOfType(mContext, mAccountId, Mailbox.TYPE_SENT);
if (sentMailbox == null) {
// Nothing to do this time around; we'll check each time through the sync loop
return;
}
Cursor c = mResolver.query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION,
MessageColumns.MAILBOX_KEY + "=? AND " + SyncColumns.SERVER_ID + " is null",
new String[] {Long.toString(sentMailbox.mId)}, null);
if (c != null) {
String sentMailboxServerId = sentMailbox.mServerId;
try {
// Upload these messages
while (c.moveToNext()) {
try {
doUpload(c.getLong(Message.ID_COLUMNS_ID_COLUMN), sentMailboxServerId);
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
} finally {
c.close();
}
}
}
private int[] getServerIds(String since) throws IOException {
String tag = writeCommand(mWriter, "uid search undeleted since " + since);
if (!readResponse(mReader, tag, "SEARCH").equals(IMAP_OK)) {
userLog("$$$ WHOA! Search failed? ");
return null;
}
userLog(">>> SEARCH RESULT");
String msgs;
Parser p;
if (mImapResponse.isEmpty()) {
return new int[0];
} else {
msgs = mImapResponse.get(0);
// Length of "* search"
p = new Parser(msgs, 8);
return p.gatherInts();
}
}
static private final int[] AUTO_WINDOW_VALUES = new int[] {
SyncWindow.SYNC_WINDOW_ALL, SyncWindow.SYNC_WINDOW_1_MONTH, SyncWindow.SYNC_WINDOW_2_WEEKS,
SyncWindow.SYNC_WINDOW_1_WEEK, SyncWindow.SYNC_WINDOW_3_DAYS};
/**
* Determine a sync window for this mailbox by trying different possibilities from among the
* allowed values (in AUTO_WINDOW_VALUES). We start testing with "all" unless there are more
* than AUTOMATIC_SYNC_WINDOW_LARGE_MAILBOX messages (we really don't want to load that many);
* otherwise, we start with one month. We'll pick any value that has fewer than
* AUTOMATIC_SYNC_WINDOW_MAX_MESSAGES messages (arbitrary, but reasonable)
* @return a reasonable sync window for this mailbox
* @throws IOException
*/
private int getAutoSyncWindow() throws IOException {
int i = (mLastExists > AUTOMATIC_SYNC_WINDOW_LARGE_MAILBOX) ? 1 : 0;
for (; i < AUTO_WINDOW_VALUES.length; i++) {
int window = AUTO_WINDOW_VALUES[i];
long days = SyncWindow.toDays(window);
Date date = new Date(System.currentTimeMillis() - (days*DAYS));
String since = IMAP_DATE_FORMAT.format(date);
int msgCount = getServerIds(since).length;
if (msgCount < AUTOMATIC_SYNC_WINDOW_MAX_MESSAGES) {
userLog("getAutoSyncWindow returns " + days + " days.");
return window;
}
}
userLog("getAutoSyncWindow returns 1 day.");
return SyncWindow.SYNC_WINDOW_1_DAY;
}
/**
* Process our list of requested attachment loads
* @throws IOException
*/
private void processRequests() throws IOException {
while (!mRequestQueue.isEmpty()) {
Request req = mRequestQueue.peek();
// Our two request types are PartRequest (loading attachment) and
// MeetingResponseRequest (respond to a meeting request)
if (req instanceof PartRequest) {
TrafficStats.setThreadStatsTag(
TrafficFlags.getAttachmentFlags(mContext, mAccount));
new AttachmentLoader(this,
(PartRequest)req).loadAttachment(mConnection);
TrafficStats.setThreadStatsTag(
TrafficFlags.getSyncFlags(mContext, mAccount));
}
// If there's an exception handling the request, we'll throw it
// Otherwise, we remove the request
mRequestQueue.remove();
}
}
private void loadMessages(ArrayList<Integer> loadList, long mailboxId) throws IOException {
int idx= 1;
boolean loadedSome = false;
int cnt = loadList.size();
while (idx <= cnt) {
ArrayList<Message> tmsgList = new ArrayList<Message> ();
int tcnt = 0;
StringBuilder tsb = new StringBuilder("uid fetch ");
for (tcnt = 0; tcnt < HEADER_BATCH_COUNT && idx <= cnt; tcnt++, idx++) {
// Load most recent first
if (tcnt > 0)
tsb.append(',');
tsb.append(loadList.get(cnt - idx));
}
tsb.append(" (uid internaldate flags envelope bodystructure)");
String tag = writeCommand(mWriter, tsb.toString());
if (readResponse(mReader, tag, "FETCH").equals(IMAP_OK)) {
// Create message and store
for (int j = 0; j < tcnt; j++) {
Message msg = createMessage(mImapResponse.get(j), mailboxId);
tmsgList.add(msg);
}
saveNewMessages(tmsgList);
}
fetchMessageData();
loadedSome = true;
}
// TODO: Use loader to watch for changes on unloaded body cursor
if (!loadedSome) {
fetchMessageData();
}
}
private void sync () throws IOException {
mThread = Thread.currentThread();
HostAuth hostAuth =
HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv);
if (hostAuth == null) return;
Connection conn = connectAndLogin(hostAuth, "main");
if (conn.status != EXIT_DONE) {
mExitStatus = conn.status;
mExitReason = conn.reason;
return;
}
setConnection(conn);
// The account might have changed!!
//*** Determine how to often to do this
if (mMailboxName.equalsIgnoreCase("inbox")) {
long startTime = System.currentTimeMillis();
readFolderList();
userLog("Folder list processed in " + (System.currentTimeMillis() - startTime) +
"ms");
}
while (!mStop) {
try {
while (!mStop) {
mIsServiceRequestPending = false;
// Now, handle various requests
processRequests();
// We'll use 14 days as the "default"
long days = 14;
int lookback = mMailbox.mSyncLookback;
if (mMailbox.mType == Mailbox.TYPE_INBOX) {
lookback = mAccount.mSyncLookback;
}
if (lookback == SyncWindow.SYNC_WINDOW_AUTO) {
if (mLastExists >= 0) {
ContentValues values = new ContentValues();
lookback = getAutoSyncWindow();
Uri uri;
if (mMailbox.mType == Mailbox.TYPE_INBOX) {
values.put(AccountColumns.SYNC_LOOKBACK, lookback);
uri = ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId);
} else {
values.put(MailboxColumns.SYNC_LOOKBACK, lookback);
uri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailboxId);
}
mResolver.update(uri, values, null, null);
}
}
if (lookback != SyncWindow.SYNC_WINDOW_UNKNOWN) {
days = SyncWindow.toDays(lookback);
}
Date date = new Date(System.currentTimeMillis() - (days*DAYS));
String since = IMAP_DATE_FORMAT.format(date);
int[] serverList = getServerIds(since);
if (serverList == null) {
// Do backoff; hope it works next time. Should never happen
mExitStatus = EXIT_IO_ERROR;
return;
}
Arrays.sort(serverList);
int[] deviceList = getUidList(null);
Reconciled r =
reconcile("MESSAGES", deviceList, serverList);
ArrayList<Integer> loadList = r.insert;
ArrayList<Integer> deleteList = r.delete;
serverList = null;
deviceList = null;
// We load message headers in batches
loadMessages(loadList, mMailboxId);
// Reflect server deletions on device; do them all at once
processServerDeletes(deleteList);
handleLocalUpdates();
handleLocalDeletes();
reconcileState(getUnreadUidList(), since, "UNREAD", "unseen",
MessageColumns.FLAG_READ, true);
reconcileState(getFlaggedUidList(), since, "FLAGGED", "flagged",
MessageColumns.FLAG_FAVORITE, false);
processUploads();
// We're done if not pushing...
if (mMailbox.mSyncInterval != Mailbox.CHECK_INTERVAL_PUSH) {
mExitStatus = EXIT_DONE;
return;
}
// If new requests have come in, process them
if (mIsServiceRequestPending)
continue;
idle();
}
} finally {
if (mConnection != null) {
try {
// Try to logout
readResponse(mReader, writeCommand(mWriter, "logout"));
mConnection.close();
} catch (IOException e) {
// We're leaving anyway
}
}
}
}
}
private void sendMail() {
long sentMailboxId = Mailbox.findMailboxOfType(mContext, mAccountId, Mailbox.TYPE_SENT);
if (sentMailboxId == Mailbox.NO_MAILBOX) {
// The user must choose a sent mailbox
mResolver.update(
ContentUris.withAppendedId(EmailContent.PICK_SENT_FOLDER_URI, mAccountId),
new ContentValues(), null, null);
}
Account account = Account.restoreAccountWithId(mContext, mAccountId);
if (account == null) {
return;
}
TrafficStats.setThreadStatsTag(TrafficFlags.getSmtpFlags(mContext, account));
// 1. Loop through all messages in the account's outbox
long outboxId = Mailbox.findMailboxOfType(mContext, account.mId, Mailbox.TYPE_OUTBOX);
if (outboxId == Mailbox.NO_MAILBOX) {
return;
}
Cursor c = mResolver.query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION,
Message.MAILBOX_KEY + "=?", new String[] { Long.toString(outboxId) }, null);
ContentValues values = new ContentValues();
values.put(MessageColumns.MAILBOX_KEY, sentMailboxId);
try {
// 2. exit early
if (c.getCount() <= 0) {
return;
}
SmtpSender sender = new SmtpSender(mContext, account, mUserLog);
// 3. loop through the available messages and send them
while (c.moveToNext()) {
long messageId = -1;
try {
messageId = c.getLong(Message.ID_COLUMNS_ID_COLUMN);
// Don't send messages with unloaded attachments
if (Utility.hasUnloadedAttachments(mContext, messageId)) {
userLog("Can't send #" + messageId + "; unloaded attachments");
continue;
}
sender.sendMessage(messageId);
// Move to sent folder
mResolver.update(ContentUris.withAppendedId(Message.CONTENT_URI, messageId),
values, null, null);
} catch (MessagingException me) {
continue;
}
}
} finally {
c.close();
}
}
@Override
public void run() {
try {
TAG = Thread.currentThread().getName();
// Check for Outbox (special "sync") and stopped
if (mMailbox.mType == Mailbox.TYPE_OUTBOX) {
sendMail();
mExitStatus = EXIT_DONE;
return;
} else if (mStop) {
return;
}
if ((mMailbox == null) || (mAccount == null)) {
return;
} else {
int trafficFlags = TrafficFlags.getSyncFlags(mContext, mAccount);
TrafficStats.setThreadStatsTag(trafficFlags | TrafficFlags.DATA_EMAIL);
// We loop because someone might have put a request in while we were syncing
// and we've missed that opportunity...
do {
if (mRequestTime != 0) {
userLog("Looping for user request...");
mRequestTime = 0;
}
if (mSyncReason >= Imap2SyncManager.SYNC_CALLBACK_START) {
try {
Imap2SyncManager.callback().syncMailboxStatus(mMailboxId,
EmailServiceStatus.IN_PROGRESS, 0);
} catch (RemoteException e1) {
// Don't care if this fails
}
}
sync();
} while (mRequestTime != 0);
}
} catch (IOException e) {
String message = e.getMessage();
userLog("Caught IOException: ", (message == null) ? "No message" : message);
mExitStatus = EXIT_IO_ERROR;
} catch (Exception e) {
userLog("Uncaught exception in Imap2SyncService", e);
} finally {
int status;
Imap2SyncManager.done(this);
if (!mStop) {
userLog("Sync finished");
switch (mExitStatus) {
case EXIT_IO_ERROR:
status = EmailServiceStatus.CONNECTION_ERROR;
break;
case EXIT_DONE:
status = EmailServiceStatus.SUCCESS;
ContentValues cv = new ContentValues();
cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis());
String s = "S" + mSyncReason + ':' + status + ':' + mChangeCount;
cv.put(Mailbox.SYNC_STATUS, s);
mContext.getContentResolver().update(
ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailboxId),
cv, null, null);
break;
case EXIT_LOGIN_FAILURE:
status = EmailServiceStatus.LOGIN_FAILED;
break;
default:
status = EmailServiceStatus.REMOTE_EXCEPTION;
errorLog("Sync ended due to an exception.");
break;
}
} else {
userLog("Stopped sync finished.");
status = EmailServiceStatus.SUCCESS;
}
// Send a callback (doesn't matter how the sync was started)
try {
// Unless the user specifically asked for a sync, we don't want to report
// connection issues, as they are likely to be transient. In this case, we
// simply report success, so that the progress indicator terminates without
// putting up an error banner
//***
if (mSyncReason != Imap2SyncManager.SYNC_UI_REQUEST &&
status == EmailServiceStatus.CONNECTION_ERROR) {
status = EmailServiceStatus.SUCCESS;
}
Imap2SyncManager.callback().syncMailboxStatus(mMailboxId, status, 0);
} catch (RemoteException e1) {
// Don't care if this fails
}
// Make sure we close our body thread (if any)
if (mBodyThread != null) {
mBodyThread.close();
}
// Make sure ExchangeService knows about this
Imap2SyncManager.kick("sync finished");
}
}
private Socket getSocket(HostAuth hostAuth) throws CertificateValidationException, IOException {
Socket socket;
try {
boolean ssl = (hostAuth.mFlags & HostAuth.FLAG_SSL) != 0;
boolean trust = (hostAuth.mFlags & HostAuth.FLAG_TRUST_ALL) != 0;
SocketAddress socketAddress = new InetSocketAddress(hostAuth.mAddress, hostAuth.mPort);
if (ssl) {
socket = SSLUtils.getSSLSocketFactory(mContext, hostAuth, trust).createSocket();
} else {
socket = new Socket();
}
socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
// After the socket connects to an SSL server, confirm that the hostname is as expected
if (ssl && !trust) {
verifyHostname(socket, hostAuth.mAddress);
}
} catch (SSLException e) {
errorLog(e.toString());
throw new CertificateValidationException(e.getMessage(), e);
}
return socket;
}
/**
* Lightweight version of SSLCertificateSocketFactory.verifyHostname, which provides this
* service but is not in the public API.
*
* Verify the hostname of the certificate used by the other end of a
* connected socket. You MUST call this if you did not supply a hostname
* to SSLCertificateSocketFactory.createSocket(). It is harmless to call this method
* redundantly if the hostname has already been verified.
*
* <p>Wildcard certificates are allowed to verify any matching hostname,
* so "foo.bar.example.com" is verified if the peer has a certificate
* for "*.example.com".
*
* @param socket An SSL socket which has been connected to a server
* @param hostname The expected hostname of the remote server
* @throws IOException if something goes wrong handshaking with the server
* @throws SSLPeerUnverifiedException if the server cannot prove its identity
*/
private void verifyHostname(Socket socket, String hostname) throws IOException {
// The code at the start of OpenSSLSocketImpl.startHandshake()
// ensures that the call is idempotent, so we can safely call it.
SSLSocket ssl = (SSLSocket) socket;
ssl.startHandshake();
SSLSession session = ssl.getSession();
if (session == null) {
throw new SSLException("Cannot verify SSL socket without session");
}
// TODO: Instead of reporting the name of the server we think we're connecting to,
// we should be reporting the bad name in the certificate. Unfortunately this is buried
// in the verifier code and is not available in the verifier API, and extracting the
// CN & alts is beyond the scope of this patch.
if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)) {
throw new SSLPeerUnverifiedException(
"Certificate hostname not useable for server: " + hostname);
}
}
/**
* Cache search results by account; this allows for "load more" support without having to
* redo the search (which can be quite slow).
*/
private static final HashMap<Long, Integer[]> sSearchResults = new HashMap<Long, Integer[]>();
@VisibleForTesting
protected static boolean isAsciiString(String str) {
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c >= 128) return false;
}
return true;
}
/**
* Wrapper for a search result with possible exception (to be sent back to the UI)
*/
private static class SearchResult {
Integer[] uids;
Exception exception;
SearchResult(Integer[] _uids, Exception _exception) {
uids = _uids;
exception = _exception;
}
}
private SearchResult getSearchResults(SearchParams searchParams) {
String filter = searchParams.mFilter;
// All servers MUST accept US-ASCII, so we'll send this as the CHARSET unless we're really
// dealing with a string that contains non-ascii characters
String charset = "US-ASCII";
if (!isAsciiString(filter)) {
charset = "UTF-8";
}
List<String> commands = new ArrayList<String>();
// This is the length of the string in octets (bytes), formatted as a string literal {n}
String octetLength = "{" + filter.getBytes().length + "}";
// Break the command up into pieces ending with the string literal length
commands.add("UID SEARCH CHARSET " + charset + " OR FROM " + octetLength);
commands.add(filter + " (OR TO " + octetLength);
commands.add(filter + " (OR CC " + octetLength);
commands.add(filter + " (OR SUBJECT " + octetLength);
commands.add(filter + " BODY " + octetLength);
commands.add(filter + ")))");
Exception exception = null;
try {
int len = commands.size();
String tag = null;
for (int i = 0; i < len; i++) {
String command = commands.get(i);
if (i == 0) {
mSocket.setSoTimeout(SEARCH_TIMEOUT);
tag = writeCommand(mWriter, command);
} else {
writeContinuation(mWriter, command);
}
if (readResponse(mReader, tag, "SEARCH").equals(IMAP_OK)) {
// Done
String msgs = mImapResponse.get(0);
Parser p = new Parser(msgs, 8);
Integer[] serverList = p.gatherIntegers();
Arrays.sort(serverList, Collections.reverseOrder());
return new SearchResult(serverList, null);
} else if (mImapResult.startsWith("+")){
continue;
} else {
errorLog("Server doesn't understand complex SEARCH?");
break;
}
}
} catch (SocketTimeoutException e) {
exception = e;
errorLog("Search timed out");
} catch (IOException e) {
exception = e;
errorLog("Search IOException");
}
return new SearchResult(new Integer[0], exception);
}
public int searchMailbox(final Context context, long accountId, SearchParams searchParams,
final long destMailboxId) throws IOException {
final Account account = Account.restoreAccountWithId(context, accountId);
final Mailbox mailbox = Mailbox.restoreMailboxWithId(context, searchParams.mMailboxId);
final Mailbox destMailbox = Mailbox.restoreMailboxWithId(context, destMailboxId);
if (account == null || mailbox == null || destMailbox == null) {
Log.d(Logging.LOG_TAG, "Attempted search for " + searchParams
+ " but account or mailbox information was missing");
return 0;
}
HostAuth hostAuth = HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv);
if (hostAuth == null) {
}
Connection conn = connectAndLogin(hostAuth, "search");
if (conn.status != EXIT_DONE) {
mExitStatus = conn.status;
return 0;
}
try {
setConnection(conn);
Integer[] sortedUids = null;
if (searchParams.mOffset == 0) {
SearchResult result = getSearchResults(searchParams);
if (result.exception == null) {
sortedUids = result.uids;
sSearchResults.put(accountId, sortedUids);
} else {
throw new IOException();
}
} else {
sortedUids = sSearchResults.get(accountId);
}
final int numSearchResults = sortedUids.length;
final int numToLoad =
Math.min(numSearchResults - searchParams.mOffset, searchParams.mLimit);
if (numToLoad <= 0) {
return 0;
}
final ArrayList<Integer> loadList = new ArrayList<Integer>();
for (int i = searchParams.mOffset; i < numToLoad + searchParams.mOffset; i++) {
loadList.add(sortedUids[i]);
}
try {
loadMessages(loadList, destMailboxId);
} catch (IOException e) {
// TODO: How do we handle this?
return 0;
}
return sortedUids.length;
} finally {
if (mSocket != null) {
try {
// Try to logout
readResponse(mReader, writeCommand(mWriter, "logout"));
mSocket.close();
} catch (IOException e) {
// We're leaving anyway
}
}
}
}
}
| false | true | void readFolderList () throws IOException {
String tag = writeCommand(mWriter, "list \"\" *");
String line;
char dchar = '/';
userLog("Loading folder list...");
ArrayList<String> parentList = new ArrayList<String>();
ArrayList<Mailbox> mailboxList = new ArrayList<Mailbox>();
while (true) {
line = mReader.readLine();
userLog(line);
if (line.startsWith(tag)) {
// Done reading folder list
break;
} else {
Parser p = new Parser(line, 2);
String cmd = p.parseAtom();
if (cmd.equalsIgnoreCase("list")) {
@SuppressWarnings("unused")
String props = p.parseListOrNil();
String delim = p.parseString();
if (delim == null)
delim = "~";
if (delim.length() == 1)
dchar = delim.charAt(0);
String serverId = p.parseStringOrAtom();
int lastDelim = serverId.lastIndexOf(delim);
String displayName;
String parentName;
if (lastDelim > 0) {
displayName = serverId.substring(lastDelim + 1);
parentName = serverId.substring(0, lastDelim);
} else {
displayName = serverId;
parentName = null;
}
Mailbox m = new Mailbox();
m.mDisplayName = displayName;
m.mAccountKey = mAccountId;
m.mServerId = serverId;
if (parentName != null && !parentList.contains(parentName)) {
parentList.add(parentName);
}
m.mFlagVisible = true;
m.mParentServerId = parentName;
m.mDelimiter = dchar;
m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER;
mailboxList.add(m);
} else {
// WTF
}
}
}
// TODO: Use narrower projection
Cursor c = mResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
Mailbox.ACCOUNT_KEY + "=?", new String[] {Long.toString(mAccountId)},
MailboxColumns.SERVER_ID + " asc");
if (c == null) return;
int cnt = c.getCount();
String[] serverIds = new String[cnt];
long[] uidvals = new long[cnt];
long[] ids = new long[cnt];
int i = 0;
try {
if (c.moveToFirst()) {
// Get arrays of information about existing mailboxes in account
do {
serverIds[i] = c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN);
uidvals[i] = c.getLong(Mailbox.CONTENT_SYNC_KEY_COLUMN);
ids[i] = c.getLong(Mailbox.CONTENT_ID_COLUMN);
i++;
} while (c.moveToNext());
}
} finally {
c.close();
}
ArrayList<Mailbox> addList = new ArrayList<Mailbox>();
for (Mailbox m: mailboxList) {
int loc = Arrays.binarySearch(serverIds, m.mServerId);
if (loc >= 0) {
// It exists
if (uidvals[loc] == 0) {
// Good enough; a match that we've never visited!
// Mark this as touched (-1)...
uidvals[loc] = -1;
} else {
// Ok, now we need to see if this is the SAME mailbox...
// For now, assume it is; move on
// TODO: There's a problem if you've 1) visited this box and 2) another box now
// has its name, but how likely is that??
uidvals[loc] = -1;
}
} else {
// We don't know about this mailbox, so we'll add it...
// BUT must see if it's a rename of one we've visited!
addList.add(m);
}
}
// TODO: Flush this list every N (100?) in case there are zillions
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
try {
for (i = 0; i < cnt; i++) {
String name = serverIds[i];
long uidval = uidvals[i];
// -1 means matched; ignore
// 0 means unmatched and never before seen
// > 0 means unmatched and HAS been seen. must find mWriter why
// TODO: Get rid of "Outbox"
if (uidval == 0 && !name.equals("Outbox") &&
!name.equalsIgnoreCase(INBOX_SERVER_NAME)) {
// Ok, here's one we've never visited and it's not in the new list
ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(
Mailbox.CONTENT_URI, ids[i])).build());
userLog("Deleting unseen mailbox; no match: " + name);
} else if (uidval > 0 && !name.equalsIgnoreCase(INBOX_SERVER_NAME)) {
boolean found = false;
for (Mailbox m : addList) {
tag = writeCommand(mWriter, "status \"" + m.mServerId + "\" (UIDVALIDITY)");
if (readResponse(mReader, tag, "STATUS").equals(IMAP_OK)) {
String str = mImapResponse.get(0).toLowerCase();
int idx = str.indexOf("uidvalidity");
long num = readLong(str, idx + 12);
if (uidval == num) {
// try {
// // This is a renamed mailbox...
// c = Mailbox.getCursorWhere(mDatabase, "account=" + mAccount.id + " and serverName=?", name);
// if (c != null && c.moveToFirst()) {
// Mailbox existing = Mailbox.restoreFromCursor(c);
// userLog("Renaming existing mailbox: " + existing.mServerId + " to: " + m.mServerId);
// existing.mDisplayName = m.mDisplayName;
// existing.mServerId = m.mServerId;
// m.mHierarchicalName = m.mServerId;
// existing.mParentServerId = m.mParentServerId;
// existing.mFlags = m.mFlags;
// existing.save(mDatabase);
// // Mark this so that we don't save it below
// m.mServerId = null;
// }
// } finally {
// if (c != null) {
// c.close();
// }
// }
found = true;
break;
}
}
}
if (!found) {
// There's no current mailbox with this uidval, so delete.
ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(
Mailbox.CONTENT_URI, ids[i])).build());
userLog("Deleting uidval mailbox; no match: " + name);
}
}
}
for (Mailbox m : addList) {
String serverId = m.mServerId;
if (serverId == null)
continue;
if (!serverId.equalsIgnoreCase(INBOX_SERVER_NAME)
&& !serverId.equalsIgnoreCase("Outbox")) {
m.mHierarchicalName = m.mServerId;
//*** For now, use Mail. We need a way to select the others...
m.mType = Mailbox.TYPE_MAIL;
ops.add(ContentProviderOperation.newInsert(
Mailbox.CONTENT_URI).withValues(m.toContentValues()).build());
userLog("Adding new mailbox: " + m.mServerId);
}
}
applyBatch(ops);
// Fixup parent stuff, flags...
MailboxUtilities.fixupUninitializedParentKeys(mContext,
Mailbox.ACCOUNT_KEY + "=" + mAccountId);
} finally {
SyncManager.kick("folder list");
}
}
| void readFolderList () throws IOException {
String tag = writeCommand(mWriter, "list \"\" *");
String line;
char dchar = '/';
userLog("Loading folder list...");
ArrayList<String> parentList = new ArrayList<String>();
ArrayList<Mailbox> mailboxList = new ArrayList<Mailbox>();
while (true) {
line = mReader.readLine();
userLog(line);
if (line.startsWith(tag)) {
// Done reading folder list
break;
} else {
Parser p = new Parser(line, 2);
String cmd = p.parseAtom();
if (cmd.equalsIgnoreCase("list")) {
@SuppressWarnings("unused")
String props = p.parseListOrNil();
String delim = p.parseString();
if (delim == null)
delim = "~";
if (delim.length() == 1)
dchar = delim.charAt(0);
String serverId = p.parseStringOrAtom();
int lastDelim = serverId.lastIndexOf(delim);
String displayName;
String parentName;
if (lastDelim > 0) {
displayName = serverId.substring(lastDelim + 1);
parentName = serverId.substring(0, lastDelim);
} else {
displayName = serverId;
parentName = null;
}
Mailbox m = new Mailbox();
m.mDisplayName = decodeFolderName(displayName, null);
m.mAccountKey = mAccountId;
m.mServerId = decodeFolderName(serverId, null);
if (parentName != null && !parentList.contains(parentName)) {
parentList.add(parentName);
}
m.mFlagVisible = true;
m.mParentServerId = parentName;
m.mDelimiter = dchar;
m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER;
mailboxList.add(m);
} else {
// WTF
}
}
}
// TODO: Use narrower projection
Cursor c = mResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
Mailbox.ACCOUNT_KEY + "=?", new String[] {Long.toString(mAccountId)},
MailboxColumns.SERVER_ID + " asc");
if (c == null) return;
int cnt = c.getCount();
String[] serverIds = new String[cnt];
long[] uidvals = new long[cnt];
long[] ids = new long[cnt];
int i = 0;
try {
if (c.moveToFirst()) {
// Get arrays of information about existing mailboxes in account
do {
serverIds[i] = c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN);
uidvals[i] = c.getLong(Mailbox.CONTENT_SYNC_KEY_COLUMN);
ids[i] = c.getLong(Mailbox.CONTENT_ID_COLUMN);
i++;
} while (c.moveToNext());
}
} finally {
c.close();
}
ArrayList<Mailbox> addList = new ArrayList<Mailbox>();
for (Mailbox m: mailboxList) {
int loc = Arrays.binarySearch(serverIds, m.mServerId);
if (loc >= 0) {
// It exists
if (uidvals[loc] == 0) {
// Good enough; a match that we've never visited!
// Mark this as touched (-1)...
uidvals[loc] = -1;
} else {
// Ok, now we need to see if this is the SAME mailbox...
// For now, assume it is; move on
// TODO: There's a problem if you've 1) visited this box and 2) another box now
// has its name, but how likely is that??
uidvals[loc] = -1;
}
} else {
// We don't know about this mailbox, so we'll add it...
// BUT must see if it's a rename of one we've visited!
addList.add(m);
}
}
// TODO: Flush this list every N (100?) in case there are zillions
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
try {
for (i = 0; i < cnt; i++) {
String name = serverIds[i];
long uidval = uidvals[i];
// -1 means matched; ignore
// 0 means unmatched and never before seen
// > 0 means unmatched and HAS been seen. must find mWriter why
// TODO: Get rid of "Outbox"
if (uidval == 0 && !name.equals("Outbox") &&
!name.equalsIgnoreCase(INBOX_SERVER_NAME)) {
// Ok, here's one we've never visited and it's not in the new list
ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(
Mailbox.CONTENT_URI, ids[i])).build());
userLog("Deleting unseen mailbox; no match: " + name);
} else if (uidval > 0 && !name.equalsIgnoreCase(INBOX_SERVER_NAME)) {
boolean found = false;
for (Mailbox m : addList) {
tag = writeCommand(mWriter, "status \"" + m.mServerId + "\" (UIDVALIDITY)");
if (readResponse(mReader, tag, "STATUS").equals(IMAP_OK)) {
String str = mImapResponse.get(0).toLowerCase();
int idx = str.indexOf("uidvalidity");
long num = readLong(str, idx + 12);
if (uidval == num) {
// try {
// // This is a renamed mailbox...
// c = Mailbox.getCursorWhere(mDatabase, "account=" + mAccount.id + " and serverName=?", name);
// if (c != null && c.moveToFirst()) {
// Mailbox existing = Mailbox.restoreFromCursor(c);
// userLog("Renaming existing mailbox: " + existing.mServerId + " to: " + m.mServerId);
// existing.mDisplayName = m.mDisplayName;
// existing.mServerId = m.mServerId;
// m.mHierarchicalName = m.mServerId;
// existing.mParentServerId = m.mParentServerId;
// existing.mFlags = m.mFlags;
// existing.save(mDatabase);
// // Mark this so that we don't save it below
// m.mServerId = null;
// }
// } finally {
// if (c != null) {
// c.close();
// }
// }
found = true;
break;
}
}
}
if (!found) {
// There's no current mailbox with this uidval, so delete.
ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(
Mailbox.CONTENT_URI, ids[i])).build());
userLog("Deleting uidval mailbox; no match: " + name);
}
}
}
for (Mailbox m : addList) {
String serverId = m.mServerId;
if (serverId == null)
continue;
if (!serverId.equalsIgnoreCase(INBOX_SERVER_NAME)
&& !serverId.equalsIgnoreCase("Outbox")) {
m.mHierarchicalName = m.mServerId;
//*** For now, use Mail. We need a way to select the others...
m.mType = Mailbox.TYPE_MAIL;
ops.add(ContentProviderOperation.newInsert(
Mailbox.CONTENT_URI).withValues(m.toContentValues()).build());
userLog("Adding new mailbox: " + m.mServerId);
}
}
applyBatch(ops);
// Fixup parent stuff, flags...
MailboxUtilities.fixupUninitializedParentKeys(mContext,
Mailbox.ACCOUNT_KEY + "=" + mAccountId);
} finally {
SyncManager.kick("folder list");
}
}
|
diff --git a/MODSRC/vazkii/tinkerer/common/block/tile/TileEnchanter.java b/MODSRC/vazkii/tinkerer/common/block/tile/TileEnchanter.java
index 409fac33..6b3ab7e5 100644
--- a/MODSRC/vazkii/tinkerer/common/block/tile/TileEnchanter.java
+++ b/MODSRC/vazkii/tinkerer/common/block/tile/TileEnchanter.java
@@ -1,330 +1,330 @@
/**
* This class was created by <Vazkii>. It's distributed as
* part of the ThaumicTinkerer Mod.
*
* ThaumicTinkerer is Open Source and distributed under a
* Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
* (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB)
*
* ThaumicTinkerer is a Derivative Work on Thaumcraft 4.
* Thaumcraft 4 (c) Azanor 2012
* (http://www.minecraftforum.net/topic/1585216-)
*
* File Created @ [14 Sep 2013, 01:07:25 (GMT)]
*/
package vazkii.tinkerer.common.block.tile;
import java.util.ArrayList;
import java.util.List;
import cpw.mods.fml.common.network.PacketDispatcher;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagInt;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet132TileEntityData;
import net.minecraft.tileentity.TileEntity;
import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.aspects.AspectList;
import thaumcraft.common.items.wands.ItemWandCasting;
import vazkii.tinkerer.common.enchantment.core.EnchantmentManager;
import vazkii.tinkerer.common.lib.LibBlockNames;
import vazkii.tinkerer.common.lib.LibFeatures;
public class TileEnchanter extends TileEntity implements ISidedInventory {
private static final String TAG_ENCHANTS = "enchants";
private static final String TAG_LEVELS = "levels";
private static final String TAG_TOTAL_ASPECTS = "totalAspects";
private static final String TAG_CURRENT_ASPECTS = "currentAspects";
private static final String TAG_WORKING = "working";
public List<Integer> enchantments = new ArrayList();
public List<Integer> levels = new ArrayList();
public AspectList totalAspects = new AspectList();
public AspectList currentAspects = new AspectList();
public boolean working = false;
ItemStack[] inventorySlots = new ItemStack[2];
public void clearEnchants() {
enchantments.clear();
levels.clear();
}
public void appendEnchant(int enchant) {
enchantments.add(enchant);
}
public void appendLevel(int level) {
levels.add(level);
}
public void removeEnchant(int index) {
enchantments.remove(index);
}
public void removeLevel(int index) {
levels.remove(index);
}
public void setEnchant(int index, int enchant) {
enchantments.set(index, enchant);
}
public void setLevel(int index, int level) {
levels.set(index, level);
}
@Override
public void updateEntity() {
if(working) {
ItemStack tool = getStackInSlot(0);
if(tool == null) {
working = false;
return;
}
enchantItem : {
for(Aspect aspect : LibFeatures.PRIMAL_ASPECTS) {
int currentAmount = currentAspects.getAmount(aspect);
int totalAmount = totalAspects.getAmount(aspect);
if(currentAmount < totalAmount)
break enchantItem;
}
working = false;
currentAspects = new AspectList();
totalAspects = new AspectList();
for(int i = 0; i < enchantments.size(); i++) {
int enchant = enchantments.get(i);
int level = levels.get(i);
tool.addEnchantment(Enchantment.enchantmentsList[enchant], level);
}
enchantments.clear();
levels.clear();
PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket());
return;
}
ItemStack wand = getStackInSlot(1);
if(wand != null && wand.getItem() instanceof ItemWandCasting) {
ItemWandCasting wandItem = (ItemWandCasting) wand.getItem();
AspectList wandAspects = wandItem.getAllVis(wand);
for(Aspect aspect : LibFeatures.PRIMAL_ASPECTS) {
int missing = totalAspects.getAmount(aspect) - currentAspects.getAmount(aspect);
int onWand = wandAspects.getAmount(aspect);
if(onWand >= 100 && missing > 0) {
- wandItem.consumeVis(wand, null, aspect, 100);
+ wandItem.consumeAllVisCrafting(wand, null, new AspectList().add(aspect, 1), true);
currentAspects.add(aspect, 1);
return;
}
}
}
}
}
public void updateAspectList() {
totalAspects = new AspectList();
for(int i = 0; i < enchantments.size(); i++) {
int enchant = enchantments.get(i);
int level = levels.get(i);
AspectList aspects = EnchantmentManager.enchantmentData.get(enchant).get(level).aspects;
for(Aspect aspect : aspects.getAspectsSorted())
totalAspects.add(aspect, aspects.getAmount(aspect));
}
}
@Override
public void readFromNBT(NBTTagCompound par1NBTTagCompound) {
super.readFromNBT(par1NBTTagCompound);
readCustomNBT(par1NBTTagCompound);
}
@Override
public void writeToNBT(NBTTagCompound par1NBTTagCompound) {
super.writeToNBT(par1NBTTagCompound);
writeCustomNBT(par1NBTTagCompound);
}
public void readCustomNBT(NBTTagCompound par1NBTTagCompound) {
working = par1NBTTagCompound.getBoolean(TAG_WORKING);
currentAspects.readFromNBT(par1NBTTagCompound.getCompoundTag(TAG_CURRENT_ASPECTS));
totalAspects.readFromNBT(par1NBTTagCompound.getCompoundTag(TAG_TOTAL_ASPECTS));
NBTTagList enchants = par1NBTTagCompound.getTagList(TAG_ENCHANTS);
enchantments.clear();
for(int i = 0; i < enchants.tagCount(); i++)
enchantments.add(((NBTTagInt) enchants.tagAt(i)).data);
NBTTagList levels = par1NBTTagCompound.getTagList(TAG_LEVELS);
this.levels.clear();
for(int i = 0; i < levels.tagCount(); i++)
this.levels.add(((NBTTagInt) levels.tagAt(i)).data);
NBTTagList var2 = par1NBTTagCompound.getTagList("Items");
inventorySlots = new ItemStack[getSizeInventory()];
for (int var3 = 0; var3 < var2.tagCount(); ++var3) {
NBTTagCompound var4 = (NBTTagCompound)var2.tagAt(var3);
byte var5 = var4.getByte("Slot");
if (var5 >= 0 && var5 < inventorySlots.length)
inventorySlots[var5] = ItemStack.loadItemStackFromNBT(var4);
}
}
public void writeCustomNBT(NBTTagCompound par1NBTTagCompound) {
NBTTagList enchants = new NBTTagList();
for(int enchant : enchantments)
enchants.appendTag(new NBTTagInt("", enchant));
NBTTagList levels = new NBTTagList();
for(int level : this.levels)
levels.appendTag(new NBTTagInt("", level));
NBTTagCompound totalAspectsCmp = new NBTTagCompound();
totalAspects.writeToNBT(totalAspectsCmp);
NBTTagCompound currentAspectsCmp = new NBTTagCompound();
currentAspects.writeToNBT(currentAspectsCmp);
par1NBTTagCompound.setBoolean(TAG_WORKING, working);
par1NBTTagCompound.setCompoundTag(TAG_TOTAL_ASPECTS, totalAspectsCmp);
par1NBTTagCompound.setCompoundTag(TAG_CURRENT_ASPECTS, currentAspectsCmp);
par1NBTTagCompound.setTag(TAG_ENCHANTS, enchants);
par1NBTTagCompound.setTag(TAG_LEVELS, levels);
NBTTagList var2 = new NBTTagList();
for (int var3 = 0; var3 < inventorySlots.length; ++var3) {
if (inventorySlots[var3] != null) {
NBTTagCompound var4 = new NBTTagCompound();
var4.setByte("Slot", (byte)var3);
inventorySlots[var3].writeToNBT(var4);
var2.appendTag(var4);
}
}
par1NBTTagCompound.setTag("Items", var2);
}
@Override
public int getSizeInventory() {
return inventorySlots.length;
}
@Override
public ItemStack getStackInSlot(int i) {
return inventorySlots[i];
}
@Override
public ItemStack decrStackSize(int i, int j) {
if (inventorySlots[i] != null) {
ItemStack stackAt;
if (inventorySlots[i].stackSize <= j) {
stackAt = inventorySlots[i];
inventorySlots[i] = null;
return stackAt;
} else {
stackAt = inventorySlots[i].splitStack(j);
if (inventorySlots[i].stackSize == 0)
inventorySlots[i] = null;
return stackAt;
}
}
return null;
}
@Override
public ItemStack getStackInSlotOnClosing(int i) {
return getStackInSlot(i);
}
@Override
public void setInventorySlotContents(int i, ItemStack itemstack) {
inventorySlots[i] = itemstack;
}
@Override
public String getInvName() {
return LibBlockNames.ENCHANTER;
}
@Override
public boolean isInvNameLocalized() {
return false;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer) {
return worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) != this ? false : entityplayer.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) <= 64;
}
@Override
public void openChest() {
// NO-OP
}
@Override
public void closeChest() {
// NO-OP
}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack) {
return false;
}
@Override
public Packet getDescriptionPacket() {
NBTTagCompound nbttagcompound = new NBTTagCompound();
writeCustomNBT(nbttagcompound);
return new Packet132TileEntityData(xCoord, yCoord, zCoord, -999, nbttagcompound);
}
@Override
public void onDataPacket(INetworkManager manager, Packet132TileEntityData packet) {
super.onDataPacket(manager, packet);
readCustomNBT(packet.customParam1);
}
@Override
public int[] getAccessibleSlotsFromSide(int var1) {
return new int[0];
}
@Override
public boolean canInsertItem(int i, ItemStack itemstack, int j) {
return false;
}
@Override
public boolean canExtractItem(int i, ItemStack itemstack, int j) {
return false;
}
}
| true | true | public void updateEntity() {
if(working) {
ItemStack tool = getStackInSlot(0);
if(tool == null) {
working = false;
return;
}
enchantItem : {
for(Aspect aspect : LibFeatures.PRIMAL_ASPECTS) {
int currentAmount = currentAspects.getAmount(aspect);
int totalAmount = totalAspects.getAmount(aspect);
if(currentAmount < totalAmount)
break enchantItem;
}
working = false;
currentAspects = new AspectList();
totalAspects = new AspectList();
for(int i = 0; i < enchantments.size(); i++) {
int enchant = enchantments.get(i);
int level = levels.get(i);
tool.addEnchantment(Enchantment.enchantmentsList[enchant], level);
}
enchantments.clear();
levels.clear();
PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket());
return;
}
ItemStack wand = getStackInSlot(1);
if(wand != null && wand.getItem() instanceof ItemWandCasting) {
ItemWandCasting wandItem = (ItemWandCasting) wand.getItem();
AspectList wandAspects = wandItem.getAllVis(wand);
for(Aspect aspect : LibFeatures.PRIMAL_ASPECTS) {
int missing = totalAspects.getAmount(aspect) - currentAspects.getAmount(aspect);
int onWand = wandAspects.getAmount(aspect);
if(onWand >= 100 && missing > 0) {
wandItem.consumeVis(wand, null, aspect, 100);
currentAspects.add(aspect, 1);
return;
}
}
}
}
}
| public void updateEntity() {
if(working) {
ItemStack tool = getStackInSlot(0);
if(tool == null) {
working = false;
return;
}
enchantItem : {
for(Aspect aspect : LibFeatures.PRIMAL_ASPECTS) {
int currentAmount = currentAspects.getAmount(aspect);
int totalAmount = totalAspects.getAmount(aspect);
if(currentAmount < totalAmount)
break enchantItem;
}
working = false;
currentAspects = new AspectList();
totalAspects = new AspectList();
for(int i = 0; i < enchantments.size(); i++) {
int enchant = enchantments.get(i);
int level = levels.get(i);
tool.addEnchantment(Enchantment.enchantmentsList[enchant], level);
}
enchantments.clear();
levels.clear();
PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket());
return;
}
ItemStack wand = getStackInSlot(1);
if(wand != null && wand.getItem() instanceof ItemWandCasting) {
ItemWandCasting wandItem = (ItemWandCasting) wand.getItem();
AspectList wandAspects = wandItem.getAllVis(wand);
for(Aspect aspect : LibFeatures.PRIMAL_ASPECTS) {
int missing = totalAspects.getAmount(aspect) - currentAspects.getAmount(aspect);
int onWand = wandAspects.getAmount(aspect);
if(onWand >= 100 && missing > 0) {
wandItem.consumeAllVisCrafting(wand, null, new AspectList().add(aspect, 1), true);
currentAspects.add(aspect, 1);
return;
}
}
}
}
}
|
diff --git a/marytts-redstart/src/main/java/marytts/tools/redstart/Redstart.java b/marytts-redstart/src/main/java/marytts/tools/redstart/Redstart.java
index 8158c2a58..25d664c7e 100644
--- a/marytts-redstart/src/main/java/marytts/tools/redstart/Redstart.java
+++ b/marytts-redstart/src/main/java/marytts/tools/redstart/Redstart.java
@@ -1,116 +1,116 @@
/**
* Copyright 2007 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
*
* This file is part of MARY TTS.
*
* MARY TTS is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package marytts.tools.redstart;
import java.io.File;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Redstart {
/**
* @param args
*/
public static void main(String[] args) {
// Determine the voice building directory in the following order:
// 1. System property "user.dir"
// 2. First command line argument
// 3. current directory
// 4. Prompt user via gui.
// Do a sanity check -- do they exist, do they have a wav/ subdirectory?
String voiceBuildingDir = null;
Vector<String> candidates = new Vector<String>();
candidates.add(System.getProperty("user.dir"));
if (args.length > 0) candidates.add(args[0]);
candidates.add("."); // current directory
for (String dir: candidates) {
if (dir != null
&& new File(dir).isDirectory()
&& new File(dir+"/text").isDirectory()) {
voiceBuildingDir = dir;
break;
}
}
if (voiceBuildingDir == null) { // need to ask user
JFrame window = new JFrame("This is the Frames's Title Bar!");
JFileChooser fc = new JFileChooser(new File("."));
fc.setDialogTitle("Choose Voice Building Directory");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
System.out.println("Opening GUI....... ");
//outDir.setText(file.getAbsolutePath());
//System.exit(0);
int returnVal = fc.showOpenDialog(window);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (file != null)
voiceBuildingDir = file.getAbsolutePath();
}
}
if (voiceBuildingDir == null) {
System.err.println("Could not get a voice building directory -- exiting.");
System.exit(0);
}
- File textDir = new File(System.getProperty("user.dir")+System.getProperty("file.separator")+"text");
+ File textDir = new File(voiceBuildingDir+System.getProperty("file.separator")+"text");
//System.out.println(System.getProperty("user.dir")+System.getProperty("file.separator")+"wav");
if(!textDir.exists()){
- int choose = JOptionPane.showOptionDialog(null,
+ JOptionPane.showOptionDialog(null,
"Before beginning a new recording session, make sure that all text files (transcriptions) are available in 'text' directory of your specified location.",
"Could not find transcriptions",
JOptionPane.OK_OPTION,
JOptionPane.ERROR_MESSAGE,
null,
new String[] {"OK"},
null);
System.err.println("Could not find 'text' directory in user specified location -- exiting.");
System.exit(0);
}
// Display splash screen
Splash splash = null;
try {
splash = new Splash();
splash.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
Test.output("OS Name: " + System.getProperty("os.name"));
Test.output("OS Architecture: " + System.getProperty("os.arch"));
Test.output("OS Version: " + System.getProperty("os.version"));
System.out.println("Welcome to Redstart, your recording session manager.");
// TESTCODE
Test.output("|Redstart.main| voiceFolderPath = " + voiceBuildingDir);
AdminWindow adminWindow = new AdminWindow(voiceBuildingDir);
if (splash != null) splash.setVisible(false);
adminWindow.setVisible(true);
}
}
| false | true | public static void main(String[] args) {
// Determine the voice building directory in the following order:
// 1. System property "user.dir"
// 2. First command line argument
// 3. current directory
// 4. Prompt user via gui.
// Do a sanity check -- do they exist, do they have a wav/ subdirectory?
String voiceBuildingDir = null;
Vector<String> candidates = new Vector<String>();
candidates.add(System.getProperty("user.dir"));
if (args.length > 0) candidates.add(args[0]);
candidates.add("."); // current directory
for (String dir: candidates) {
if (dir != null
&& new File(dir).isDirectory()
&& new File(dir+"/text").isDirectory()) {
voiceBuildingDir = dir;
break;
}
}
if (voiceBuildingDir == null) { // need to ask user
JFrame window = new JFrame("This is the Frames's Title Bar!");
JFileChooser fc = new JFileChooser(new File("."));
fc.setDialogTitle("Choose Voice Building Directory");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
System.out.println("Opening GUI....... ");
//outDir.setText(file.getAbsolutePath());
//System.exit(0);
int returnVal = fc.showOpenDialog(window);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (file != null)
voiceBuildingDir = file.getAbsolutePath();
}
}
if (voiceBuildingDir == null) {
System.err.println("Could not get a voice building directory -- exiting.");
System.exit(0);
}
File textDir = new File(System.getProperty("user.dir")+System.getProperty("file.separator")+"text");
//System.out.println(System.getProperty("user.dir")+System.getProperty("file.separator")+"wav");
if(!textDir.exists()){
int choose = JOptionPane.showOptionDialog(null,
"Before beginning a new recording session, make sure that all text files (transcriptions) are available in 'text' directory of your specified location.",
"Could not find transcriptions",
JOptionPane.OK_OPTION,
JOptionPane.ERROR_MESSAGE,
null,
new String[] {"OK"},
null);
System.err.println("Could not find 'text' directory in user specified location -- exiting.");
System.exit(0);
}
// Display splash screen
Splash splash = null;
try {
splash = new Splash();
splash.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
Test.output("OS Name: " + System.getProperty("os.name"));
Test.output("OS Architecture: " + System.getProperty("os.arch"));
Test.output("OS Version: " + System.getProperty("os.version"));
System.out.println("Welcome to Redstart, your recording session manager.");
// TESTCODE
Test.output("|Redstart.main| voiceFolderPath = " + voiceBuildingDir);
AdminWindow adminWindow = new AdminWindow(voiceBuildingDir);
if (splash != null) splash.setVisible(false);
adminWindow.setVisible(true);
}
| public static void main(String[] args) {
// Determine the voice building directory in the following order:
// 1. System property "user.dir"
// 2. First command line argument
// 3. current directory
// 4. Prompt user via gui.
// Do a sanity check -- do they exist, do they have a wav/ subdirectory?
String voiceBuildingDir = null;
Vector<String> candidates = new Vector<String>();
candidates.add(System.getProperty("user.dir"));
if (args.length > 0) candidates.add(args[0]);
candidates.add("."); // current directory
for (String dir: candidates) {
if (dir != null
&& new File(dir).isDirectory()
&& new File(dir+"/text").isDirectory()) {
voiceBuildingDir = dir;
break;
}
}
if (voiceBuildingDir == null) { // need to ask user
JFrame window = new JFrame("This is the Frames's Title Bar!");
JFileChooser fc = new JFileChooser(new File("."));
fc.setDialogTitle("Choose Voice Building Directory");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
System.out.println("Opening GUI....... ");
//outDir.setText(file.getAbsolutePath());
//System.exit(0);
int returnVal = fc.showOpenDialog(window);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (file != null)
voiceBuildingDir = file.getAbsolutePath();
}
}
if (voiceBuildingDir == null) {
System.err.println("Could not get a voice building directory -- exiting.");
System.exit(0);
}
File textDir = new File(voiceBuildingDir+System.getProperty("file.separator")+"text");
//System.out.println(System.getProperty("user.dir")+System.getProperty("file.separator")+"wav");
if(!textDir.exists()){
JOptionPane.showOptionDialog(null,
"Before beginning a new recording session, make sure that all text files (transcriptions) are available in 'text' directory of your specified location.",
"Could not find transcriptions",
JOptionPane.OK_OPTION,
JOptionPane.ERROR_MESSAGE,
null,
new String[] {"OK"},
null);
System.err.println("Could not find 'text' directory in user specified location -- exiting.");
System.exit(0);
}
// Display splash screen
Splash splash = null;
try {
splash = new Splash();
splash.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
Test.output("OS Name: " + System.getProperty("os.name"));
Test.output("OS Architecture: " + System.getProperty("os.arch"));
Test.output("OS Version: " + System.getProperty("os.version"));
System.out.println("Welcome to Redstart, your recording session manager.");
// TESTCODE
Test.output("|Redstart.main| voiceFolderPath = " + voiceBuildingDir);
AdminWindow adminWindow = new AdminWindow(voiceBuildingDir);
if (splash != null) splash.setVisible(false);
adminWindow.setVisible(true);
}
|
diff --git a/src/java/org/astrogrid/samp/test/CalcStorm.java b/src/java/org/astrogrid/samp/test/CalcStorm.java
index 4fb2ae0..0a98e0b 100644
--- a/src/java/org/astrogrid/samp/test/CalcStorm.java
+++ b/src/java/org/astrogrid/samp/test/CalcStorm.java
@@ -1,327 +1,328 @@
package org.astrogrid.samp.test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import org.astrogrid.samp.client.ClientProfile;
import org.astrogrid.samp.client.HubConnection;
import org.astrogrid.samp.gui.HubMonitor;
import org.astrogrid.samp.xmlrpc.StandardClientProfile;
import org.astrogrid.samp.xmlrpc.XmlRpcKit;
/**
* Runs a load of Calculator clients at once all sending messages to each other.
* Suitable for load testing or benchmarking a hub.
*
* @author Mark Taylor
* @since 22 Jul 2008
*/
public class CalcStorm {
private final ClientProfile profile_;
private final Random random_;
private final int nClient_;
private final int nQuery_;
private final Calculator.SendMode sendMode_;
private static final Logger logger_ =
Logger.getLogger( CalcStorm.class.getName() );
/**
* Constructor.
*
* @param profile hub connection factory
* @param random random number generator
* @param nClient number of clients to run
* @param nQuery number of messages each client will send
* @param sendMode delivery pattern for messages
*/
public CalcStorm( ClientProfile profile, Random random, int nClient,
int nQuery, Calculator.SendMode sendMode ) {
profile_ = profile;
random_ = random;
nClient_ = nClient;
nQuery_ = nQuery;
sendMode_ = sendMode;
}
/**
* Runs a lot of calculators at once all talking to each other.
*
* @throws TestException if any tests fail
*/
public void run() throws IOException {
// Set up clients.
final Calculator[] calcs = new Calculator[ nClient_ ];
final String[] ids = new String[ nClient_ ];
final Random[] randoms = new Random[ nClient_ ];
for ( int ic = 0; ic < nClient_; ic++ ) {
HubConnection conn = profile_.register();
if ( conn == null ) {
throw new IOException( "No hub is running" );
}
randoms[ ic ] = new Random( random_.nextLong() );
ids[ ic ] = conn.getRegInfo().getSelfId();
calcs[ ic ] = new Calculator( conn, randoms[ ic ] );
}
// Set up one thread per client to do the message sending.
Thread[] calcThreads = new Thread[ nClient_ ];
final Throwable[] errors = new Throwable[ 1 ];
for ( int ic = 0; ic < nClient_; ic++ ) {
final Calculator calc = calcs[ ic ];
final Random random = randoms[ ic ];
calcThreads[ ic ] = new Thread( "Calc" + ic ) {
public void run() {
try {
for ( int iq = 0; iq < nQuery_ && errors[ 0 ] == null;
iq++ ) {
calc.sendMessage( ids[ random.nextInt( nClient_ ) ],
sendMode_ );
}
calc.flush();
}
catch ( Throwable e ) {
errors[ 0 ] = e;
}
}
};
}
// Start the threads running.
for ( int ic = 0; ic < nClient_; ic++ ) {
calcThreads[ ic ].start();
}
// Wait for all the threads to finish.
try {
for ( int ic = 0; ic < nClient_; ic++ ) {
calcThreads[ ic ].join();
}
}
catch ( InterruptedException e ) {
throw new TestException( "Interrupted", e );
}
// If we are using the notification delivery pattern, wait until
// all the clients have received all the messages they are expecting.
// In the case of call/response this is not necessary, since the
// message sender threads will only complete their run() methods
// when the responses have come back, which must mean that the
// messages arrived at their recipients.
if ( sendMode_ == Calculator.NOTIFY_MODE ||
sendMode_ == Calculator.RANDOM_MODE ) {
for ( boolean done = false; ! done; ) {
int totCalc = 0;
for ( int ic = 0; ic < nClient_; ic++ ) {
totCalc += calcs[ ic ].getReceiveCount();
}
done = totCalc >= nClient_ * nQuery_;
if ( ! done ) {
Thread.yield();
}
}
}
// Unregister the clients.
for ( int ic = 0; ic < nClient_; ic++ ) {
calcs[ ic ].getConnection().unregister();
}
// If any errors occurred on the sending thread, rethrow one of them
// here.
if ( errors[ 0 ] != null ) {
throw new TestException( "Error in calculator thread: "
+ errors[ 0 ].getMessage(),
errors[ 0 ] );
}
// Check that the number of messages sent and the number received
// was what it should have been.
int totCalc = 0;
for ( int ic = 0; ic < nClient_; ic++ ) {
Calculator calc = calcs[ ic ];
Tester.assertEquals( nQuery_, calc.getSendCount() );
totCalc += calc.getReceiveCount();
}
Tester.assertEquals( totCalc, nClient_ * nQuery_ );
}
/**
* Does the work for the main method.
* Use -help flag for documentation.
*
* @param args command-line arguments
* @return 0 means success
*/
public static int runMain( String[] args ) throws IOException {
// Set up usage message.
String usage = new StringBuffer()
.append( "\n Usage:" )
.append( "\n " )
.append( CalcStorm.class.getName() )
.append( "\n " )
.append( " [-help]" )
.append( " [-/+verbose]" )
.append( " [-xmlrpc apache|internal]" )
.append( " [-gui]" )
.append( "\n " )
.append( " [-nclient <n>]" )
.append( " [-nquery <n>]" )
.append( " [-mode sync|async|notify|random]" )
.append( "\n" )
.toString();
// Prepare default values for test.
Random random = new Random( 2333333 );
int nClient = 20;
int nQuery = 100;
Calculator.SendMode sendMode = Calculator.RANDOM_MODE;
int verbAdjust = 0;
boolean gui = false;
XmlRpcKit xmlrpc = null;
// Parse arguments, modifying test parameters as appropriate.
List argList = new ArrayList( Arrays.asList( args ) );
try {
for ( Iterator it = argList.iterator(); it.hasNext(); ) {
String arg = (String) it.next();
if ( arg.startsWith( "-nc" ) && it.hasNext() ) {
it.remove();
String snc = (String) it.next();
it.remove();
nClient = Integer.parseInt( snc );
}
else if ( arg.startsWith( "-nq" ) && it.hasNext() ) {
it.remove();
String snq = (String) it.next();
it.remove();
nQuery = Integer.parseInt( snq );
}
else if ( arg.equals( "-mode" ) && it.hasNext() ) {
it.remove();
String smode = (String) it.next();
it.remove();
final Calculator.SendMode sm;
if ( smode.toLowerCase().startsWith( "sync" ) ) {
sm = Calculator.SYNCH_MODE;
}
else if ( smode.toLowerCase().startsWith( "async" ) ) {
sm = Calculator.ASYNCH_MODE;
}
else if ( smode.toLowerCase().startsWith( "notif" ) ) {
sm = Calculator.NOTIFY_MODE;
}
else if ( smode.toLowerCase().startsWith( "rand" ) ) {
sm = Calculator.RANDOM_MODE;
}
else {
System.err.println( usage );
return 1;
}
sendMode = sm;
}
else if ( arg.equals( "-gui" ) ) {
it.remove();
gui = true;
}
else if ( arg.equals( "-nogui" ) ) {
it.remove();
gui = false;
}
else if ( arg.equals( "-xmlrpc" ) && it.hasNext() ) {
it.remove();
String impl = (String) it.next();
+ it.remove();
try {
xmlrpc = XmlRpcKit.getInstanceByName( impl );
}
catch ( Exception e ) {
logger_.log( Level.INFO,
"No XMLRPC implementation " + impl,
e );
System.err.println( usage );
return 1;
}
}
else if ( arg.startsWith( "-v" ) ) {
it.remove();
verbAdjust--;
}
else if ( arg.startsWith( "+v" ) ) {
it.remove();
verbAdjust++;
}
else if ( arg.startsWith( "-h" ) ) {
System.out.println( usage );
return 0;
}
else {
System.err.println( usage );
return 1;
}
}
}
catch ( RuntimeException e ) {
System.err.println( usage );
return 1;
}
if ( ! argList.isEmpty() ) {
System.err.println( usage );
return 1;
}
// Adjust logging in accordance with verboseness flags.
int logLevel = Level.WARNING.intValue() + 100 * verbAdjust;
Logger.getLogger( "org.astrogrid.samp" )
.setLevel( Level.parse( Integer.toString( logLevel ) ) );
// Prepare profile.
ClientProfile profile =
xmlrpc == null ? StandardClientProfile.getInstance()
: new StandardClientProfile( xmlrpc );
// Set up GUI monitor if required.
JFrame frame;
if ( gui ) {
frame = new JFrame( "CalcStorm Monitor" );
frame.getContentPane().add( new HubMonitor( profile, 1 ) );
frame.pack();
frame.setVisible( true );
}
else {
frame = null;
}
// Run the test.
long start = System.currentTimeMillis();
new CalcStorm( profile, random, nClient, nQuery, sendMode ).run();
long time = System.currentTimeMillis() - start;
System.out.println( "Elapsed time: " + time + " ms"
+ " (" + (int) ( time * 1000. / ( nClient * nQuery ) )
+ " us per message)" );
// Tidy up and return.
if ( frame != null ) {
frame.dispose();
}
return 0;
}
/**
* Main method. Use -help flag.
*/
public static void main( String[] args ) throws IOException {
int status = runMain( args );
if ( status != 0 ) {
System.exit( status );
}
}
}
| true | true | public static int runMain( String[] args ) throws IOException {
// Set up usage message.
String usage = new StringBuffer()
.append( "\n Usage:" )
.append( "\n " )
.append( CalcStorm.class.getName() )
.append( "\n " )
.append( " [-help]" )
.append( " [-/+verbose]" )
.append( " [-xmlrpc apache|internal]" )
.append( " [-gui]" )
.append( "\n " )
.append( " [-nclient <n>]" )
.append( " [-nquery <n>]" )
.append( " [-mode sync|async|notify|random]" )
.append( "\n" )
.toString();
// Prepare default values for test.
Random random = new Random( 2333333 );
int nClient = 20;
int nQuery = 100;
Calculator.SendMode sendMode = Calculator.RANDOM_MODE;
int verbAdjust = 0;
boolean gui = false;
XmlRpcKit xmlrpc = null;
// Parse arguments, modifying test parameters as appropriate.
List argList = new ArrayList( Arrays.asList( args ) );
try {
for ( Iterator it = argList.iterator(); it.hasNext(); ) {
String arg = (String) it.next();
if ( arg.startsWith( "-nc" ) && it.hasNext() ) {
it.remove();
String snc = (String) it.next();
it.remove();
nClient = Integer.parseInt( snc );
}
else if ( arg.startsWith( "-nq" ) && it.hasNext() ) {
it.remove();
String snq = (String) it.next();
it.remove();
nQuery = Integer.parseInt( snq );
}
else if ( arg.equals( "-mode" ) && it.hasNext() ) {
it.remove();
String smode = (String) it.next();
it.remove();
final Calculator.SendMode sm;
if ( smode.toLowerCase().startsWith( "sync" ) ) {
sm = Calculator.SYNCH_MODE;
}
else if ( smode.toLowerCase().startsWith( "async" ) ) {
sm = Calculator.ASYNCH_MODE;
}
else if ( smode.toLowerCase().startsWith( "notif" ) ) {
sm = Calculator.NOTIFY_MODE;
}
else if ( smode.toLowerCase().startsWith( "rand" ) ) {
sm = Calculator.RANDOM_MODE;
}
else {
System.err.println( usage );
return 1;
}
sendMode = sm;
}
else if ( arg.equals( "-gui" ) ) {
it.remove();
gui = true;
}
else if ( arg.equals( "-nogui" ) ) {
it.remove();
gui = false;
}
else if ( arg.equals( "-xmlrpc" ) && it.hasNext() ) {
it.remove();
String impl = (String) it.next();
try {
xmlrpc = XmlRpcKit.getInstanceByName( impl );
}
catch ( Exception e ) {
logger_.log( Level.INFO,
"No XMLRPC implementation " + impl,
e );
System.err.println( usage );
return 1;
}
}
else if ( arg.startsWith( "-v" ) ) {
it.remove();
verbAdjust--;
}
else if ( arg.startsWith( "+v" ) ) {
it.remove();
verbAdjust++;
}
else if ( arg.startsWith( "-h" ) ) {
System.out.println( usage );
return 0;
}
else {
System.err.println( usage );
return 1;
}
}
}
catch ( RuntimeException e ) {
System.err.println( usage );
return 1;
}
if ( ! argList.isEmpty() ) {
System.err.println( usage );
return 1;
}
// Adjust logging in accordance with verboseness flags.
int logLevel = Level.WARNING.intValue() + 100 * verbAdjust;
Logger.getLogger( "org.astrogrid.samp" )
.setLevel( Level.parse( Integer.toString( logLevel ) ) );
// Prepare profile.
ClientProfile profile =
xmlrpc == null ? StandardClientProfile.getInstance()
: new StandardClientProfile( xmlrpc );
// Set up GUI monitor if required.
JFrame frame;
if ( gui ) {
frame = new JFrame( "CalcStorm Monitor" );
frame.getContentPane().add( new HubMonitor( profile, 1 ) );
frame.pack();
frame.setVisible( true );
}
else {
frame = null;
}
// Run the test.
long start = System.currentTimeMillis();
new CalcStorm( profile, random, nClient, nQuery, sendMode ).run();
long time = System.currentTimeMillis() - start;
System.out.println( "Elapsed time: " + time + " ms"
+ " (" + (int) ( time * 1000. / ( nClient * nQuery ) )
+ " us per message)" );
// Tidy up and return.
if ( frame != null ) {
frame.dispose();
}
return 0;
}
| public static int runMain( String[] args ) throws IOException {
// Set up usage message.
String usage = new StringBuffer()
.append( "\n Usage:" )
.append( "\n " )
.append( CalcStorm.class.getName() )
.append( "\n " )
.append( " [-help]" )
.append( " [-/+verbose]" )
.append( " [-xmlrpc apache|internal]" )
.append( " [-gui]" )
.append( "\n " )
.append( " [-nclient <n>]" )
.append( " [-nquery <n>]" )
.append( " [-mode sync|async|notify|random]" )
.append( "\n" )
.toString();
// Prepare default values for test.
Random random = new Random( 2333333 );
int nClient = 20;
int nQuery = 100;
Calculator.SendMode sendMode = Calculator.RANDOM_MODE;
int verbAdjust = 0;
boolean gui = false;
XmlRpcKit xmlrpc = null;
// Parse arguments, modifying test parameters as appropriate.
List argList = new ArrayList( Arrays.asList( args ) );
try {
for ( Iterator it = argList.iterator(); it.hasNext(); ) {
String arg = (String) it.next();
if ( arg.startsWith( "-nc" ) && it.hasNext() ) {
it.remove();
String snc = (String) it.next();
it.remove();
nClient = Integer.parseInt( snc );
}
else if ( arg.startsWith( "-nq" ) && it.hasNext() ) {
it.remove();
String snq = (String) it.next();
it.remove();
nQuery = Integer.parseInt( snq );
}
else if ( arg.equals( "-mode" ) && it.hasNext() ) {
it.remove();
String smode = (String) it.next();
it.remove();
final Calculator.SendMode sm;
if ( smode.toLowerCase().startsWith( "sync" ) ) {
sm = Calculator.SYNCH_MODE;
}
else if ( smode.toLowerCase().startsWith( "async" ) ) {
sm = Calculator.ASYNCH_MODE;
}
else if ( smode.toLowerCase().startsWith( "notif" ) ) {
sm = Calculator.NOTIFY_MODE;
}
else if ( smode.toLowerCase().startsWith( "rand" ) ) {
sm = Calculator.RANDOM_MODE;
}
else {
System.err.println( usage );
return 1;
}
sendMode = sm;
}
else if ( arg.equals( "-gui" ) ) {
it.remove();
gui = true;
}
else if ( arg.equals( "-nogui" ) ) {
it.remove();
gui = false;
}
else if ( arg.equals( "-xmlrpc" ) && it.hasNext() ) {
it.remove();
String impl = (String) it.next();
it.remove();
try {
xmlrpc = XmlRpcKit.getInstanceByName( impl );
}
catch ( Exception e ) {
logger_.log( Level.INFO,
"No XMLRPC implementation " + impl,
e );
System.err.println( usage );
return 1;
}
}
else if ( arg.startsWith( "-v" ) ) {
it.remove();
verbAdjust--;
}
else if ( arg.startsWith( "+v" ) ) {
it.remove();
verbAdjust++;
}
else if ( arg.startsWith( "-h" ) ) {
System.out.println( usage );
return 0;
}
else {
System.err.println( usage );
return 1;
}
}
}
catch ( RuntimeException e ) {
System.err.println( usage );
return 1;
}
if ( ! argList.isEmpty() ) {
System.err.println( usage );
return 1;
}
// Adjust logging in accordance with verboseness flags.
int logLevel = Level.WARNING.intValue() + 100 * verbAdjust;
Logger.getLogger( "org.astrogrid.samp" )
.setLevel( Level.parse( Integer.toString( logLevel ) ) );
// Prepare profile.
ClientProfile profile =
xmlrpc == null ? StandardClientProfile.getInstance()
: new StandardClientProfile( xmlrpc );
// Set up GUI monitor if required.
JFrame frame;
if ( gui ) {
frame = new JFrame( "CalcStorm Monitor" );
frame.getContentPane().add( new HubMonitor( profile, 1 ) );
frame.pack();
frame.setVisible( true );
}
else {
frame = null;
}
// Run the test.
long start = System.currentTimeMillis();
new CalcStorm( profile, random, nClient, nQuery, sendMode ).run();
long time = System.currentTimeMillis() - start;
System.out.println( "Elapsed time: " + time + " ms"
+ " (" + (int) ( time * 1000. / ( nClient * nQuery ) )
+ " us per message)" );
// Tidy up and return.
if ( frame != null ) {
frame.dispose();
}
return 0;
}
|
diff --git a/mcu/src/org/smbarbour/mcu/AppletLauncherThread.java b/mcu/src/org/smbarbour/mcu/AppletLauncherThread.java
index b96d2a3..ec217c5 100644
--- a/mcu/src/org/smbarbour/mcu/AppletLauncherThread.java
+++ b/mcu/src/org/smbarbour/mcu/AppletLauncherThread.java
@@ -1,236 +1,238 @@
package org.smbarbour.mcu;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import org.smbarbour.mcu.util.LoginData;
import org.smbarbour.mcu.util.MCUpdater;
import org.smbarbour.mcu.util.ServerList;
public class AppletLauncherThread implements GenericLauncherThread, Runnable {
private ConsoleArea console;
private MainForm parent;
private LoginData session;
private String jrePath;
private String minMem;
private String maxMem;
private File output;
private Thread thread;
private boolean forceKilled;
private ServerList server;
private Process task;
private JButton launchButton;
private MenuItem killItem;
private boolean ready;
public AppletLauncherThread(MainForm parent, LoginData session, String jrePath, String minMem, String maxMem, File output, ServerList server) {
this.parent = parent;
this.session = session;
this.jrePath = jrePath;
this.minMem = minMem;
this.maxMem = maxMem;
this.output = output;
this.server = server;
}
public static AppletLauncherThread launch(MainForm parent, LoginData session, String jrePath, String minMem, String maxMem, File output, ConsoleArea console, ServerList server) {
AppletLauncherThread me = new AppletLauncherThread(parent, session, jrePath, minMem, maxMem, output, server);
me.console = console;
console.setText("");
return me;
}
@Override
public void run() {
String javaBin = "java";
File binDir = (new File(jrePath)).toPath().resolve("bin").toFile();
if( binDir.exists() ) {
javaBin = binDir.toPath().resolve("java").toString();
}
List<String> args = new ArrayList<String>();
args.add(javaBin);
args.add("-XX:+UseConcMarkSweepGC");
args.add("-XX:+CMSIncrementalMode");
args.add("-XX:+AggressiveOpts");
args.add("-Xms" + this.minMem);
args.add("-Xmx" + this.maxMem);
args.add("-classpath");
args.add(MCUpdater.getJarFile().toString());
args.add("org.smbarbour.mcu.MinecraftFrame");
args.add(session.getUserName());
args.add(session.getSessionId());
args.add(server.getName());
args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).toString());
args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).resolve("bin").toString());
args.add(server.getAddress());
args.add(server.getIconUrl());
if (!Version.isMasterBranch()) {
parent.log("Process args:");
Iterator<String> itArgs = args.iterator();
while (itArgs.hasNext()) {
String entry = itArgs.next();
parent.log(entry);
}
}
ProcessBuilder pb = new ProcessBuilder(args);
System.out.println("Running on: " + System.getProperty("os.name"));
if(System.getProperty("os.name").startsWith("Linux")) {
pb.environment().put("LD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("lib").resolve("i386").toString());
+ } else if(System.getProperty("os.name").startsWith("Linux")) {
+ pb.environment().put("DYLD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("lib").resolve("i386").toString());
}
pb.redirectErrorStream(true);
BufferedWriter buffWrite = null;
try {
buffWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
} catch (FileNotFoundException e) {
log(e.getMessage()+"\n");
e.printStackTrace();
}
try {
task = pb.start();
BufferedReader buffRead = new BufferedReader(new InputStreamReader(task.getInputStream()));
String line;
buffRead.mark(1024);
final String firstLine = buffRead.readLine();
setReady();
if (firstLine == null ||
firstLine.startsWith("Error occurred during initialization of VM") ||
firstLine.startsWith("Could not create the Java virtual machine.")) {
log("!!! Failure to launch detected.\n");
// fetch the whole error message
StringBuilder err = new StringBuilder(firstLine);
while ((line = buffRead.readLine()) != null) {
err.append('\n');
err.append(line);
}
log(err+"\n");
JOptionPane.showMessageDialog(null, err);
} else {
buffRead.reset();
minimizeFrame();
log("* Launching client...\n");
int counter = 0;
while ((line = buffRead.readLine()) != null)
{
if (buffWrite != null) {
buffWrite.write(line);
buffWrite.newLine();
counter++;
if (counter >= 20)
{
buffWrite.flush();
counter = 0;
}
} else {
System.out.println(line);
}
if( line.length() > 0) {
log(line+"\n");
}
}
}
buffWrite.flush();
buffWrite.close();
restoreFrame();
log("* Exiting Minecraft"+(forceKilled?" (killed)":"")+"\n");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private void restoreFrame() {
parent.restore();
toggleKillable(false);
}
private void minimizeFrame() {
parent.minimize(true);
toggleKillable(true);
}
private void setReady() {
ready = true;
if(launchButton != null) {
launchButton.setEnabled(true);
}
}
private void toggleKillable(boolean enabled) {
if( killItem == null ) return;
killItem.setEnabled(enabled);
if( enabled ) {
final AppletLauncherThread thread = this;
killItem.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
thread.stop();
}
});
} else {
for( ActionListener listener : killItem.getActionListeners() ) {
killItem.removeActionListener(listener);
}
killItem = null;
}
}
@Override
public void start() {
thread = new Thread(this);
thread.start();
}
@Override
public void stop() {
if( task != null ) {
final int confirm = JOptionPane.showConfirmDialog(null,
"Are you sure you want to kill Minecraft?\nThis could result in corrupted world save data.",
"Kill Minecraft",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if( confirm == JOptionPane.YES_OPTION ) {
forceKilled = true;
try {
task.destroy();
} catch( Exception e ) {
// maximum paranoia here
e.printStackTrace();
}
}
}
}
private void log(String msg) {
if( console == null ) return;
console.log(msg);
}
@Override
public void register(MainForm form, JButton btnLaunchMinecraft, MenuItem killItem) {
launchButton = btnLaunchMinecraft;
this.killItem = killItem;
if( ready ) {
setReady();
}
}
}
| true | true | public void run() {
String javaBin = "java";
File binDir = (new File(jrePath)).toPath().resolve("bin").toFile();
if( binDir.exists() ) {
javaBin = binDir.toPath().resolve("java").toString();
}
List<String> args = new ArrayList<String>();
args.add(javaBin);
args.add("-XX:+UseConcMarkSweepGC");
args.add("-XX:+CMSIncrementalMode");
args.add("-XX:+AggressiveOpts");
args.add("-Xms" + this.minMem);
args.add("-Xmx" + this.maxMem);
args.add("-classpath");
args.add(MCUpdater.getJarFile().toString());
args.add("org.smbarbour.mcu.MinecraftFrame");
args.add(session.getUserName());
args.add(session.getSessionId());
args.add(server.getName());
args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).toString());
args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).resolve("bin").toString());
args.add(server.getAddress());
args.add(server.getIconUrl());
if (!Version.isMasterBranch()) {
parent.log("Process args:");
Iterator<String> itArgs = args.iterator();
while (itArgs.hasNext()) {
String entry = itArgs.next();
parent.log(entry);
}
}
ProcessBuilder pb = new ProcessBuilder(args);
System.out.println("Running on: " + System.getProperty("os.name"));
if(System.getProperty("os.name").startsWith("Linux")) {
pb.environment().put("LD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("lib").resolve("i386").toString());
}
pb.redirectErrorStream(true);
BufferedWriter buffWrite = null;
try {
buffWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
} catch (FileNotFoundException e) {
log(e.getMessage()+"\n");
e.printStackTrace();
}
try {
task = pb.start();
BufferedReader buffRead = new BufferedReader(new InputStreamReader(task.getInputStream()));
String line;
buffRead.mark(1024);
final String firstLine = buffRead.readLine();
setReady();
if (firstLine == null ||
firstLine.startsWith("Error occurred during initialization of VM") ||
firstLine.startsWith("Could not create the Java virtual machine.")) {
log("!!! Failure to launch detected.\n");
// fetch the whole error message
StringBuilder err = new StringBuilder(firstLine);
while ((line = buffRead.readLine()) != null) {
err.append('\n');
err.append(line);
}
log(err+"\n");
JOptionPane.showMessageDialog(null, err);
} else {
buffRead.reset();
minimizeFrame();
log("* Launching client...\n");
int counter = 0;
while ((line = buffRead.readLine()) != null)
{
if (buffWrite != null) {
buffWrite.write(line);
buffWrite.newLine();
counter++;
if (counter >= 20)
{
buffWrite.flush();
counter = 0;
}
} else {
System.out.println(line);
}
if( line.length() > 0) {
log(line+"\n");
}
}
}
buffWrite.flush();
buffWrite.close();
restoreFrame();
log("* Exiting Minecraft"+(forceKilled?" (killed)":"")+"\n");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
| public void run() {
String javaBin = "java";
File binDir = (new File(jrePath)).toPath().resolve("bin").toFile();
if( binDir.exists() ) {
javaBin = binDir.toPath().resolve("java").toString();
}
List<String> args = new ArrayList<String>();
args.add(javaBin);
args.add("-XX:+UseConcMarkSweepGC");
args.add("-XX:+CMSIncrementalMode");
args.add("-XX:+AggressiveOpts");
args.add("-Xms" + this.minMem);
args.add("-Xmx" + this.maxMem);
args.add("-classpath");
args.add(MCUpdater.getJarFile().toString());
args.add("org.smbarbour.mcu.MinecraftFrame");
args.add(session.getUserName());
args.add(session.getSessionId());
args.add(server.getName());
args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).toString());
args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).resolve("bin").toString());
args.add(server.getAddress());
args.add(server.getIconUrl());
if (!Version.isMasterBranch()) {
parent.log("Process args:");
Iterator<String> itArgs = args.iterator();
while (itArgs.hasNext()) {
String entry = itArgs.next();
parent.log(entry);
}
}
ProcessBuilder pb = new ProcessBuilder(args);
System.out.println("Running on: " + System.getProperty("os.name"));
if(System.getProperty("os.name").startsWith("Linux")) {
pb.environment().put("LD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("lib").resolve("i386").toString());
} else if(System.getProperty("os.name").startsWith("Linux")) {
pb.environment().put("DYLD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("lib").resolve("i386").toString());
}
pb.redirectErrorStream(true);
BufferedWriter buffWrite = null;
try {
buffWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
} catch (FileNotFoundException e) {
log(e.getMessage()+"\n");
e.printStackTrace();
}
try {
task = pb.start();
BufferedReader buffRead = new BufferedReader(new InputStreamReader(task.getInputStream()));
String line;
buffRead.mark(1024);
final String firstLine = buffRead.readLine();
setReady();
if (firstLine == null ||
firstLine.startsWith("Error occurred during initialization of VM") ||
firstLine.startsWith("Could not create the Java virtual machine.")) {
log("!!! Failure to launch detected.\n");
// fetch the whole error message
StringBuilder err = new StringBuilder(firstLine);
while ((line = buffRead.readLine()) != null) {
err.append('\n');
err.append(line);
}
log(err+"\n");
JOptionPane.showMessageDialog(null, err);
} else {
buffRead.reset();
minimizeFrame();
log("* Launching client...\n");
int counter = 0;
while ((line = buffRead.readLine()) != null)
{
if (buffWrite != null) {
buffWrite.write(line);
buffWrite.newLine();
counter++;
if (counter >= 20)
{
buffWrite.flush();
counter = 0;
}
} else {
System.out.println(line);
}
if( line.length() > 0) {
log(line+"\n");
}
}
}
buffWrite.flush();
buffWrite.close();
restoreFrame();
log("* Exiting Minecraft"+(forceKilled?" (killed)":"")+"\n");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
|
diff --git a/cascading-core/src/main/java/cascading/pipe/Splice.java b/cascading-core/src/main/java/cascading/pipe/Splice.java
index bc6fe3a6..b3e21ad3 100644
--- a/cascading-core/src/main/java/cascading/pipe/Splice.java
+++ b/cascading-core/src/main/java/cascading/pipe/Splice.java
@@ -1,1416 +1,1416 @@
/*
* Copyright (c) 2007-2013 Concurrent, Inc. All Rights Reserved.
*
* Project and contact information: http://www.cascading.org/
*
* This file is part of the Cascading 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 cascading.pipe;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import cascading.flow.FlowElement;
import cascading.flow.planner.Scope;
import cascading.pipe.joiner.InnerJoin;
import cascading.pipe.joiner.Joiner;
import cascading.tuple.Fields;
import cascading.tuple.FieldsResolverException;
import cascading.tuple.TupleException;
import cascading.tuple.coerce.Coercions;
import cascading.tuple.type.CoercibleType;
import cascading.util.Util;
import static java.util.Arrays.asList;
/**
* The base class for {@link GroupBy}, {@link CoGroup}, {@link Merge}, and {@link HashJoin}. This class should not be used directly.
*
* @see GroupBy
* @see CoGroup
* @see Merge
* @see HashJoin
*/
public class Splice extends Pipe
{
static enum Kind
{
GroupBy, CoGroup, Merge, Join
}
private Kind kind;
/** Field spliceName */
private String spliceName;
/** Field pipes */
private final List<Pipe> pipes = new ArrayList<Pipe>();
/** Field groupFieldsMap */
protected final Map<String, Fields> keyFieldsMap = new LinkedHashMap<String, Fields>(); // keep order
/** Field sortFieldsMap */
protected Map<String, Fields> sortFieldsMap = new LinkedHashMap<String, Fields>(); // keep order
/** Field reverseOrder */
private boolean reverseOrder = false;
/** Field declaredFields */
protected Fields declaredFields;
/** Field resultGroupFields */
protected Fields resultGroupFields;
/** Field repeat */
private int numSelfJoins = 0;
/** Field coGrouper */
private Joiner joiner;
/** Field pipePos */
private transient Map<String, Integer> pipePos;
/**
* Constructor Splice creates a new Splice instance.
*
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
* @param declaredFields of type Fields
*/
protected Splice( Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields, Fields declaredFields )
{
this( lhs, lhsGroupFields, rhs, rhsGroupFields, declaredFields, null, null );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
* @param declaredFields of type Fields
* @param resultGroupFields of type Fields
*/
protected Splice( Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields, Fields declaredFields, Fields resultGroupFields )
{
this( lhs, lhsGroupFields, rhs, rhsGroupFields, declaredFields, resultGroupFields, null );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
* @param declaredFields of type Fields
* @param joiner of type CoGrouper
*/
protected Splice( Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields, Fields declaredFields, Joiner joiner )
{
this( Pipe.pipes( lhs, rhs ), Fields.fields( lhsGroupFields, rhsGroupFields ), declaredFields, joiner );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
* @param declaredFields of type Fields
* @param resultGroupFields of type Fields
* @param joiner of type Joiner
*/
protected Splice( Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields, Fields declaredFields, Fields resultGroupFields, Joiner joiner )
{
this( Pipe.pipes( lhs, rhs ), Fields.fields( lhsGroupFields, rhsGroupFields ), declaredFields, resultGroupFields, joiner );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
* @param joiner of type CoGrouper
*/
protected Splice( Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields, Joiner joiner )
{
this( lhs, lhsGroupFields, rhs, rhsGroupFields, null, joiner );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
*/
protected Splice( Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields )
{
this( Pipe.pipes( lhs, rhs ), Fields.fields( lhsGroupFields, rhsGroupFields ) );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipes of type Pipe...
*/
protected Splice( Pipe... pipes )
{
this( pipes, (Fields[]) null );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipes of type Pipe[]
* @param groupFields of type Fields[]
*/
protected Splice( Pipe[] pipes, Fields[] groupFields )
{
this( null, pipes, groupFields, null, null );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipes of type Pipe[]
* @param groupFields of type Fields[]
*/
protected Splice( String spliceName, Pipe[] pipes, Fields[] groupFields )
{
this( spliceName, pipes, groupFields, null, null );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipes of type Pipe[]
* @param groupFields of type Fields[]
* @param declaredFields of type Fields
*/
protected Splice( String spliceName, Pipe[] pipes, Fields[] groupFields, Fields declaredFields )
{
this( spliceName, pipes, groupFields, declaredFields, null );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipes of type Pipe[]
* @param groupFields of type Fields[]
* @param declaredFields of type Fields
* @param resultGroupFields of type Fields
*/
protected Splice( String spliceName, Pipe[] pipes, Fields[] groupFields, Fields declaredFields, Fields resultGroupFields )
{
this( spliceName, pipes, groupFields, declaredFields, resultGroupFields, null );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipes of type Pipe[]
* @param groupFields of type Fields[]
* @param declaredFields of type Fields
* @param joiner of type CoGrouper
*/
protected Splice( Pipe[] pipes, Fields[] groupFields, Fields declaredFields, Joiner joiner )
{
this( null, pipes, groupFields, declaredFields, null, joiner );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipes of type Pipe[]
* @param groupFields of type Fields[]
* @param declaredFields of type Fields
* @param resultGroupFields of type Fields
* @param joiner of type Joiner
*/
protected Splice( Pipe[] pipes, Fields[] groupFields, Fields declaredFields, Fields resultGroupFields, Joiner joiner )
{
this( null, pipes, groupFields, declaredFields, resultGroupFields, joiner );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipes of type Pipe[]
* @param groupFields of type Fields[]
* @param declaredFields of type Fields
* @param joiner of type CoGrouper
*/
protected Splice( String spliceName, Pipe[] pipes, Fields[] groupFields, Fields declaredFields, Fields resultGroupFields, Joiner joiner )
{
setKind();
this.spliceName = spliceName;
int uniques = new HashSet<Pipe>( asList( Pipe.resolvePreviousAll( pipes ) ) ).size();
if( pipes.length > 1 && uniques == 1 )
{
if( new HashSet<Fields>( asList( groupFields ) ).size() != 1 )
throw new IllegalArgumentException( "all groupFields must be identical" );
addPipe( pipes[ 0 ] );
this.numSelfJoins = pipes.length - 1;
this.keyFieldsMap.put( pipes[ 0 ].getName(), groupFields[ 0 ] );
if( resultGroupFields != null && groupFields[ 0 ].size() * pipes.length != resultGroupFields.size() )
throw new IllegalArgumentException( "resultGroupFields and cogroup joined fields must be same size" );
}
else
{
int last = -1;
for( int i = 0; i < pipes.length; i++ )
{
addPipe( pipes[ i ] );
if( groupFields == null || groupFields.length == 0 )
{
addGroupFields( pipes[ i ], Fields.FIRST );
continue;
}
if( last != -1 && last != groupFields[ i ].size() )
throw new IllegalArgumentException( "all groupFields must be same size" );
last = groupFields[ i ].size();
addGroupFields( pipes[ i ], groupFields[ i ] );
}
if( resultGroupFields != null && last * pipes.length != resultGroupFields.size() )
throw new IllegalArgumentException( "resultGroupFields and cogroup resulting joined fields must be same size" );
}
this.declaredFields = declaredFields;
this.resultGroupFields = resultGroupFields;
this.joiner = joiner;
verifyCoGrouper();
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
* @param declaredFields of type Fields
*/
protected Splice( String spliceName, Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields, Fields declaredFields )
{
this( lhs, lhsGroupFields, rhs, rhsGroupFields, declaredFields );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
* @param declaredFields of type Fields
* @param resultGroupFields of type Fields
*/
protected Splice( String spliceName, Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields, Fields declaredFields, Fields resultGroupFields )
{
this( lhs, lhsGroupFields, rhs, rhsGroupFields, declaredFields, resultGroupFields );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
* @param declaredFields of type Fields
* @param joiner of type CoGrouper
*/
protected Splice( String spliceName, Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields, Fields declaredFields, Joiner joiner )
{
this( lhs, lhsGroupFields, rhs, rhsGroupFields, declaredFields, joiner );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
* @param declaredFields of type Fields
* @param resultGroupFields of type Fields
* @param joiner of type Joiner
*/
protected Splice( String spliceName, Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields, Fields declaredFields, Fields resultGroupFields, Joiner joiner )
{
this( lhs, lhsGroupFields, rhs, rhsGroupFields, declaredFields, resultGroupFields, joiner );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
* @param joiner of type CoGrouper
*/
protected Splice( String spliceName, Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields, Joiner joiner )
{
this( lhs, lhsGroupFields, rhs, rhsGroupFields, joiner );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param lhs of type Pipe
* @param lhsGroupFields of type Fields
* @param rhs of type Pipe
* @param rhsGroupFields of type Fields
*/
protected Splice( String spliceName, Pipe lhs, Fields lhsGroupFields, Pipe rhs, Fields rhsGroupFields )
{
this( lhs, lhsGroupFields, rhs, rhsGroupFields );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipes of type Pipe...
*/
protected Splice( String spliceName, Pipe... pipes )
{
this( pipes );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
* @param declaredFields of type Fields
*/
protected Splice( Pipe pipe, Fields groupFields, int numSelfJoins, Fields declaredFields )
{
this( pipe, groupFields, numSelfJoins );
this.declaredFields = declaredFields;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
* @param declaredFields of type Fields
* @param resultGroupFields of type Fields
*/
protected Splice( Pipe pipe, Fields groupFields, int numSelfJoins, Fields declaredFields, Fields resultGroupFields )
{
this( pipe, groupFields, numSelfJoins );
this.declaredFields = declaredFields;
this.resultGroupFields = resultGroupFields;
if( resultGroupFields != null && groupFields.size() * numSelfJoins != resultGroupFields.size() )
throw new IllegalArgumentException( "resultGroupFields and cogroup resulting join fields must be same size" );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
* @param declaredFields of type Fields
* @param joiner of type CoGrouper
*/
protected Splice( Pipe pipe, Fields groupFields, int numSelfJoins, Fields declaredFields, Joiner joiner )
{
this( pipe, groupFields, numSelfJoins, declaredFields );
this.joiner = joiner;
verifyCoGrouper();
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
* @param declaredFields of type Fields
* @param resultGroupFields of type Fields
* @param joiner of type Joiner
*/
protected Splice( Pipe pipe, Fields groupFields, int numSelfJoins, Fields declaredFields, Fields resultGroupFields, Joiner joiner )
{
this( pipe, groupFields, numSelfJoins, declaredFields, resultGroupFields );
this.joiner = joiner;
verifyCoGrouper();
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
* @param joiner of type CoGrouper
*/
protected Splice( Pipe pipe, Fields groupFields, int numSelfJoins, Joiner joiner )
{
setKind();
addPipe( pipe );
this.keyFieldsMap.put( pipe.getName(), groupFields );
this.numSelfJoins = numSelfJoins;
this.joiner = joiner;
verifyCoGrouper();
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
*/
protected Splice( Pipe pipe, Fields groupFields, int numSelfJoins )
{
this( pipe, groupFields, numSelfJoins, (Joiner) null );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
* @param declaredFields of type Fields
*/
protected Splice( String spliceName, Pipe pipe, Fields groupFields, int numSelfJoins, Fields declaredFields )
{
this( pipe, groupFields, numSelfJoins, declaredFields );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
* @param declaredFields of type Fields
* @param resultGroupFields of type Fields
*/
protected Splice( String spliceName, Pipe pipe, Fields groupFields, int numSelfJoins, Fields declaredFields, Fields resultGroupFields )
{
this( pipe, groupFields, numSelfJoins, declaredFields, resultGroupFields );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
* @param declaredFields of type Fields
* @param joiner of type CoGrouper
*/
protected Splice( String spliceName, Pipe pipe, Fields groupFields, int numSelfJoins, Fields declaredFields, Joiner joiner )
{
this( pipe, groupFields, numSelfJoins, declaredFields, joiner );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
* @param declaredFields of type Fields
* @param resultGroupFields of type Fields
* @param joiner of type Joiner
*/
protected Splice( String spliceName, Pipe pipe, Fields groupFields, int numSelfJoins, Fields declaredFields, Fields resultGroupFields, Joiner joiner )
{
this( pipe, groupFields, numSelfJoins, declaredFields, resultGroupFields, joiner );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
* @param joiner of type CoGrouper
*/
protected Splice( String spliceName, Pipe pipe, Fields groupFields, int numSelfJoins, Joiner joiner )
{
this( pipe, groupFields, numSelfJoins, joiner );
this.spliceName = spliceName;
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param numSelfJoins of type int
*/
protected Splice( String spliceName, Pipe pipe, Fields groupFields, int numSelfJoins )
{
this( pipe, groupFields, numSelfJoins );
this.spliceName = spliceName;
}
////////////
// GROUPBY
////////////
/**
* Constructor Splice creates a new Splice instance where grouping occurs on {@link Fields#ALL} fields.
*
* @param pipe of type Pipe
*/
protected Splice( Pipe pipe )
{
this( null, pipe, Fields.ALL, null, false );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipe of type Pipe
* @param groupFields of type Fields
*/
protected Splice( Pipe pipe, Fields groupFields )
{
this( null, pipe, groupFields, null, false );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipe of type Pipe
* @param groupFields of type Fields
*/
protected Splice( String spliceName, Pipe pipe, Fields groupFields )
{
this( spliceName, pipe, groupFields, null, false );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param sortFields of type Fields
*/
protected Splice( Pipe pipe, Fields groupFields, Fields sortFields )
{
this( null, pipe, groupFields, sortFields, false );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param sortFields of type Fields
*/
protected Splice( String spliceName, Pipe pipe, Fields groupFields, Fields sortFields )
{
this( spliceName, pipe, groupFields, sortFields, false );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param sortFields of type Fields
* @param reverseOrder of type boolean
*/
protected Splice( Pipe pipe, Fields groupFields, Fields sortFields, boolean reverseOrder )
{
this( null, pipe, groupFields, sortFields, reverseOrder );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param sortFields of type Fields
* @param reverseOrder of type boolean
*/
protected Splice( String spliceName, Pipe pipe, Fields groupFields, Fields sortFields, boolean reverseOrder )
{
this( spliceName, Pipe.pipes( pipe ), groupFields, sortFields, reverseOrder );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipes of type Pipe
* @param groupFields of type Fields
*/
protected Splice( Pipe[] pipes, Fields groupFields )
{
this( null, pipes, groupFields, null, false );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipes of type Pipe
* @param groupFields of type Fields
*/
protected Splice( String spliceName, Pipe[] pipes, Fields groupFields )
{
this( spliceName, pipes, groupFields, null, false );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipes of type Pipe
* @param groupFields of type Fields
* @param sortFields of type Fields
*/
protected Splice( Pipe[] pipes, Fields groupFields, Fields sortFields )
{
this( null, pipes, groupFields, sortFields, false );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipe of type Pipe
* @param groupFields of type Fields
* @param sortFields of type Fields
*/
protected Splice( String spliceName, Pipe[] pipe, Fields groupFields, Fields sortFields )
{
this( spliceName, pipe, groupFields, sortFields, false );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param pipes of type Pipe
* @param groupFields of type Fields
* @param sortFields of type Fields
* @param reverseOrder of type boolean
*/
protected Splice( Pipe[] pipes, Fields groupFields, Fields sortFields, boolean reverseOrder )
{
this( null, pipes, groupFields, sortFields, reverseOrder );
}
/**
* Constructor Splice creates a new Splice instance.
*
* @param spliceName of type String
* @param pipes of type Pipe[]
* @param groupFields of type Fields
* @param sortFields of type Fields
* @param reverseOrder of type boolean
*/
protected Splice( String spliceName, Pipe[] pipes, Fields groupFields, Fields sortFields, boolean reverseOrder )
{
setKind();
this.spliceName = spliceName;
for( Pipe pipe : pipes )
{
addPipe( pipe );
this.keyFieldsMap.put( pipe.getName(), groupFields );
if( sortFields != null )
this.sortFieldsMap.put( pipe.getName(), sortFields );
}
this.reverseOrder = reverseOrder;
this.joiner = new InnerJoin();
}
private void verifyCoGrouper()
{
if( joiner == null )
{
joiner = new InnerJoin();
return;
}
if( joiner.numJoins() == -1 )
return;
int joins = Math.max( numSelfJoins, keyFieldsMap.size() - 1 ); // joining two streams is one join
if( joins != joiner.numJoins() )
throw new IllegalArgumentException( "invalid joiner, only accepts " + joiner.numJoins() + " joins, there are: " + joins );
}
private void setKind()
{
if( this instanceof GroupBy )
kind = Kind.GroupBy;
else if( this instanceof CoGroup )
kind = Kind.CoGroup;
else if( this instanceof Merge )
kind = Kind.Merge;
else
kind = Kind.Join;
}
/**
* Method getDeclaredFields returns the declaredFields of this Splice object.
*
* @return the declaredFields (type Fields) of this Splice object.
*/
public Fields getDeclaredFields()
{
return declaredFields;
}
private void addPipe( Pipe pipe )
{
if( pipe.getName() == null )
throw new IllegalArgumentException( "each input pipe must have a name" );
pipes.add( pipe ); // allow same pipe
}
private void addGroupFields( Pipe pipe, Fields fields )
{
if( keyFieldsMap.containsKey( pipe.getName() ) )
throw new IllegalArgumentException( "each input pipe branch must be uniquely named" );
keyFieldsMap.put( pipe.getName(), fields );
}
@Override
public String getName()
{
if( spliceName != null )
return spliceName;
StringBuffer buffer = new StringBuffer();
for( Pipe pipe : pipes )
{
if( buffer.length() != 0 )
{
if( isGroupBy() || isMerge() )
buffer.append( "+" );
else if( isCoGroup() || isJoin() )
buffer.append( "*" ); // more semantically correct
}
buffer.append( pipe.getName() );
}
spliceName = buffer.toString();
return spliceName;
}
@Override
public Pipe[] getPrevious()
{
return pipes.toArray( new Pipe[ pipes.size() ] );
}
/**
* Method getGroupingSelectors returns the groupingSelectors of this Splice object.
*
* @return the groupingSelectors (type Map<String, Fields>) of this Splice object.
*/
public Map<String, Fields> getKeySelectors()
{
return keyFieldsMap;
}
/**
* Method getSortingSelectors returns the sortingSelectors of this Splice object.
*
* @return the sortingSelectors (type Map<String, Fields>) of this Splice object.
*/
public Map<String, Fields> getSortingSelectors()
{
return sortFieldsMap;
}
/**
* Method isSorted returns true if this Splice instance is sorting values other than the group fields.
*
* @return the sorted (type boolean) of this Splice object.
*/
public boolean isSorted()
{
return !sortFieldsMap.isEmpty();
}
/**
* Method isSortReversed returns true if sorting is reversed.
*
* @return the sortReversed (type boolean) of this Splice object.
*/
public boolean isSortReversed()
{
return reverseOrder;
}
public synchronized Map<String, Integer> getPipePos()
{
if( pipePos != null )
return pipePos;
pipePos = new HashMap<String, Integer>();
int pos = 0;
for( Object pipe : pipes )
pipePos.put( ( (Pipe) pipe ).getName(), pos++ );
return pipePos;
}
public Joiner getJoiner()
{
return joiner;
}
/**
* Method isGroupBy returns true if this Splice instance will perform a GroupBy operation.
*
* @return the groupBy (type boolean) of this Splice object.
*/
public final boolean isGroupBy()
{
return kind == Kind.GroupBy;
}
public final boolean isCoGroup()
{
return kind == Kind.CoGroup;
}
public final boolean isMerge()
{
return kind == Kind.Merge;
}
public final boolean isJoin()
{
return kind == Kind.Join;
}
public int getNumSelfJoins()
{
return numSelfJoins;
}
boolean isSelfJoin()
{
return numSelfJoins != 0;
}
// FIELDS
@Override
public Scope outgoingScopeFor( Set<Scope> incomingScopes )
{
Map<String, Fields> groupingSelectors = resolveGroupingSelectors( incomingScopes );
Map<String, Fields> sortingSelectors = resolveSortingSelectors( incomingScopes );
Fields declared = resolveDeclared( incomingScopes );
Fields outGroupingFields = resultGroupFields;
if( outGroupingFields == null && isCoGroup() )
outGroupingFields = createJoinFields( incomingScopes, groupingSelectors, declared );
// for Group, the outgoing fields are the same as those declared
return new Scope( getName(), declared, outGroupingFields, groupingSelectors, sortingSelectors, declared, isGroupBy() );
}
private Fields createJoinFields( Set<Scope> incomingScopes, Map<String, Fields> groupingSelectors, Fields declared )
{
Map<String, Fields> incomingFields = new HashMap<String, Fields>();
for( Scope scope : incomingScopes )
incomingFields.put( scope.getName(), scope.getIncomingSpliceFields() );
Fields outGroupingFields = Fields.NONE;
int offset = 0;
for( Pipe pipe : pipes ) // need to retain order of pipes
{
String pipeName = pipe.getName();
Fields pipeGroupingSelector = groupingSelectors.get( pipeName );
Fields incomingField = incomingFields.get( pipeName );
if( !pipeGroupingSelector.isNone() )
{
Fields offsetFields = incomingField.selectPos( pipeGroupingSelector, offset );
Fields resolvedSelect = declared.select( offsetFields );
outGroupingFields = outGroupingFields.append( resolvedSelect );
}
offset += incomingField.size();
}
return outGroupingFields;
}
Map<String, Fields> resolveGroupingSelectors( Set<Scope> incomingScopes )
{
try
{
Map<String, Fields> groupingSelectors = getKeySelectors();
Map<String, Fields> groupingFields = resolveSelectorsAgainstIncoming( incomingScopes, groupingSelectors, "grouping" );
if( !verifySameSize( groupingFields ) )
throw new OperatorException( this, "all grouping fields must be same size: " + toString() );
verifySameTypes( groupingSelectors, groupingFields );
return groupingFields;
}
catch( FieldsResolverException exception )
{
throw new OperatorException( this, OperatorException.Kind.grouping, exception.getSourceFields(), exception.getSelectorFields(), exception );
}
catch( RuntimeException exception )
{
throw new OperatorException( this, "could not resolve grouping selector in: " + this, exception );
}
}
private boolean verifySameTypes( Map<String, Fields> groupingSelectors, Map<String, Fields> groupingFields )
{
// create array of field positions with comparators from the grouping selectors
// unsure which side has the comparators declared so make a union
boolean[] hasComparator = new boolean[ groupingFields.values().iterator().next().size() ];
for( Map.Entry<String, Fields> entry : groupingSelectors.entrySet() )
{
Comparator[] comparatorsArray = entry.getValue().getComparators();
for( int i = 0; i < comparatorsArray.length; i++ )
hasComparator[ i ] = hasComparator[ i ] || comparatorsArray[ i ] != null;
}
// compare all the rhs fields with the lhs (lhs and rhs are arbitrary here)
Iterator<Fields> iterator = groupingFields.values().iterator();
Fields lhsFields = iterator.next();
Type[] lhsTypes = lhsFields.getTypes();
// if types are null, no basis for comparison
if( lhsTypes == null )
return true;
while( iterator.hasNext() )
{
Fields rhsFields = iterator.next();
Type[] rhsTypes = rhsFields.getTypes();
// if types are null, no basis for comparison
if( rhsTypes == null )
return true;
for( int i = 0; i < lhsTypes.length; i++ )
{
if( hasComparator[ i ] )
continue;
Type lhs = lhsTypes[ i ];
Type rhs = rhsTypes[ i ];
lhs = getCanonicalType( lhs );
rhs = getCanonicalType( rhs );
if( lhs.equals( rhs ) )
continue;
Fields lhsError = new Fields( lhsFields.get( i ), lhsFields.getType( i ) );
Fields rhsError = new Fields( rhsFields.get( i ), rhsFields.getType( i ) );
throw new OperatorException( this, "grouping fields must declare same types:" + lhsError.printVerbose() + " not same as " + rhsError.printVerbose() );
}
}
return true;
}
private Type getCanonicalType( Type type )
{
if( type instanceof CoercibleType )
type = ( (CoercibleType) type ).getCanonicalType();
// if one side is primitive, normalize to its primitive wrapper type
if( type instanceof Class )
type = Coercions.asNonPrimitive( (Class) type );
return type;
}
private boolean verifySameSize( Map<String, Fields> groupingFields )
{
Iterator<Fields> iterator = groupingFields.values().iterator();
int size = iterator.next().size();
while( iterator.hasNext() )
{
Fields groupingField = iterator.next();
if( groupingField.size() != size )
return false;
size = groupingField.size();
}
return true;
}
private Map<String, Fields> resolveSelectorsAgainstIncoming( Set<Scope> incomingScopes, Map<String, Fields> selectors, String type )
{
Map<String, Fields> resolvedFields = new HashMap<String, Fields>();
for( Scope incomingScope : incomingScopes )
{
Fields selector = selectors.get( incomingScope.getName() );
if( selector == null )
throw new OperatorException( this, "no " + type + " selector found for: " + incomingScope.getName() );
Fields incomingFields;
if( selector.isNone() )
incomingFields = Fields.NONE;
else if( selector.isAll() )
incomingFields = incomingScope.getIncomingSpliceFields();
else if( selector.isGroup() )
incomingFields = incomingScope.getOutGroupingFields();
else if( selector.isValues() )
incomingFields = incomingScope.getOutValuesFields().subtract( incomingScope.getOutGroupingFields() );
else
incomingFields = incomingScope.getIncomingSpliceFields().select( selector );
resolvedFields.put( incomingScope.getName(), incomingFields );
}
return resolvedFields;
}
Map<String, Fields> resolveSortingSelectors( Set<Scope> incomingScopes )
{
try
{
if( getSortingSelectors().isEmpty() )
return null;
return resolveSelectorsAgainstIncoming( incomingScopes, getSortingSelectors(), "sorting" );
}
catch( FieldsResolverException exception )
{
throw new OperatorException( this, OperatorException.Kind.sorting, exception.getSourceFields(), exception.getSelectorFields(), exception );
}
catch( RuntimeException exception )
{
throw new OperatorException( this, "could not resolve sorting selector in: " + this, exception );
}
}
@Override
public Fields resolveIncomingOperationPassThroughFields( Scope incomingScope )
{
return incomingScope.getIncomingSpliceFields();
}
Fields resolveDeclared( Set<Scope> incomingScopes )
{
try
{
Fields declaredFields = getDeclaredFields();
if( declaredFields != null ) // null for GroupBy
{
if( incomingScopes.size() != pipes.size() && isSelfJoin() )
throw new OperatorException( this, "self joins without intermediate operators are not permitted, see 'numSelfJoins' constructor or identity function" );
int size = 0;
boolean foundUnknown = false;
List<Fields> appendableFields = getOrderedResolvedFields( incomingScopes );
for( Fields fields : appendableFields )
{
foundUnknown = foundUnknown || fields.isUnknown();
size += fields.size();
}
// we must relax field checking in the face of unkown fields
if( !foundUnknown && declaredFields.size() != size * ( numSelfJoins + 1 ) )
{
if( isSelfJoin() )
throw new OperatorException( this, "declared grouped fields not same size as grouped values, declared: " + declaredFields.printVerbose() + " != size: " + size * ( numSelfJoins + 1 ) );
else
throw new OperatorException( this, "declared grouped fields not same size as grouped values, declared: " + declaredFields.printVerbose() + " resolved: " + Util.print( appendableFields, "" ) );
}
int i = 0;
for( Fields appendableField : appendableFields )
{
Type[] types = appendableField.getTypes();
if( types == null )
{
i += appendableField.size();
continue;
}
for( Type type : types )
{
if( type != null )
declaredFields = declaredFields.applyType( i, type );
i++;
}
}
return declaredFields;
}
// support merge or cogrouping here
if( isGroupBy() || isMerge() )
{
Iterator<Scope> iterator = incomingScopes.iterator();
Fields commonFields = iterator.next().getIncomingSpliceFields();
while( iterator.hasNext() )
{
Scope incomingScope = iterator.next();
Fields fields = incomingScope.getIncomingSpliceFields();
if( !commonFields.equalsFields( fields ) )
- throw new OperatorException( this, "merged streams must declare the same field names, expected: " + commonFields.printVerbose() + " found: " + fields.printVerbose() );
+ throw new OperatorException( this, "merged streams must declare the same field names, in the same order, expected: " + commonFields.printVerbose() + " found: " + fields.printVerbose() );
}
return commonFields;
}
else
{
List<Fields> appendableFields = getOrderedResolvedFields( incomingScopes );
Fields appendedFields = new Fields();
try
{
// will fail on name collisions
for( Fields appendableField : appendableFields )
appendedFields = appendedFields.append( appendableField );
}
catch( TupleException exception )
{
String fields = "";
for( Fields appendableField : appendableFields )
fields += appendableField.print();
throw new OperatorException( this, "found duplicate field names in joined tuple stream: " + fields, exception );
}
return appendedFields;
}
}
catch( OperatorException exception )
{
throw exception;
}
catch( RuntimeException exception )
{
throw new OperatorException( this, "could not resolve declared fields in: " + this, exception );
}
}
private List<Fields> getOrderedResolvedFields( Set<Scope> incomingScopes )
{
Map<String, Scope> scopesMap = new HashMap<String, Scope>();
for( Scope incomingScope : incomingScopes )
scopesMap.put( incomingScope.getName(), incomingScope );
List<Fields> appendableFields = new ArrayList<Fields>();
for( Pipe pipe : pipes )
appendableFields.add( scopesMap.get( pipe.getName() ).getIncomingSpliceFields() );
return appendableFields;
}
@Override
public boolean isEquivalentTo( FlowElement element )
{
boolean equivalentTo = super.isEquivalentTo( element );
if( !equivalentTo )
return equivalentTo;
Splice splice = (Splice) element;
if( !keyFieldsMap.equals( splice.keyFieldsMap ) )
return false;
if( !pipes.equals( splice.pipes ) )
return false;
return true;
}
// OBJECT OVERRIDES
@Override
@SuppressWarnings({"RedundantIfStatement"})
public boolean equals( Object object )
{
if( this == object )
return true;
if( object == null || getClass() != object.getClass() )
return false;
if( !super.equals( object ) )
return false;
Splice splice = (Splice) object;
if( spliceName != null ? !spliceName.equals( splice.spliceName ) : splice.spliceName != null )
return false;
if( keyFieldsMap != null ? !keyFieldsMap.equals( splice.keyFieldsMap ) : splice.keyFieldsMap != null )
return false;
if( pipes != null ? !pipes.equals( splice.pipes ) : splice.pipes != null )
return false;
return true;
}
@Override
public int hashCode()
{
int result = super.hashCode();
result = 31 * result + ( pipes != null ? pipes.hashCode() : 0 );
result = 31 * result + ( keyFieldsMap != null ? keyFieldsMap.hashCode() : 0 );
result = 31 * result + ( spliceName != null ? spliceName.hashCode() : 0 );
return result;
}
@Override
public String toString()
{
StringBuilder buffer = new StringBuilder( super.toString() );
buffer.append( "[by:" );
for( String name : keyFieldsMap.keySet() )
{
if( keyFieldsMap.size() > 1 )
buffer.append( " " ).append( name ).append( ":" );
buffer.append( keyFieldsMap.get( name ).printVerbose() );
}
if( isSelfJoin() )
buffer.append( "[numSelfJoins:" ).append( numSelfJoins ).append( "]" );
buffer.append( "]" );
return buffer.toString();
}
@Override
protected void printInternal( StringBuffer buffer, Scope scope )
{
super.printInternal( buffer, scope );
Map<String, Fields> map = scope.getKeySelectors();
if( map != null )
{
buffer.append( "[by:" );
// important to retain incoming pipe order
for( Map.Entry<String, Fields> entry : keyFieldsMap.entrySet() )
{
String name = entry.getKey();
if( map.size() > 1 )
buffer.append( name ).append( ":" );
buffer.append( map.get( name ).print() ); // get resolved keys
}
if( isSelfJoin() )
buffer.append( "[numSelfJoins:" ).append( numSelfJoins ).append( "]" );
buffer.append( "]" );
}
}
}
| true | true | Fields resolveDeclared( Set<Scope> incomingScopes )
{
try
{
Fields declaredFields = getDeclaredFields();
if( declaredFields != null ) // null for GroupBy
{
if( incomingScopes.size() != pipes.size() && isSelfJoin() )
throw new OperatorException( this, "self joins without intermediate operators are not permitted, see 'numSelfJoins' constructor or identity function" );
int size = 0;
boolean foundUnknown = false;
List<Fields> appendableFields = getOrderedResolvedFields( incomingScopes );
for( Fields fields : appendableFields )
{
foundUnknown = foundUnknown || fields.isUnknown();
size += fields.size();
}
// we must relax field checking in the face of unkown fields
if( !foundUnknown && declaredFields.size() != size * ( numSelfJoins + 1 ) )
{
if( isSelfJoin() )
throw new OperatorException( this, "declared grouped fields not same size as grouped values, declared: " + declaredFields.printVerbose() + " != size: " + size * ( numSelfJoins + 1 ) );
else
throw new OperatorException( this, "declared grouped fields not same size as grouped values, declared: " + declaredFields.printVerbose() + " resolved: " + Util.print( appendableFields, "" ) );
}
int i = 0;
for( Fields appendableField : appendableFields )
{
Type[] types = appendableField.getTypes();
if( types == null )
{
i += appendableField.size();
continue;
}
for( Type type : types )
{
if( type != null )
declaredFields = declaredFields.applyType( i, type );
i++;
}
}
return declaredFields;
}
// support merge or cogrouping here
if( isGroupBy() || isMerge() )
{
Iterator<Scope> iterator = incomingScopes.iterator();
Fields commonFields = iterator.next().getIncomingSpliceFields();
while( iterator.hasNext() )
{
Scope incomingScope = iterator.next();
Fields fields = incomingScope.getIncomingSpliceFields();
if( !commonFields.equalsFields( fields ) )
throw new OperatorException( this, "merged streams must declare the same field names, expected: " + commonFields.printVerbose() + " found: " + fields.printVerbose() );
}
return commonFields;
}
else
{
List<Fields> appendableFields = getOrderedResolvedFields( incomingScopes );
Fields appendedFields = new Fields();
try
{
// will fail on name collisions
for( Fields appendableField : appendableFields )
appendedFields = appendedFields.append( appendableField );
}
catch( TupleException exception )
{
String fields = "";
for( Fields appendableField : appendableFields )
fields += appendableField.print();
throw new OperatorException( this, "found duplicate field names in joined tuple stream: " + fields, exception );
}
return appendedFields;
}
}
catch( OperatorException exception )
{
throw exception;
}
catch( RuntimeException exception )
{
throw new OperatorException( this, "could not resolve declared fields in: " + this, exception );
}
}
| Fields resolveDeclared( Set<Scope> incomingScopes )
{
try
{
Fields declaredFields = getDeclaredFields();
if( declaredFields != null ) // null for GroupBy
{
if( incomingScopes.size() != pipes.size() && isSelfJoin() )
throw new OperatorException( this, "self joins without intermediate operators are not permitted, see 'numSelfJoins' constructor or identity function" );
int size = 0;
boolean foundUnknown = false;
List<Fields> appendableFields = getOrderedResolvedFields( incomingScopes );
for( Fields fields : appendableFields )
{
foundUnknown = foundUnknown || fields.isUnknown();
size += fields.size();
}
// we must relax field checking in the face of unkown fields
if( !foundUnknown && declaredFields.size() != size * ( numSelfJoins + 1 ) )
{
if( isSelfJoin() )
throw new OperatorException( this, "declared grouped fields not same size as grouped values, declared: " + declaredFields.printVerbose() + " != size: " + size * ( numSelfJoins + 1 ) );
else
throw new OperatorException( this, "declared grouped fields not same size as grouped values, declared: " + declaredFields.printVerbose() + " resolved: " + Util.print( appendableFields, "" ) );
}
int i = 0;
for( Fields appendableField : appendableFields )
{
Type[] types = appendableField.getTypes();
if( types == null )
{
i += appendableField.size();
continue;
}
for( Type type : types )
{
if( type != null )
declaredFields = declaredFields.applyType( i, type );
i++;
}
}
return declaredFields;
}
// support merge or cogrouping here
if( isGroupBy() || isMerge() )
{
Iterator<Scope> iterator = incomingScopes.iterator();
Fields commonFields = iterator.next().getIncomingSpliceFields();
while( iterator.hasNext() )
{
Scope incomingScope = iterator.next();
Fields fields = incomingScope.getIncomingSpliceFields();
if( !commonFields.equalsFields( fields ) )
throw new OperatorException( this, "merged streams must declare the same field names, in the same order, expected: " + commonFields.printVerbose() + " found: " + fields.printVerbose() );
}
return commonFields;
}
else
{
List<Fields> appendableFields = getOrderedResolvedFields( incomingScopes );
Fields appendedFields = new Fields();
try
{
// will fail on name collisions
for( Fields appendableField : appendableFields )
appendedFields = appendedFields.append( appendableField );
}
catch( TupleException exception )
{
String fields = "";
for( Fields appendableField : appendableFields )
fields += appendableField.print();
throw new OperatorException( this, "found duplicate field names in joined tuple stream: " + fields, exception );
}
return appendedFields;
}
}
catch( OperatorException exception )
{
throw exception;
}
catch( RuntimeException exception )
{
throw new OperatorException( this, "could not resolve declared fields in: " + this, exception );
}
}
|
diff --git a/src/main/java/org/dynmap/ClientUpdateComponent.java b/src/main/java/org/dynmap/ClientUpdateComponent.java
index 97fa8210..14173101 100644
--- a/src/main/java/org/dynmap/ClientUpdateComponent.java
+++ b/src/main/java/org/dynmap/ClientUpdateComponent.java
@@ -1,75 +1,77 @@
package org.dynmap;
import static org.dynmap.JSONUtils.a;
import static org.dynmap.JSONUtils.s;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class ClientUpdateComponent extends Component {
public ClientUpdateComponent(final DynmapPlugin plugin, ConfigurationNode configuration) {
super(plugin, configuration);
plugin.events.addListener("buildclientupdate", new Event.Listener<ClientUpdateEvent>() {
@Override
public void triggered(ClientUpdateEvent e) {
buildClientUpdate(e);
}
});
}
protected void buildClientUpdate(ClientUpdateEvent e) {
World world = e.world.world;
JSONObject u = e.update;
long since = e.timestamp;
String worldName = world.getName();
s(u, "servertime", world.getTime() % 24000);
s(u, "hasStorm", world.hasStorm());
s(u, "isThundering", world.isThundering());
s(u, "players", new JSONArray());
Player[] players = plugin.playerList.getVisiblePlayers();
for(int i=0;i<players.length;i++) {
Player p = players[i];
Location pl = p.getLocation();
JSONObject jp = new JSONObject();
s(jp, "type", "player");
s(jp, "name", ChatColor.stripColor(p.getDisplayName()));
s(jp, "account", p.getName());
/* Don't leak player location for world not visible on maps, or if sendposition disbaled */
DynmapWorld pworld = MapManager.mapman.worldsLookup.get(p.getWorld().getName());
- if(configuration.getBoolean("sendpositon", true) && (pworld != null) && pworld.sendposition) {
+ /* Fix typo on 'sendpositon' to 'sendposition', keep bad one in case someone used it */
+ if(configuration.getBoolean("sendposition", true) && configuration.getBoolean("sendpositon", true) &&
+ (pworld != null) && pworld.sendposition) {
s(jp, "world", p.getWorld().getName());
s(jp, "x", pl.getX());
s(jp, "y", pl.getY());
s(jp, "z", pl.getZ());
}
else {
s(jp, "world", "-some-other-bogus-world-");
s(jp, "x", 0.0);
s(jp, "y", 64.0);
s(jp, "z", 0.0);
}
/* Only send health if enabled AND we're on visible world */
if (configuration.getBoolean("sendhealth", false) && (pworld != null) && pworld.sendhealth) {
s(jp, "health", p.getHealth());
s(jp, "armor", Armor.getArmorPoints(p));
}
else {
s(jp, "health", 0);
s(jp, "armor", 0);
}
a(u, "players", jp);
}
s(u, "updates", new JSONArray());
for(Object update : plugin.mapManager.getWorldUpdates(worldName, since)) {
a(u, "updates", (Client.Update)update);
}
}
}
| true | true | protected void buildClientUpdate(ClientUpdateEvent e) {
World world = e.world.world;
JSONObject u = e.update;
long since = e.timestamp;
String worldName = world.getName();
s(u, "servertime", world.getTime() % 24000);
s(u, "hasStorm", world.hasStorm());
s(u, "isThundering", world.isThundering());
s(u, "players", new JSONArray());
Player[] players = plugin.playerList.getVisiblePlayers();
for(int i=0;i<players.length;i++) {
Player p = players[i];
Location pl = p.getLocation();
JSONObject jp = new JSONObject();
s(jp, "type", "player");
s(jp, "name", ChatColor.stripColor(p.getDisplayName()));
s(jp, "account", p.getName());
/* Don't leak player location for world not visible on maps, or if sendposition disbaled */
DynmapWorld pworld = MapManager.mapman.worldsLookup.get(p.getWorld().getName());
if(configuration.getBoolean("sendpositon", true) && (pworld != null) && pworld.sendposition) {
s(jp, "world", p.getWorld().getName());
s(jp, "x", pl.getX());
s(jp, "y", pl.getY());
s(jp, "z", pl.getZ());
}
else {
s(jp, "world", "-some-other-bogus-world-");
s(jp, "x", 0.0);
s(jp, "y", 64.0);
s(jp, "z", 0.0);
}
/* Only send health if enabled AND we're on visible world */
if (configuration.getBoolean("sendhealth", false) && (pworld != null) && pworld.sendhealth) {
s(jp, "health", p.getHealth());
s(jp, "armor", Armor.getArmorPoints(p));
}
else {
s(jp, "health", 0);
s(jp, "armor", 0);
}
a(u, "players", jp);
}
s(u, "updates", new JSONArray());
for(Object update : plugin.mapManager.getWorldUpdates(worldName, since)) {
a(u, "updates", (Client.Update)update);
}
}
| protected void buildClientUpdate(ClientUpdateEvent e) {
World world = e.world.world;
JSONObject u = e.update;
long since = e.timestamp;
String worldName = world.getName();
s(u, "servertime", world.getTime() % 24000);
s(u, "hasStorm", world.hasStorm());
s(u, "isThundering", world.isThundering());
s(u, "players", new JSONArray());
Player[] players = plugin.playerList.getVisiblePlayers();
for(int i=0;i<players.length;i++) {
Player p = players[i];
Location pl = p.getLocation();
JSONObject jp = new JSONObject();
s(jp, "type", "player");
s(jp, "name", ChatColor.stripColor(p.getDisplayName()));
s(jp, "account", p.getName());
/* Don't leak player location for world not visible on maps, or if sendposition disbaled */
DynmapWorld pworld = MapManager.mapman.worldsLookup.get(p.getWorld().getName());
/* Fix typo on 'sendpositon' to 'sendposition', keep bad one in case someone used it */
if(configuration.getBoolean("sendposition", true) && configuration.getBoolean("sendpositon", true) &&
(pworld != null) && pworld.sendposition) {
s(jp, "world", p.getWorld().getName());
s(jp, "x", pl.getX());
s(jp, "y", pl.getY());
s(jp, "z", pl.getZ());
}
else {
s(jp, "world", "-some-other-bogus-world-");
s(jp, "x", 0.0);
s(jp, "y", 64.0);
s(jp, "z", 0.0);
}
/* Only send health if enabled AND we're on visible world */
if (configuration.getBoolean("sendhealth", false) && (pworld != null) && pworld.sendhealth) {
s(jp, "health", p.getHealth());
s(jp, "armor", Armor.getArmorPoints(p));
}
else {
s(jp, "health", 0);
s(jp, "armor", 0);
}
a(u, "players", jp);
}
s(u, "updates", new JSONArray());
for(Object update : plugin.mapManager.getWorldUpdates(worldName, since)) {
a(u, "updates", (Client.Update)update);
}
}
|
diff --git a/src/dao/PostDAO.java b/src/dao/PostDAO.java
index 138e735..5e9f04e 100644
--- a/src/dao/PostDAO.java
+++ b/src/dao/PostDAO.java
@@ -1,210 +1,210 @@
package dao;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import javax.naming.*;
import javax.sql.*;
import org.apache.catalina.connector.Request;
import bean.*;
public class PostDAO {
public static DataSource getDataSource() throws NamingException {
Context initCtx = null;
Context envCtx = null;
// Obtain our environment naming context
initCtx = new InitialContext();
envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our data source
return (DataSource) envCtx.lookup("jdbc/WebDB");
}
public static ArrayList<Post> getPage(int page) throws SQLException, NamingException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<Comment> comment = new ArrayList<Comment>();
if (page <= 0) {
page = 1;
}
DataSource ds = getDataSource();
ArrayList<Post> result = new ArrayList<Post>();
int startPos = (page - 1) * 20;
try {
conn = ds.getConnection();
// 전체 글 테이블 SELECT.. startPos부터 numItems까지
stmt = conn.createStatement();
- rs = stmt.executeQuery("select * from member,article order by article.postdate desc limit " + startPos + ", 20");
+ rs = stmt.executeQuery("select DISTINCT * from member,article where member.userid = article.userid order by article.postdate desc limit " + startPos + ", 20");
// 먼저 글의 목록을 받아온다
while(rs.next()) {
result.add(new Post(new Member( rs.getString("userid"),
rs.getString("userpassword"),
rs.getTimestamp("registerdate"),
rs.getString("lastname"),
rs.getString("firstname"),
rs.getString("nickname"),
rs.getString("profilephoto"),
rs.getString("gender"),
rs.getString("email"),
rs.getString("introduce"),
rs.getString("website"),
rs.getString("info"),
rs.getInt("level")),
new Article(rs.getInt("postid"),
rs.getString("userid"),
rs.getInt("albumid"),
rs.getString("photo"),
rs.getString("content"),
rs.getTimestamp("postdate"),
rs.getString("category"),
rs.getInt("hits"),
rs.getInt("likehits"),
rs.getInt("postip")),
new ArrayList<Comment>()));
}
// 글의 목록에 코멘트 리스트를 채워준다.
for(int i=0; i < result.size(); i++) {
comment = CommentDAO.getCommentList(result.get(i).getArticle().getPostid());
result.get(i).setComment(comment);
}
} finally {
// 무슨 일이 있어도 리소스를 제대로 종료
if (rs != null) try{rs.close();} catch(SQLException e) {}
if (stmt != null) try{stmt.close();} catch(SQLException e) {}
if (conn != null) try{conn.close();} catch(SQLException e) {}
}
return result;
}
public static ArrayList<Post> getAllPage() throws SQLException, NamingException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<Comment> comment = new ArrayList<Comment>();
DataSource ds = getDataSource();
ArrayList<Post> result = new ArrayList<Post>();
try {
conn = ds.getConnection();
stmt = conn.createStatement();
// 전체 글 테이블 SELECT.. startPos부터 numItems까지
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from member,article where member.userid = article.userid order by article.postdate desc");
// 먼저 글의 목록을 받아온다
while(rs.next()) {
result.add(new Post(new Member( rs.getString("userid"),
rs.getString("userpassword"),
rs.getTimestamp("registerdate"),
rs.getString("lastname"),
rs.getString("firstname"),
rs.getString("nickname"),
rs.getString("profilephoto"),
rs.getString("gender"),
rs.getString("email"),
rs.getString("introduce"),
rs.getString("website"),
rs.getString("info"),
rs.getInt("level")),
new Article(rs.getInt("postid"),
rs.getString("userid"),
rs.getInt("albumid"),
rs.getString("photo"),
rs.getString("content"),
rs.getTimestamp("postdate"),
rs.getString("category"),
rs.getInt("hits"),
rs.getInt("likehits"),
rs.getInt("postip")),
new ArrayList<Comment>()));
}
// 글의 목록에 코멘트 리스트를 채워준다.
for(int i=0; i < result.size(); i++) {
comment = CommentDAO.getCommentList(result.get(i).getArticle().getPostid());
result.get(i).setComment(comment);
}
} finally {
// 무슨 일이 있어도 리소스를 제대로 종료
if (rs != null) try{rs.close();} catch(SQLException e) {}
if (stmt != null) try{stmt.close();} catch(SQLException e) {}
if (conn != null) try{conn.close();} catch(SQLException e) {}
}
return result;
}
public static Post findByPostID(int id) throws SQLException, NamingException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList<Comment> comment = new ArrayList<Comment>();
Post post = new Post();
DataSource ds = getDataSource();
try {
conn = ds.getConnection();
stmt = conn.prepareStatement("select DISTINCT * from article, member where article.postid = ? and article.userid = member.userid");
stmt.setInt(1, id);
rs = stmt.executeQuery();
// 먼저 글의 목록을 받아온다
while(rs.next()) {
post = new Post(new Member( rs.getString("userid"),
rs.getString("userpassword"),
rs.getTimestamp("registerdate"),
rs.getString("lastname"),
rs.getString("firstname"),
rs.getString("nickname"),
rs.getString("profilephoto"),
rs.getString("gender"),
rs.getString("email"),
rs.getString("introduce"),
rs.getString("website"),
rs.getString("info"),
rs.getInt("level")),
new Article(rs.getInt("postid"),
rs.getString("userid"),
rs.getInt("albumid"),
rs.getString("photo"),
rs.getString("content"),
rs.getTimestamp("postdate"),
rs.getString("category"),
rs.getInt("hits"),
rs.getInt("likehits"),
rs.getInt("postip")),
new ArrayList<Comment>());
}
comment = CommentDAO.getCommentList(id);
post.setComment(comment);
} finally {
// 무슨 일이 있어도 리소스를 제대로 종료
if (rs != null) try{rs.close();} catch(SQLException e) {}
if (stmt != null) try{stmt.close();} catch(SQLException e) {}
if (conn != null) try{conn.close();} catch(SQLException e) {}
}
return post;
}
}
| true | true | public static ArrayList<Post> getPage(int page) throws SQLException, NamingException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<Comment> comment = new ArrayList<Comment>();
if (page <= 0) {
page = 1;
}
DataSource ds = getDataSource();
ArrayList<Post> result = new ArrayList<Post>();
int startPos = (page - 1) * 20;
try {
conn = ds.getConnection();
// 전체 글 테이블 SELECT.. startPos부터 numItems까지
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from member,article order by article.postdate desc limit " + startPos + ", 20");
// 먼저 글의 목록을 받아온다
while(rs.next()) {
result.add(new Post(new Member( rs.getString("userid"),
rs.getString("userpassword"),
rs.getTimestamp("registerdate"),
rs.getString("lastname"),
rs.getString("firstname"),
rs.getString("nickname"),
rs.getString("profilephoto"),
rs.getString("gender"),
rs.getString("email"),
rs.getString("introduce"),
rs.getString("website"),
rs.getString("info"),
rs.getInt("level")),
new Article(rs.getInt("postid"),
rs.getString("userid"),
rs.getInt("albumid"),
rs.getString("photo"),
rs.getString("content"),
rs.getTimestamp("postdate"),
rs.getString("category"),
rs.getInt("hits"),
rs.getInt("likehits"),
rs.getInt("postip")),
new ArrayList<Comment>()));
}
// 글의 목록에 코멘트 리스트를 채워준다.
for(int i=0; i < result.size(); i++) {
comment = CommentDAO.getCommentList(result.get(i).getArticle().getPostid());
result.get(i).setComment(comment);
}
} finally {
// 무슨 일이 있어도 리소스를 제대로 종료
if (rs != null) try{rs.close();} catch(SQLException e) {}
if (stmt != null) try{stmt.close();} catch(SQLException e) {}
if (conn != null) try{conn.close();} catch(SQLException e) {}
}
return result;
}
| public static ArrayList<Post> getPage(int page) throws SQLException, NamingException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<Comment> comment = new ArrayList<Comment>();
if (page <= 0) {
page = 1;
}
DataSource ds = getDataSource();
ArrayList<Post> result = new ArrayList<Post>();
int startPos = (page - 1) * 20;
try {
conn = ds.getConnection();
// 전체 글 테이블 SELECT.. startPos부터 numItems까지
stmt = conn.createStatement();
rs = stmt.executeQuery("select DISTINCT * from member,article where member.userid = article.userid order by article.postdate desc limit " + startPos + ", 20");
// 먼저 글의 목록을 받아온다
while(rs.next()) {
result.add(new Post(new Member( rs.getString("userid"),
rs.getString("userpassword"),
rs.getTimestamp("registerdate"),
rs.getString("lastname"),
rs.getString("firstname"),
rs.getString("nickname"),
rs.getString("profilephoto"),
rs.getString("gender"),
rs.getString("email"),
rs.getString("introduce"),
rs.getString("website"),
rs.getString("info"),
rs.getInt("level")),
new Article(rs.getInt("postid"),
rs.getString("userid"),
rs.getInt("albumid"),
rs.getString("photo"),
rs.getString("content"),
rs.getTimestamp("postdate"),
rs.getString("category"),
rs.getInt("hits"),
rs.getInt("likehits"),
rs.getInt("postip")),
new ArrayList<Comment>()));
}
// 글의 목록에 코멘트 리스트를 채워준다.
for(int i=0; i < result.size(); i++) {
comment = CommentDAO.getCommentList(result.get(i).getArticle().getPostid());
result.get(i).setComment(comment);
}
} finally {
// 무슨 일이 있어도 리소스를 제대로 종료
if (rs != null) try{rs.close();} catch(SQLException e) {}
if (stmt != null) try{stmt.close();} catch(SQLException e) {}
if (conn != null) try{conn.close();} catch(SQLException e) {}
}
return result;
}
|
diff --git a/src/cat/mobilejazz/database/content/DataProvider.java b/src/cat/mobilejazz/database/content/DataProvider.java
index 8729924..25b434f 100644
--- a/src/cat/mobilejazz/database/content/DataProvider.java
+++ b/src/cat/mobilejazz/database/content/DataProvider.java
@@ -1,707 +1,707 @@
package cat.mobilejazz.database.content;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.WeakHashMap;
import org.apache.http.auth.AuthenticationException;
import org.json.JSONException;
import org.json.JSONObject;
import android.accounts.Account;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteTransactionListener;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import cat.mobilejazz.database.Column;
import cat.mobilejazz.database.Database;
import cat.mobilejazz.database.ProgressListener;
import cat.mobilejazz.database.SQLUtils;
import cat.mobilejazz.database.Storage;
import cat.mobilejazz.database.Table;
import cat.mobilejazz.database.View;
import cat.mobilejazz.database.content.DataAdapter.DataAdapterListener;
import cat.mobilejazz.database.query.Select;
import cat.mobilejazz.utilities.debug.Debug;
/**
* A generic implementation of a content provider. It allows to track change
* history by employing a separate table {@code CHANGES}.
*
* All uris are of the form: {@code content://<authority>/
* <table>[/<id>][?<parameters>} where the possible uri parameters are the
* following:
* <ul>
* <li>Record query changes ({@link #QUERY_KEY_RECORD_CHANGES}, {@link boolean}
* ): Defines whether or not the changes to the database should be automatically
* recorded as a change in the respective table.</li>
* <li>Notify observers of this change ({@link #QUERY_KEY_NOTIFY}, {@link
* boolean}): Defines whether or not data observers should be informed of the
* changes to the database that are a result of this sql statement.</li>
* <li>Insert or update ({@link #QUERY_KEY_INSERT_OR_UPDATE}, {@link boolean}):
* Applies only to insert statements. If it is set to {@code true}, the insert
* will attempt to replace an existing entry if there is already a row in the
* table that has the same id.</li>
* <li>Group by ({@link #QUERY_KEY_GROUP_BY}, {@link String}): Since GROUP BY is
* not part of the content provider interface, this parameter allows to define
* an arbitrary SQL GROUP BY suffix. Note that you do not need to specify
* {@code "GROUP BY"} as part of the {@link String}.</li>
* <li>Custom action ({@link #QUERY_KEY_ACTION}, {@link String}): Allows to
* define a custom action for the change that is to be recorded. If this is not
* specified, the action will be analogous to the type of the sql statement
* (i.e. create, replace, delete)</li>
* <li>Custom change value ({@link #QUERY_KEY_CHANGE_VALUE}, {@link String}):
* Allows to define a custom set of values that should be uploaded to the
* server. This is typically a JSON string, but it can be any {@link String}
* that is understood by the class that processes uploads. If this is not
* specified, the TODO</li>
* <li>Custom info ({@link #QUERY_KEY_ADDITIONAL_DATA}, {@link String}): Allows
* to define a custom set of auxiliary info values that are not directly pushed
* to the server, but may help in estimating server apis and defining the
* packet. If this is not specified, the TODO</li>
* </ul>
**/
public abstract class DataProvider extends ContentProvider {
public static final String QUERY_KEY_RECORD_CHANGES = "rch";
public static final String QUERY_FALSE = "0";
public static final String QUERY_TRUE = "1";
public static final String QUERY_KEY_CHANGE_VALUE = "chv";
public static final String QUERY_KEY_ACTION = "act";
public static final String QUERY_KEY_NOTIFY = "not";
public static final String QUERY_KEY_GROUP_BY = "gby";
public static final String QUERY_KEY_ADDITIONAL_DATA = "dep";
public static final String QUERY_KEY_INSERT_OR_UPDATE = "iou";
private static class Notification {
private Uri uri;
private ResolvedUri resolvedUri;
public Notification(Uri uri, ResolvedUri resolvedUri) {
this.uri = uri;
this.resolvedUri = resolvedUri;
}
}
protected class ResolvedUri {
private String table;
private Account user;
private Long id;
Bundle queryParams;
public ResolvedUri(String table, String user, Long id, Bundle queryParams) {
this.table = table;
this.user = new Account(user, getAccountType());
this.id = id;
this.queryParams = queryParams;
}
public ResolvedUri(String table, String user, Bundle queryParams) {
this(table, user, null, queryParams);
}
public String extendSelection(String selection) {
// TODO make this more general. Replace _ID by the
// primary key column name (in most cases it is _ID anyway).
if (id != null) {
if (TextUtils.isEmpty(selection))
return "_ID = " + id;
else
return selection + " AND _ID = " + id;
} else {
return selection;
}
}
public String getString(String queryKey) {
return queryParams.getString(queryKey);
}
public boolean getBoolean(String queryKey) {
return queryParams.getBoolean(queryKey);
}
public int getInt(String queryKey) {
return queryParams.getInt(queryKey);
}
public long getLong(String queryKey) {
return queryParams.getLong(queryKey);
}
public void setId(long id) {
this.id = id;
}
}
private static final int ROW_URI = 0;
private static final int TABLE_URI = 1;
protected Uri getUri(String user, String table) {
return new Uri.Builder().scheme("content").authority(getAuthority()).appendPath(user).appendPath(table).build();
}
protected Uri getUri(Account user, String table) {
return new Uri.Builder().scheme("content").authority(getAuthority()).appendPath(user.name).appendPath(table)
.build();
}
public static Uri withParams(Uri uri, boolean recordChange) {
String queryValue = (recordChange) ? QUERY_TRUE : QUERY_FALSE;
return uri.buildUpon().appendQueryParameter(QUERY_KEY_RECORD_CHANGES, queryValue).build();
}
public static Uri withParams(Uri uri, long id, boolean recordChange) {
return ContentUris.withAppendedId(withParams(uri, recordChange), id);
}
/**
* A UriMatcher instance
*/
private UriMatcher sUriMatcher;
private Map<String, SQLiteOpenHelper> mDatabaseHelpers;
private Map<Uri, List<Uri>> mDependencies;
private Map<String, String[]> mUIDs;
private boolean mAggregateNotifications;
private List<Notification> mNotifications;
protected abstract Database getDatabase();
protected abstract String getAccountType();
protected abstract String getAuthority();
protected abstract SQLiteOpenHelper getDatabaseHelper(Context context, Account account);
protected abstract DataAdapter getDataAdapter();
@Override
public boolean onCreate() {
mDatabaseHelpers = new HashMap<String, SQLiteOpenHelper>();
mDependencies = new WeakHashMap<Uri, List<Uri>>();
mNotifications = new ArrayList<Notification>();
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(getAuthority(), "*/*/#", ROW_URI);
sUriMatcher.addURI(getAuthority(), "*/*", TABLE_URI);
mUIDs = new HashMap<String, String[]>();
Database db = getDatabase();
for (Table t : db.getTables()) {
List<String> uids = new ArrayList<String>();
for (Column c : t.getColumns()) {
if (c.isUID()) {
uids.add(c.getName());
}
}
mUIDs.put(t.getName(), uids.toArray(new String[] {}));
}
return true;
}
private SQLiteOpenHelper getDatabaseHelper(Account account) {
synchronized (mDatabaseHelpers) {
SQLiteOpenHelper dbHelper = mDatabaseHelpers.get(account.name);
if (dbHelper == null) {
dbHelper = getDatabaseHelper(getContext(), account);
mDatabaseHelpers.put(account.name, dbHelper);
}
return dbHelper;
}
}
private SQLiteDatabase getReadableDatabase(Account user) {
return getDatabaseHelper(user).getReadableDatabase();
}
private SQLiteDatabase getWritableDatabase(Account user) {
return getDatabaseHelper(user).getWritableDatabase();
}
public List<Uri> getDependencies(Uri uri, ResolvedUri resolvedUri) {
if (mDependencies.containsKey(uri)) {
return mDependencies.get(uri);
} else {
List<Uri> result = new ArrayList<Uri>();
Table table = getDatabase().getTableOrThrow(resolvedUri.table);
for (View v : table.getReferencedBy()) {
Uri baseUri = getUri(resolvedUri.user, v.getName());
// if (resolvedUri.id != null) {
// result.add(ContentUris.withAppendedId(baseUri,
// resolvedUri.id));
// } else {
result.add(baseUri);
// }
}
mDependencies.put(uri, result);
return result;
}
}
private boolean getBooleanQueryParameter(Uri uri, String key, boolean defaultValue) {
String value = uri.getQueryParameter(key);
if (value == null) {
return defaultValue;
} else {
return !value.equals(QUERY_FALSE);
}
}
private int getIntegerQueryParameter(Uri uri, String key, int defaultValue) {
String value = uri.getQueryParameter(key);
if (value == null) {
return defaultValue;
} else {
return Integer.parseInt(value);
}
}
private long getLongQueryParameter(Uri uri, String key, long defaultValue) {
String value = uri.getQueryParameter(key);
if (value == null) {
return defaultValue;
} else {
return Integer.parseInt(value);
}
}
/**
* Translates the given {@link Uri} to the corresponding table or view name.
*
* @param uri
* The content uri.
* @return A table or view name that corresponds to the given content
* {@link Uri}.
*/
protected ResolvedUri resolveUri(Uri uri) {
// boolean recordChanges =
Bundle queryParams = new Bundle();
queryParams.putBoolean(QUERY_KEY_RECORD_CHANGES, getBooleanQueryParameter(uri, QUERY_KEY_RECORD_CHANGES, true));
queryParams.putString(QUERY_KEY_CHANGE_VALUE, uri.getQueryParameter(QUERY_KEY_CHANGE_VALUE));
queryParams.putBoolean(QUERY_KEY_NOTIFY, getBooleanQueryParameter(uri, QUERY_KEY_NOTIFY, true));
queryParams.putInt(QUERY_KEY_ACTION, getIntegerQueryParameter(uri, QUERY_KEY_ACTION, -1));
queryParams.putString(QUERY_KEY_GROUP_BY, uri.getQueryParameter(QUERY_KEY_GROUP_BY));
queryParams.putString(QUERY_KEY_ADDITIONAL_DATA, uri.getQueryParameter(QUERY_KEY_ADDITIONAL_DATA));
queryParams.putBoolean(QUERY_KEY_INSERT_OR_UPDATE,
getBooleanQueryParameter(uri, QUERY_KEY_INSERT_OR_UPDATE, false));
List<String> pathSegments = uri.getPathSegments();
if (sUriMatcher.match(uri) == TABLE_URI) {
return new ResolvedUri(pathSegments.get(1), pathSegments.get(0), queryParams);
} else {
long id = ContentUris.parseId(uri);
return new ResolvedUri(pathSegments.get(1), pathSegments.get(0), id, queryParams);
}
}
protected void notifyChange(Uri uri, ResolvedUri resolvedUri) {
if (resolvedUri.getBoolean(QUERY_KEY_NOTIFY) && !mAggregateNotifications) {
Debug.debug("Notifying for " + uri);
getContext().getContentResolver().notifyChange(uri, null, resolvedUri.getBoolean(QUERY_KEY_RECORD_CHANGES));
for (Uri depUri : getDependencies(uri, resolvedUri)) {
if (resolvedUri.getBoolean(QUERY_KEY_RECORD_CHANGES))
Debug.debug("Requesting Upload Sync");
Debug.debug("Notifying for " + depUri);
getContext().getContentResolver().notifyChange(depUri, null,
resolvedUri.getBoolean(QUERY_KEY_RECORD_CHANGES));
}
} else if (mAggregateNotifications) {
mNotifications.add(new Notification(uri, resolvedUri));
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
ResolvedUri resolvedUri = resolveUri(uri);
SQLiteDatabase db = getReadableDatabase(resolvedUri.user);
Cursor cursor = db.query(resolvedUri.table, projection, resolvedUri.extendSelection(selection), selectionArgs,
resolvedUri.getString(QUERY_KEY_GROUP_BY), null, sortOrder);
if (resolvedUri.table.equals(Changes.TABLE_NAME)) {
Debug.verbose("Query[%d]: %s, %s, %s, %s, %s", cursor.getCount(), uri, Arrays.toString(projection),
selection, Arrays.toString(selectionArgs), sortOrder);
} else {
Debug.debug("Query[%d]: %s, %s, %s, %s, %s", cursor.getCount(), uri, Arrays.toString(projection),
selection, Arrays.toString(selectionArgs), sortOrder);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
/**
* Gets the name of the column that stores the id that should be entered in
* the object id field of the changes table. Subclasses may override this to
* for example use a server id instead of the local sqlite id. If this
* method returns {@code BaseColumns._ID} the "native" id field is used. The
* native id field is the one that is defined as the primary key of the
* table and is also used when appending ids in uris.
*
* @param table
* the table
* @return the native id field {@code BaseColumns._ID} by default.
*/
protected String getChangeIdColumn(String table) {
return BaseColumns._ID;
}
protected ContentValues getChanges(SQLiteDatabase db, int action, String table, long id, ContentValues values,
String customChangeValue, String additionalData) {
try {
String json = customChangeValue;
if (json == null) {
JSONObject obj = getDataAdapter().renderValues(values, table, Storage.REMOTE);
json = obj.toString();
}
ContentValues changes = new ContentValues();
String changeIdColumn = getChangeIdColumn(table);
long objId = id;
if (!changeIdColumn.equals(BaseColumns._ID)) {
if (values != null && values.containsKey(changeIdColumn)) {
objId = values.getAsLong(changeIdColumn);
- } else {
+ } else if (id != 0L) {
Cursor c = db.query(table, new String[] { changeIdColumn }, "_id = ?",
new String[] { String.valueOf(id) }, null, null, null);
c.moveToFirst();
objId = c.getLong(0);
c.close();
}
}
changes.put(Changes.COLUMN_TABLE, table);
changes.put(Changes.COLUMN_NATIVE_ID, id);
changes.put(Changes.COLUMN_ID, objId);
changes.put(Changes.COLUMN_ACTION, action);
changes.put(Changes.COLUMN_TIMESTAMP, SQLUtils.formatTimestamp(new Date()));
changes.put(Changes.COLUMN_VALUES, json);
// changes.put(Changes.COLUMN_API_PATH, apiPath);
JSONObject info = getDataAdapter().renderValues(values, table, Storage.INFO);
if (additionalData != null) {
try {
JSONObject addData = new JSONObject(additionalData);
Iterator<String> additionalDataIterator = addData.keys();
while (additionalDataIterator.hasNext()) {
String key = additionalDataIterator.next();
info.put(key, addData.get(key));
}
} catch (JSONException e) {
// additionalData is in a non-valid format: give a warning
Debug.warning(String
.format("Additional data needs to be in a JSON valid formatting. Found instead: %s",
additionalData));
}
}
changes.put(Changes.COLUMN_ADDITIONAL_DATA, info.toString());
return changes;
} catch (JSONException e) {
Debug.logException(e);
}
return null;
}
// protected void updateGroupId(SQLiteDatabase db, long id) {
// if (mGroupId == null) {
// ContentValues groupIdValues = new ContentValues();
// groupIdValues.put(Changes.COLUMN_GROUP_ID, id);
// db.update(Changes.TABLE_NAME, groupIdValues, Changes._ID + " = ?",
// new String[] { String.valueOf(id) });
// if (mAggregateNotifications) {
// mGroupId = id;
// }
// }
// }
protected void insertSingleChange(SQLiteDatabase db, int action, long id, ResolvedUri resolvedUri,
ContentValues values) {
ContentValues changes = getChanges(db, action, resolvedUri.table, id, values,
resolvedUri.getString(QUERY_KEY_CHANGE_VALUE), resolvedUri.getString(QUERY_KEY_ADDITIONAL_DATA));
db.insert(Changes.TABLE_NAME, null, changes);
}
protected void insertChanges(int action, SQLiteDatabase db, Uri uri, ResolvedUri resolvedUri, String selection,
String[] selectionArgs, ContentValues values) {
if (resolvedUri.queryParams.getBoolean(QUERY_KEY_RECORD_CHANGES)
&& !resolvedUri.table.equals(Changes.TABLE_NAME)) {
int customAction = resolvedUri.getInt(QUERY_KEY_ACTION);
if (customAction >= 0) {
// overwrite default action:
action = customAction;
}
if (resolvedUri.id != null) {
insertSingleChange(db, action, resolvedUri.id, resolvedUri, values);
} else if (action == Changes.ACTION_REMOVE) {
insertSingleChange(db, action, 0, resolvedUri, values);
} else {
Cursor cursor = query(uri, new String[] { getChangeIdColumn(resolvedUri.table) }, selection,
selectionArgs, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
long id = cursor.getLong(0);
insertSingleChange(db, action, id, resolvedUri, values);
cursor.moveToNext();
}
}
}
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
/**
* When value of a UID when it is requested the first time for a particular
* table-column pair. This may be overridden by subclasses to achieve some
* desired behavior.
*
* @return {@code 0} in the default implementation.
*/
protected long firstUIDValue() {
return 0L;
}
/**
* Gets the next UID value provided the last one. This may be overridden by
* subclasses to achieve some desired behavior. Keep in mind, however, that
* the generated sequence of UIDs need to be distinct.
*
* @param value
* the last generated UID.
* @return {@code value+1} in the default implementation.
*/
protected long nextUIDValue(long value) {
return value + 1;
}
public synchronized long newUID(String table, String column) {
SharedPreferences pref = getContext().getSharedPreferences("uid", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
long maxValue = pref.getLong(table + ":" + column, firstUIDValue());
editor.putLong(table + ":" + column, nextUIDValue(maxValue)).commit();
return maxValue;
}
private void fillUIDs(String table, ContentValues values) {
String[] uids = mUIDs.get(table);
for (String uidColumn : uids) {
if (!values.containsKey(uidColumn)) {
values.put(uidColumn, newUID(table, uidColumn));
}
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
Debug.info(String.format("Inserting %s with %s", uri, values));
ResolvedUri resolvedUri = resolveUri(uri);
SQLiteDatabase db = getWritableDatabase(resolvedUri.user);
if (resolvedUri.id != null) {
throw new IllegalArgumentException("Invalid content uri for insert: " + uri);
}
long rowId = 0;
fillUIDs(resolvedUri.table, values);
// if (values.containsKey(BaseColumns._ID)) {
// throw new RuntimeException();
// }
try {
db.beginTransaction();
if (resolvedUri.getBoolean(QUERY_KEY_INSERT_OR_UPDATE)) {
rowId = db.insertWithOnConflict(resolvedUri.table, null, values, SQLiteDatabase.CONFLICT_REPLACE);
} else {
rowId = db.insert(resolvedUri.table, null, values);
}
resolvedUri.setId(rowId);
insertChanges(Changes.ACTION_CREATE, db, uri, resolvedUri, null, null, values);
if (rowId >= 0) {
notifyChange(uri, resolvedUri);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Debug.info("Inserted rowId: " + rowId);
return ContentUris.withAppendedId(uri, rowId);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
Debug.info(String.format("Deleting %s (%s, %s)", uri, selection, Arrays.toString(selectionArgs)));
ResolvedUri resolvedUri = resolveUri(uri);
SQLiteDatabase db = getWritableDatabase(resolvedUri.user);
int deletedRows = 0;
try {
db.beginTransaction();
insertChanges(Changes.ACTION_REMOVE, db, uri, resolvedUri, selection, selectionArgs, null);
deletedRows = db.delete(resolvedUri.table, resolvedUri.extendSelection(selection), selectionArgs);
if (deletedRows > 0) {
notifyChange(uri, resolvedUri);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Debug.info(String.format("Deleted %d rows.", deletedRows));
return deletedRows;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// if (values.containsKey(BaseColumns._ID)) {
// throw new RuntimeException();
// }
Debug.info(String.format("Updating %s (%s, %s) with %s", uri, selection, Arrays.toString(selectionArgs), values));
ResolvedUri resolvedUri = resolveUri(uri);
SQLiteDatabase db = getWritableDatabase(resolvedUri.user);
int updatedRows = 0;
try {
db.beginTransaction();
insertChanges(Changes.ACTION_UPDATE, db, uri, resolvedUri, selection, selectionArgs, values);
updatedRows = db.update(resolvedUri.table, values, resolvedUri.extendSelection(selection), selectionArgs);
if (updatedRows > 0) {
notifyChange(uri, resolvedUri);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Debug.info(String.format("Updated %d rows", updatedRows));
return updatedRows;
}
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
mAggregateNotifications = true;
ContentProviderResult[] result = new ContentProviderResult[operations.size()];
int i = 0;
for (ContentProviderOperation o : operations) {
// Set<String> queryParams = o.getUri().getQueryParameterNames();
/*
* TODO; set the no-notification flag. Then aggregate notifications
* here and don't use a member because of thread safety.
*/
result[i] = o.apply(this, result, i++);
}
mAggregateNotifications = false;
for (Notification n : mNotifications) {
notifyChange(n.uri, n.resolvedUri);
}
mNotifications.clear();
return result;
}
public ContentProviderResult[] applyBatch(Account account, ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
SQLiteDatabase db = getWritableDatabase(account);
ContentProviderResult[] result = new ContentProviderResult[operations.size()];
int i = 0;
db.beginTransaction();
try {
for (ContentProviderOperation op : operations) {
op.apply(this, result, i++);
}
db.setTransactionSuccessful();
return result;
} finally {
db.endTransaction();
}
}
public void beginTransaction(Account account) {
getWritableDatabase(account).beginTransaction();
}
public void setTransactionSuccessful(Account account) {
getWritableDatabase(account).setTransactionSuccessful();
}
public void endTransaction(Account account) {
getWritableDatabase(account).endTransaction();
}
public void beginTransaction(Account account, SQLiteTransactionListener listener) {
if (listener != null) {
getWritableDatabase(account).beginTransactionWithListener(listener);
} else {
beginTransaction(account);
}
}
public void updateFromServer(Account account, CollectionFilter filter, ProgressListener listener, long expectedCount)
throws IOException, AuthenticationException {
Debug.warning(String.format("updating from reader: %s, %s", account.name, filter));
SQLiteDatabase db = getWritableDatabase(account);
DataProcessor processor = new DataProcessor(this, account.name, db, listener, filter.getTable(), expectedCount,
filter.getSelect());
for (String apiPath : filter.getApiPaths()) {
getDataAdapter().process(getContext(), account, filter.getTable(), apiPath, processor, null, null);
}
try {
Debug.warning(String.format("Begin Transaction: %s", filter));
db.beginTransaction();
// if (filter.getSelect() != null) {
// Debug.warning(String.format("Deleting: %s, %s, %s",
// filter.getTable(), filter.getSelection(),
// Arrays.toString(filter.getSelectionArgs())));
// int deletedRows = db.delete(filter.getTable(),
// filter.getSelection(), filter.getSelectionArgs());
// Debug.warning(String.format("Deleted %d rows", deletedRows));
// }
processor.performOperations();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
Debug.warning(String.format("End Transaction: %s", filter));
}
processor.notifyChanges();
}
}
| true | true | protected ContentValues getChanges(SQLiteDatabase db, int action, String table, long id, ContentValues values,
String customChangeValue, String additionalData) {
try {
String json = customChangeValue;
if (json == null) {
JSONObject obj = getDataAdapter().renderValues(values, table, Storage.REMOTE);
json = obj.toString();
}
ContentValues changes = new ContentValues();
String changeIdColumn = getChangeIdColumn(table);
long objId = id;
if (!changeIdColumn.equals(BaseColumns._ID)) {
if (values != null && values.containsKey(changeIdColumn)) {
objId = values.getAsLong(changeIdColumn);
} else {
Cursor c = db.query(table, new String[] { changeIdColumn }, "_id = ?",
new String[] { String.valueOf(id) }, null, null, null);
c.moveToFirst();
objId = c.getLong(0);
c.close();
}
}
changes.put(Changes.COLUMN_TABLE, table);
changes.put(Changes.COLUMN_NATIVE_ID, id);
changes.put(Changes.COLUMN_ID, objId);
changes.put(Changes.COLUMN_ACTION, action);
changes.put(Changes.COLUMN_TIMESTAMP, SQLUtils.formatTimestamp(new Date()));
changes.put(Changes.COLUMN_VALUES, json);
// changes.put(Changes.COLUMN_API_PATH, apiPath);
JSONObject info = getDataAdapter().renderValues(values, table, Storage.INFO);
if (additionalData != null) {
try {
JSONObject addData = new JSONObject(additionalData);
Iterator<String> additionalDataIterator = addData.keys();
while (additionalDataIterator.hasNext()) {
String key = additionalDataIterator.next();
info.put(key, addData.get(key));
}
} catch (JSONException e) {
// additionalData is in a non-valid format: give a warning
Debug.warning(String
.format("Additional data needs to be in a JSON valid formatting. Found instead: %s",
additionalData));
}
}
changes.put(Changes.COLUMN_ADDITIONAL_DATA, info.toString());
return changes;
} catch (JSONException e) {
Debug.logException(e);
}
return null;
}
| protected ContentValues getChanges(SQLiteDatabase db, int action, String table, long id, ContentValues values,
String customChangeValue, String additionalData) {
try {
String json = customChangeValue;
if (json == null) {
JSONObject obj = getDataAdapter().renderValues(values, table, Storage.REMOTE);
json = obj.toString();
}
ContentValues changes = new ContentValues();
String changeIdColumn = getChangeIdColumn(table);
long objId = id;
if (!changeIdColumn.equals(BaseColumns._ID)) {
if (values != null && values.containsKey(changeIdColumn)) {
objId = values.getAsLong(changeIdColumn);
} else if (id != 0L) {
Cursor c = db.query(table, new String[] { changeIdColumn }, "_id = ?",
new String[] { String.valueOf(id) }, null, null, null);
c.moveToFirst();
objId = c.getLong(0);
c.close();
}
}
changes.put(Changes.COLUMN_TABLE, table);
changes.put(Changes.COLUMN_NATIVE_ID, id);
changes.put(Changes.COLUMN_ID, objId);
changes.put(Changes.COLUMN_ACTION, action);
changes.put(Changes.COLUMN_TIMESTAMP, SQLUtils.formatTimestamp(new Date()));
changes.put(Changes.COLUMN_VALUES, json);
// changes.put(Changes.COLUMN_API_PATH, apiPath);
JSONObject info = getDataAdapter().renderValues(values, table, Storage.INFO);
if (additionalData != null) {
try {
JSONObject addData = new JSONObject(additionalData);
Iterator<String> additionalDataIterator = addData.keys();
while (additionalDataIterator.hasNext()) {
String key = additionalDataIterator.next();
info.put(key, addData.get(key));
}
} catch (JSONException e) {
// additionalData is in a non-valid format: give a warning
Debug.warning(String
.format("Additional data needs to be in a JSON valid formatting. Found instead: %s",
additionalData));
}
}
changes.put(Changes.COLUMN_ADDITIONAL_DATA, info.toString());
return changes;
} catch (JSONException e) {
Debug.logException(e);
}
return null;
}
|
diff --git a/selenium_testing/test/Test_03_W0100_Search_for_a_data_set.java b/selenium_testing/test/Test_03_W0100_Search_for_a_data_set.java
index 90b4fd5..85a2e59 100644
--- a/selenium_testing/test/Test_03_W0100_Search_for_a_data_set.java
+++ b/selenium_testing/test/Test_03_W0100_Search_for_a_data_set.java
@@ -1,95 +1,95 @@
package com.example.tests;
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.regex.Pattern;
public class Test_03_W0100_Search_for_a_data_set extends SeleneseTestCase {
@Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://buildbot.oceanobservatories.org:8080/");
selenium.start();
}
@Test
public void test_03_W0100_Search_for_a_data_set() throws Exception {
selenium.open("/ooici-pres-0.1/");
selenium.click("login_button");
selenium.waitForPageToLoad("30000");
selenium.click("wayflogonbutton");
selenium.waitForPageToLoad("30000");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Cilogon.org is asking for some information from")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.type("Email", "U_S_E_R-N_A_M_E");
selenium.type("Passwd", "P_A_S_S-W_O_R_D");
selenium.click("signIn");
selenium.waitForPageToLoad("30000");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Showing 1 to 8 of 8 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("radioBoundingDefined");
selenium.type("ge_bb_north", "21.4");
selenium.type("ge_bb_south", "21.3");
- selenium.type("ge_bb_east", "-157.6");
- selenium.type("ge_bb_west", "-157.9");
+ selenium.type("ge_bb_east", "157.6");
+ selenium.type("ge_bb_west", "157.9");
//selenium.click("apply_filter_button"); // This is the one to lose
selenium.click("radioAllPubRes");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
- try { if (selenium.isTextPresent("Showing 1 to 1 of 1 entries")) break; } catch (Exception e) {}
+ try { if (selenium.isTextPresent("Showing 1 to 2 of 2 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("//tr[@id='3319A67F-81F3-424F-8E69-4F28C4E04806']/td[2]");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("7723 Moanalua RG No 1 at alt 1000 ft")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("radioBoundingAll");
//selenium.click("apply_filter_button"); // This is the one to lose
selenium.click("radioAllPubRes");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Showing 1 to 8 of 8 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
//selenium.type("//input[@type='text']", "HYCOM");
selenium.typeKeys("//input[@type='text']", "HYCOM");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Showing 1 to 2 of 2 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("//tr[@id='3319A67F-81F3-424F-8E69-4F28C4E04800']/td[3]");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Data HyCom")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("logout_link");
selenium.waitForPageToLoad("30000");
selenium.open("http://google.com");
selenium.click("gbgs4");
selenium.click("gb_71");
selenium.waitForPageToLoad("30000");
}
@After
public void tearDown() throws Exception {
selenium.stop();
}
}
| false | true | public void test_03_W0100_Search_for_a_data_set() throws Exception {
selenium.open("/ooici-pres-0.1/");
selenium.click("login_button");
selenium.waitForPageToLoad("30000");
selenium.click("wayflogonbutton");
selenium.waitForPageToLoad("30000");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Cilogon.org is asking for some information from")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.type("Email", "U_S_E_R-N_A_M_E");
selenium.type("Passwd", "P_A_S_S-W_O_R_D");
selenium.click("signIn");
selenium.waitForPageToLoad("30000");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Showing 1 to 8 of 8 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("radioBoundingDefined");
selenium.type("ge_bb_north", "21.4");
selenium.type("ge_bb_south", "21.3");
selenium.type("ge_bb_east", "-157.6");
selenium.type("ge_bb_west", "-157.9");
//selenium.click("apply_filter_button"); // This is the one to lose
selenium.click("radioAllPubRes");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Showing 1 to 1 of 1 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("//tr[@id='3319A67F-81F3-424F-8E69-4F28C4E04806']/td[2]");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("7723 Moanalua RG No 1 at alt 1000 ft")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("radioBoundingAll");
//selenium.click("apply_filter_button"); // This is the one to lose
selenium.click("radioAllPubRes");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Showing 1 to 8 of 8 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
//selenium.type("//input[@type='text']", "HYCOM");
selenium.typeKeys("//input[@type='text']", "HYCOM");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Showing 1 to 2 of 2 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("//tr[@id='3319A67F-81F3-424F-8E69-4F28C4E04800']/td[3]");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Data HyCom")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("logout_link");
selenium.waitForPageToLoad("30000");
selenium.open("http://google.com");
selenium.click("gbgs4");
selenium.click("gb_71");
selenium.waitForPageToLoad("30000");
}
| public void test_03_W0100_Search_for_a_data_set() throws Exception {
selenium.open("/ooici-pres-0.1/");
selenium.click("login_button");
selenium.waitForPageToLoad("30000");
selenium.click("wayflogonbutton");
selenium.waitForPageToLoad("30000");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Cilogon.org is asking for some information from")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.type("Email", "U_S_E_R-N_A_M_E");
selenium.type("Passwd", "P_A_S_S-W_O_R_D");
selenium.click("signIn");
selenium.waitForPageToLoad("30000");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Showing 1 to 8 of 8 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("radioBoundingDefined");
selenium.type("ge_bb_north", "21.4");
selenium.type("ge_bb_south", "21.3");
selenium.type("ge_bb_east", "157.6");
selenium.type("ge_bb_west", "157.9");
//selenium.click("apply_filter_button"); // This is the one to lose
selenium.click("radioAllPubRes");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Showing 1 to 2 of 2 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("//tr[@id='3319A67F-81F3-424F-8E69-4F28C4E04806']/td[2]");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("7723 Moanalua RG No 1 at alt 1000 ft")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("radioBoundingAll");
//selenium.click("apply_filter_button"); // This is the one to lose
selenium.click("radioAllPubRes");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Showing 1 to 8 of 8 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
//selenium.type("//input[@type='text']", "HYCOM");
selenium.typeKeys("//input[@type='text']", "HYCOM");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Showing 1 to 2 of 2 entries")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("//tr[@id='3319A67F-81F3-424F-8E69-4F28C4E04800']/td[3]");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isTextPresent("Data HyCom")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("logout_link");
selenium.waitForPageToLoad("30000");
selenium.open("http://google.com");
selenium.click("gbgs4");
selenium.click("gb_71");
selenium.waitForPageToLoad("30000");
}
|
diff --git a/SoftwareProjectDay/src/edu/se/se441/threads/Employee.java b/SoftwareProjectDay/src/edu/se/se441/threads/Employee.java
index 0c8d4ad..3983342 100644
--- a/SoftwareProjectDay/src/edu/se/se441/threads/Employee.java
+++ b/SoftwareProjectDay/src/edu/se/se441/threads/Employee.java
@@ -1,212 +1,212 @@
package edu.se.se441.threads;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.Random;
import edu.se.se441.*;
public class Employee extends Thread {
// Latches and Barriers
private CountDownLatch startSignal;
// Times
private long dayStartTime, dayEndTime, lunchTime, lunchDuration;
// Meeting attended Booleans
private boolean attendedEndOfDayMeeting;
private Object leadQLock = new Object();
private int teamNumber, empNumber;
private boolean isLead;
private boolean isWaitingQuestion;
private boolean hadLunch;
private Office office;
public Employee(boolean isLead, Office office, int teamNumber, int empNumber){
this.isLead = isLead;
this.office = office;
hadLunch = false;
isWaitingQuestion = false;
this.teamNumber = teamNumber;
this.empNumber = empNumber;
if(isLead) office.setLead(teamNumber, this);
}
public void run(){
this.setName(getEmployeeName());
Random r = new Random();
try {
// Starting all threads at the same time (clock == 0 / "8:00AM").
startSignal.await();
// Arrive sometime between 8:00 and 8:30
Thread.sleep(10 * r.nextInt(30));
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " arrives at office");
dayStartTime = office.getTime();
dayEndTime = dayStartTime + 800; // Work at least 8 hours
- lunchTime = r.nextInt(200) + 1200; // Lunch starts between 12 and 2
- lunchDuration = r.nextInt((int) (1700-dayEndTime-30)) + 30; // Figure out lunch duration
+ lunchTime = r.nextInt(60) + 1200 + r.nextInt(2)*100; // Lunch starts between 12 and 2
+ lunchDuration = r.nextInt((int)(1700-dayEndTime-70)) + 30; // Figure out lunch duration
dayEndTime += lunchDuration; // Add to end time.
office.addTimeEvent(lunchTime); // Lunch Time
office.addTimeEvent(dayEndTime); // End of day
// Waiting for team leads for the meeting.
if(isLead){
office.waitForStandupMeeting();
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " is at standup meeting");
Thread.sleep(150);
}
// Wait for the team meeting to start.
office.waitForTeamMeeting(teamNumber);
office.haveTeamMeeting(teamNumber, this);
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " left team meeting");
} catch (InterruptedException e) {
e.printStackTrace();
}
// Start main while loop here.
while(true){
// Wait until Employee should do something
office.startWorking();
if(!runChecks()){
break;
}
// If Leader, and question, ask manager
if(isLead && isWaitingQuestion){
office.getManager().askQuestion(this);
}
// Should a question be asked?
int random = r.nextInt(20);
//decides whether or not to ask a question
if(random == 0){
//Team lead asking a question
if(isLead){
office.getManager().askQuestion(this);
}
//Employee asking a question
else{
if(r.nextBoolean()){
office.getLead(teamNumber).askQuestion(this);
}
}
}
if(!runChecks()){
break;
}
}
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " leaves");
}
/**
* @return if false, break;
*/
private boolean runChecks(){
// Check 1: Is it time to go home?
if(office.getTime() >= dayEndTime){
// End the thread
return false;
}
// Lunch time?
if(office.getTime() >= lunchTime && !hadLunch){
try {
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " goes to lunch");
sleep(lunchDuration*10);
} catch (InterruptedException e) {
e.printStackTrace();
}
hadLunch = true;
}
// Is it time for the 4 oclock meeting?
if(office.getTime() >= 1600 && !attendedEndOfDayMeeting){
office.waitForEndOfDayMeeting();
try {
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " attends end of day meeting");
sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
attendedEndOfDayMeeting = true;
}
return true;
}
// Only for Team Leaders, called when asked a question that needs to be passed up to manager.
public void askQuestion(Employee asker){
Employee teamLeader = office.getLead(teamNumber);
try {
synchronized(leadQLock){
// Leader already has a question that hasn't been answered.
while(teamLeader.isWaitingQuestion){
leadQLock.wait();
}
// Set our question.
teamLeader.getsQuestion();
office.notifyWorking();
}
synchronized(office.getManager().getQuestionLock()){
// Is the manager answering the question
while(teamLeader.isWaitingQuestion){
if(office.getTime() >= 1600 && !attendedEndOfDayMeeting){
office.waitForEndOfDayMeeting();
sleep(150);
attendedEndOfDayMeeting = true;
}
office.getManager().getQuestionLock().wait();
}
}
synchronized(leadQLock){
teamLeader.questionAnswered();
leadQLock.notifyAll();
}
}catch (InterruptedException e) {
e.printStackTrace();
}
}
public void setStartSignal(CountDownLatch startSignal) {
this.startSignal = startSignal;
}
public void getsQuestion(){
isWaitingQuestion = true;
}
public void questionAnswered(){
isWaitingQuestion = false;
}
public boolean isWaitingQuestion() {
return isWaitingQuestion;
}
public boolean isAttendedEndOfDayMeeting() {
return attendedEndOfDayMeeting;
}
public void setAttendedEndOfDayMeeting(boolean attendedEndOfDayMeeting) {
this.attendedEndOfDayMeeting = attendedEndOfDayMeeting;
}
public String getEmployeeName(){
String name = (int)(teamNumber+1) + "" + (int)(empNumber+1);
return name;
}
}
| true | true | public void run(){
this.setName(getEmployeeName());
Random r = new Random();
try {
// Starting all threads at the same time (clock == 0 / "8:00AM").
startSignal.await();
// Arrive sometime between 8:00 and 8:30
Thread.sleep(10 * r.nextInt(30));
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " arrives at office");
dayStartTime = office.getTime();
dayEndTime = dayStartTime + 800; // Work at least 8 hours
lunchTime = r.nextInt(200) + 1200; // Lunch starts between 12 and 2
lunchDuration = r.nextInt((int) (1700-dayEndTime-30)) + 30; // Figure out lunch duration
dayEndTime += lunchDuration; // Add to end time.
office.addTimeEvent(lunchTime); // Lunch Time
office.addTimeEvent(dayEndTime); // End of day
// Waiting for team leads for the meeting.
if(isLead){
office.waitForStandupMeeting();
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " is at standup meeting");
Thread.sleep(150);
}
// Wait for the team meeting to start.
office.waitForTeamMeeting(teamNumber);
office.haveTeamMeeting(teamNumber, this);
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " left team meeting");
} catch (InterruptedException e) {
e.printStackTrace();
}
// Start main while loop here.
while(true){
// Wait until Employee should do something
office.startWorking();
if(!runChecks()){
break;
}
// If Leader, and question, ask manager
if(isLead && isWaitingQuestion){
office.getManager().askQuestion(this);
}
// Should a question be asked?
int random = r.nextInt(20);
//decides whether or not to ask a question
if(random == 0){
//Team lead asking a question
if(isLead){
office.getManager().askQuestion(this);
}
//Employee asking a question
else{
if(r.nextBoolean()){
office.getLead(teamNumber).askQuestion(this);
}
}
}
if(!runChecks()){
break;
}
}
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " leaves");
}
| public void run(){
this.setName(getEmployeeName());
Random r = new Random();
try {
// Starting all threads at the same time (clock == 0 / "8:00AM").
startSignal.await();
// Arrive sometime between 8:00 and 8:30
Thread.sleep(10 * r.nextInt(30));
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " arrives at office");
dayStartTime = office.getTime();
dayEndTime = dayStartTime + 800; // Work at least 8 hours
lunchTime = r.nextInt(60) + 1200 + r.nextInt(2)*100; // Lunch starts between 12 and 2
lunchDuration = r.nextInt((int)(1700-dayEndTime-70)) + 30; // Figure out lunch duration
dayEndTime += lunchDuration; // Add to end time.
office.addTimeEvent(lunchTime); // Lunch Time
office.addTimeEvent(dayEndTime); // End of day
// Waiting for team leads for the meeting.
if(isLead){
office.waitForStandupMeeting();
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " is at standup meeting");
Thread.sleep(150);
}
// Wait for the team meeting to start.
office.waitForTeamMeeting(teamNumber);
office.haveTeamMeeting(teamNumber, this);
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " left team meeting");
} catch (InterruptedException e) {
e.printStackTrace();
}
// Start main while loop here.
while(true){
// Wait until Employee should do something
office.startWorking();
if(!runChecks()){
break;
}
// If Leader, and question, ask manager
if(isLead && isWaitingQuestion){
office.getManager().askQuestion(this);
}
// Should a question be asked?
int random = r.nextInt(20);
//decides whether or not to ask a question
if(random == 0){
//Team lead asking a question
if(isLead){
office.getManager().askQuestion(this);
}
//Employee asking a question
else{
if(r.nextBoolean()){
office.getLead(teamNumber).askQuestion(this);
}
}
}
if(!runChecks()){
break;
}
}
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " leaves");
}
|
diff --git a/src/me/hunterboerner/war/Commands.java b/src/me/hunterboerner/war/Commands.java
index 8564a31..e4d90d8 100644
--- a/src/me/hunterboerner/war/Commands.java
+++ b/src/me/hunterboerner/war/Commands.java
@@ -1,97 +1,103 @@
package me.hunterboerner.war;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commands implements CommandExecutor {
private War plugin;
public Commands(War war) {
this.plugin = war;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label,String[] args) {
if(cmd.getName().equalsIgnoreCase("war")){
if(!(sender instanceof Player)){
plugin.logMessage("Only a player may use the war command.");
}else{
Player player = (Player) sender;
if(player.hasPermission("war.commands")){
if(args.length==0){
player.sendMessage(ChatColor.RED + "No argument specified");
return false;
}
if(args[0].equals("declare")){
if(args.length==2){
Player target = player.getServer().getPlayer(args[1]);
if(target==null){
player.sendMessage(ChatColor.RED + "Player "+args[1]+" does not exist or is not online.");
return true;
}
if(target.equals(player)){
player.sendMessage(ChatColor.RED + "One is always at war with oneself.");
return true;
}
if(!plugin.addWar(player, target)){
player.sendMessage(ChatColor.RED + "You were already at war with that person!");
return true;
}
+ if(!plugin.addWar(target, player)){
+ return true;
+ }
player.sendMessage(ChatColor.DARK_PURPLE + "You have declared war on " + target.getName());
for(Player bystander : player.getServer().getOnlinePlayers()){
if(!bystander.equals(player) && !bystander.equals(target)){
bystander.sendMessage( player.getName() + "has declared war on: " + target.getName() );
}
}
plugin.logMessage(player.getName() + " used " + "/war " + args[0] + " on " + args[1]);
}else{
player.sendMessage(ChatColor.RED +"A target must be specified when declaring war!");
return false;
}
}else if(args[0].equals("world")){
player.sendMessage(ChatColor.DARK_PURPLE + "You have started a world war!");
player.getServer().broadcastMessage(ChatColor.RED + player.getName() + " has started a world war!");
plugin.logMessage(player.getName() + " used " + "/war " + args[0]);
}else if(args[0].equals("truce")){
if(args.length==2){
Player target = player.getServer().getPlayer(args[1]);
if(target==null){
player.sendMessage(ChatColor.RED + "Player "+args[1]+" does not exist or is not online.");
return true;
}
if(target.equals(player)){
player.sendMessage(ChatColor.RED + "One should always be at peace with ones self.");
return true;
}
if(!plugin.removeWar(player, target)){
player.sendMessage(ChatColor.RED + "You were not at war with that person!");
return true;
}
+ if(!plugin.removeWar(target, player)){
+ return true;
+ }
player.sendMessage(ChatColor.GREEN + "You have made peace with " + target.getName());
for(Player bystander : player.getServer().getOnlinePlayers()){
if(!bystander.equals(player) && !bystander.equals(target)){
bystander.sendMessage( player.getName() + "has made peace with: " + target.getName() );
}
}
plugin.logMessage(player.getName() + " used " + "/war " + args[0] + " on " + args[1]);
}else{
player.sendMessage(ChatColor.RED +"A target must be specified when declaring a truce!");
return false;
}
}
}else{
player.sendMessage(ChatColor.RED + "Permission denied" );
}
}
}
return true;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String label,String[] args) {
if(cmd.getName().equalsIgnoreCase("war")){
if(!(sender instanceof Player)){
plugin.logMessage("Only a player may use the war command.");
}else{
Player player = (Player) sender;
if(player.hasPermission("war.commands")){
if(args.length==0){
player.sendMessage(ChatColor.RED + "No argument specified");
return false;
}
if(args[0].equals("declare")){
if(args.length==2){
Player target = player.getServer().getPlayer(args[1]);
if(target==null){
player.sendMessage(ChatColor.RED + "Player "+args[1]+" does not exist or is not online.");
return true;
}
if(target.equals(player)){
player.sendMessage(ChatColor.RED + "One is always at war with oneself.");
return true;
}
if(!plugin.addWar(player, target)){
player.sendMessage(ChatColor.RED + "You were already at war with that person!");
return true;
}
player.sendMessage(ChatColor.DARK_PURPLE + "You have declared war on " + target.getName());
for(Player bystander : player.getServer().getOnlinePlayers()){
if(!bystander.equals(player) && !bystander.equals(target)){
bystander.sendMessage( player.getName() + "has declared war on: " + target.getName() );
}
}
plugin.logMessage(player.getName() + " used " + "/war " + args[0] + " on " + args[1]);
}else{
player.sendMessage(ChatColor.RED +"A target must be specified when declaring war!");
return false;
}
}else if(args[0].equals("world")){
player.sendMessage(ChatColor.DARK_PURPLE + "You have started a world war!");
player.getServer().broadcastMessage(ChatColor.RED + player.getName() + " has started a world war!");
plugin.logMessage(player.getName() + " used " + "/war " + args[0]);
}else if(args[0].equals("truce")){
if(args.length==2){
Player target = player.getServer().getPlayer(args[1]);
if(target==null){
player.sendMessage(ChatColor.RED + "Player "+args[1]+" does not exist or is not online.");
return true;
}
if(target.equals(player)){
player.sendMessage(ChatColor.RED + "One should always be at peace with ones self.");
return true;
}
if(!plugin.removeWar(player, target)){
player.sendMessage(ChatColor.RED + "You were not at war with that person!");
return true;
}
player.sendMessage(ChatColor.GREEN + "You have made peace with " + target.getName());
for(Player bystander : player.getServer().getOnlinePlayers()){
if(!bystander.equals(player) && !bystander.equals(target)){
bystander.sendMessage( player.getName() + "has made peace with: " + target.getName() );
}
}
plugin.logMessage(player.getName() + " used " + "/war " + args[0] + " on " + args[1]);
}else{
player.sendMessage(ChatColor.RED +"A target must be specified when declaring a truce!");
return false;
}
}
}else{
player.sendMessage(ChatColor.RED + "Permission denied" );
}
}
}
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label,String[] args) {
if(cmd.getName().equalsIgnoreCase("war")){
if(!(sender instanceof Player)){
plugin.logMessage("Only a player may use the war command.");
}else{
Player player = (Player) sender;
if(player.hasPermission("war.commands")){
if(args.length==0){
player.sendMessage(ChatColor.RED + "No argument specified");
return false;
}
if(args[0].equals("declare")){
if(args.length==2){
Player target = player.getServer().getPlayer(args[1]);
if(target==null){
player.sendMessage(ChatColor.RED + "Player "+args[1]+" does not exist or is not online.");
return true;
}
if(target.equals(player)){
player.sendMessage(ChatColor.RED + "One is always at war with oneself.");
return true;
}
if(!plugin.addWar(player, target)){
player.sendMessage(ChatColor.RED + "You were already at war with that person!");
return true;
}
if(!plugin.addWar(target, player)){
return true;
}
player.sendMessage(ChatColor.DARK_PURPLE + "You have declared war on " + target.getName());
for(Player bystander : player.getServer().getOnlinePlayers()){
if(!bystander.equals(player) && !bystander.equals(target)){
bystander.sendMessage( player.getName() + "has declared war on: " + target.getName() );
}
}
plugin.logMessage(player.getName() + " used " + "/war " + args[0] + " on " + args[1]);
}else{
player.sendMessage(ChatColor.RED +"A target must be specified when declaring war!");
return false;
}
}else if(args[0].equals("world")){
player.sendMessage(ChatColor.DARK_PURPLE + "You have started a world war!");
player.getServer().broadcastMessage(ChatColor.RED + player.getName() + " has started a world war!");
plugin.logMessage(player.getName() + " used " + "/war " + args[0]);
}else if(args[0].equals("truce")){
if(args.length==2){
Player target = player.getServer().getPlayer(args[1]);
if(target==null){
player.sendMessage(ChatColor.RED + "Player "+args[1]+" does not exist or is not online.");
return true;
}
if(target.equals(player)){
player.sendMessage(ChatColor.RED + "One should always be at peace with ones self.");
return true;
}
if(!plugin.removeWar(player, target)){
player.sendMessage(ChatColor.RED + "You were not at war with that person!");
return true;
}
if(!plugin.removeWar(target, player)){
return true;
}
player.sendMessage(ChatColor.GREEN + "You have made peace with " + target.getName());
for(Player bystander : player.getServer().getOnlinePlayers()){
if(!bystander.equals(player) && !bystander.equals(target)){
bystander.sendMessage( player.getName() + "has made peace with: " + target.getName() );
}
}
plugin.logMessage(player.getName() + " used " + "/war " + args[0] + " on " + args[1]);
}else{
player.sendMessage(ChatColor.RED +"A target must be specified when declaring a truce!");
return false;
}
}
}else{
player.sendMessage(ChatColor.RED + "Permission denied" );
}
}
}
return true;
}
|
diff --git a/LaTeXDraw/src/net/sf/latexdraw/actions/ScaleShapes.java b/LaTeXDraw/src/net/sf/latexdraw/actions/ScaleShapes.java
index e30ff984..2ab30542 100644
--- a/LaTeXDraw/src/net/sf/latexdraw/actions/ScaleShapes.java
+++ b/LaTeXDraw/src/net/sf/latexdraw/actions/ScaleShapes.java
@@ -1,193 +1,193 @@
package net.sf.latexdraw.actions;
import java.awt.geom.Rectangle2D;
import net.sf.latexdraw.glib.models.interfaces.GLibUtilities;
import net.sf.latexdraw.glib.models.interfaces.IGroup;
import net.sf.latexdraw.glib.models.interfaces.IPoint;
import net.sf.latexdraw.glib.models.interfaces.IShape.Position;
import org.malai.undo.Undoable;
/**
* This action scales the selected shapes of a drawing.<br>
* <br>
* This file is part of LaTeXDraw.<br>
* Copyright (c) 2005-2012 Arnaud BLOUIN<br>
* <br>
* LaTeXDraw is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later version.
* <br>
* LaTeXDraw is distributed 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.<br>
* <br>
* 29/11/2011<br>
* @author Arnaud BLOUIN
* @since 3.0
*/
public class ScaleShapes extends ShapeAction<IGroup> implements Undoable, Modifying {
/** The direction of the scaling. */
protected Position refPosition;
/** The new X position used to compute the scale factor. */
protected double newX;
/** The new Y position used to compute the scale factor. */
protected double newY;
/** The bound of the selected shapes used to perform the scaling. */
private Rectangle2D bound;
/** The old width of the selection. */
private double oldWidth;
/** The old height of the selection. */
private double oldHeight;
/**
* Creates the action.
*/
public ScaleShapes() {
super();
oldWidth = Double.NaN;
oldHeight = Double.NaN;
newX = Double.NaN;
newY = Double.NaN;
bound = new Rectangle2D.Double();
}
@Override
public boolean isRegisterable() {
return hadEffect();
}
@Override
public boolean canDo() {
return super.canDo() && refPosition!=null && isValidScales();
}
private boolean isValidScales() {
switch(refPosition) {
case EAST: case WEST:
- return isValidScale(newX) && getScaledWidth()>0.;
+ return isValidScale(newX) && getScaledWidth()>1.;
case NORTH: case SOUTH:
- return isValidScale(newY) && getScaledHeight()>0.;
+ return isValidScale(newY) && getScaledHeight()>1.;
default:
return isValidScale(newX) && isValidScale(newY) && getScaledHeight()>1. && getScaledWidth()>1.;
}
}
private boolean isValidScale(final double scale) {
return GLibUtilities.INSTANCE.isValidCoordinate(scale) && scale>0;
}
@Override
protected void doActionBody() {
if(Double.isNaN(oldWidth)) {
final IPoint br = shape.getBottomRightPoint();
final IPoint tl = shape.getTopLeftPoint();
oldWidth = br.getX() - tl.getX();
oldHeight = br.getY() - tl.getY();
updateBound(tl, br);
}
redo();
}
private void updateBound(final IPoint tl, final IPoint br) {
bound.setFrameFromDiagonal(tl.getX(), tl.getY(), br.getX(), br.getY());
}
@Override
public void undo() {
shape.scale(oldWidth, oldHeight, refPosition, bound);
drawing.setModified(true);
updateBound(shape.getTopLeftPoint(), shape.getBottomRightPoint());
}
@Override
public void setShape(final IGroup shape) {
super.setShape(shape);
if(shape!=null)
updateBound(shape.getTopLeftPoint(), shape.getBottomRightPoint());
}
private double getScaledHeight() {
if(refPosition.isSouth())
return bound.getHeight() + bound.getY() - newY;
else if(refPosition.isNorth())
return bound.getHeight() + newY - bound.getMaxY();
return 0.;
}
private double getScaledWidth() {
if(refPosition.isWest())
return bound.getWidth() + newX - bound.getMaxX();
else if(refPosition.isEast())
return bound.getWidth() + bound.getX() - newX;
return 0.;
}
@Override
public void redo() {
shape.scale(getScaledWidth(), getScaledHeight(), refPosition, bound);
drawing.setModified(true);
updateBound(shape.getTopLeftPoint(), shape.getBottomRightPoint());
}
@Override
public String getUndoName() {
return "Resizing";
}
/**
* @return The reference position of the scaling.
* @since 3.0
*/
public Position getRefPosition() {
return refPosition;
}
/**
* @param newX The new X position used to compute the scale factor.
* @since 3.0
*/
public final void setNewX(final double newX) {
this.newX = newX;
}
/**
* @param newY The new Y position used to compute the scale factor.
* @since 3.0
*/
public final void setNewY(final double newY) {
this.newY = newY;
}
/**
* @param refPosition The reference position of the scaling.
* @since 3.0
*/
public void setRefPosition(final Position refPosition) {
this.refPosition = refPosition;
}
}
| false | true | private boolean isValidScales() {
switch(refPosition) {
case EAST: case WEST:
return isValidScale(newX) && getScaledWidth()>0.;
case NORTH: case SOUTH:
return isValidScale(newY) && getScaledHeight()>0.;
default:
return isValidScale(newX) && isValidScale(newY) && getScaledHeight()>1. && getScaledWidth()>1.;
}
}
| private boolean isValidScales() {
switch(refPosition) {
case EAST: case WEST:
return isValidScale(newX) && getScaledWidth()>1.;
case NORTH: case SOUTH:
return isValidScale(newY) && getScaledHeight()>1.;
default:
return isValidScale(newX) && isValidScale(newY) && getScaledHeight()>1. && getScaledWidth()>1.;
}
}
|
diff --git a/src/rajawali/primitives/Plane.java b/src/rajawali/primitives/Plane.java
index 69a7016e..ea349317 100644
--- a/src/rajawali/primitives/Plane.java
+++ b/src/rajawali/primitives/Plane.java
@@ -1,84 +1,84 @@
package rajawali.primitives;
import rajawali.BaseObject3D;
public class Plane extends BaseObject3D {
protected float mWidth;
protected float mHeight;
protected int mSegmentsW;
protected int mSegmentsH;
public Plane() {
this(1f, 1f, 1, 1);
}
public Plane(float width, float height, int segmentsW, int segmentsH) {
super();
mWidth = width;
mHeight = height;
mSegmentsW = segmentsW;
mSegmentsH = segmentsH;
init();
}
private void init() {
int i, j;
int numVertices = (mSegmentsW + 1) * (mSegmentsH + 1);
float[] vertices = new float[numVertices * 3];
float[] textureCoords = new float[numVertices * 2];
float[] normals = new float[numVertices * 3];
float[] colors = new float[numVertices * 4];
int[] indices = new int[mSegmentsW * mSegmentsH * 6];
int vertexCount = 0;
int texCoordCount = 0;
for (i = 0; i <= mSegmentsW; i++) {
for (j = 0; j <= mSegmentsH; j++) {
vertices[vertexCount] = ((float) i / (float) mSegmentsW - 0.5f) * mWidth;
vertices[vertexCount + 1] = ((float) j / (float) mSegmentsH - 0.5f) * mHeight;
vertices[vertexCount + 2] = 0;
- textureCoords[texCoordCount++] = (float) j / (float) mSegmentsW;
- textureCoords[texCoordCount++] = 1.0f - (float) i / (float) mSegmentsH;
+ textureCoords[texCoordCount++] = (float) i / (float) mSegmentsW;
+ textureCoords[texCoordCount++] = 1.0f - (float) j / (float) mSegmentsH;
normals[vertexCount] = 0;
normals[vertexCount + 1] = 0;
normals[vertexCount + 2] = 1;
vertexCount += 3;
}
}
int colspan = mSegmentsH + 1;
int indexCount = 0;
for (int col = 0; col < mSegmentsW; col++) {
for (int row = 0; row < mSegmentsH; row++) {
int ul = col * colspan + row;
int ll = ul + 1;
int ur = (col + 1) * colspan + row;
int lr = ur + 1;
indices[indexCount++] = (int) ul;
indices[indexCount++] = (int) ur;
indices[indexCount++] = (int) lr;
indices[indexCount++] = (int) ul;
indices[indexCount++] = (int) lr;
indices[indexCount++] = (int) ll;
}
}
int numColors = numVertices * 4;
for (j = 0; j < numColors; j += 4)
{
colors[j] = 1.0f;
colors[j + 1] = 1.0f;
colors[j + 2] = 1.0f;
colors[j + 3] = 1.0f;
}
setData(vertices, normals, textureCoords, colors, indices);
}
}
| true | true | private void init() {
int i, j;
int numVertices = (mSegmentsW + 1) * (mSegmentsH + 1);
float[] vertices = new float[numVertices * 3];
float[] textureCoords = new float[numVertices * 2];
float[] normals = new float[numVertices * 3];
float[] colors = new float[numVertices * 4];
int[] indices = new int[mSegmentsW * mSegmentsH * 6];
int vertexCount = 0;
int texCoordCount = 0;
for (i = 0; i <= mSegmentsW; i++) {
for (j = 0; j <= mSegmentsH; j++) {
vertices[vertexCount] = ((float) i / (float) mSegmentsW - 0.5f) * mWidth;
vertices[vertexCount + 1] = ((float) j / (float) mSegmentsH - 0.5f) * mHeight;
vertices[vertexCount + 2] = 0;
textureCoords[texCoordCount++] = (float) j / (float) mSegmentsW;
textureCoords[texCoordCount++] = 1.0f - (float) i / (float) mSegmentsH;
normals[vertexCount] = 0;
normals[vertexCount + 1] = 0;
normals[vertexCount + 2] = 1;
vertexCount += 3;
}
}
int colspan = mSegmentsH + 1;
int indexCount = 0;
for (int col = 0; col < mSegmentsW; col++) {
for (int row = 0; row < mSegmentsH; row++) {
int ul = col * colspan + row;
int ll = ul + 1;
int ur = (col + 1) * colspan + row;
int lr = ur + 1;
indices[indexCount++] = (int) ul;
indices[indexCount++] = (int) ur;
indices[indexCount++] = (int) lr;
indices[indexCount++] = (int) ul;
indices[indexCount++] = (int) lr;
indices[indexCount++] = (int) ll;
}
}
int numColors = numVertices * 4;
for (j = 0; j < numColors; j += 4)
{
colors[j] = 1.0f;
colors[j + 1] = 1.0f;
colors[j + 2] = 1.0f;
colors[j + 3] = 1.0f;
}
setData(vertices, normals, textureCoords, colors, indices);
}
| private void init() {
int i, j;
int numVertices = (mSegmentsW + 1) * (mSegmentsH + 1);
float[] vertices = new float[numVertices * 3];
float[] textureCoords = new float[numVertices * 2];
float[] normals = new float[numVertices * 3];
float[] colors = new float[numVertices * 4];
int[] indices = new int[mSegmentsW * mSegmentsH * 6];
int vertexCount = 0;
int texCoordCount = 0;
for (i = 0; i <= mSegmentsW; i++) {
for (j = 0; j <= mSegmentsH; j++) {
vertices[vertexCount] = ((float) i / (float) mSegmentsW - 0.5f) * mWidth;
vertices[vertexCount + 1] = ((float) j / (float) mSegmentsH - 0.5f) * mHeight;
vertices[vertexCount + 2] = 0;
textureCoords[texCoordCount++] = (float) i / (float) mSegmentsW;
textureCoords[texCoordCount++] = 1.0f - (float) j / (float) mSegmentsH;
normals[vertexCount] = 0;
normals[vertexCount + 1] = 0;
normals[vertexCount + 2] = 1;
vertexCount += 3;
}
}
int colspan = mSegmentsH + 1;
int indexCount = 0;
for (int col = 0; col < mSegmentsW; col++) {
for (int row = 0; row < mSegmentsH; row++) {
int ul = col * colspan + row;
int ll = ul + 1;
int ur = (col + 1) * colspan + row;
int lr = ur + 1;
indices[indexCount++] = (int) ul;
indices[indexCount++] = (int) ur;
indices[indexCount++] = (int) lr;
indices[indexCount++] = (int) ul;
indices[indexCount++] = (int) lr;
indices[indexCount++] = (int) ll;
}
}
int numColors = numVertices * 4;
for (j = 0; j < numColors; j += 4)
{
colors[j] = 1.0f;
colors[j + 1] = 1.0f;
colors[j + 2] = 1.0f;
colors[j + 3] = 1.0f;
}
setData(vertices, normals, textureCoords, colors, indices);
}
|
diff --git a/src/main/java/net/croxis/plugins/civilmineation/Civilmineation.java b/src/main/java/net/croxis/plugins/civilmineation/Civilmineation.java
index 4fadebd..8feb060 100644
--- a/src/main/java/net/croxis/plugins/civilmineation/Civilmineation.java
+++ b/src/main/java/net/croxis/plugins/civilmineation/Civilmineation.java
@@ -1,657 +1,657 @@
package net.croxis.plugins.civilmineation;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import net.croxis.plugins.civilmineation.components.CityComponent;
import net.croxis.plugins.civilmineation.components.CivilizationComponent;
import net.croxis.plugins.civilmineation.components.Ent;
import net.croxis.plugins.civilmineation.components.PermissionComponent;
import net.croxis.plugins.civilmineation.components.PlotComponent;
import net.croxis.plugins.civilmineation.components.ResidentComponent;
import net.croxis.plugins.civilmineation.events.ResidentJoinEvent;
import net.croxis.plugins.research.Tech;
import net.croxis.plugins.research.TechManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import net.milkbowl.vault.economy.Economy;
public class Civilmineation extends JavaPlugin implements Listener {
public static CivAPI api;
private static final Logger logger = Logger.getLogger("Minecraft");
public static void log(String message){
logger.info("[Civ] " + message);
}
public static void log(Level level, String message){
logger.info("[Civ] " + message);
}
public static void logDebug(String message){
logger.info("[Civ][Debug] " + message);
}
public void onDisable() {
// TODO: Place any custom disable code here.
}
static public boolean setupEconomy() {
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
RegisteredServiceProvider<Economy> rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
return false;
}
CivAPI.econ = rsp.getProvider();
return CivAPI.econ != null;
}
public void onEnable() {
setupDatabase();
api = new CivAPI(this);
//if (!setupEconomy() ) {
// log(Level.SEVERE, "Disabled due to no Vault dependency found!");
// getServer().getPluginManager().disablePlugin(this);
// return;
//}
getServer().getPluginManager().registerEvents(this, this);
getServer().getPluginManager().registerEvents(new ActionPermissionListener(), this);
getServer().getPluginManager().registerEvents(new SignInteractListener(), this);
getCommand("tech").setExecutor(new TechCommand(this));
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run(){
logDebug("Running Turn");
getServer().broadcastMessage(ChatColor.GOLD + "Ending turn");
for (Player player : getServer().getOnlinePlayers()){
ResidentComponent resident = CivAPI.getResident(player);
if (resident.getCity() != null){
CivAPI.addCulture(resident.getCity(), 1);
CivAPI.addResearch(resident.getCity(), 1);
} else {
Tech learned = TechManager.addPoints(player, 1);
if(learned != null)
player.sendMessage("You have learned " + learned.name);
}
}
for (CityComponent city : CivAPI.getCities()){
CivAPI.addResearch(city, getDatabase().find(PlotComponent.class).where().eq("city", city).eq("type", CityPlotType.LIBRARY).findList().size());
CivAPI.updateCityCharter(city);
}
getServer().broadcastMessage(ChatColor.AQUA + "Beginning turn");
}
}, 18000, 18000);
}
public Ent createEntity(){
Ent ent = new Ent();
getDatabase().save(ent);
return ent;
}
public Ent createEntity(String name){
Ent ent = new Ent();
ent.setDebugName(name);
getDatabase().save(ent);
return ent;
}
@Override
public List<Class<?>> getDatabaseClasses() {
List<Class<?>> list = new ArrayList<Class<?>>();
list.add(Ent.class);
list.add(ResidentComponent.class);
list.add(CityComponent.class);
list.add(CivilizationComponent.class);
list.add(PlotComponent.class);
list.add(PermissionComponent.class);
return list;
}
private void setupDatabase()
{
try
{
getDatabase().find(Ent.class).findRowCount();
}
catch(PersistenceException ex)
{
System.out.println("Installing database for " + getDescription().getName() + " due to first time usage");
installDDL();
}
//Ent ent = createEntity();
//CivilizationComponent wilderness = new CivilizationComponent();
//wilderness.setName("Wilderness");
//addComponent(ent, wilderness);
}
@EventHandler
public void onSignChangeEvent(SignChangeEvent event){
ResidentComponent resident = CivAPI.getResident(event.getPlayer().getName());
PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk());
// Void plots are ok, if fact required for this set
if (event.getLine(0).equalsIgnoreCase("[New Civ]")){
if (CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is claimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){
event.getPlayer().sendMessage("Civ name on second line, Capital name on third line");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
CivilizationComponent civComponent = getDatabase().find(CivilizationComponent.class).where().ieq("name", event.getLine(1)).findUnique();
CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique();
if (civComponent != null || cityComponent != null){
event.getPlayer().sendMessage("That civ or city name already exists");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (resident.getCity() != null){
event.getPlayer().sendMessage("You must leave your city first.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (plot != null){
if (plot.getCity() != null){
event.getPlayer().sendMessage("That plot is part of a city.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
}
//TODO: Distance check to another city
//TODO: Check for room for interface placements
CivilizationComponent civ = CivAPI.createCiv(event.getLine(1));
ResidentComponent mayor = CivAPI.getResident(event.getPlayer());
CityComponent city = CivAPI.createCity(event.getLine(2), event.getPlayer(), mayor, event.getBlock(), civ, true);
event.getBlock().getRelative(BlockFace.UP).setTypeIdAndData(68, city.getCharterRotation(), true);
Sign plotSign = (Sign) event.getBlock().getRelative(BlockFace.UP).getState();
- CivAPI.claimPlot(event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), city.getName() + " Founding Square", event.getBlock().getRelative(BlockFace.UP), resident.getCity());
+ CivAPI.claimPlot(event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), city.getName() + " Founding Square", event.getBlock().getRelative(BlockFace.UP), city);
plotSign.setLine(0, city.getName());
plotSign.update();
event.setLine(0, ChatColor.DARK_AQUA + "City Charter");
event.setLine(3, "Mayor " + event.getPlayer().getName());
event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true);
//event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true);
CivAPI.updateCityCharter(city);
} else if (event.getLine(0).equalsIgnoreCase("[claim]")){
if (CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is claimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (resident.getCity() == null){
event.setCancelled(true);
event.getPlayer().sendMessage("You must be a city admin");
event.getBlock().breakNaturally();
return;
} else if (!resident.isCityAssistant()
&& !resident.isMayor()){
event.setCancelled(true);
event.getPlayer().sendMessage("You must be a city admin");
event.getBlock().breakNaturally();
return;
}
if (plot != null){
if (plot.getCity() != null){
event.setCancelled(true);
event.getPlayer().sendMessage("A city has already claimed this chunk");
event.getBlock().breakNaturally();
return;
}
} else if (resident.getCity().getCulture() < Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)){
event.setCancelled(true);
event.getPlayer().sendMessage("You do not have enough culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(resident.getCity().getCulture()) + ChatColor.BLACK + "/" + ChatColor.LIGHT_PURPLE + Double.toString(Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)));
event.getBlock().breakNaturally();
return;
}
CivAPI.claimPlot(event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), event.getBlock(), resident.getCity());
event.setLine(0, resident.getCity().getName());
return;
} else if (event.getLine(0).equalsIgnoreCase("[new city]")){
if (CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is claimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){
event.getPlayer().sendMessage("City name on second line, Mayor name on third line");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (!CivAPI.isNationalAdmin(resident)){
event.getPlayer().sendMessage("You must be a national leader or assistant.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
ResidentComponent mayor = CivAPI.getResident(event.getLine(2));
if (mayor == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique();
if (cityComponent != null){
event.getPlayer().sendMessage("That city name already exists");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (mayor.getCity() == null){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (!mayor.getCity().getCivilization().getName().equalsIgnoreCase(resident.getCity().getCivilization().getName())){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (mayor.isMayor()){
event.getPlayer().sendMessage("That player can not be an existing mayor.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (plot != null){
if (plot.getCity() != null){
event.getPlayer().sendMessage("That plot is part of a city.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
}
if (resident.getCity().getCulture() < 50){
event.getPlayer().sendMessage("Not enough culture to found a city.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
resident.getCity().setCulture(resident.getCity().getCulture() - 50);
getDatabase().save(resident.getCity());
CityComponent city = CivAPI.createCity(event.getLine(1), event.getPlayer(), mayor, event.getBlock(), mayor.getCity().getCivilization(), false);
CivAPI.claimPlot(event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), city.getName() + " Founding Square", event.getBlock().getRelative(BlockFace.UP), resident.getCity());
event.setLine(0, ChatColor.BLUE + "City Charter");
event.setLine(1, city.getCivilization().getName());
event.setLine(2, city.getName());
event.setLine(3, "Mayor " + mayor.getName());
event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true);
//event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true);
CivAPI.updateCityCharter(city);
CivAPI.broadcastToCiv("The city of " + city.getName() + " has been founded!", mayor.getCity().getCivilization());
} else if (event.getLine(0).equalsIgnoreCase("[civ assist]")){
ResidentComponent king = CivAPI.getResident(event.getPlayer());
event.getBlock().breakNaturally();
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Assistant name on the second line.");
event.setCancelled(true);
return;
} else if (!CivAPI.isKing(king)){
event.getPlayer().sendMessage("You must be a king.");
event.setCancelled(true);
return;
}
ResidentComponent assistant = CivAPI.getResident(event.getLine(1));
if (assistant == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
return;
}
if (assistant.getCity() == null){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
return;
}
if (!king.getCity().getCivilization().getName().equalsIgnoreCase(assistant.getCity().getCivilization().getName())){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
return;
}
assistant.setCivAssistant(!assistant.isCivAssistant());
getDatabase().save(assistant);
if(assistant.isCivAssistant())
CivAPI.broadcastToCiv(assistant.getName() + " is now a civ assistant!", king.getCity().getCivilization());
else
CivAPI.broadcastToCiv(assistant.getName() + " is no longer a civ assistant!", king.getCity().getCivilization());
return;
} else if (event.getLine(0).equalsIgnoreCase("[city assist]")){
ResidentComponent mayor = CivAPI.getResident(event.getPlayer());
event.getBlock().breakNaturally();
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Assistant name on the second line.");
event.setCancelled(true);
return;
} else if (!mayor.isMayor()){
event.getPlayer().sendMessage("You must be a mayor.");
event.setCancelled(true);
return;
}
ResidentComponent assistant = CivAPI.getResident(event.getLine(1));
if (assistant == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
return;
}
if (assistant.getCity() == null){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
if (!mayor.getCity().getName().equalsIgnoreCase(assistant.getCity().getName())){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
assistant.setCityAssistant(!assistant.isCityAssistant());
getDatabase().save(assistant);
if(assistant.isCityAssistant())
CivAPI.broadcastToCity(assistant.getName() + " is now a city assistant!", mayor.getCity());
else
CivAPI.broadcastToCity(assistant.getName() + " is no longer a city assistant!", mayor.getCity());
return;
} else if (event.getLine(0).equalsIgnoreCase("[kick]")) {
event.getBlock().breakNaturally();
if (!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin");
event.setCancelled(true);
return;
}
event.getBlock().breakNaturally();
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Kickee name on the second line.");
event.setCancelled(true);
return;
}
ResidentComponent kickee = CivAPI.getResident(event.getLine(1));
if (kickee == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
return;
}
if (kickee.getCity() == null){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
if (!resident.getCity().getName().equalsIgnoreCase(kickee.getCity().getName())){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
if (CivAPI.isCityAdmin(kickee)){
event.getPlayer().sendMessage("Mayors and assistants must be demoted before kick!.");
event.setCancelled(true);
return;
}
CivAPI.removeResident(kickee);
} else if (event.getLine(0).equalsIgnoreCase("[sell]")) {
double price = 0;
if (!CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is unclaimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if(!event.getLine(1).isEmpty())
try{
price = Double.parseDouble(event.getLine(1));
} catch (NumberFormatException e) {
event.getPlayer().sendMessage("Bad price value");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if(plot.getResident() == null){
if(!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
Sign sign = CivAPI.getPlotSign(plot);
if(sign == null){
CivAPI.setPlotSign((Sign) event.getBlock().getState());
plot = CivAPI.getPlot(event.getBlock().getChunk());
CivAPI.updatePlotSign(plot);
} else {
event.getBlock().breakNaturally();
}
sign = CivAPI.getPlotSign(plot);
sign.setLine(2, "=For Sale=");
sign.setLine(3, Double.toString(price));
sign.update();
event.getBlock().breakNaturally();
return;
} else {
if(CivAPI.isCityAdmin(resident) || plot.getResident().getName().equalsIgnoreCase(resident.getName())){
Sign sign = CivAPI.getPlotSign(plot);
if(sign == null){
CivAPI.setPlotSign((Sign) event.getBlock().getState());
plot = CivAPI.getPlot(event.getBlock().getChunk());
CivAPI.updatePlotSign(plot);
} else {
event.getBlock().breakNaturally();
}
sign = CivAPI.getPlotSign(plot);
sign.setLine(2, "=For Sale=");
sign.setLine(3, Double.toString(price));
return;
} else {
event.getPlayer().sendMessage("You are not a city admin or plot owner");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
}
} else if (event.getLine(0).equalsIgnoreCase("[plot]")) {
//NOTE: This has to be set inside event. Cannot cast as block as
//event will override sign.setLine()
if (!CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is unclaimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
try{
CivAPI.getPlotSign(plot).getBlock().breakNaturally();
} catch (Exception e){
}
if(plot.getResident() == null){
if(!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
event.setLine(0, plot.getCity().getName());
event.getPlayer().sendMessage("Plot sign updated");
} else {
if(CivAPI.isCityAdmin(resident) || plot.getResident().getName().equalsIgnoreCase(resident.getName())){
plot.setSignX(event.getBlock().getX());
plot.setSignY(event.getBlock().getY());
plot.setSignZ(event.getBlock().getZ());
getDatabase().save(plot);
if(getServer().getPlayer(plot.getResident().getName()).isOnline()){
event.setLine(0, ChatColor.GREEN + plot.getResident().getName());
} else {
event.setLine(0, ChatColor.RED + plot.getResident().getName());
}
event.getPlayer().sendMessage("Plot sign updated");
}
}
} else if (event.getLine(0).equalsIgnoreCase("[build]")) {
if (!CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is unclaimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
event.getBlock().breakNaturally();
if (!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin or plot owner");
event.setCancelled(true);
return;
}
if (!plot.getCity().getName().equalsIgnoreCase(resident.getCity().getName())){
event.getPlayer().sendMessage("This is not your city");
event.setCancelled(true);
return;
}
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Invalid building type");
event.setCancelled(true);
return;
}
CityPlotType type = CityPlotType.valueOf(event.getLine(1));
double cost = 0;
double value = 0;
if (type == null){
event.getPlayer().sendMessage("Invalid building type");
event.setCancelled(true);
return;
}
if (type.equals(CityPlotType.LIBRARY)){
long time = System.currentTimeMillis();
for (int x=0; x<16; x++){
for (int z=0; z<16; z++){
for (int y=0; y<getServer().getWorld("world").getMaxHeight(); y++){
if (event.getBlock().getChunk().getChunkSnapshot().getBlockTypeId(x, y, z) == 47)
value++;
}
}
}
logDebug("Library scan time: " + Long.toString(System.currentTimeMillis() - time));
cost = 25;
if (!TechManager.getResearched(CivAPI.getMayor(resident).getName()).contains(TechManager.techs.get("Writing"))){
event.getPlayer().sendMessage("You need Writing");
event.setCancelled(true);
return;
}
}
if (type.equals(CityPlotType.LIBRARY)){
if (value < cost){
event.getPlayer().sendMessage("Insufficant books: " + Double.toString(value) + "/" + Double.toString(cost));
event.setCancelled(true);
return;
}
} else if (5 == 6){//TODO: This is for finance based construction
if (CivAPI.econ.getBalance(plot.getCity().getName()) < cost){
event.getPlayer().sendMessage("Insufficant funds");
event.setCancelled(true);
return;
}
CivAPI.econ.withdrawPlayer(plot.getCity().getName(), cost);
}
plot.setType(type);
if (plot.getResident() == null)
plot.setName(plot.getCity().getName() + " " + type.toString());
else
if (getServer().getPlayer(plot.getResident().getName()).isOnline())
plot.setName(ChatColor.GREEN + plot.getResident().getName() + " " + type.toString());
else
plot.setName(ChatColor.RED + plot.getResident().getName() + " " + type.toString());
getDatabase().save(plot);
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
ResidentComponent resident = CivAPI.getResident(event.getPlayer());
if (resident == null){
Ent entity = createEntity();
resident = new ResidentComponent();
resident.setRegistered(System.currentTimeMillis());
resident.setName(event.getPlayer().getName());
resident.setEntityID(entity);
getDatabase().save(resident);
PermissionComponent perm = new PermissionComponent();
perm.setEntityID(resident.getEntityID());
perm.setName(resident.getName());
perm.setAll(false);
perm.setResidentBuild(true);
perm.setResidentDestroy(true);
perm.setResidentItemUse(true);
perm.setResidentSwitch(true);
getDatabase().save(perm);
}
String title = "";
if (resident.isMayor()){
title = "Mayor ";
if (resident.getCity().isCapital())
title = "King ";
} else if (resident.getCity() == null)
title = "Wild ";
event.getPlayer().sendMessage("Welcome, " + title + event.getPlayer().getDisplayName() + "!");
ResidentJoinEvent resEvent = new ResidentJoinEvent(resident.getName(), resident.getEntityID().getId());
Bukkit.getServer().getPluginManager().callEvent(resEvent);
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event){
if (event.getFrom().getWorld().getChunkAt(event.getFrom()).getX()
!= event.getTo().getWorld().getChunkAt(event.getTo()).getX()
|| event.getFrom().getWorld().getChunkAt(event.getFrom()).getZ()
!= event.getTo().getWorld().getChunkAt(event.getTo()).getZ()){
//event.getPlayer().sendMessage("Message will go here");
PlotComponent plot = CivAPI.getPlot(event.getTo().getChunk());
PlotComponent plotFrom = CivAPI.getPlot(event.getFrom().getChunk());
if (plot == null && plotFrom != null){
event.getPlayer().sendMessage("Wilds");
} else if (plot == null && plotFrom == null){
// Needed to prevent future NPES
} else if (plot != null && plotFrom == null){
// TODO: City enter event
event.getPlayer().sendMessage(plot.getName());
} else if (!plot.getName().equalsIgnoreCase(plotFrom.getName())){
event.getPlayer().sendMessage(plot.getName());
}
}
}
}
| true | true | public void onSignChangeEvent(SignChangeEvent event){
ResidentComponent resident = CivAPI.getResident(event.getPlayer().getName());
PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk());
// Void plots are ok, if fact required for this set
if (event.getLine(0).equalsIgnoreCase("[New Civ]")){
if (CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is claimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){
event.getPlayer().sendMessage("Civ name on second line, Capital name on third line");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
CivilizationComponent civComponent = getDatabase().find(CivilizationComponent.class).where().ieq("name", event.getLine(1)).findUnique();
CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique();
if (civComponent != null || cityComponent != null){
event.getPlayer().sendMessage("That civ or city name already exists");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (resident.getCity() != null){
event.getPlayer().sendMessage("You must leave your city first.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (plot != null){
if (plot.getCity() != null){
event.getPlayer().sendMessage("That plot is part of a city.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
}
//TODO: Distance check to another city
//TODO: Check for room for interface placements
CivilizationComponent civ = CivAPI.createCiv(event.getLine(1));
ResidentComponent mayor = CivAPI.getResident(event.getPlayer());
CityComponent city = CivAPI.createCity(event.getLine(2), event.getPlayer(), mayor, event.getBlock(), civ, true);
event.getBlock().getRelative(BlockFace.UP).setTypeIdAndData(68, city.getCharterRotation(), true);
Sign plotSign = (Sign) event.getBlock().getRelative(BlockFace.UP).getState();
CivAPI.claimPlot(event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), city.getName() + " Founding Square", event.getBlock().getRelative(BlockFace.UP), resident.getCity());
plotSign.setLine(0, city.getName());
plotSign.update();
event.setLine(0, ChatColor.DARK_AQUA + "City Charter");
event.setLine(3, "Mayor " + event.getPlayer().getName());
event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true);
//event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true);
CivAPI.updateCityCharter(city);
} else if (event.getLine(0).equalsIgnoreCase("[claim]")){
if (CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is claimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (resident.getCity() == null){
event.setCancelled(true);
event.getPlayer().sendMessage("You must be a city admin");
event.getBlock().breakNaturally();
return;
} else if (!resident.isCityAssistant()
&& !resident.isMayor()){
event.setCancelled(true);
event.getPlayer().sendMessage("You must be a city admin");
event.getBlock().breakNaturally();
return;
}
if (plot != null){
if (plot.getCity() != null){
event.setCancelled(true);
event.getPlayer().sendMessage("A city has already claimed this chunk");
event.getBlock().breakNaturally();
return;
}
} else if (resident.getCity().getCulture() < Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)){
event.setCancelled(true);
event.getPlayer().sendMessage("You do not have enough culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(resident.getCity().getCulture()) + ChatColor.BLACK + "/" + ChatColor.LIGHT_PURPLE + Double.toString(Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)));
event.getBlock().breakNaturally();
return;
}
CivAPI.claimPlot(event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), event.getBlock(), resident.getCity());
event.setLine(0, resident.getCity().getName());
return;
} else if (event.getLine(0).equalsIgnoreCase("[new city]")){
if (CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is claimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){
event.getPlayer().sendMessage("City name on second line, Mayor name on third line");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (!CivAPI.isNationalAdmin(resident)){
event.getPlayer().sendMessage("You must be a national leader or assistant.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
ResidentComponent mayor = CivAPI.getResident(event.getLine(2));
if (mayor == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique();
if (cityComponent != null){
event.getPlayer().sendMessage("That city name already exists");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (mayor.getCity() == null){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (!mayor.getCity().getCivilization().getName().equalsIgnoreCase(resident.getCity().getCivilization().getName())){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (mayor.isMayor()){
event.getPlayer().sendMessage("That player can not be an existing mayor.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (plot != null){
if (plot.getCity() != null){
event.getPlayer().sendMessage("That plot is part of a city.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
}
if (resident.getCity().getCulture() < 50){
event.getPlayer().sendMessage("Not enough culture to found a city.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
resident.getCity().setCulture(resident.getCity().getCulture() - 50);
getDatabase().save(resident.getCity());
CityComponent city = CivAPI.createCity(event.getLine(1), event.getPlayer(), mayor, event.getBlock(), mayor.getCity().getCivilization(), false);
CivAPI.claimPlot(event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), city.getName() + " Founding Square", event.getBlock().getRelative(BlockFace.UP), resident.getCity());
event.setLine(0, ChatColor.BLUE + "City Charter");
event.setLine(1, city.getCivilization().getName());
event.setLine(2, city.getName());
event.setLine(3, "Mayor " + mayor.getName());
event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true);
//event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true);
CivAPI.updateCityCharter(city);
CivAPI.broadcastToCiv("The city of " + city.getName() + " has been founded!", mayor.getCity().getCivilization());
} else if (event.getLine(0).equalsIgnoreCase("[civ assist]")){
ResidentComponent king = CivAPI.getResident(event.getPlayer());
event.getBlock().breakNaturally();
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Assistant name on the second line.");
event.setCancelled(true);
return;
} else if (!CivAPI.isKing(king)){
event.getPlayer().sendMessage("You must be a king.");
event.setCancelled(true);
return;
}
ResidentComponent assistant = CivAPI.getResident(event.getLine(1));
if (assistant == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
return;
}
if (assistant.getCity() == null){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
return;
}
if (!king.getCity().getCivilization().getName().equalsIgnoreCase(assistant.getCity().getCivilization().getName())){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
return;
}
assistant.setCivAssistant(!assistant.isCivAssistant());
getDatabase().save(assistant);
if(assistant.isCivAssistant())
CivAPI.broadcastToCiv(assistant.getName() + " is now a civ assistant!", king.getCity().getCivilization());
else
CivAPI.broadcastToCiv(assistant.getName() + " is no longer a civ assistant!", king.getCity().getCivilization());
return;
} else if (event.getLine(0).equalsIgnoreCase("[city assist]")){
ResidentComponent mayor = CivAPI.getResident(event.getPlayer());
event.getBlock().breakNaturally();
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Assistant name on the second line.");
event.setCancelled(true);
return;
} else if (!mayor.isMayor()){
event.getPlayer().sendMessage("You must be a mayor.");
event.setCancelled(true);
return;
}
ResidentComponent assistant = CivAPI.getResident(event.getLine(1));
if (assistant == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
return;
}
if (assistant.getCity() == null){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
if (!mayor.getCity().getName().equalsIgnoreCase(assistant.getCity().getName())){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
assistant.setCityAssistant(!assistant.isCityAssistant());
getDatabase().save(assistant);
if(assistant.isCityAssistant())
CivAPI.broadcastToCity(assistant.getName() + " is now a city assistant!", mayor.getCity());
else
CivAPI.broadcastToCity(assistant.getName() + " is no longer a city assistant!", mayor.getCity());
return;
} else if (event.getLine(0).equalsIgnoreCase("[kick]")) {
event.getBlock().breakNaturally();
if (!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin");
event.setCancelled(true);
return;
}
event.getBlock().breakNaturally();
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Kickee name on the second line.");
event.setCancelled(true);
return;
}
ResidentComponent kickee = CivAPI.getResident(event.getLine(1));
if (kickee == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
return;
}
if (kickee.getCity() == null){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
if (!resident.getCity().getName().equalsIgnoreCase(kickee.getCity().getName())){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
if (CivAPI.isCityAdmin(kickee)){
event.getPlayer().sendMessage("Mayors and assistants must be demoted before kick!.");
event.setCancelled(true);
return;
}
CivAPI.removeResident(kickee);
} else if (event.getLine(0).equalsIgnoreCase("[sell]")) {
double price = 0;
if (!CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is unclaimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if(!event.getLine(1).isEmpty())
try{
price = Double.parseDouble(event.getLine(1));
} catch (NumberFormatException e) {
event.getPlayer().sendMessage("Bad price value");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if(plot.getResident() == null){
if(!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
Sign sign = CivAPI.getPlotSign(plot);
if(sign == null){
CivAPI.setPlotSign((Sign) event.getBlock().getState());
plot = CivAPI.getPlot(event.getBlock().getChunk());
CivAPI.updatePlotSign(plot);
} else {
event.getBlock().breakNaturally();
}
sign = CivAPI.getPlotSign(plot);
sign.setLine(2, "=For Sale=");
sign.setLine(3, Double.toString(price));
sign.update();
event.getBlock().breakNaturally();
return;
} else {
if(CivAPI.isCityAdmin(resident) || plot.getResident().getName().equalsIgnoreCase(resident.getName())){
Sign sign = CivAPI.getPlotSign(plot);
if(sign == null){
CivAPI.setPlotSign((Sign) event.getBlock().getState());
plot = CivAPI.getPlot(event.getBlock().getChunk());
CivAPI.updatePlotSign(plot);
} else {
event.getBlock().breakNaturally();
}
sign = CivAPI.getPlotSign(plot);
sign.setLine(2, "=For Sale=");
sign.setLine(3, Double.toString(price));
return;
} else {
event.getPlayer().sendMessage("You are not a city admin or plot owner");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
}
} else if (event.getLine(0).equalsIgnoreCase("[plot]")) {
//NOTE: This has to be set inside event. Cannot cast as block as
//event will override sign.setLine()
if (!CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is unclaimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
try{
CivAPI.getPlotSign(plot).getBlock().breakNaturally();
} catch (Exception e){
}
if(plot.getResident() == null){
if(!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
event.setLine(0, plot.getCity().getName());
event.getPlayer().sendMessage("Plot sign updated");
} else {
if(CivAPI.isCityAdmin(resident) || plot.getResident().getName().equalsIgnoreCase(resident.getName())){
plot.setSignX(event.getBlock().getX());
plot.setSignY(event.getBlock().getY());
plot.setSignZ(event.getBlock().getZ());
getDatabase().save(plot);
if(getServer().getPlayer(plot.getResident().getName()).isOnline()){
event.setLine(0, ChatColor.GREEN + plot.getResident().getName());
} else {
event.setLine(0, ChatColor.RED + plot.getResident().getName());
}
event.getPlayer().sendMessage("Plot sign updated");
}
}
} else if (event.getLine(0).equalsIgnoreCase("[build]")) {
if (!CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is unclaimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
event.getBlock().breakNaturally();
if (!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin or plot owner");
event.setCancelled(true);
return;
}
if (!plot.getCity().getName().equalsIgnoreCase(resident.getCity().getName())){
event.getPlayer().sendMessage("This is not your city");
event.setCancelled(true);
return;
}
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Invalid building type");
event.setCancelled(true);
return;
}
CityPlotType type = CityPlotType.valueOf(event.getLine(1));
double cost = 0;
double value = 0;
if (type == null){
event.getPlayer().sendMessage("Invalid building type");
event.setCancelled(true);
return;
}
if (type.equals(CityPlotType.LIBRARY)){
long time = System.currentTimeMillis();
for (int x=0; x<16; x++){
for (int z=0; z<16; z++){
for (int y=0; y<getServer().getWorld("world").getMaxHeight(); y++){
if (event.getBlock().getChunk().getChunkSnapshot().getBlockTypeId(x, y, z) == 47)
value++;
}
}
}
logDebug("Library scan time: " + Long.toString(System.currentTimeMillis() - time));
cost = 25;
if (!TechManager.getResearched(CivAPI.getMayor(resident).getName()).contains(TechManager.techs.get("Writing"))){
event.getPlayer().sendMessage("You need Writing");
event.setCancelled(true);
return;
}
}
if (type.equals(CityPlotType.LIBRARY)){
if (value < cost){
event.getPlayer().sendMessage("Insufficant books: " + Double.toString(value) + "/" + Double.toString(cost));
event.setCancelled(true);
return;
}
} else if (5 == 6){//TODO: This is for finance based construction
if (CivAPI.econ.getBalance(plot.getCity().getName()) < cost){
event.getPlayer().sendMessage("Insufficant funds");
event.setCancelled(true);
return;
}
CivAPI.econ.withdrawPlayer(plot.getCity().getName(), cost);
}
plot.setType(type);
if (plot.getResident() == null)
plot.setName(plot.getCity().getName() + " " + type.toString());
else
if (getServer().getPlayer(plot.getResident().getName()).isOnline())
plot.setName(ChatColor.GREEN + plot.getResident().getName() + " " + type.toString());
else
plot.setName(ChatColor.RED + plot.getResident().getName() + " " + type.toString());
getDatabase().save(plot);
}
}
| public void onSignChangeEvent(SignChangeEvent event){
ResidentComponent resident = CivAPI.getResident(event.getPlayer().getName());
PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk());
// Void plots are ok, if fact required for this set
if (event.getLine(0).equalsIgnoreCase("[New Civ]")){
if (CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is claimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){
event.getPlayer().sendMessage("Civ name on second line, Capital name on third line");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
CivilizationComponent civComponent = getDatabase().find(CivilizationComponent.class).where().ieq("name", event.getLine(1)).findUnique();
CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique();
if (civComponent != null || cityComponent != null){
event.getPlayer().sendMessage("That civ or city name already exists");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (resident.getCity() != null){
event.getPlayer().sendMessage("You must leave your city first.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (plot != null){
if (plot.getCity() != null){
event.getPlayer().sendMessage("That plot is part of a city.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
}
//TODO: Distance check to another city
//TODO: Check for room for interface placements
CivilizationComponent civ = CivAPI.createCiv(event.getLine(1));
ResidentComponent mayor = CivAPI.getResident(event.getPlayer());
CityComponent city = CivAPI.createCity(event.getLine(2), event.getPlayer(), mayor, event.getBlock(), civ, true);
event.getBlock().getRelative(BlockFace.UP).setTypeIdAndData(68, city.getCharterRotation(), true);
Sign plotSign = (Sign) event.getBlock().getRelative(BlockFace.UP).getState();
CivAPI.claimPlot(event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), city.getName() + " Founding Square", event.getBlock().getRelative(BlockFace.UP), city);
plotSign.setLine(0, city.getName());
plotSign.update();
event.setLine(0, ChatColor.DARK_AQUA + "City Charter");
event.setLine(3, "Mayor " + event.getPlayer().getName());
event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true);
//event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true);
CivAPI.updateCityCharter(city);
} else if (event.getLine(0).equalsIgnoreCase("[claim]")){
if (CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is claimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (resident.getCity() == null){
event.setCancelled(true);
event.getPlayer().sendMessage("You must be a city admin");
event.getBlock().breakNaturally();
return;
} else if (!resident.isCityAssistant()
&& !resident.isMayor()){
event.setCancelled(true);
event.getPlayer().sendMessage("You must be a city admin");
event.getBlock().breakNaturally();
return;
}
if (plot != null){
if (plot.getCity() != null){
event.setCancelled(true);
event.getPlayer().sendMessage("A city has already claimed this chunk");
event.getBlock().breakNaturally();
return;
}
} else if (resident.getCity().getCulture() < Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)){
event.setCancelled(true);
event.getPlayer().sendMessage("You do not have enough culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(resident.getCity().getCulture()) + ChatColor.BLACK + "/" + ChatColor.LIGHT_PURPLE + Double.toString(Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)));
event.getBlock().breakNaturally();
return;
}
CivAPI.claimPlot(event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), event.getBlock(), resident.getCity());
event.setLine(0, resident.getCity().getName());
return;
} else if (event.getLine(0).equalsIgnoreCase("[new city]")){
if (CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is claimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (event.getLine(1).isEmpty() || event.getLine(2).isEmpty()){
event.getPlayer().sendMessage("City name on second line, Mayor name on third line");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (!CivAPI.isNationalAdmin(resident)){
event.getPlayer().sendMessage("You must be a national leader or assistant.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
ResidentComponent mayor = CivAPI.getResident(event.getLine(2));
if (mayor == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
CityComponent cityComponent = getDatabase().find(CityComponent.class).where().ieq("name", event.getLine(2)).findUnique();
if (cityComponent != null){
event.getPlayer().sendMessage("That city name already exists");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (mayor.getCity() == null){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (!mayor.getCity().getCivilization().getName().equalsIgnoreCase(resident.getCity().getCivilization().getName())){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (mayor.isMayor()){
event.getPlayer().sendMessage("That player can not be an existing mayor.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if (plot != null){
if (plot.getCity() != null){
event.getPlayer().sendMessage("That plot is part of a city.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
}
if (resident.getCity().getCulture() < 50){
event.getPlayer().sendMessage("Not enough culture to found a city.");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
resident.getCity().setCulture(resident.getCity().getCulture() - 50);
getDatabase().save(resident.getCity());
CityComponent city = CivAPI.createCity(event.getLine(1), event.getPlayer(), mayor, event.getBlock(), mayor.getCity().getCivilization(), false);
CivAPI.claimPlot(event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), city.getName() + " Founding Square", event.getBlock().getRelative(BlockFace.UP), resident.getCity());
event.setLine(0, ChatColor.BLUE + "City Charter");
event.setLine(1, city.getCivilization().getName());
event.setLine(2, city.getName());
event.setLine(3, "Mayor " + mayor.getName());
event.getBlock().getRelative(BlockFace.DOWN).setTypeIdAndData(68, city.getCharterRotation(), true);
//event.getBlock().getRelative(BlockFace.DOWN).getRelative(BlockFace.DOWN).setTypeIdAndData(68, rotation, true);
CivAPI.updateCityCharter(city);
CivAPI.broadcastToCiv("The city of " + city.getName() + " has been founded!", mayor.getCity().getCivilization());
} else if (event.getLine(0).equalsIgnoreCase("[civ assist]")){
ResidentComponent king = CivAPI.getResident(event.getPlayer());
event.getBlock().breakNaturally();
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Assistant name on the second line.");
event.setCancelled(true);
return;
} else if (!CivAPI.isKing(king)){
event.getPlayer().sendMessage("You must be a king.");
event.setCancelled(true);
return;
}
ResidentComponent assistant = CivAPI.getResident(event.getLine(1));
if (assistant == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
return;
}
if (assistant.getCity() == null){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
return;
}
if (!king.getCity().getCivilization().getName().equalsIgnoreCase(assistant.getCity().getCivilization().getName())){
event.getPlayer().sendMessage("That player must be in your civ!.");
event.setCancelled(true);
return;
}
assistant.setCivAssistant(!assistant.isCivAssistant());
getDatabase().save(assistant);
if(assistant.isCivAssistant())
CivAPI.broadcastToCiv(assistant.getName() + " is now a civ assistant!", king.getCity().getCivilization());
else
CivAPI.broadcastToCiv(assistant.getName() + " is no longer a civ assistant!", king.getCity().getCivilization());
return;
} else if (event.getLine(0).equalsIgnoreCase("[city assist]")){
ResidentComponent mayor = CivAPI.getResident(event.getPlayer());
event.getBlock().breakNaturally();
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Assistant name on the second line.");
event.setCancelled(true);
return;
} else if (!mayor.isMayor()){
event.getPlayer().sendMessage("You must be a mayor.");
event.setCancelled(true);
return;
}
ResidentComponent assistant = CivAPI.getResident(event.getLine(1));
if (assistant == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
return;
}
if (assistant.getCity() == null){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
if (!mayor.getCity().getName().equalsIgnoreCase(assistant.getCity().getName())){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
assistant.setCityAssistant(!assistant.isCityAssistant());
getDatabase().save(assistant);
if(assistant.isCityAssistant())
CivAPI.broadcastToCity(assistant.getName() + " is now a city assistant!", mayor.getCity());
else
CivAPI.broadcastToCity(assistant.getName() + " is no longer a city assistant!", mayor.getCity());
return;
} else if (event.getLine(0).equalsIgnoreCase("[kick]")) {
event.getBlock().breakNaturally();
if (!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin");
event.setCancelled(true);
return;
}
event.getBlock().breakNaturally();
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Kickee name on the second line.");
event.setCancelled(true);
return;
}
ResidentComponent kickee = CivAPI.getResident(event.getLine(1));
if (kickee == null){
event.getPlayer().sendMessage("That player does not exist.");
event.setCancelled(true);
return;
}
if (kickee.getCity() == null){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
if (!resident.getCity().getName().equalsIgnoreCase(kickee.getCity().getName())){
event.getPlayer().sendMessage("That player must be in your city!.");
event.setCancelled(true);
return;
}
if (CivAPI.isCityAdmin(kickee)){
event.getPlayer().sendMessage("Mayors and assistants must be demoted before kick!.");
event.setCancelled(true);
return;
}
CivAPI.removeResident(kickee);
} else if (event.getLine(0).equalsIgnoreCase("[sell]")) {
double price = 0;
if (!CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is unclaimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if(!event.getLine(1).isEmpty())
try{
price = Double.parseDouble(event.getLine(1));
} catch (NumberFormatException e) {
event.getPlayer().sendMessage("Bad price value");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
if(plot.getResident() == null){
if(!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
Sign sign = CivAPI.getPlotSign(plot);
if(sign == null){
CivAPI.setPlotSign((Sign) event.getBlock().getState());
plot = CivAPI.getPlot(event.getBlock().getChunk());
CivAPI.updatePlotSign(plot);
} else {
event.getBlock().breakNaturally();
}
sign = CivAPI.getPlotSign(plot);
sign.setLine(2, "=For Sale=");
sign.setLine(3, Double.toString(price));
sign.update();
event.getBlock().breakNaturally();
return;
} else {
if(CivAPI.isCityAdmin(resident) || plot.getResident().getName().equalsIgnoreCase(resident.getName())){
Sign sign = CivAPI.getPlotSign(plot);
if(sign == null){
CivAPI.setPlotSign((Sign) event.getBlock().getState());
plot = CivAPI.getPlot(event.getBlock().getChunk());
CivAPI.updatePlotSign(plot);
} else {
event.getBlock().breakNaturally();
}
sign = CivAPI.getPlotSign(plot);
sign.setLine(2, "=For Sale=");
sign.setLine(3, Double.toString(price));
return;
} else {
event.getPlayer().sendMessage("You are not a city admin or plot owner");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
}
} else if (event.getLine(0).equalsIgnoreCase("[plot]")) {
//NOTE: This has to be set inside event. Cannot cast as block as
//event will override sign.setLine()
if (!CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is unclaimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
try{
CivAPI.getPlotSign(plot).getBlock().breakNaturally();
} catch (Exception e){
}
if(plot.getResident() == null){
if(!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
event.setLine(0, plot.getCity().getName());
event.getPlayer().sendMessage("Plot sign updated");
} else {
if(CivAPI.isCityAdmin(resident) || plot.getResident().getName().equalsIgnoreCase(resident.getName())){
plot.setSignX(event.getBlock().getX());
plot.setSignY(event.getBlock().getY());
plot.setSignZ(event.getBlock().getZ());
getDatabase().save(plot);
if(getServer().getPlayer(plot.getResident().getName()).isOnline()){
event.setLine(0, ChatColor.GREEN + plot.getResident().getName());
} else {
event.setLine(0, ChatColor.RED + plot.getResident().getName());
}
event.getPlayer().sendMessage("Plot sign updated");
}
}
} else if (event.getLine(0).equalsIgnoreCase("[build]")) {
if (!CivAPI.isClaimed(plot)){
event.getPlayer().sendMessage("This plot is unclaimed");
event.setCancelled(true);
event.getBlock().breakNaturally();
return;
}
event.getBlock().breakNaturally();
if (!CivAPI.isCityAdmin(resident)){
event.getPlayer().sendMessage("You are not a city admin or plot owner");
event.setCancelled(true);
return;
}
if (!plot.getCity().getName().equalsIgnoreCase(resident.getCity().getName())){
event.getPlayer().sendMessage("This is not your city");
event.setCancelled(true);
return;
}
if (event.getLine(1).isEmpty()){
event.getPlayer().sendMessage("Invalid building type");
event.setCancelled(true);
return;
}
CityPlotType type = CityPlotType.valueOf(event.getLine(1));
double cost = 0;
double value = 0;
if (type == null){
event.getPlayer().sendMessage("Invalid building type");
event.setCancelled(true);
return;
}
if (type.equals(CityPlotType.LIBRARY)){
long time = System.currentTimeMillis();
for (int x=0; x<16; x++){
for (int z=0; z<16; z++){
for (int y=0; y<getServer().getWorld("world").getMaxHeight(); y++){
if (event.getBlock().getChunk().getChunkSnapshot().getBlockTypeId(x, y, z) == 47)
value++;
}
}
}
logDebug("Library scan time: " + Long.toString(System.currentTimeMillis() - time));
cost = 25;
if (!TechManager.getResearched(CivAPI.getMayor(resident).getName()).contains(TechManager.techs.get("Writing"))){
event.getPlayer().sendMessage("You need Writing");
event.setCancelled(true);
return;
}
}
if (type.equals(CityPlotType.LIBRARY)){
if (value < cost){
event.getPlayer().sendMessage("Insufficant books: " + Double.toString(value) + "/" + Double.toString(cost));
event.setCancelled(true);
return;
}
} else if (5 == 6){//TODO: This is for finance based construction
if (CivAPI.econ.getBalance(plot.getCity().getName()) < cost){
event.getPlayer().sendMessage("Insufficant funds");
event.setCancelled(true);
return;
}
CivAPI.econ.withdrawPlayer(plot.getCity().getName(), cost);
}
plot.setType(type);
if (plot.getResident() == null)
plot.setName(plot.getCity().getName() + " " + type.toString());
else
if (getServer().getPlayer(plot.getResident().getName()).isOnline())
plot.setName(ChatColor.GREEN + plot.getResident().getName() + " " + type.toString());
else
plot.setName(ChatColor.RED + plot.getResident().getName() + " " + type.toString());
getDatabase().save(plot);
}
}
|
diff --git a/src/net/sf/freecol/server/model/ServerColony.java b/src/net/sf/freecol/server/model/ServerColony.java
index 96282393c..0309b0706 100644
--- a/src/net/sf/freecol/server/model/ServerColony.java
+++ b/src/net/sf/freecol/server/model/ServerColony.java
@@ -1,573 +1,573 @@
/**
* Copyright (C) 2002-2011 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.server.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.logging.Logger;
import net.sf.freecol.common.model.AbstractGoods;
import net.sf.freecol.common.model.BuildQueue;
import net.sf.freecol.common.model.BuildableType;
import net.sf.freecol.common.model.Building;
import net.sf.freecol.common.model.BuildingType;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.ColonyTile;
import net.sf.freecol.common.model.ExportData;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsContainer;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.Market;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.ProductionInfo;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TileImprovement;
import net.sf.freecol.common.model.TypeCountMap;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.Unit.UnitState;
import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.model.WorkLocation;
import net.sf.freecol.common.util.Utils;
import net.sf.freecol.server.control.ChangeSet;
import net.sf.freecol.server.control.ChangeSet.See;
/**
* The server version of a colony.
*/
public class ServerColony extends Colony implements ServerModelObject {
private static final Logger logger = Logger.getLogger(ServerColony.class.getName());
// Temporary variable:
private int lastVisited;
/**
* Trivial constructor required for all ServerModelObjects.
*/
public ServerColony(Game game, String id) {
super(game, id);
}
/**
* Creates a new ServerColony.
*
* @param game The <code>Game</code> in which this object belongs.
* @param owner The <code>Player</code> owning this <code>Colony</code>.
* @param name The name of the new <code>Colony</code>.
* @param tile The location of the <code>Colony</code>.
*/
public ServerColony(Game game, Player owner, String name, Tile tile) {
super(game, owner, name, tile);
Specification spec = getSpecification();
goodsContainer = new GoodsContainer(game, this);
goodsContainer.addPropertyChangeListener(this);
sonsOfLiberty = 0;
oldSonsOfLiberty = 0;
established = game.getTurn();
tile.setOwner(owner);
if (!tile.hasRoad()) {
TileImprovement road
= new TileImprovement(game, tile,
spec.getTileImprovementType("model.improvement.road"));
road.setTurnsToComplete(0);
road.setVirtual(true);
tile.add(road);
}
ColonyTile colonyTile = new ServerColonyTile(game, this, tile);
colonyTiles.add(colonyTile);
for (Tile t : tile.getSurroundingTiles(getRadius())) {
colonyTiles.add(new ServerColonyTile(game, this, t));
if (t.getType().isWater()) {
landLocked = false;
}
}
// set up default production queues
if (landLocked) {
buildQueue.add(spec.getBuildingType("model.building.warehouse"));
} else {
buildQueue.add(spec.getBuildingType("model.building.docks"));
getFeatureContainer().addAbility(HAS_PORT);
}
for (UnitType unitType : spec.getUnitTypesWithAbility("model.ability.bornInColony")) {
if (!unitType.getGoodsRequired().isEmpty()) {
populationQueue.add(unitType);
}
}
Building building;
List<BuildingType> buildingTypes = spec.getBuildingTypeList();
for (BuildingType buildingType : buildingTypes) {
if (buildingType.isAutomaticBuild()
|| isAutomaticBuild(buildingType)) {
building = new ServerBuilding(getGame(), this, buildingType);
addBuilding(building);
}
}
lastVisited = -1;
}
/**
* New turn for this colony.
* Try to find out if the colony is going to survive (last colonist does
* not starve) before generating lots of production-related messages.
* TODO: use the warehouse to store things?
*
* @param random A <code>Random</code> number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csNewTurn(Random random, ChangeSet cs) {
logger.finest("ServerColony.csNewTurn, for " + toString());
ServerPlayer owner = (ServerPlayer) getOwner();
Specification spec = getSpecification();
boolean tileDirty = false;
boolean colonyDirty = false;
List<FreeColGameObject> updates = new ArrayList<FreeColGameObject>();
GoodsContainer container = getGoodsContainer();
container.saveState();
java.util.Map<Object, ProductionInfo> info = getProductionAndConsumption();
TypeCountMap<GoodsType> netProduction = new TypeCountMap<GoodsType>();
for (Entry<Object, ProductionInfo> entry : info.entrySet()) {
ProductionInfo productionInfo = entry.getValue();
if (entry.getKey() instanceof WorkLocation) {
WorkLocation workLocation = (WorkLocation) entry.getKey();
((ServerModelObject) workLocation).csNewTurn(random, cs);
if (workLocation.getUnitCount() > 0) {
for (AbstractGoods goods : productionInfo.getProduction()) {
int experience = goods.getAmount() / workLocation.getUnitCount();
for (Unit unit : workLocation.getUnitList()) {
unit.setExperience(unit.getExperience() + experience);
cs.addPartial(See.only(owner), unit, "experience");
}
}
}
} else if (entry.getKey() instanceof BuildQueue
&& !productionInfo.getConsumption().isEmpty()) {
// this means we are actually building something
BuildQueue queue = (BuildQueue) entry.getKey();
BuildableType buildable = queue.getCurrentlyBuilding();
if (buildable instanceof UnitType) {
tileDirty = buildUnit(queue, cs, random);
} else if (buildable instanceof BuildingType) {
colonyDirty = buildBuilding(queue, cs, updates);
} else {
throw new IllegalStateException("Bogus buildable: " + buildable);
}
// Having removed something from the build queue, nudge it again
// to see if there is a problem with the next item if any.
buildable = csGetBuildable(cs);
}
for (AbstractGoods goods : productionInfo.getProduction()) {
netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount());
}
for (AbstractGoods goods : productionInfo.getStorage()) {
netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount());
}
for (AbstractGoods goods : productionInfo.getConsumption()) {
netProduction.incrementCount(goods.getType().getStoredAs(), -goods.getAmount());
}
}
// Apply the changes accumulated in the netProduction map
for (Entry<GoodsType, Integer> entry
: netProduction.getValues().entrySet()) {
GoodsType goodsType = entry.getKey();
int net = entry.getValue();
int stored = getGoodsCount(goodsType);
if (net + stored < 0) {
removeGoods(goodsType, stored);
} else {
addGoods(goodsType, net);
}
}
// Now check the food situation
int storedFood = getGoodsCount(spec.getPrimaryFoodType());
if (storedFood <= 0) {
if (getUnitCount() > 1) {
Unit victim = Utils.getRandomMember(logger, "Choose starver",
getUnitList(), random);
updates.add((FreeColGameObject) victim.getLocation());
cs.addDispose(owner, this, victim);
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.UNIT_LOST,
"model.colony.colonistStarved",
this)
.addName("%colony%", getName()));
} else { // Its dead, Jim.
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.UNIT_LOST,
"model.colony.colonyStarved",
this)
.addName("%colony%", getName()));
cs.addDispose(owner, getTile(), this);
return;
}
} else {
int netFood = netProduction.getCount(spec.getPrimaryFoodType());
- int turns = Math.abs(storedFood / netFood);
- if (netFood < 0 && turns <= 3) {
+ int turns;
+ if (netFood < 0 && (turns = storedFood / -netFood) <= 3) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WARNING,
"model.colony.famineFeared",
this)
.addName("%colony%", getName())
.addName("%number%", String.valueOf(turns)));
logger.finest("Famine feared in " + getName()
+ " food=" + storedFood
+ " production=" + netFood
+ " turns=" + turns);
}
}
/** TODO: do we want this?
if (goodsInput == 0 && !canAutoProduce()
&& getMaximumGoodsInput() > 0) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.MISSING_GOODS,
"model.building.notEnoughInput",
colony, goodsInputType)
.add("%inputGoods%", goodsInputType.getNameKey())
.add("%building%", getNameKey())
.addName("%colony%", colony.getName()));
}
*/
// Export goods if custom house is built.
// Do not flush price changes yet, as any price change may change
// yet again in csYearlyGoodsRemoval.
if (hasAbility("model.ability.export")) {
boolean gold = false;
for (Goods goods : container.getCompactGoods()) {
GoodsType type = goods.getType();
ExportData data = getExportData(type);
if (data.isExported()
&& (owner.canTrade(goods, Market.Access.CUSTOM_HOUSE))) {
int amount = goods.getAmount() - data.getExportLevel();
if (amount > 0) {
owner.sell(container, type, amount, random);
gold = true;
}
}
}
if (gold) {
cs.addPartial(See.only(owner), owner, "gold");
}
}
// Throw away goods there is no room for, and warn about
// levels that will be exceeded next turn
int limit = getWarehouseCapacity();
int adjustment = limit / GoodsContainer.CARGO_SIZE;
for (Goods goods : container.getCompactGoods()) {
GoodsType type = goods.getType();
if (!type.isStorable()) continue;
ExportData exportData = getExportData(type);
int low = exportData.getLowLevel() * adjustment;
int high = exportData.getHighLevel() * adjustment;
int amount = goods.getAmount();
int oldAmount = container.getOldGoodsCount(type);
if (amount < low && oldAmount >= low) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY,
"model.building.warehouseEmpty",
this, type)
.add("%goods%", type.getNameKey())
.addAmount("%level%", low)
.addName("%colony%", getName()));
continue;
}
if (type.limitIgnored()) continue;
String messageId = null;
int waste = 0;
if (amount > limit) {
// limit has been exceeded
waste = amount - limit;
container.removeGoods(type, waste);
messageId = "model.building.warehouseWaste";
} else if (amount == limit && oldAmount < limit) {
// limit has been reached during this turn
messageId = "model.building.warehouseOverfull";
} else if (amount > high && oldAmount <= high) {
// high-water-mark has been reached this turn
messageId = "model.building.warehouseFull";
}
if (messageId != null) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY,
messageId, this, type)
.add("%goods%", type.getNameKey())
.addAmount("%waste%", waste)
.addAmount("%level%", high)
.addName("%colony%", getName()));
}
// No problem this turn, but what about the next?
if (!(exportData.isExported()
&& hasAbility("model.ability.export")
&& owner.canTrade(type, Market.Access.CUSTOM_HOUSE))
&& amount <= limit) {
int loss = amount + netProduction.getCount(type) - limit;
if (loss > 0) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY,
"model.building.warehouseSoonFull",
this, type)
.add("%goods%", goods.getNameKey())
.addName("%colony%", getName())
.addAmount("%amount%", loss));
}
}
}
// Check for free buildings
for (BuildingType buildingType : spec.getBuildingTypeList()) {
if (isAutomaticBuild(buildingType)) {
addBuilding(new ServerBuilding(getGame(), this, buildingType));
}
}
// Update SoL.
updateSoL();
if (sonsOfLiberty / 10 != oldSonsOfLiberty / 10) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY,
(sonsOfLiberty > oldSonsOfLiberty)
? "model.colony.SoLIncrease"
: "model.colony.SoLDecrease",
this, spec.getGoodsType("model.goods.bells"))
.addAmount("%oldSoL%", oldSonsOfLiberty)
.addAmount("%newSoL%", sonsOfLiberty)
.addName("%colony%", getName()));
ModelMessage govMgtMessage = checkForGovMgtChangeMessage();
if (govMgtMessage != null) {
cs.addMessage(See.only(owner), govMgtMessage);
}
}
updateProductionBonus();
// Try to update minimally.
if (tileDirty) {
cs.add(See.perhaps(), getTile());
} else {
cs.add(See.only(owner), this);
}
}
private boolean buildUnit(BuildQueue buildQueue, ChangeSet cs, Random random) {
Unit unit = new ServerUnit(getGame(), getTile(), owner,
(UnitType) buildQueue.getCurrentlyBuilding(),
UnitState.ACTIVE);
if (unit.hasAbility("model.ability.bornInColony")) {
cs.addMessage(See.only((ServerPlayer) owner),
new ModelMessage(ModelMessage.MessageType.UNIT_ADDED,
"model.colony.newColonist",
this, unit)
.addName("%colony%", getName()));
if (buildQueue.size() > 1) {
Collections.shuffle(buildQueue.getValues(), random);
}
} else {
cs.addMessage(See.only((ServerPlayer) owner),
new ModelMessage(ModelMessage.MessageType.UNIT_ADDED,
"model.colony.unitReady",
this, unit)
.addName("%colony%", getName())
.addStringTemplate("%unit%", unit.getLabel()));
// Remove the unit-to-build unless it is the last entry.
if (buildQueue.size() > 1) buildQueue.remove(0);
}
logger.info("New unit created in " + getName() + ": " + unit.toString());
return true;
}
private boolean buildBuilding(BuildQueue buildQueue, ChangeSet cs, List<FreeColGameObject> updates) {
BuildingType type = (BuildingType) buildQueue.getCurrentlyBuilding();
BuildingType from = type.getUpgradesFrom();
boolean success;
boolean colonyDirty = false;
if (from == null) {
addBuilding(new ServerBuilding(getGame(), this, type));
colonyDirty = true;
success = true;
} else {
Building building = getBuilding(from);
if (building.upgrade()) {
updates.add(building);
success = true;
} else {
cs.addMessage(See.only((ServerPlayer) owner),
new ModelMessage(ModelMessage.MessageType.BUILDING_COMPLETED,
"colonyPanel.unbuildable",
this)
.addName("%colony%", getName())
.add("%object%", type.getNameKey()));
success = false;
}
}
if (success) {
tile.updatePlayerExploredTiles(); // See stockade changes
cs.addMessage(See.only((ServerPlayer) owner),
new ModelMessage(ModelMessage.MessageType.BUILDING_COMPLETED,
"model.colony.buildingReady",
this)
.addName("%colony%", getName())
.add("%building%", type.getNameKey()));
if (buildQueue.size() == 1) {
cs.addMessage(See.only((ServerPlayer) owner),
new ModelMessage(ModelMessage.MessageType.BUILDING_COMPLETED,
"model.colony.notBuildingAnything",
this)
.addName("%colony%", getName())
.add("%building%", type.getNameKey()));
}
}
buildQueue.remove(0);
return colonyDirty;
}
/**
* Gets what this colony really is building, removing anything that
* is currently impossible.
*
* @param cs A <code>ChangeSet</code> to update.
* @return A buildable that can be built, or null if nothing.
*/
private BuildableType csGetBuildable(ChangeSet cs) {
ServerPlayer owner = (ServerPlayer) getOwner();
Specification spec = getSpecification();
while (!buildQueue.isEmpty()) {
BuildableType buildable = buildQueue.getCurrentlyBuilding();
switch (getNoBuildReason(buildable)) {
case NONE:
return buildable;
case NOT_BUILDING:
for (GoodsType goodsType : spec.getGoodsTypeList()) {
if (goodsType.isBuildingMaterial()
&& !goodsType.isStorable()
&& getProductionOf(goodsType) > 0) {
// Production is idle
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WARNING,
"model.colony.cannotBuild",
this)
.addName("%colony%", getName()));
}
}
return null;
case POPULATION_TOO_SMALL:
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WARNING,
"model.colony.buildNeedPop",
this)
.addName("%colony%", getName())
.add("%building%", buildable.getNameKey()));
break;
default: // Are there other warnings to send?
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WARNING,
"colonyPanel.unbuildable",
this, buildable)
.addName("%colony%", getName())
.add("%object%", buildable.getNameKey()));
break;
}
buildQueue.remove(0);
}
return null;
}
/**
* Are all the requirements to complete a buildable satisfied?
*
* @param buildable The <code>Buildable</code> to check.
* @param cs A <code>ChangeSet</code> to update.
*/
private boolean csHasAllRequirements(BuildableType buildable,
ChangeSet cs) {
ServerPlayer owner = (ServerPlayer) getOwner();
GoodsContainer container = getGoodsContainer();
// Check availability of goods required for construction
ArrayList<ModelMessage> messages = new ArrayList<ModelMessage>();
for (AbstractGoods required : buildable.getGoodsRequired()) {
GoodsType type = required.getType();
int available = container.getGoodsCount(type);
if (available < required.getAmount()) {
if (type.isStorable()) {
int need = required.getAmount() - available;
messages.add(new ModelMessage(ModelMessage.MessageType.MISSING_GOODS,
"model.colony.buildableNeedsGoods",
this, type)
.addName("%colony%", getName())
.add("%buildable%", buildable.getNameKey())
.addName("%amount%", String.valueOf(need))
.add("%goodsType%", type.getNameKey()));
} else {
// Not complete due to missing unstorable goods
// (probably hammers) so there is no point griping.
return false;
}
}
}
if (!messages.isEmpty()) {
// Not complete due to missing storable goods.
// Gripe away.
for (ModelMessage message : messages) {
cs.addMessage(See.only(owner), message);
}
return false;
}
return true;
}
/**
* Returns the tag name of the root element representing this object.
*
* @return "serverColony"
*/
public String getServerXMLElementTagName() {
return "serverColony";
}
}
| true | true | public void csNewTurn(Random random, ChangeSet cs) {
logger.finest("ServerColony.csNewTurn, for " + toString());
ServerPlayer owner = (ServerPlayer) getOwner();
Specification spec = getSpecification();
boolean tileDirty = false;
boolean colonyDirty = false;
List<FreeColGameObject> updates = new ArrayList<FreeColGameObject>();
GoodsContainer container = getGoodsContainer();
container.saveState();
java.util.Map<Object, ProductionInfo> info = getProductionAndConsumption();
TypeCountMap<GoodsType> netProduction = new TypeCountMap<GoodsType>();
for (Entry<Object, ProductionInfo> entry : info.entrySet()) {
ProductionInfo productionInfo = entry.getValue();
if (entry.getKey() instanceof WorkLocation) {
WorkLocation workLocation = (WorkLocation) entry.getKey();
((ServerModelObject) workLocation).csNewTurn(random, cs);
if (workLocation.getUnitCount() > 0) {
for (AbstractGoods goods : productionInfo.getProduction()) {
int experience = goods.getAmount() / workLocation.getUnitCount();
for (Unit unit : workLocation.getUnitList()) {
unit.setExperience(unit.getExperience() + experience);
cs.addPartial(See.only(owner), unit, "experience");
}
}
}
} else if (entry.getKey() instanceof BuildQueue
&& !productionInfo.getConsumption().isEmpty()) {
// this means we are actually building something
BuildQueue queue = (BuildQueue) entry.getKey();
BuildableType buildable = queue.getCurrentlyBuilding();
if (buildable instanceof UnitType) {
tileDirty = buildUnit(queue, cs, random);
} else if (buildable instanceof BuildingType) {
colonyDirty = buildBuilding(queue, cs, updates);
} else {
throw new IllegalStateException("Bogus buildable: " + buildable);
}
// Having removed something from the build queue, nudge it again
// to see if there is a problem with the next item if any.
buildable = csGetBuildable(cs);
}
for (AbstractGoods goods : productionInfo.getProduction()) {
netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount());
}
for (AbstractGoods goods : productionInfo.getStorage()) {
netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount());
}
for (AbstractGoods goods : productionInfo.getConsumption()) {
netProduction.incrementCount(goods.getType().getStoredAs(), -goods.getAmount());
}
}
// Apply the changes accumulated in the netProduction map
for (Entry<GoodsType, Integer> entry
: netProduction.getValues().entrySet()) {
GoodsType goodsType = entry.getKey();
int net = entry.getValue();
int stored = getGoodsCount(goodsType);
if (net + stored < 0) {
removeGoods(goodsType, stored);
} else {
addGoods(goodsType, net);
}
}
// Now check the food situation
int storedFood = getGoodsCount(spec.getPrimaryFoodType());
if (storedFood <= 0) {
if (getUnitCount() > 1) {
Unit victim = Utils.getRandomMember(logger, "Choose starver",
getUnitList(), random);
updates.add((FreeColGameObject) victim.getLocation());
cs.addDispose(owner, this, victim);
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.UNIT_LOST,
"model.colony.colonistStarved",
this)
.addName("%colony%", getName()));
} else { // Its dead, Jim.
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.UNIT_LOST,
"model.colony.colonyStarved",
this)
.addName("%colony%", getName()));
cs.addDispose(owner, getTile(), this);
return;
}
} else {
int netFood = netProduction.getCount(spec.getPrimaryFoodType());
int turns = Math.abs(storedFood / netFood);
if (netFood < 0 && turns <= 3) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WARNING,
"model.colony.famineFeared",
this)
.addName("%colony%", getName())
.addName("%number%", String.valueOf(turns)));
logger.finest("Famine feared in " + getName()
+ " food=" + storedFood
+ " production=" + netFood
+ " turns=" + turns);
}
}
/** TODO: do we want this?
if (goodsInput == 0 && !canAutoProduce()
&& getMaximumGoodsInput() > 0) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.MISSING_GOODS,
"model.building.notEnoughInput",
colony, goodsInputType)
.add("%inputGoods%", goodsInputType.getNameKey())
.add("%building%", getNameKey())
.addName("%colony%", colony.getName()));
}
*/
// Export goods if custom house is built.
// Do not flush price changes yet, as any price change may change
// yet again in csYearlyGoodsRemoval.
if (hasAbility("model.ability.export")) {
boolean gold = false;
for (Goods goods : container.getCompactGoods()) {
GoodsType type = goods.getType();
ExportData data = getExportData(type);
if (data.isExported()
&& (owner.canTrade(goods, Market.Access.CUSTOM_HOUSE))) {
int amount = goods.getAmount() - data.getExportLevel();
if (amount > 0) {
owner.sell(container, type, amount, random);
gold = true;
}
}
}
if (gold) {
cs.addPartial(See.only(owner), owner, "gold");
}
}
// Throw away goods there is no room for, and warn about
// levels that will be exceeded next turn
int limit = getWarehouseCapacity();
int adjustment = limit / GoodsContainer.CARGO_SIZE;
for (Goods goods : container.getCompactGoods()) {
GoodsType type = goods.getType();
if (!type.isStorable()) continue;
ExportData exportData = getExportData(type);
int low = exportData.getLowLevel() * adjustment;
int high = exportData.getHighLevel() * adjustment;
int amount = goods.getAmount();
int oldAmount = container.getOldGoodsCount(type);
if (amount < low && oldAmount >= low) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY,
"model.building.warehouseEmpty",
this, type)
.add("%goods%", type.getNameKey())
.addAmount("%level%", low)
.addName("%colony%", getName()));
continue;
}
if (type.limitIgnored()) continue;
String messageId = null;
int waste = 0;
if (amount > limit) {
// limit has been exceeded
waste = amount - limit;
container.removeGoods(type, waste);
messageId = "model.building.warehouseWaste";
} else if (amount == limit && oldAmount < limit) {
// limit has been reached during this turn
messageId = "model.building.warehouseOverfull";
} else if (amount > high && oldAmount <= high) {
// high-water-mark has been reached this turn
messageId = "model.building.warehouseFull";
}
if (messageId != null) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY,
messageId, this, type)
.add("%goods%", type.getNameKey())
.addAmount("%waste%", waste)
.addAmount("%level%", high)
.addName("%colony%", getName()));
}
// No problem this turn, but what about the next?
if (!(exportData.isExported()
&& hasAbility("model.ability.export")
&& owner.canTrade(type, Market.Access.CUSTOM_HOUSE))
&& amount <= limit) {
int loss = amount + netProduction.getCount(type) - limit;
if (loss > 0) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY,
"model.building.warehouseSoonFull",
this, type)
.add("%goods%", goods.getNameKey())
.addName("%colony%", getName())
.addAmount("%amount%", loss));
}
}
}
// Check for free buildings
for (BuildingType buildingType : spec.getBuildingTypeList()) {
if (isAutomaticBuild(buildingType)) {
addBuilding(new ServerBuilding(getGame(), this, buildingType));
}
}
// Update SoL.
updateSoL();
if (sonsOfLiberty / 10 != oldSonsOfLiberty / 10) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY,
(sonsOfLiberty > oldSonsOfLiberty)
? "model.colony.SoLIncrease"
: "model.colony.SoLDecrease",
this, spec.getGoodsType("model.goods.bells"))
.addAmount("%oldSoL%", oldSonsOfLiberty)
.addAmount("%newSoL%", sonsOfLiberty)
.addName("%colony%", getName()));
ModelMessage govMgtMessage = checkForGovMgtChangeMessage();
if (govMgtMessage != null) {
cs.addMessage(See.only(owner), govMgtMessage);
}
}
updateProductionBonus();
// Try to update minimally.
if (tileDirty) {
cs.add(See.perhaps(), getTile());
} else {
cs.add(See.only(owner), this);
}
}
| public void csNewTurn(Random random, ChangeSet cs) {
logger.finest("ServerColony.csNewTurn, for " + toString());
ServerPlayer owner = (ServerPlayer) getOwner();
Specification spec = getSpecification();
boolean tileDirty = false;
boolean colonyDirty = false;
List<FreeColGameObject> updates = new ArrayList<FreeColGameObject>();
GoodsContainer container = getGoodsContainer();
container.saveState();
java.util.Map<Object, ProductionInfo> info = getProductionAndConsumption();
TypeCountMap<GoodsType> netProduction = new TypeCountMap<GoodsType>();
for (Entry<Object, ProductionInfo> entry : info.entrySet()) {
ProductionInfo productionInfo = entry.getValue();
if (entry.getKey() instanceof WorkLocation) {
WorkLocation workLocation = (WorkLocation) entry.getKey();
((ServerModelObject) workLocation).csNewTurn(random, cs);
if (workLocation.getUnitCount() > 0) {
for (AbstractGoods goods : productionInfo.getProduction()) {
int experience = goods.getAmount() / workLocation.getUnitCount();
for (Unit unit : workLocation.getUnitList()) {
unit.setExperience(unit.getExperience() + experience);
cs.addPartial(See.only(owner), unit, "experience");
}
}
}
} else if (entry.getKey() instanceof BuildQueue
&& !productionInfo.getConsumption().isEmpty()) {
// this means we are actually building something
BuildQueue queue = (BuildQueue) entry.getKey();
BuildableType buildable = queue.getCurrentlyBuilding();
if (buildable instanceof UnitType) {
tileDirty = buildUnit(queue, cs, random);
} else if (buildable instanceof BuildingType) {
colonyDirty = buildBuilding(queue, cs, updates);
} else {
throw new IllegalStateException("Bogus buildable: " + buildable);
}
// Having removed something from the build queue, nudge it again
// to see if there is a problem with the next item if any.
buildable = csGetBuildable(cs);
}
for (AbstractGoods goods : productionInfo.getProduction()) {
netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount());
}
for (AbstractGoods goods : productionInfo.getStorage()) {
netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount());
}
for (AbstractGoods goods : productionInfo.getConsumption()) {
netProduction.incrementCount(goods.getType().getStoredAs(), -goods.getAmount());
}
}
// Apply the changes accumulated in the netProduction map
for (Entry<GoodsType, Integer> entry
: netProduction.getValues().entrySet()) {
GoodsType goodsType = entry.getKey();
int net = entry.getValue();
int stored = getGoodsCount(goodsType);
if (net + stored < 0) {
removeGoods(goodsType, stored);
} else {
addGoods(goodsType, net);
}
}
// Now check the food situation
int storedFood = getGoodsCount(spec.getPrimaryFoodType());
if (storedFood <= 0) {
if (getUnitCount() > 1) {
Unit victim = Utils.getRandomMember(logger, "Choose starver",
getUnitList(), random);
updates.add((FreeColGameObject) victim.getLocation());
cs.addDispose(owner, this, victim);
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.UNIT_LOST,
"model.colony.colonistStarved",
this)
.addName("%colony%", getName()));
} else { // Its dead, Jim.
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.UNIT_LOST,
"model.colony.colonyStarved",
this)
.addName("%colony%", getName()));
cs.addDispose(owner, getTile(), this);
return;
}
} else {
int netFood = netProduction.getCount(spec.getPrimaryFoodType());
int turns;
if (netFood < 0 && (turns = storedFood / -netFood) <= 3) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WARNING,
"model.colony.famineFeared",
this)
.addName("%colony%", getName())
.addName("%number%", String.valueOf(turns)));
logger.finest("Famine feared in " + getName()
+ " food=" + storedFood
+ " production=" + netFood
+ " turns=" + turns);
}
}
/** TODO: do we want this?
if (goodsInput == 0 && !canAutoProduce()
&& getMaximumGoodsInput() > 0) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.MISSING_GOODS,
"model.building.notEnoughInput",
colony, goodsInputType)
.add("%inputGoods%", goodsInputType.getNameKey())
.add("%building%", getNameKey())
.addName("%colony%", colony.getName()));
}
*/
// Export goods if custom house is built.
// Do not flush price changes yet, as any price change may change
// yet again in csYearlyGoodsRemoval.
if (hasAbility("model.ability.export")) {
boolean gold = false;
for (Goods goods : container.getCompactGoods()) {
GoodsType type = goods.getType();
ExportData data = getExportData(type);
if (data.isExported()
&& (owner.canTrade(goods, Market.Access.CUSTOM_HOUSE))) {
int amount = goods.getAmount() - data.getExportLevel();
if (amount > 0) {
owner.sell(container, type, amount, random);
gold = true;
}
}
}
if (gold) {
cs.addPartial(See.only(owner), owner, "gold");
}
}
// Throw away goods there is no room for, and warn about
// levels that will be exceeded next turn
int limit = getWarehouseCapacity();
int adjustment = limit / GoodsContainer.CARGO_SIZE;
for (Goods goods : container.getCompactGoods()) {
GoodsType type = goods.getType();
if (!type.isStorable()) continue;
ExportData exportData = getExportData(type);
int low = exportData.getLowLevel() * adjustment;
int high = exportData.getHighLevel() * adjustment;
int amount = goods.getAmount();
int oldAmount = container.getOldGoodsCount(type);
if (amount < low && oldAmount >= low) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY,
"model.building.warehouseEmpty",
this, type)
.add("%goods%", type.getNameKey())
.addAmount("%level%", low)
.addName("%colony%", getName()));
continue;
}
if (type.limitIgnored()) continue;
String messageId = null;
int waste = 0;
if (amount > limit) {
// limit has been exceeded
waste = amount - limit;
container.removeGoods(type, waste);
messageId = "model.building.warehouseWaste";
} else if (amount == limit && oldAmount < limit) {
// limit has been reached during this turn
messageId = "model.building.warehouseOverfull";
} else if (amount > high && oldAmount <= high) {
// high-water-mark has been reached this turn
messageId = "model.building.warehouseFull";
}
if (messageId != null) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY,
messageId, this, type)
.add("%goods%", type.getNameKey())
.addAmount("%waste%", waste)
.addAmount("%level%", high)
.addName("%colony%", getName()));
}
// No problem this turn, but what about the next?
if (!(exportData.isExported()
&& hasAbility("model.ability.export")
&& owner.canTrade(type, Market.Access.CUSTOM_HOUSE))
&& amount <= limit) {
int loss = amount + netProduction.getCount(type) - limit;
if (loss > 0) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY,
"model.building.warehouseSoonFull",
this, type)
.add("%goods%", goods.getNameKey())
.addName("%colony%", getName())
.addAmount("%amount%", loss));
}
}
}
// Check for free buildings
for (BuildingType buildingType : spec.getBuildingTypeList()) {
if (isAutomaticBuild(buildingType)) {
addBuilding(new ServerBuilding(getGame(), this, buildingType));
}
}
// Update SoL.
updateSoL();
if (sonsOfLiberty / 10 != oldSonsOfLiberty / 10) {
cs.addMessage(See.only(owner),
new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY,
(sonsOfLiberty > oldSonsOfLiberty)
? "model.colony.SoLIncrease"
: "model.colony.SoLDecrease",
this, spec.getGoodsType("model.goods.bells"))
.addAmount("%oldSoL%", oldSonsOfLiberty)
.addAmount("%newSoL%", sonsOfLiberty)
.addName("%colony%", getName()));
ModelMessage govMgtMessage = checkForGovMgtChangeMessage();
if (govMgtMessage != null) {
cs.addMessage(See.only(owner), govMgtMessage);
}
}
updateProductionBonus();
// Try to update minimally.
if (tileDirty) {
cs.add(See.perhaps(), getTile());
} else {
cs.add(See.only(owner), this);
}
}
|
diff --git a/src/ui/shared/java/com/flexive/war/servlet/ExportServlet.java b/src/ui/shared/java/com/flexive/war/servlet/ExportServlet.java
index e9fb24a5..1bf0f7df 100644
--- a/src/ui/shared/java/com/flexive/war/servlet/ExportServlet.java
+++ b/src/ui/shared/java/com/flexive/war/servlet/ExportServlet.java
@@ -1,142 +1,142 @@
/***************************************************************
* This file is part of the [fleXive](R) project.
*
* Copyright (c) 1999-2008
* UCS - unique computing solutions gmbh (http://www.ucs.at)
* All rights reserved
*
* The [fleXive](R) project is free software; you can redistribute
* it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation;
* either version 2 of the License, or (at your option) any
* later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
* A copy is found in the textfile GPL.txt and important notices to the
* license from the author are found in LICENSE.txt distributed with
* these libraries.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* For further information about UCS - unique computing solutions gmbh,
* please see the company website: http://www.ucs.at
*
* For further information about [fleXive](R), please see the
* project website: http://www.flexive.org
*
*
* This copyright notice MUST APPEAR in all copies of the file!
***************************************************************/
package com.flexive.war.servlet;
import com.flexive.shared.CacheAdmin;
import com.flexive.shared.EJBLookup;
import com.flexive.shared.FxContext;
import com.flexive.shared.exceptions.FxApplicationException;
import com.flexive.shared.security.Role;
import com.flexive.shared.security.UserTicket;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
/**
* XML Export servlet
* <p/>
* Format:
* <p/>
* /export/type/name
* <p/>
* TODO:
* /export/content/pk
* /export/tree/startnode
*
* @author Markus Plesser ([email protected]), UCS - unique computing solutions gmbh (http://www.ucs.at)
* @version $Rev
*/
public class ExportServlet implements Servlet {
private static transient Log LOG = LogFactory.getLog(ExportServlet.class);
private final static String BASEURL = "/export/";
private ServletConfig servletConfig;
/**
* {@inheritDoc}
*/
public void init(ServletConfig servletConfig) throws ServletException {
this.servletConfig = servletConfig;
}
/**
* {@inheritDoc}
*/
public ServletConfig getServletConfig() {
return servletConfig;
}
/**
* {@inheritDoc}
*/
public String getServletInfo() {
return "ExportServlet";
}
/**
* {@inheritDoc}
*/
public void destroy() {
}
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String[] params = URLDecoder.decode(request.getRequestURI().substring(request.getContextPath().length() + BASEURL.length()), "UTF-8").split("/");
if (params.length == 2 && "type".equals(params[0])) {
exportType(request, response, params[1]);
return;
}
response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
}
/**
* Export a type
*
* @param request request
* @param response reponse
* @param type type name
* @throws IOException on errors
*/
private void exportType(HttpServletRequest request, HttpServletResponse response, String type) throws IOException {
final UserTicket ticket = FxContext.get().getTicket();
if (!ticket.isInRole(Role.StructureManagement)) {
LOG.warn("Tried to export type [" + type + "] without being in role StructureManagment!");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String xml;
try {
xml = EJBLookup.getTypeEngine().export(CacheAdmin.getEnvironment().getType(type).getId());
} catch (FxApplicationException e) {
LOG.error(e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
return;
}
response.setContentType("text/xml");
- response.setContentLength(xml.length());
+ response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + type + ".xml\";");
try {
- response.getOutputStream().print(xml);
+ response.getOutputStream().write(xml.getBytes("UTF-8"));
} finally {
response.getOutputStream().close();
}
}
}
| false | true | private void exportType(HttpServletRequest request, HttpServletResponse response, String type) throws IOException {
final UserTicket ticket = FxContext.get().getTicket();
if (!ticket.isInRole(Role.StructureManagement)) {
LOG.warn("Tried to export type [" + type + "] without being in role StructureManagment!");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String xml;
try {
xml = EJBLookup.getTypeEngine().export(CacheAdmin.getEnvironment().getType(type).getId());
} catch (FxApplicationException e) {
LOG.error(e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
return;
}
response.setContentType("text/xml");
response.setContentLength(xml.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + type + ".xml\";");
try {
response.getOutputStream().print(xml);
} finally {
response.getOutputStream().close();
}
}
| private void exportType(HttpServletRequest request, HttpServletResponse response, String type) throws IOException {
final UserTicket ticket = FxContext.get().getTicket();
if (!ticket.isInRole(Role.StructureManagement)) {
LOG.warn("Tried to export type [" + type + "] without being in role StructureManagment!");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String xml;
try {
xml = EJBLookup.getTypeEngine().export(CacheAdmin.getEnvironment().getType(type).getId());
} catch (FxApplicationException e) {
LOG.error(e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
return;
}
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + type + ".xml\";");
try {
response.getOutputStream().write(xml.getBytes("UTF-8"));
} finally {
response.getOutputStream().close();
}
}
|
diff --git a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
index 56c6d6585..4582e98d9 100644
--- a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
+++ b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
@@ -1,469 +1,470 @@
/**
* 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.solr.servlet;
import java.io.IOException;
import java.io.Writer;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.OutputStreamWriter;
import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.WeakHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.common.cloud.CloudState;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.util.FastWriter;
import org.apache.solr.common.util.ContentStreamBase;
import org.apache.solr.core.*;
import org.apache.solr.request.*;
import org.apache.solr.response.BinaryQueryResponseWriter;
import org.apache.solr.response.QueryResponseWriter;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.servlet.cache.HttpCacheHeaderUtil;
import org.apache.solr.servlet.cache.Method;
/**
* This filter looks at the incoming URL maps them to handlers defined in solrconfig.xml
*
* @since solr 1.2
*/
public class SolrDispatchFilter implements Filter
{
final Logger log = LoggerFactory.getLogger(SolrDispatchFilter.class);
protected volatile CoreContainer cores;
protected String pathPrefix = null; // strip this from the beginning of a path
protected String abortErrorMessage = null;
protected final Map<SolrConfig, SolrRequestParsers> parsers = new WeakHashMap<SolrConfig, SolrRequestParsers>();
protected final SolrRequestParsers adminRequestParser;
private static final Charset UTF8 = Charset.forName("UTF-8");
public SolrDispatchFilter() {
try {
adminRequestParser = new SolrRequestParsers(new Config(null,"solr",new InputSource(new ByteArrayInputStream("<root/>".getBytes("UTF-8"))),"") );
} catch (Exception e) {
//unlikely
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,e);
}
}
public void init(FilterConfig config) throws ServletException
{
log.info("SolrDispatchFilter.init()");
CoreContainer.Initializer init = createInitializer();
try {
// web.xml configuration
this.pathPrefix = config.getInitParameter( "path-prefix" );
this.cores = init.initialize();
log.info("user.dir=" + System.getProperty("user.dir"));
}
catch( Throwable t ) {
// catch this so our filter still works
log.error( "Could not start Solr. Check solr/home property and the logs");
SolrCore.log( t );
}
log.info("SolrDispatchFilter.init() done");
}
public CoreContainer getCores() {
return cores;
}
/** Method to override to change how CoreContainer initialization is performed. */
protected CoreContainer.Initializer createInitializer() {
return new CoreContainer.Initializer();
}
public void destroy() {
if (cores != null) {
cores.shutdown();
cores = null;
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if( abortErrorMessage != null ) {
((HttpServletResponse)response).sendError( 500, abortErrorMessage );
return;
}
if (this.cores == null) {
((HttpServletResponse)response).sendError( 403, "Server is shutting down" );
return;
}
CoreContainer cores = this.cores;
if( request instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
SolrRequestHandler handler = null;
SolrQueryRequest solrReq = null;
SolrCore core = null;
String corename = "";
try {
// put the core container in request attribute
req.setAttribute("org.apache.solr.CoreContainer", cores);
String path = req.getServletPath();
if( req.getPathInfo() != null ) {
// this lets you handle /update/commit when /update is a servlet
path += req.getPathInfo();
}
if( pathPrefix != null && path.startsWith( pathPrefix ) ) {
path = path.substring( pathPrefix.length() );
}
// check for management path
String alternate = cores.getManagementPath();
if (alternate != null && path.startsWith(alternate)) {
path = path.substring(0, alternate.length());
}
// unused feature ?
int idx = path.indexOf( ':' );
if( idx > 0 ) {
// save the portion after the ':' for a 'handler' path parameter
path = path.substring( 0, idx );
}
// Check for the core admin page
if( path.equals( cores.getAdminPath() ) ) {
handler = cores.getMultiCoreHandler();
solrReq = adminRequestParser.parse(null,path, req);
handleAdminRequest(req, response, handler, solrReq);
return;
}
else {
//otherwise, we should find a core from the path
idx = path.indexOf( "/", 1 );
if( idx > 1 ) {
// try to get the corename as a request parameter first
corename = path.substring( 1, idx );
core = cores.getCore(corename);
if (core != null) {
path = path.substring( idx );
}
}
if (core == null) {
- if (cores.isZooKeeperAware() && corename.length() == 0) {
- core = cores.getCore("");
- } else if (!cores.isZooKeeperAware()) {
+ if (!cores.isZooKeeperAware() ) {
core = cores.getCore("");
}
}
}
if (core == null && cores.isZooKeeperAware()) {
// we couldn't find the core - lets make sure a collection was not specified instead
core = getCoreByCollection(cores, core, corename, path);
if (core != null) {
// we found a core, update the path
path = path.substring( idx );
+ } else {
+ // try the default core
+ core = cores.getCore("");
}
// TODO: if we couldn't find it locally, look on other nodes
}
// With a valid core...
if( core != null ) {
final SolrConfig config = core.getSolrConfig();
// get or create/cache the parser for the core
SolrRequestParsers parser = null;
parser = parsers.get(config);
if( parser == null ) {
parser = new SolrRequestParsers(config);
parsers.put(config, parser );
}
// Determine the handler from the url path if not set
// (we might already have selected the cores handler)
if( handler == null && path.length() > 1 ) { // don't match "" or "/" as valid path
handler = core.getRequestHandler( path );
// no handler yet but allowed to handle select; let's check
if( handler == null && parser.isHandleSelect() ) {
if( "/select".equals( path ) || "/select/".equals( path ) ) {
solrReq = parser.parse( core, path, req );
String qt = solrReq.getParams().get( CommonParams.QT );
handler = core.getRequestHandler( qt );
if( handler == null ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "unknown handler: "+qt);
}
}
}
}
// With a valid handler and a valid core...
if( handler != null ) {
// if not a /select, create the request
if( solrReq == null ) {
solrReq = parser.parse( core, path, req );
}
final Method reqMethod = Method.getMethod(req.getMethod());
HttpCacheHeaderUtil.setCacheControlHeader(config, resp, reqMethod);
// unless we have been explicitly told not to, do cache validation
// if we fail cache validation, execute the query
if (config.getHttpCachingConfig().isNever304() ||
!HttpCacheHeaderUtil.doCacheHeaderValidation(solrReq, req, reqMethod, resp)) {
SolrQueryResponse solrRsp = new SolrQueryResponse();
/* even for HEAD requests, we need to execute the handler to
* ensure we don't get an error (and to make sure the correct
* QueryResponseWriter is selected and we get the correct
* Content-Type)
*/
SolrRequestInfo.setRequestInfo(new SolrRequestInfo(solrReq, solrRsp));
this.execute( req, handler, solrReq, solrRsp );
HttpCacheHeaderUtil.checkHttpCachingVeto(solrRsp, resp, reqMethod);
// add info to http headers
//TODO: See SOLR-232 and SOLR-267.
/*try {
NamedList solrRspHeader = solrRsp.getResponseHeader();
for (int i=0; i<solrRspHeader.size(); i++) {
((javax.servlet.http.HttpServletResponse) response).addHeader(("Solr-" + solrRspHeader.getName(i)), String.valueOf(solrRspHeader.getVal(i)));
}
} catch (ClassCastException cce) {
log.log(Level.WARNING, "exception adding response header log information", cce);
}*/
QueryResponseWriter responseWriter = core.getQueryResponseWriter(solrReq);
writeResponse(solrRsp, response, responseWriter, solrReq, reqMethod);
}
return; // we are done with a valid handler
}
// otherwise (we have a core), let's ensure the core is in the SolrCore request attribute so
// a servlet/jsp can retrieve it
else {
req.setAttribute("org.apache.solr.SolrCore", core);
// Modify the request so each core gets its own /admin
if( path.startsWith( "/admin" ) ) {
req.getRequestDispatcher( pathPrefix == null ? path : pathPrefix + path ).forward( request, response );
return;
}
}
}
log.debug("no handler or core retrieved for " + path + ", follow through...");
}
catch (Throwable ex) {
sendError( (HttpServletResponse)response, ex );
return;
}
finally {
if( solrReq != null ) {
solrReq.close();
}
if (core != null) {
core.close();
}
SolrRequestInfo.clearRequestInfo();
}
}
// Otherwise let the webapp handle the request
chain.doFilter(request, response);
}
private SolrCore getCoreByCollection(CoreContainer cores, SolrCore core,
String corename, String path) {
String collection = corename;
ZkStateReader zkStateReader = cores.getZkController().getZkStateReader();
CloudState cloudState = zkStateReader.getCloudState();
Map<String,Slice> slices = cloudState.getSlices(collection);
if (slices == null) {
return null;
}
// look for a core on this node
Set<Entry<String,Slice>> entries = slices.entrySet();
done:
for (Entry<String,Slice> entry : entries) {
// first see if we have the leader
ZkNodeProps leaderProps = cloudState.getLeader(collection, entry.getKey());
core = checkProps(cores, core, path, leaderProps);
if (core != null) {
break done;
}
// check everyone then
Map<String,ZkNodeProps> shards = entry.getValue().getShards();
Set<Entry<String,ZkNodeProps>> shardEntries = shards.entrySet();
for (Entry<String,ZkNodeProps> shardEntry : shardEntries) {
ZkNodeProps zkProps = shardEntry.getValue();
core = checkProps(cores, core, path, zkProps);
if (core != null) {
break done;
}
}
}
return core;
}
private SolrCore checkProps(CoreContainer cores, SolrCore core, String path,
ZkNodeProps zkProps) {
String corename;
if (cores.getZkController().getNodeName().equals(zkProps.get(ZkStateReader.NODE_NAME_PROP))) {
corename = zkProps.get(ZkStateReader.CORE_NAME_PROP);
core = cores.getCore(corename);
}
return core;
}
private void handleAdminRequest(HttpServletRequest req, ServletResponse response, SolrRequestHandler handler,
SolrQueryRequest solrReq) throws IOException {
SolrQueryResponse solrResp = new SolrQueryResponse();
final NamedList<Object> responseHeader = new SimpleOrderedMap<Object>();
solrResp.add("responseHeader", responseHeader);
NamedList toLog = solrResp.getToLog();
toLog.add("webapp", req.getContextPath());
toLog.add("path", solrReq.getContext().get("path"));
toLog.add("params", "{" + solrReq.getParamString() + "}");
handler.handleRequest(solrReq, solrResp);
SolrCore.setResponseHeaderValues(handler, solrReq, solrResp);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < toLog.size(); i++) {
String name = toLog.getName(i);
Object val = toLog.getVal(i);
sb.append(name).append("=").append(val).append(" ");
}
QueryResponseWriter respWriter = SolrCore.DEFAULT_RESPONSE_WRITERS.get(solrReq.getParams().get(CommonParams.WT));
if (respWriter == null) respWriter = SolrCore.DEFAULT_RESPONSE_WRITERS.get("standard");
writeResponse(solrResp, response, respWriter, solrReq, Method.getMethod(req.getMethod()));
}
private void writeResponse(SolrQueryResponse solrRsp, ServletResponse response,
QueryResponseWriter responseWriter, SolrQueryRequest solrReq, Method reqMethod)
throws IOException {
if (solrRsp.getException() != null) {
sendError((HttpServletResponse) response, solrRsp.getException());
} else {
// Now write it out
final String ct = responseWriter.getContentType(solrReq, solrRsp);
// don't call setContentType on null
if (null != ct) response.setContentType(ct);
if (Method.HEAD != reqMethod) {
if (responseWriter instanceof BinaryQueryResponseWriter) {
BinaryQueryResponseWriter binWriter = (BinaryQueryResponseWriter) responseWriter;
binWriter.write(response.getOutputStream(), solrReq, solrRsp);
} else {
String charset = ContentStreamBase.getCharsetFromContentType(ct);
Writer out = (charset == null || charset.equalsIgnoreCase("UTF-8"))
? new OutputStreamWriter(response.getOutputStream(), UTF8)
: new OutputStreamWriter(response.getOutputStream(), charset);
out = new FastWriter(out);
responseWriter.write(out, solrReq, solrRsp);
out.flush();
}
}
//else http HEAD request, nothing to write out, waited this long just to get ContentType
}
}
protected void execute( HttpServletRequest req, SolrRequestHandler handler, SolrQueryRequest sreq, SolrQueryResponse rsp) {
// a custom filter could add more stuff to the request before passing it on.
// for example: sreq.getContext().put( "HttpServletRequest", req );
// used for logging query stats in SolrCore.execute()
sreq.getContext().put( "webapp", req.getContextPath() );
sreq.getCore().execute( handler, sreq, rsp );
}
protected void sendError(HttpServletResponse res, Throwable ex) throws IOException {
int code=500;
String trace = "";
if( ex instanceof SolrException ) {
code = ((SolrException)ex).code();
}
String msg = null;
for (Throwable th = ex; th != null; th = th.getCause()) {
msg = th.getMessage();
if (msg != null) break;
}
// For any regular code, don't include the stack trace
if( code == 500 || code < 100 ) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
trace = "\n\n"+sw.toString();
SolrException.log(log, null, ex);
// non standard codes have undefined results with various servers
if( code < 100 ) {
log.warn( "invalid return code: "+code );
code = 500;
}
}
res.sendError( code, msg + trace );
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
/**
* Set the prefix for all paths. This is useful if you want to apply the
* filter to something other then /*, perhaps because you are merging this
* filter into a larger web application.
*
* For example, if web.xml specifies:
*
* <filter-mapping>
* <filter-name>SolrRequestFilter</filter-name>
* <url-pattern>/xxx/*</url-pattern>
* </filter-mapping>
*
* Make sure to set the PathPrefix to "/xxx" either with this function
* or in web.xml.
*
* <init-param>
* <param-name>path-prefix</param-name>
* <param-value>/xxx</param-value>
* </init-param>
*
*/
public void setPathPrefix(String pathPrefix) {
this.pathPrefix = pathPrefix;
}
public String getPathPrefix() {
return pathPrefix;
}
}
| false | true | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if( abortErrorMessage != null ) {
((HttpServletResponse)response).sendError( 500, abortErrorMessage );
return;
}
if (this.cores == null) {
((HttpServletResponse)response).sendError( 403, "Server is shutting down" );
return;
}
CoreContainer cores = this.cores;
if( request instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
SolrRequestHandler handler = null;
SolrQueryRequest solrReq = null;
SolrCore core = null;
String corename = "";
try {
// put the core container in request attribute
req.setAttribute("org.apache.solr.CoreContainer", cores);
String path = req.getServletPath();
if( req.getPathInfo() != null ) {
// this lets you handle /update/commit when /update is a servlet
path += req.getPathInfo();
}
if( pathPrefix != null && path.startsWith( pathPrefix ) ) {
path = path.substring( pathPrefix.length() );
}
// check for management path
String alternate = cores.getManagementPath();
if (alternate != null && path.startsWith(alternate)) {
path = path.substring(0, alternate.length());
}
// unused feature ?
int idx = path.indexOf( ':' );
if( idx > 0 ) {
// save the portion after the ':' for a 'handler' path parameter
path = path.substring( 0, idx );
}
// Check for the core admin page
if( path.equals( cores.getAdminPath() ) ) {
handler = cores.getMultiCoreHandler();
solrReq = adminRequestParser.parse(null,path, req);
handleAdminRequest(req, response, handler, solrReq);
return;
}
else {
//otherwise, we should find a core from the path
idx = path.indexOf( "/", 1 );
if( idx > 1 ) {
// try to get the corename as a request parameter first
corename = path.substring( 1, idx );
core = cores.getCore(corename);
if (core != null) {
path = path.substring( idx );
}
}
if (core == null) {
if (cores.isZooKeeperAware() && corename.length() == 0) {
core = cores.getCore("");
} else if (!cores.isZooKeeperAware()) {
core = cores.getCore("");
}
}
}
if (core == null && cores.isZooKeeperAware()) {
// we couldn't find the core - lets make sure a collection was not specified instead
core = getCoreByCollection(cores, core, corename, path);
if (core != null) {
// we found a core, update the path
path = path.substring( idx );
}
// TODO: if we couldn't find it locally, look on other nodes
}
// With a valid core...
if( core != null ) {
final SolrConfig config = core.getSolrConfig();
// get or create/cache the parser for the core
SolrRequestParsers parser = null;
parser = parsers.get(config);
if( parser == null ) {
parser = new SolrRequestParsers(config);
parsers.put(config, parser );
}
// Determine the handler from the url path if not set
// (we might already have selected the cores handler)
if( handler == null && path.length() > 1 ) { // don't match "" or "/" as valid path
handler = core.getRequestHandler( path );
// no handler yet but allowed to handle select; let's check
if( handler == null && parser.isHandleSelect() ) {
if( "/select".equals( path ) || "/select/".equals( path ) ) {
solrReq = parser.parse( core, path, req );
String qt = solrReq.getParams().get( CommonParams.QT );
handler = core.getRequestHandler( qt );
if( handler == null ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "unknown handler: "+qt);
}
}
}
}
// With a valid handler and a valid core...
if( handler != null ) {
// if not a /select, create the request
if( solrReq == null ) {
solrReq = parser.parse( core, path, req );
}
final Method reqMethod = Method.getMethod(req.getMethod());
HttpCacheHeaderUtil.setCacheControlHeader(config, resp, reqMethod);
// unless we have been explicitly told not to, do cache validation
// if we fail cache validation, execute the query
if (config.getHttpCachingConfig().isNever304() ||
!HttpCacheHeaderUtil.doCacheHeaderValidation(solrReq, req, reqMethod, resp)) {
SolrQueryResponse solrRsp = new SolrQueryResponse();
/* even for HEAD requests, we need to execute the handler to
* ensure we don't get an error (and to make sure the correct
* QueryResponseWriter is selected and we get the correct
* Content-Type)
*/
SolrRequestInfo.setRequestInfo(new SolrRequestInfo(solrReq, solrRsp));
this.execute( req, handler, solrReq, solrRsp );
HttpCacheHeaderUtil.checkHttpCachingVeto(solrRsp, resp, reqMethod);
// add info to http headers
//TODO: See SOLR-232 and SOLR-267.
/*try {
NamedList solrRspHeader = solrRsp.getResponseHeader();
for (int i=0; i<solrRspHeader.size(); i++) {
((javax.servlet.http.HttpServletResponse) response).addHeader(("Solr-" + solrRspHeader.getName(i)), String.valueOf(solrRspHeader.getVal(i)));
}
} catch (ClassCastException cce) {
log.log(Level.WARNING, "exception adding response header log information", cce);
}*/
QueryResponseWriter responseWriter = core.getQueryResponseWriter(solrReq);
writeResponse(solrRsp, response, responseWriter, solrReq, reqMethod);
}
return; // we are done with a valid handler
}
// otherwise (we have a core), let's ensure the core is in the SolrCore request attribute so
// a servlet/jsp can retrieve it
else {
req.setAttribute("org.apache.solr.SolrCore", core);
// Modify the request so each core gets its own /admin
if( path.startsWith( "/admin" ) ) {
req.getRequestDispatcher( pathPrefix == null ? path : pathPrefix + path ).forward( request, response );
return;
}
}
}
log.debug("no handler or core retrieved for " + path + ", follow through...");
}
catch (Throwable ex) {
sendError( (HttpServletResponse)response, ex );
return;
}
finally {
if( solrReq != null ) {
solrReq.close();
}
if (core != null) {
core.close();
}
SolrRequestInfo.clearRequestInfo();
}
}
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if( abortErrorMessage != null ) {
((HttpServletResponse)response).sendError( 500, abortErrorMessage );
return;
}
if (this.cores == null) {
((HttpServletResponse)response).sendError( 403, "Server is shutting down" );
return;
}
CoreContainer cores = this.cores;
if( request instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
SolrRequestHandler handler = null;
SolrQueryRequest solrReq = null;
SolrCore core = null;
String corename = "";
try {
// put the core container in request attribute
req.setAttribute("org.apache.solr.CoreContainer", cores);
String path = req.getServletPath();
if( req.getPathInfo() != null ) {
// this lets you handle /update/commit when /update is a servlet
path += req.getPathInfo();
}
if( pathPrefix != null && path.startsWith( pathPrefix ) ) {
path = path.substring( pathPrefix.length() );
}
// check for management path
String alternate = cores.getManagementPath();
if (alternate != null && path.startsWith(alternate)) {
path = path.substring(0, alternate.length());
}
// unused feature ?
int idx = path.indexOf( ':' );
if( idx > 0 ) {
// save the portion after the ':' for a 'handler' path parameter
path = path.substring( 0, idx );
}
// Check for the core admin page
if( path.equals( cores.getAdminPath() ) ) {
handler = cores.getMultiCoreHandler();
solrReq = adminRequestParser.parse(null,path, req);
handleAdminRequest(req, response, handler, solrReq);
return;
}
else {
//otherwise, we should find a core from the path
idx = path.indexOf( "/", 1 );
if( idx > 1 ) {
// try to get the corename as a request parameter first
corename = path.substring( 1, idx );
core = cores.getCore(corename);
if (core != null) {
path = path.substring( idx );
}
}
if (core == null) {
if (!cores.isZooKeeperAware() ) {
core = cores.getCore("");
}
}
}
if (core == null && cores.isZooKeeperAware()) {
// we couldn't find the core - lets make sure a collection was not specified instead
core = getCoreByCollection(cores, core, corename, path);
if (core != null) {
// we found a core, update the path
path = path.substring( idx );
} else {
// try the default core
core = cores.getCore("");
}
// TODO: if we couldn't find it locally, look on other nodes
}
// With a valid core...
if( core != null ) {
final SolrConfig config = core.getSolrConfig();
// get or create/cache the parser for the core
SolrRequestParsers parser = null;
parser = parsers.get(config);
if( parser == null ) {
parser = new SolrRequestParsers(config);
parsers.put(config, parser );
}
// Determine the handler from the url path if not set
// (we might already have selected the cores handler)
if( handler == null && path.length() > 1 ) { // don't match "" or "/" as valid path
handler = core.getRequestHandler( path );
// no handler yet but allowed to handle select; let's check
if( handler == null && parser.isHandleSelect() ) {
if( "/select".equals( path ) || "/select/".equals( path ) ) {
solrReq = parser.parse( core, path, req );
String qt = solrReq.getParams().get( CommonParams.QT );
handler = core.getRequestHandler( qt );
if( handler == null ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "unknown handler: "+qt);
}
}
}
}
// With a valid handler and a valid core...
if( handler != null ) {
// if not a /select, create the request
if( solrReq == null ) {
solrReq = parser.parse( core, path, req );
}
final Method reqMethod = Method.getMethod(req.getMethod());
HttpCacheHeaderUtil.setCacheControlHeader(config, resp, reqMethod);
// unless we have been explicitly told not to, do cache validation
// if we fail cache validation, execute the query
if (config.getHttpCachingConfig().isNever304() ||
!HttpCacheHeaderUtil.doCacheHeaderValidation(solrReq, req, reqMethod, resp)) {
SolrQueryResponse solrRsp = new SolrQueryResponse();
/* even for HEAD requests, we need to execute the handler to
* ensure we don't get an error (and to make sure the correct
* QueryResponseWriter is selected and we get the correct
* Content-Type)
*/
SolrRequestInfo.setRequestInfo(new SolrRequestInfo(solrReq, solrRsp));
this.execute( req, handler, solrReq, solrRsp );
HttpCacheHeaderUtil.checkHttpCachingVeto(solrRsp, resp, reqMethod);
// add info to http headers
//TODO: See SOLR-232 and SOLR-267.
/*try {
NamedList solrRspHeader = solrRsp.getResponseHeader();
for (int i=0; i<solrRspHeader.size(); i++) {
((javax.servlet.http.HttpServletResponse) response).addHeader(("Solr-" + solrRspHeader.getName(i)), String.valueOf(solrRspHeader.getVal(i)));
}
} catch (ClassCastException cce) {
log.log(Level.WARNING, "exception adding response header log information", cce);
}*/
QueryResponseWriter responseWriter = core.getQueryResponseWriter(solrReq);
writeResponse(solrRsp, response, responseWriter, solrReq, reqMethod);
}
return; // we are done with a valid handler
}
// otherwise (we have a core), let's ensure the core is in the SolrCore request attribute so
// a servlet/jsp can retrieve it
else {
req.setAttribute("org.apache.solr.SolrCore", core);
// Modify the request so each core gets its own /admin
if( path.startsWith( "/admin" ) ) {
req.getRequestDispatcher( pathPrefix == null ? path : pathPrefix + path ).forward( request, response );
return;
}
}
}
log.debug("no handler or core retrieved for " + path + ", follow through...");
}
catch (Throwable ex) {
sendError( (HttpServletResponse)response, ex );
return;
}
finally {
if( solrReq != null ) {
solrReq.close();
}
if (core != null) {
core.close();
}
SolrRequestInfo.clearRequestInfo();
}
}
|
diff --git a/src/org/geworkbench/engine/WelcomeScreen.java b/src/org/geworkbench/engine/WelcomeScreen.java
index ee71c76b..a9a5abab 100644
--- a/src/org/geworkbench/engine/WelcomeScreen.java
+++ b/src/org/geworkbench/engine/WelcomeScreen.java
@@ -1,109 +1,110 @@
package org.geworkbench.engine;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.engine.config.GUIFramework;
import org.geworkbench.engine.config.VisualPlugin;
import org.geworkbench.engine.skin.Skin;
/**
* Welcome Screen.
* This by default shows up when you start
* a new version of geWorkbench. When the user clicks the 'Hide' button, it
* will go away unless the user opens it again from help menu.
*
* @author yc2480
* @author zji
* @version $Id$
*/
public class WelcomeScreen extends JPanel implements VisualPlugin {
private static final long serialVersionUID = -4675518732204562565L;
static Log log = LogFactory.getLog(WelcomeScreen.class);
/*
* The name of the welcome file. This file can either be a plain text file
* or a html file.
*/
private static final String WELCOMETEXT_FILENAME = "welcometext.html";
/*
* The panel to hold JEditorPane, so the text field will expand to the whole
* visual area. (Using BorderLayout.CENTER)
*/
private JPanel textFieldPanel = null;
/* The text area to show welcome message */
private JEditorPane textField = null;
/* The button to remove welcome component. */
private JButton button = new JButton("Hide");;
/*
* will be at the bottom of the visual area, and will use default layout, so
* button can be in the middle of it.
*/
private JPanel buttonPanel = null;
/**
* This constructor will load the welcome file and display it in visual
* area.
*/
public WelcomeScreen() {
textFieldPanel = new JPanel();
textFieldPanel.setLayout(new BorderLayout());
String filename = WELCOMETEXT_FILENAME;
try {
/* Try load the welcome file */
textField = new JEditorPane();
textField.setContentType("text/html");
textField.read(new BufferedReader(new FileReader(filename)),
filename);
textFieldPanel.add(textField, BorderLayout.CENTER);
+ textField.setEditable(false);
} catch (IOException e1) {
/*
* If we can not load the welcome file, disable welcome component
* for failover.
*/
log.error("File " + filename + " not found.");
removeSelf();
return;
}
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
removeSelf();
}
});
buttonPanel = new JPanel();
buttonPanel.add(button);
textFieldPanel.add(buttonPanel, BorderLayout.SOUTH);
}
private void removeSelf() {
Skin skin = (Skin)GUIFramework.getFrame();
skin.hideWelcomeScreen();
}
/*
* (non-Javadoc)
*
* @see org.geworkbench.engine.config.VisualPlugin#getComponent()
*/
public Component getComponent() {
return textFieldPanel;
}
}
| true | true | public WelcomeScreen() {
textFieldPanel = new JPanel();
textFieldPanel.setLayout(new BorderLayout());
String filename = WELCOMETEXT_FILENAME;
try {
/* Try load the welcome file */
textField = new JEditorPane();
textField.setContentType("text/html");
textField.read(new BufferedReader(new FileReader(filename)),
filename);
textFieldPanel.add(textField, BorderLayout.CENTER);
} catch (IOException e1) {
/*
* If we can not load the welcome file, disable welcome component
* for failover.
*/
log.error("File " + filename + " not found.");
removeSelf();
return;
}
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
removeSelf();
}
});
buttonPanel = new JPanel();
buttonPanel.add(button);
textFieldPanel.add(buttonPanel, BorderLayout.SOUTH);
}
| public WelcomeScreen() {
textFieldPanel = new JPanel();
textFieldPanel.setLayout(new BorderLayout());
String filename = WELCOMETEXT_FILENAME;
try {
/* Try load the welcome file */
textField = new JEditorPane();
textField.setContentType("text/html");
textField.read(new BufferedReader(new FileReader(filename)),
filename);
textFieldPanel.add(textField, BorderLayout.CENTER);
textField.setEditable(false);
} catch (IOException e1) {
/*
* If we can not load the welcome file, disable welcome component
* for failover.
*/
log.error("File " + filename + " not found.");
removeSelf();
return;
}
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
removeSelf();
}
});
buttonPanel = new JPanel();
buttonPanel.add(button);
textFieldPanel.add(buttonPanel, BorderLayout.SOUTH);
}
|
diff --git a/src/com/mpl/altimeter/BackgroundView.java b/src/com/mpl/altimeter/BackgroundView.java
index 03bb8e8..5b1c36d 100644
--- a/src/com/mpl/altimeter/BackgroundView.java
+++ b/src/com/mpl/altimeter/BackgroundView.java
@@ -1,74 +1,74 @@
package com.mpl.altimeter;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import com.trevorpage.tpsvg.SVGView;
public class BackgroundView extends SVGView {
private static final String TAG = "BackgroundView";
private double _altitude = 0;
private Paint _painter = new Paint();
private static int _color = Color.YELLOW;
private static int _maxHeight = 9000;
private static int _minHeight = -4947;
private static int _offset = _maxHeight - _minHeight;
public BackgroundView(Context context) {
super(context);
init();
}
public BackgroundView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BackgroundView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
_painter.setColor(_color);
setFill(true);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Get the real displayed image size
int realHeight = getHeight();
int realWidth = getWidth();
- boolean higher = getHeight() / getWidth() > 1280 / 800;
+ boolean higher = (float)getHeight() / getWidth() > (float)1280 / 800;
if (higher)
realWidth = 800 * getHeight() / 1280;
else
realHeight = 1280 * getWidth() / 800;
Log.d(TAG, "real w: " + realWidth);
Log.d(TAG, "real h: " + realHeight);
int height = getHeightForImageHeight(realHeight);
canvas.drawLine(0, height, realWidth, height, _painter);
}
public void setAltitude(double altitude) {
if (altitude > _maxHeight)
altitude = _maxHeight;
else if (altitude < _minHeight)
altitude = _minHeight;
_altitude = altitude;
invalidate();
}
private int getHeightForImageHeight(int imageHeight) {
Log.d(TAG, "image height: " + imageHeight);
int res = (int)(imageHeight * (1 - ((_altitude - _minHeight) / _offset)));
Log.d(TAG, String.valueOf(res) + " (" + _altitude + "m)");
return res;
}
}
| true | true | public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Get the real displayed image size
int realHeight = getHeight();
int realWidth = getWidth();
boolean higher = getHeight() / getWidth() > 1280 / 800;
if (higher)
realWidth = 800 * getHeight() / 1280;
else
realHeight = 1280 * getWidth() / 800;
Log.d(TAG, "real w: " + realWidth);
Log.d(TAG, "real h: " + realHeight);
int height = getHeightForImageHeight(realHeight);
canvas.drawLine(0, height, realWidth, height, _painter);
}
| public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Get the real displayed image size
int realHeight = getHeight();
int realWidth = getWidth();
boolean higher = (float)getHeight() / getWidth() > (float)1280 / 800;
if (higher)
realWidth = 800 * getHeight() / 1280;
else
realHeight = 1280 * getWidth() / 800;
Log.d(TAG, "real w: " + realWidth);
Log.d(TAG, "real h: " + realHeight);
int height = getHeightForImageHeight(realHeight);
canvas.drawLine(0, height, realWidth, height, _painter);
}
|
diff --git a/applications/rainbow/src/net/sf/okapi/applications/rainbow/utilities/textrewriting/Utility.java b/applications/rainbow/src/net/sf/okapi/applications/rainbow/utilities/textrewriting/Utility.java
index 04d53dbe1..dc219851f 100644
--- a/applications/rainbow/src/net/sf/okapi/applications/rainbow/utilities/textrewriting/Utility.java
+++ b/applications/rainbow/src/net/sf/okapi/applications/rainbow/utilities/textrewriting/Utility.java
@@ -1,339 +1,339 @@
/*===========================================================================
Copyright (C) 2008 by the Okapi Framework contributors
-----------------------------------------------------------------------------
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
============================================================================*/
package net.sf.okapi.applications.rainbow.utilities.textrewriting;
import net.sf.okapi.applications.rainbow.utilities.BaseFilterDrivenUtility;
import net.sf.okapi.common.IParameters;
import net.sf.okapi.common.Util;
import net.sf.okapi.common.filters.FilterEvent;
import net.sf.okapi.common.resource.IResource;
import net.sf.okapi.common.resource.StartDocument;
import net.sf.okapi.common.resource.TextContainer;
import net.sf.okapi.common.resource.TextFragment;
import net.sf.okapi.common.resource.TextUnit;
import net.sf.okapi.lib.segmentation.SRXDocument;
import net.sf.okapi.lib.segmentation.Segmenter;
import net.sf.okapi.lib.translation.QueryResult;
import net.sf.okapi.tm.simpletm.SimpleTMConnector;
public class Utility extends BaseFilterDrivenUtility {
private static final char TMPSTARTSEG = '\u0002';
private static final char TMPENDSEG = '\u0003';
private static final char STARTSEG = '[';
private static final char ENDSEG = ']';
private Parameters params;
private Segmenter srcSeg;
private Segmenter trgSeg;
private SimpleTMConnector tmQ;
public Utility () {
params = new Parameters();
}
public String getName () {
return "oku_textrewriting";
}
public void preprocess () {
// Load the segmentation rules
if ( params.segment ) {
SRXDocument doc = new SRXDocument();
doc.loadRules(params.sourceSrxPath);
if ( doc.hasWarning() ) logger.warn(doc.getWarning());
srcSeg = doc.applyLanguageRules(srcLang, null);
if ( !params.sourceSrxPath.equals(params.targetSrxPath) ) {
doc.loadRules(params.targetSrxPath);
if ( doc.hasWarning() ) logger.warn(doc.getWarning());
}
trgSeg = doc.applyLanguageRules(trgLang, null);
}
if ( params.type == Parameters.TYPE_TRANSLATEEXACTMATCHES ) {
tmQ = new SimpleTMConnector();
tmQ.open(params.tmPath);
}
}
public void postprocess () {
if ( tmQ != null ) {
tmQ.close();
tmQ = null;
}
}
public IParameters getParameters () {
return params;
}
public boolean hasParameters () {
return true;
}
public boolean needsRoots () {
return false;
}
public void setParameters (IParameters paramsObject) {
params = (Parameters)paramsObject;
}
public boolean isFilterDriven () {
return true;
}
public int requestInputCount () {
return 1;
}
public FilterEvent handleEvent (FilterEvent event) {
switch ( event.getEventType() ) {
case START_DOCUMENT:
processStartDocument((StartDocument)event.getResource());
break;
case TEXT_UNIT:
processTextUnit((TextUnit)event.getResource());
break;
}
return event;
}
private void processStartDocument (StartDocument resource) {
if ( tmQ != null ) {
tmQ.setAttribute("FileName", Util.getFilename(resource.getName(), true));
}
}
private void processTextUnit (TextUnit tu) {
// Skip non-translatable
if ( !tu.isTranslatable() ) return;
// Skip if already translate (only if required)
if ( !params.applyToExistingTarget && tu.hasTarget(trgLang) ) return;
// Apply the segmentation and/or segment marks if requested
if ( params.segment || params.markSegments ) {
if ( tu.hasTarget(trgLang) ) {
if ( params.segment ) {
trgSeg.computeSegments(tu.getTarget(trgLang));
tu.getTarget(trgLang).createSegments(trgSeg.getSegmentRanges());
}
}
else {
if ( params.segment ) {
srcSeg.computeSegments(tu.getSource());
tu.getSource().createSegments(srcSeg.getSegmentRanges());
}
}
}
// Else: do the requested modifications
// Make sure we have target content
tu.createTarget(trgLang, false, IResource.COPY_ALL);
// Translate is done before we merge possible segments
if ( params.type == Parameters.TYPE_TRANSLATEEXACTMATCHES ) {
translate(tu);
}
// Merge all segments if needed
if ( params.segment || params.markSegments ) {
mergeSegments(tu.getTarget(trgLang));
}
// Other text modification are done after merging all segments
switch ( params.type ) {
case Parameters.TYPE_XNREPLACE:
replaceWithXN(tu);
break;
case Parameters.TYPE_KEEPINLINE:
removeText(tu);
break;
}
- if ( params.addPrefix || params.addSuffix || params.addName ) {
+ if ( params.addPrefix || params.addSuffix || params.addName || params.addID ) {
addText(tu);
}
}
/**
* Removes the text but leaves the inline code.
* @param tu the text unit to process.
*/
private void removeText (TextUnit tu) {
String result = tu.getTarget(trgLang).getCodedText();
StringBuilder sb = new StringBuilder();
for ( int i=0; i<result.length(); i++ ) {
switch ( result.charAt(i) ) {
case TextFragment.MARKER_OPENING:
case TextFragment.MARKER_CLOSING:
case TextFragment.MARKER_ISOLATED:
case TextFragment.MARKER_SEGMENT:
sb.append(result.charAt(i));
sb.append(result.charAt(++i));
break;
case TMPSTARTSEG: // Keep segment marks if needed
if ( params.markSegments ) sb.append(STARTSEG);
break;
case TMPENDSEG: // Keep segment marks if needed
if ( params.markSegments ) sb.append(ENDSEG);
break;
default: // Do not keep other characters
break;
}
}
TextContainer cnt = tu.getTarget(trgLang);
cnt.setCodedText(sb.toString());
}
/**
* Merges back segments into a single content, while optionally adding
* brackets to denote the segments. If the unit is not segmented, brackets
* are added if required.
* @param container The TextContainer object to un-segment.
*/
private void mergeSegments (TextContainer container) {
// Set variables
StringBuilder text = new StringBuilder(container.getCodedText());
char start = STARTSEG;
char end = ENDSEG;
if ( params.type == Parameters.TYPE_KEEPINLINE ) {
// Use temporary marks if we need to remove the text after
// This way '[' and ']' is real text get removed too
start = TMPSTARTSEG;
end = TMPENDSEG;
}
if ( !container.isSegmented() ) {
if ( params.markSegments ) {
container.setCodedText(start+text.toString()+end);
}
return;
}
// Add the markers if needed
if ( params.markSegments ) {
// Insert the segment marks if requested
for ( int i=0; i<text.length(); i++ ) {
switch ( text.charAt(i) ) {
case TextContainer.MARKER_OPENING:
case TextContainer.MARKER_CLOSING:
case TextContainer.MARKER_ISOLATED:
i++; // Normal skip
break;
case TextContainer.MARKER_SEGMENT:
text.insert(i, start);
i += 3; // The bracket, the marker, the code index
text.insert(i, end);
// Next i increment will skip over the closing mark
break;
}
}
// Replace the original coded text by the one with markers
container.setCodedText(text.toString());
}
// Merge all segments
container.mergeAllSegments();
}
private void translate (TextUnit tu) {
try {
// Target is set if needed
QueryResult qr;
tmQ.setAttribute("GroupName", tu.getName());
TextContainer tc = tu.getTarget(trgLang);
if ( tc.isSegmented() ) {
int seg = 0;
for ( TextFragment tf : tc.getSegments() ) {
if ( tmQ.query(tf) == 1 ) {
qr = tmQ.next();
tc.getSegments().set(seg, qr.target);
}
seg++;
}
}
else {
if ( tmQ.query(tc) == 1 ) {
qr = tmQ.next();
tc = new TextContainer();
tc.append(qr.target);
tu.setTarget(trgLang, tc);
}
}
}
catch ( Throwable e ) {
logger.warn("Error while translating: ", e);
}
}
/**
* Replaces letters with Xs and digits with Ns.
* @param tu the text unit to process.
*/
private void replaceWithXN (TextUnit tu) {
String tmp = null;
try {
tmp = tu.getTarget(trgLang).getCodedText().replaceAll("\\p{Lu}|\\p{Lo}", "X");
tmp = tmp.replaceAll("\\p{Ll}", "x");
tmp = tmp.replaceAll("\\d", "N");
TextContainer cnt = tu.getTarget(trgLang);
cnt.setCodedText(tmp, tu.getSourceContent().getCodes(), false);
}
catch ( Throwable e ) {
logger.warn("Error when updating content: '"+tmp+"'", e);
}
}
/**
* Adds prefix and/or suffix to the target. This method assumes that
* the item has gone through the first transformation already.
* @param tu The text unit to process.
*/
private void addText (TextUnit tu) {
String tmp = null;
try {
// Use the target as the text to change.
tmp = tu.getTarget(trgLang).getCodedText();
if ( params.addPrefix ) {
tmp = params.prefix + tmp;
}
if ( params.addName ) {
String name = tu.getName();
if (( name != null ) && ( name.length() > 0 )) tmp += "_"+name;
else tmp += "_"+tu.getId();
}
if ( params.addID ) {
tmp += "_"+tu.getId();
}
if ( params.addSuffix ) {
tmp += params.suffix;
}
TextContainer cnt = tu.getTarget(trgLang);
cnt.setCodedText(tmp, tu.getSourceContent().getCodes(), false);
}
catch ( Throwable e ) {
logger.warn("Error when adding text to '"+tmp+"'", e);
}
}
}
| true | true | private void processTextUnit (TextUnit tu) {
// Skip non-translatable
if ( !tu.isTranslatable() ) return;
// Skip if already translate (only if required)
if ( !params.applyToExistingTarget && tu.hasTarget(trgLang) ) return;
// Apply the segmentation and/or segment marks if requested
if ( params.segment || params.markSegments ) {
if ( tu.hasTarget(trgLang) ) {
if ( params.segment ) {
trgSeg.computeSegments(tu.getTarget(trgLang));
tu.getTarget(trgLang).createSegments(trgSeg.getSegmentRanges());
}
}
else {
if ( params.segment ) {
srcSeg.computeSegments(tu.getSource());
tu.getSource().createSegments(srcSeg.getSegmentRanges());
}
}
}
// Else: do the requested modifications
// Make sure we have target content
tu.createTarget(trgLang, false, IResource.COPY_ALL);
// Translate is done before we merge possible segments
if ( params.type == Parameters.TYPE_TRANSLATEEXACTMATCHES ) {
translate(tu);
}
// Merge all segments if needed
if ( params.segment || params.markSegments ) {
mergeSegments(tu.getTarget(trgLang));
}
// Other text modification are done after merging all segments
switch ( params.type ) {
case Parameters.TYPE_XNREPLACE:
replaceWithXN(tu);
break;
case Parameters.TYPE_KEEPINLINE:
removeText(tu);
break;
}
if ( params.addPrefix || params.addSuffix || params.addName ) {
addText(tu);
}
}
| private void processTextUnit (TextUnit tu) {
// Skip non-translatable
if ( !tu.isTranslatable() ) return;
// Skip if already translate (only if required)
if ( !params.applyToExistingTarget && tu.hasTarget(trgLang) ) return;
// Apply the segmentation and/or segment marks if requested
if ( params.segment || params.markSegments ) {
if ( tu.hasTarget(trgLang) ) {
if ( params.segment ) {
trgSeg.computeSegments(tu.getTarget(trgLang));
tu.getTarget(trgLang).createSegments(trgSeg.getSegmentRanges());
}
}
else {
if ( params.segment ) {
srcSeg.computeSegments(tu.getSource());
tu.getSource().createSegments(srcSeg.getSegmentRanges());
}
}
}
// Else: do the requested modifications
// Make sure we have target content
tu.createTarget(trgLang, false, IResource.COPY_ALL);
// Translate is done before we merge possible segments
if ( params.type == Parameters.TYPE_TRANSLATEEXACTMATCHES ) {
translate(tu);
}
// Merge all segments if needed
if ( params.segment || params.markSegments ) {
mergeSegments(tu.getTarget(trgLang));
}
// Other text modification are done after merging all segments
switch ( params.type ) {
case Parameters.TYPE_XNREPLACE:
replaceWithXN(tu);
break;
case Parameters.TYPE_KEEPINLINE:
removeText(tu);
break;
}
if ( params.addPrefix || params.addSuffix || params.addName || params.addID ) {
addText(tu);
}
}
|
diff --git a/org.eclipse.emf.emfstore.client.test/src/org/eclipse/emf/emfstore/client/test/api/ModelElementTest.java b/org.eclipse.emf.emfstore.client.test/src/org/eclipse/emf/emfstore/client/test/api/ModelElementTest.java
index c587746a1..0f67b68a9 100644
--- a/org.eclipse.emf.emfstore.client.test/src/org/eclipse/emf/emfstore/client/test/api/ModelElementTest.java
+++ b/org.eclipse.emf.emfstore.client.test/src/org/eclipse/emf/emfstore/client/test/api/ModelElementTest.java
@@ -1,662 +1,662 @@
/*******************************************************************************
* Copyright 2011 Chair for Applied Software Engineering,
* Technische Universitaet Muenchen.
* 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:
******************************************************************************/
package org.eclipse.emf.emfstore.client.test.api;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ConcurrentModificationException;
import java.util.Set;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.command.MoveCommand;
import org.eclipse.emf.edit.command.RemoveCommand;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.emfstore.bowling.BowlingPackage;
import org.eclipse.emf.emfstore.bowling.Game;
import org.eclipse.emf.emfstore.bowling.League;
import org.eclipse.emf.emfstore.bowling.Matchup;
import org.eclipse.emf.emfstore.bowling.Player;
import org.eclipse.emf.emfstore.bowling.Tournament;
import org.eclipse.emf.emfstore.client.ESLocalProject;
import org.eclipse.emf.emfstore.client.ESWorkspaceProvider;
import org.eclipse.emf.emfstore.common.model.ESModelElementId;
import org.eclipse.emf.emfstore.internal.client.model.util.EMFStoreCommand;
import org.junit.Test;
/**
* ModelElementTest.
*
* @author Tobias Verhoeven
*/
public class ModelElementTest {
/**
* Tests adding model elements.
*/
@Test
public void testAddModelElementsWithoutCommands() {
ESLocalProject localProject = ESWorkspaceProvider.INSTANCE.getWorkspace().createLocalProject("Testprojekt");
League leagueA = ProjectChangeUtil.createLeague("America");
League leagueB = ProjectChangeUtil.createLeague("Europe");
localProject.getModelElements().add(leagueA);
localProject.getModelElements().add(leagueB);
assertEquals(2, localProject.getAllModelElements().size());
Player playerA = ProjectChangeUtil.createPlayer("Hans");
Player playerB = ProjectChangeUtil.createPlayer("Anton");
leagueA.getPlayers().add(playerA);
leagueA.getPlayers().add(playerB);
assertEquals(4, localProject.getAllModelElements().size());
Player playerC = ProjectChangeUtil.createPlayer("Paul");
Player playerD = ProjectChangeUtil.createPlayer("Klaus");
leagueA.getPlayers().add(playerC);
leagueA.getPlayers().add(playerD);
assertEquals(6, localProject.getAllModelElements().size());
assertEquals(2, localProject.getModelElements().size());
Tournament tournamentA = ProjectChangeUtil.createTournament(false);
localProject.getModelElements().add(tournamentA);
Matchup matchupA = ProjectChangeUtil.createMatchup(null, null);
Matchup matchupB = ProjectChangeUtil.createMatchup(null, null);
Game gameA = ProjectChangeUtil.createGame(playerA);
Game gameB = ProjectChangeUtil.createGame(playerB);
Game gameC = ProjectChangeUtil.createGame(playerC);
Game gameD = ProjectChangeUtil.createGame(playerD);
tournamentA.getMatchups().add(matchupA);
matchupA.getGames().add(gameA);
matchupA.getGames().add(gameB);
assertEquals(10, localProject.getAllModelElements().size());
tournamentA.getMatchups().add(matchupB);
matchupB.getGames().add(gameC);
matchupB.getGames().add(gameD);
assertEquals(13, localProject.getAllModelElements().size());
assertEquals(3, localProject.getModelElements().size());
}
/**
* Tests adding model elements.
*/
@Test
public void testAddModelElementsWithCommands() {
final ESLocalProject localProject = ESWorkspaceProvider.INSTANCE.getWorkspace().createLocalProject(
"Testprojekt");
final League leagueA = ProjectChangeUtil.createLeague("America");
final League leagueB = ProjectChangeUtil.createLeague("Europe");
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(leagueA);
localProject.getModelElements().add(leagueB);
}
}.execute();
assertEquals(2, localProject.getAllModelElements().size());
final Player playerA = ProjectChangeUtil.createPlayer("Hans");
final Player playerB = ProjectChangeUtil.createPlayer("Anton");
new EMFStoreCommand() {
@Override
protected void doRun() {
leagueA.getPlayers().add(playerA);
leagueA.getPlayers().add(playerB);
}
}.execute();
assertEquals(4, localProject.getAllModelElements().size());
final Player playerC = ProjectChangeUtil.createPlayer("Paul");
final Player playerD = ProjectChangeUtil.createPlayer("Klaus");
new EMFStoreCommand() {
@Override
protected void doRun() {
leagueA.getPlayers().add(playerC);
leagueA.getPlayers().add(playerD);
}
}.execute();
assertEquals(6, localProject.getAllModelElements().size());
assertEquals(2, localProject.getModelElements().size());
final Tournament tournamentA = ProjectChangeUtil.createTournament(false);
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournamentA);
}
}.execute();
final Matchup matchupA = ProjectChangeUtil.createMatchup(null, null);
final Matchup matchupB = ProjectChangeUtil.createMatchup(null, null);
final Game gameA = ProjectChangeUtil.createGame(playerA);
final Game gameB = ProjectChangeUtil.createGame(playerB);
final Game gameC = ProjectChangeUtil.createGame(playerC);
final Game gameD = ProjectChangeUtil.createGame(playerD);
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentA.getMatchups().add(matchupA);
matchupA.getGames().add(gameA);
matchupA.getGames().add(gameB);
}
}.execute();
assertEquals(10, localProject.getAllModelElements().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentA.getMatchups().add(matchupB);
matchupB.getGames().add(gameC);
matchupB.getGames().add(gameD);
}
}.execute();
assertEquals(13, localProject.getAllModelElements().size());
assertEquals(3, localProject.getModelElements().size());
}
@Test(expected = ConcurrentModificationException.class)
public void testDeleteAllModelElementsWithCommand() {
final ESLocalProject localProject = ProjectChangeUtil.createBasicBowlingProject();
new EMFStoreCommand() {
@Override
protected void doRun() {
Set<EObject> elements = localProject.getAllModelElements();
for (EObject object : elements) {
localProject.getModelElements().remove(object);
}
}
}.execute();
assertEquals(0, localProject.getAllModelElements().size());
}
@Test(expected = ConcurrentModificationException.class)
public void testDeleteAllModelElementsWithoutCommand() {
final ESLocalProject localProject = ProjectChangeUtil.createBasicBowlingProject();
Set<EObject> elements = localProject.getAllModelElements();
for (EObject object : elements) {
localProject.getModelElements().remove(object);
}
assertEquals(0, localProject.getAllModelElements().size());
}
/**
* adds and deletes model element and undos the deletion.
*/
@Test
public void testDeleteUndoWithCommand() {
final ESLocalProject localProject = ProjectChangeUtil.createBasicBowlingProject();
final Player player = ProjectChangeUtil.createPlayer("Heinrich");
final int SIZE = localProject.getAllModelElements().size();
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(player);
}
}.run(false);
assertTrue(localProject.getAllModelElements().contains(player));
assertTrue(localProject.contains(player));
ESModelElementId id = localProject.getModelElementId(player);
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().remove(player);
}
}.run(false);
assertEquals(SIZE, localProject.getAllModelElements().size());
assertFalse(localProject.getAllModelElements().contains(player));
assertFalse(localProject.contains(player));
assertNull(localProject.getModelElement(id));
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.undoLastOperation();
}
}.run(false);
assertEquals(SIZE + 1, localProject.getAllModelElements().size());
assertFalse(localProject.getAllModelElements().contains(player));
assertFalse(localProject.contains(player));
assertNotNull(localProject.getModelElement(id));
}
/**
* adds and deletes model element and undos the deletion.
*/
@Test
public void testDeleteUndoWithoutCommand() {
final ESLocalProject localProject = ProjectChangeUtil.createBasicBowlingProject();
final Player player = ProjectChangeUtil.createPlayer("Heinrich");
final int SIZE = localProject.getAllModelElements().size();
localProject.getModelElements().add(player);
assertTrue(localProject.getAllModelElements().contains(player));
assertTrue(localProject.contains(player));
ESModelElementId id = localProject.getModelElementId(player);
localProject.getModelElements().remove(player);
assertEquals(SIZE, localProject.getAllModelElements().size());
assertFalse(localProject.getAllModelElements().contains(player));
assertFalse(localProject.contains(player));
localProject.undoLastOperation();
assertEquals(SIZE + 1, localProject.getAllModelElements().size());
assertFalse(localProject.getAllModelElements().contains(player));
assertFalse(localProject.contains(player));
assertNotNull(localProject.getModelElement(id));
}
@Test
public void testReferenceDeletionWithCommand() {
final ESLocalProject localProject = ProjectChangeUtil.createBasicBowlingProject();
final Tournament tournament = ProjectChangeUtil.createTournament(true);
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournament);
}
}.run(false);
final Player player = ProjectChangeUtil.createPlayer("Heinrich");
final Player player2 = ProjectChangeUtil.createPlayer("Walter");
final Player player3 = ProjectChangeUtil.createPlayer("Wilhelm");
new EMFStoreCommand() {
@Override
protected void doRun() {
tournament.getPlayers().add(player);
tournament.getPlayers().add(player2);
tournament.getPlayers().add(player3);
}
}.run(false);
assertEquals(3, tournament.getPlayers().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().remove(player2);
}
}.execute();
assertEquals(2, tournament.getPlayers().size());
assertTrue(localProject.contains(player));
assertTrue(localProject.contains(player3));
assertFalse(localProject.contains(player2));
}
@Test
public void testReferenceDeletionWithoutCommand() {
final ESLocalProject localProject = ProjectChangeUtil.createBasicBowlingProject();
final Tournament tournament = ProjectChangeUtil.createTournament(true);
localProject.getModelElements().add(tournament);
final Player player = ProjectChangeUtil.createPlayer("Heinrich");
final Player player2 = ProjectChangeUtil.createPlayer("Walter");
final Player player3 = ProjectChangeUtil.createPlayer("Wilhelm");
tournament.getPlayers().add(player);
tournament.getPlayers().add(player2);
tournament.getPlayers().add(player3);
assertEquals(3, tournament.getPlayers().size());
tournament.getPlayers().remove(player2);
assertEquals(2, tournament.getPlayers().size());
assertTrue(localProject.contains(player));
assertTrue(localProject.contains(player3));
// TODO: enable this assert once the operation recorder works without commands too
// assertFalse(localProject.contains(player2));
}
@Test
public void testMultiReferenceRevertWithCommand() {
final ESLocalProject localProject = ProjectChangeUtil.createBasicBowlingProject();
final Tournament tournament = ProjectChangeUtil.createTournament(true);
final int numTrophies = 40;
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournament);
}
}.run(false);
new EMFStoreCommand() {
@Override
protected void doRun() {
for (int i = 0; i < numTrophies; i++)
tournament.getReceivesTrophy().add(false);
}
}.run(false);
assertEquals(numTrophies, tournament.getReceivesTrophy().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.revert();
}
}.run(false);
assertEquals(0, tournament.getReceivesTrophy().size());
}
@Test
public void testMultiReferenceDeleteRevertWithCommand() {
final ESLocalProject localProject = ProjectChangeUtil.createBasicBowlingProject();
final Tournament tournament = ProjectChangeUtil.createTournament(true);
final int numTrophies = 40;
final int numDeletes = 10;
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournament);
}
}.run(false);
new EMFStoreCommand() {
@Override
protected void doRun() {
for (int i = 0; i < numTrophies; i++)
tournament.getReceivesTrophy().add(false);
}
}.run(false);
assertEquals(numTrophies, tournament.getReceivesTrophy().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
for (int i = 0; i < numDeletes; i++)
tournament.getReceivesTrophy().remove(i);
}
}.run(false);
assertEquals(numTrophies - numDeletes, tournament.getReceivesTrophy().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.revert();
}
}.run(false);
assertEquals(0, tournament.getReceivesTrophy().size());
}
@Test
public void testMultiReferenceRemoveRevertWithCommand() {
final ESLocalProject localProject = ProjectChangeUtil.createBasicBowlingProject();
final Tournament tournament = ProjectChangeUtil.createTournament(true);
final int numTrophies = 40;
final int numDeletes = 10;
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournament);
}
}.run(false);
new EMFStoreCommand() {
@Override
protected void doRun() {
for (int i = 0; i < numTrophies; i++)
tournament.getReceivesTrophy().add(false);
}
}.run(false);
assertEquals(numTrophies, tournament.getReceivesTrophy().size());
EditingDomain domain = AdapterFactoryEditingDomain.getEditingDomainFor(tournament);
for (int i = 0; i < numDeletes; i++)
domain.getCommandStack().execute(
RemoveCommand.create(domain,
tournament, BowlingPackage.eINSTANCE.getTournament_ReceivesTrophy(), Boolean.FALSE));
assertEquals(numTrophies - numDeletes, tournament.getReceivesTrophy().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.revert();
}
}.run(false);
assertEquals(0, tournament.getReceivesTrophy().size());
}
@Test
public void testMultiReferenceMoveRevertWithCommand() {
final ESLocalProject localProject = ProjectChangeUtil.createBasicBowlingProject();
final Tournament tournament = ProjectChangeUtil.createTournament(true);
final int numTrophies = 40;
final int numDeletes = 10;
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournament);
}
}.run(false);
new EMFStoreCommand() {
@Override
protected void doRun() {
for (int i = 0; i < numTrophies; i++)
tournament.getReceivesTrophy().add(Boolean.FALSE);
}
}.run(false);
assertEquals(numTrophies, tournament.getReceivesTrophy().size());
EditingDomain domain = AdapterFactoryEditingDomain.getEditingDomainFor(tournament);
for (int i = 10; i < numDeletes; i++)
domain.getCommandStack().execute(
MoveCommand.create(domain,
tournament, BowlingPackage.eINSTANCE.getTournament_ReceivesTrophy(), Boolean.FALSE,
i - 1));
assertEquals(numTrophies, tournament.getReceivesTrophy().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.revert();
}
}.run(false);
assertEquals(0, tournament.getReceivesTrophy().size());
}
@Test
public void testUndoAddOperation() {
final ESLocalProject localProject = ProjectChangeUtil.createBasicBowlingProject();
final Tournament tournamentA = ProjectChangeUtil.createTournament(true);
final Tournament tournamentB = ProjectChangeUtil.createTournament(true);
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournamentA);
localProject.getModelElements().add(tournamentB);
}
}.run(false);
final Matchup matchupA = ProjectChangeUtil.createMatchup(null, null);
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentA.getMatchups().add(matchupA);
}
}.run(false);
assertEquals(1, tournamentA.getMatchups().size());
assertTrue(tournamentA.getMatchups().contains(matchupA));
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentB.getMatchups().add(matchupA);
}
}.run(false);
assertEquals(1, tournamentB.getMatchups().size());
assertTrue(tournamentB.getMatchups().contains(matchupA));
assertEquals(0, tournamentA.getMatchups().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.undoLastOperation();
}
}.run(false);
assertEquals(0, tournamentB.getMatchups().size());
assertEquals(1, tournamentA.getMatchups().size());
assertTrue(tournamentA.getMatchups().contains(matchupA));
}
@Test
public void testUndoMoveOperation() {
final ESLocalProject localProject = ESWorkspaceProvider.INSTANCE.getWorkspace().createLocalProject(
- "SimpleEmptyProject", "");
+ "SimpleEmptyProject");
final Tournament tournamentA = ProjectChangeUtil.createTournament(true);
final Tournament tournamentB = ProjectChangeUtil.createTournament(true);
final Matchup matchupA = ProjectChangeUtil.createMatchup(null, null);
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournamentA);
}
}.run(false);
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentA.getMatchups().add(matchupA);
}
}.run(false);
ESModelElementId matchupID = localProject.getModelElementId(matchupA);
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournamentB);
}
}.run(false);
assertEquals(1, tournamentA.getMatchups().size());
assertTrue(tournamentA.getMatchups().contains(matchupA));
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentA.getMatchups().remove(matchupA);
}
}.run(false);
assertEquals(2, localProject.getModelElements().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentB.getMatchups().add(matchupA);
}
}.run(false);
assertEquals(1, tournamentB.getMatchups().size());
assertTrue(tournamentB.getMatchups().contains(matchupA));
assertEquals(0, tournamentA.getMatchups().size());
assertEquals(2, localProject.getModelElements().size());
// undos move from root to container
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.undoLastOperation();
}
}.run(false);
assertEquals(0, tournamentB.getMatchups().size());
assertEquals(0, tournamentA.getMatchups().size());
assertEquals(3, localProject.getModelElements().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.undoLastOperation();
}
}.run(false);
assertEquals(0, tournamentA.getMatchups().size());
assertEquals(2, localProject.getModelElements().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.undoLastOperation();
}
}.run(false);
assertEquals(1, tournamentA.getMatchups().size());
assertEquals(2, localProject.getModelElements().size());
assertEquals(matchupID, localProject.getModelElementId(tournamentA.getMatchups().get(0)));
}
}
| true | true | public void testUndoMoveOperation() {
final ESLocalProject localProject = ESWorkspaceProvider.INSTANCE.getWorkspace().createLocalProject(
"SimpleEmptyProject", "");
final Tournament tournamentA = ProjectChangeUtil.createTournament(true);
final Tournament tournamentB = ProjectChangeUtil.createTournament(true);
final Matchup matchupA = ProjectChangeUtil.createMatchup(null, null);
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournamentA);
}
}.run(false);
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentA.getMatchups().add(matchupA);
}
}.run(false);
ESModelElementId matchupID = localProject.getModelElementId(matchupA);
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournamentB);
}
}.run(false);
assertEquals(1, tournamentA.getMatchups().size());
assertTrue(tournamentA.getMatchups().contains(matchupA));
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentA.getMatchups().remove(matchupA);
}
}.run(false);
assertEquals(2, localProject.getModelElements().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentB.getMatchups().add(matchupA);
}
}.run(false);
assertEquals(1, tournamentB.getMatchups().size());
assertTrue(tournamentB.getMatchups().contains(matchupA));
assertEquals(0, tournamentA.getMatchups().size());
assertEquals(2, localProject.getModelElements().size());
// undos move from root to container
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.undoLastOperation();
}
}.run(false);
assertEquals(0, tournamentB.getMatchups().size());
assertEquals(0, tournamentA.getMatchups().size());
assertEquals(3, localProject.getModelElements().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.undoLastOperation();
}
}.run(false);
assertEquals(0, tournamentA.getMatchups().size());
assertEquals(2, localProject.getModelElements().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.undoLastOperation();
}
}.run(false);
assertEquals(1, tournamentA.getMatchups().size());
assertEquals(2, localProject.getModelElements().size());
assertEquals(matchupID, localProject.getModelElementId(tournamentA.getMatchups().get(0)));
}
| public void testUndoMoveOperation() {
final ESLocalProject localProject = ESWorkspaceProvider.INSTANCE.getWorkspace().createLocalProject(
"SimpleEmptyProject");
final Tournament tournamentA = ProjectChangeUtil.createTournament(true);
final Tournament tournamentB = ProjectChangeUtil.createTournament(true);
final Matchup matchupA = ProjectChangeUtil.createMatchup(null, null);
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournamentA);
}
}.run(false);
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentA.getMatchups().add(matchupA);
}
}.run(false);
ESModelElementId matchupID = localProject.getModelElementId(matchupA);
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.getModelElements().add(tournamentB);
}
}.run(false);
assertEquals(1, tournamentA.getMatchups().size());
assertTrue(tournamentA.getMatchups().contains(matchupA));
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentA.getMatchups().remove(matchupA);
}
}.run(false);
assertEquals(2, localProject.getModelElements().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
tournamentB.getMatchups().add(matchupA);
}
}.run(false);
assertEquals(1, tournamentB.getMatchups().size());
assertTrue(tournamentB.getMatchups().contains(matchupA));
assertEquals(0, tournamentA.getMatchups().size());
assertEquals(2, localProject.getModelElements().size());
// undos move from root to container
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.undoLastOperation();
}
}.run(false);
assertEquals(0, tournamentB.getMatchups().size());
assertEquals(0, tournamentA.getMatchups().size());
assertEquals(3, localProject.getModelElements().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.undoLastOperation();
}
}.run(false);
assertEquals(0, tournamentA.getMatchups().size());
assertEquals(2, localProject.getModelElements().size());
new EMFStoreCommand() {
@Override
protected void doRun() {
localProject.undoLastOperation();
}
}.run(false);
assertEquals(1, tournamentA.getMatchups().size());
assertEquals(2, localProject.getModelElements().size());
assertEquals(matchupID, localProject.getModelElementId(tournamentA.getMatchups().get(0)));
}
|
diff --git a/src/main/java/com/dumptruckman/chunky/module/ChunkyCommand.java b/src/main/java/com/dumptruckman/chunky/module/ChunkyCommand.java
index 54846fd..a44df5d 100644
--- a/src/main/java/com/dumptruckman/chunky/module/ChunkyCommand.java
+++ b/src/main/java/com/dumptruckman/chunky/module/ChunkyCommand.java
@@ -1,119 +1,119 @@
package com.dumptruckman.chunky.module;
import com.dumptruckman.chunky.util.Logging;
import java.util.HashMap;
import java.util.List;
/**
* @author dumptruckman, SwearWord
*/
public class ChunkyCommand {
private String name;
private ChunkyCommand parent;
private List<String> aliases;
private String description;
private List<String> helpLines;
private ChunkyCommandExecutor executor;
private String fullName;
private HashMap<String, ChunkyCommand> children;
private String chatName;
public ChunkyCommand(String name, List<String> aliases, String description, List<String> helpLines, ChunkyCommandExecutor executor) {
this(name, aliases, description, helpLines, executor, null);
}
public ChunkyCommand(String name, List<String> aliases, String description, List<String> helpLines, ChunkyCommandExecutor executor, ChunkyCommand parentCommand) {
this.name = name.toLowerCase();
if (aliases != null) {
for (int i = 0; i < aliases.size(); i++) {
aliases.set(i, aliases.get(i).toLowerCase());
}
}
this.aliases = aliases;
this.description = description;
this.helpLines = helpLines;
this.parent = parentCommand;
this.executor = executor;
this.children = new HashMap<String, ChunkyCommand>();
this.fullName = name;
ChunkyCommand currentParent = parentCommand;
while (true) {
if (currentParent == null) break;
this.fullName = currentParent.getName() + "." + this.fullName;
currentParent = currentParent.getParent();
}
String[] splitName = this.fullName.split(".");
- String chatName = "/";
+ chatName = "/";
for (int i = 0; i < splitName.length; i++) {
Logging.debug(splitName[i]);
if (i != 0) chatName += " ";
chatName += splitName[i];
}
}
public final String getName() {
return name;
}
public final String getFullName() {
return fullName;
}
public final String getChatName() {
return chatName;
}
public final ChunkyCommand getParent() {
return parent;
}
public final HashMap<String, ChunkyCommand> getChildren() {
@SuppressWarnings("unchecked")
HashMap<String, ChunkyCommand> children = (HashMap<String, ChunkyCommand>)this.children.clone();
return children;
}
public final List<String> getAliases() {
return aliases;
}
public final String getDescription() {
return description;
}
public final List<String> getHelpLines() {
return helpLines;
}
public final ChunkyCommandExecutor getExecutor() {
return executor;
}
protected final boolean addChild(ChunkyCommand child) {
if (!children.containsKey(child.getFullName())) {
children.put(child.getFullName(), child);
return true;
}
return false;
}
public final ChunkyCommand getChild(String fullName) {
return children.get(fullName);
}
public final boolean hasChild(String fullName) {
return getChild(fullName) != null;
}
public boolean equals(Object o) {
return o instanceof ChunkyCommand && ((ChunkyCommand)o).getFullName().equals(this.getFullName());
}
public int hashCode() {
return getFullName().hashCode();
}
}
| true | true | public ChunkyCommand(String name, List<String> aliases, String description, List<String> helpLines, ChunkyCommandExecutor executor, ChunkyCommand parentCommand) {
this.name = name.toLowerCase();
if (aliases != null) {
for (int i = 0; i < aliases.size(); i++) {
aliases.set(i, aliases.get(i).toLowerCase());
}
}
this.aliases = aliases;
this.description = description;
this.helpLines = helpLines;
this.parent = parentCommand;
this.executor = executor;
this.children = new HashMap<String, ChunkyCommand>();
this.fullName = name;
ChunkyCommand currentParent = parentCommand;
while (true) {
if (currentParent == null) break;
this.fullName = currentParent.getName() + "." + this.fullName;
currentParent = currentParent.getParent();
}
String[] splitName = this.fullName.split(".");
String chatName = "/";
for (int i = 0; i < splitName.length; i++) {
Logging.debug(splitName[i]);
if (i != 0) chatName += " ";
chatName += splitName[i];
}
}
| public ChunkyCommand(String name, List<String> aliases, String description, List<String> helpLines, ChunkyCommandExecutor executor, ChunkyCommand parentCommand) {
this.name = name.toLowerCase();
if (aliases != null) {
for (int i = 0; i < aliases.size(); i++) {
aliases.set(i, aliases.get(i).toLowerCase());
}
}
this.aliases = aliases;
this.description = description;
this.helpLines = helpLines;
this.parent = parentCommand;
this.executor = executor;
this.children = new HashMap<String, ChunkyCommand>();
this.fullName = name;
ChunkyCommand currentParent = parentCommand;
while (true) {
if (currentParent == null) break;
this.fullName = currentParent.getName() + "." + this.fullName;
currentParent = currentParent.getParent();
}
String[] splitName = this.fullName.split(".");
chatName = "/";
for (int i = 0; i < splitName.length; i++) {
Logging.debug(splitName[i]);
if (i != 0) chatName += " ";
chatName += splitName[i];
}
}
|
diff --git a/com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/core/CoreMoSyncPlugin.java b/com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/core/CoreMoSyncPlugin.java
index 474de62b..2ea74477 100644
--- a/com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/core/CoreMoSyncPlugin.java
+++ b/com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/core/CoreMoSyncPlugin.java
@@ -1,780 +1,778 @@
/* Copyright (C) 2009 Mobile Sorcery AB
This program is free software; you can redistribute it and/or modify it
under the terms of the Eclipse Public License v1.0.
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 Eclipse Public License v1.0 for
more details.
You should have received a copy of the Eclipse Public License v1.0 along
with this program. It is also available at http://www.eclipse.org/legal/epl-v10.html
*/
package com.mobilesorcery.sdk.core;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobManager;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.equinox.security.storage.SecurePreferencesFactory;
import org.eclipse.equinox.security.storage.StorageException;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import com.mobilesorcery.sdk.core.launch.IEmulatorLauncher;
import com.mobilesorcery.sdk.core.launch.MoReLauncher;
import com.mobilesorcery.sdk.core.security.IApplicationPermissions;
import com.mobilesorcery.sdk.internal.ErrorPackager;
import com.mobilesorcery.sdk.internal.PID;
import com.mobilesorcery.sdk.internal.PROCESS;
import com.mobilesorcery.sdk.internal.PackagerProxy;
import com.mobilesorcery.sdk.internal.PropertyInitializerProxy;
import com.mobilesorcery.sdk.internal.RebuildListener;
import com.mobilesorcery.sdk.internal.ReindexListener;
import com.mobilesorcery.sdk.internal.debug.MoSyncBreakpointSynchronizer;
import com.mobilesorcery.sdk.internal.dependencies.DependencyManager;
import com.mobilesorcery.sdk.internal.launch.EmulatorLauncherProxy;
import com.mobilesorcery.sdk.internal.security.ApplicationPermissions;
import com.mobilesorcery.sdk.lib.JNALibInitializer;
import com.mobilesorcery.sdk.profiles.filter.DeviceFilterFactoryProxy;
import com.mobilesorcery.sdk.profiles.filter.IDeviceFilterFactory;
import com.mobilesorcery.sdk.profiles.filter.elementfactories.ConstantFilterFactory;
import com.mobilesorcery.sdk.profiles.filter.elementfactories.FeatureFilterFactory;
import com.mobilesorcery.sdk.profiles.filter.elementfactories.ProfileFilterFactory;
import com.mobilesorcery.sdk.profiles.filter.elementfactories.VendorFilterFactory;
/**
* The activator class controls the plug-in life cycle
*/
public class CoreMoSyncPlugin extends AbstractUIPlugin implements IPropertyChangeListener, IResourceChangeListener {
// The plug-in ID
public static final String PLUGIN_ID = "com.mobilesorcery.sdk.core";
private static final String SECURE_ROOT_NODE = "mosync.com";
// The shared instance
private static CoreMoSyncPlugin plugin;
private ArrayList<Pattern> patterns = new ArrayList<Pattern>();
private ArrayList<IPackager> packagers = new ArrayList<IPackager>();
private Map<String, Map<String, IPropertyInitializer>> propertyInitializers = new HashMap<String, Map<String, IPropertyInitializer>>();
private HashMap<String, IEmulatorLauncher> launchers = new HashMap<String, IEmulatorLauncher>();
private DependencyManager<IProject> projectDependencyManager;
private Properties panicMessages = new Properties();
private ReindexListener reindexListener;
private Integer[] sortedPanicErrorCodes;
private MoSyncBreakpointSynchronizer bpSync;
private boolean isHeadless = false;
private HashMap<String, IDeviceFilterFactory> factories;
private boolean updaterInitialized;
private IUpdater updater;
private IProvider<IProcessConsole, String> ideProcessConsoleProvider;
private EmulatorProcessManager emulatorProcessManager;
private String[] buildConfigurationTypes;
private HashMap<String, Integer> logCounts = new HashMap<String, Integer>();
/**
* The constructor
*/
public CoreMoSyncPlugin() {
}
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
isHeadless = Boolean.TRUE.equals(System.getProperty("com.mobilesorcery.headless"));
initReIndexerListener();
initRebuildListener();
initNativeLibs(context);
initPackagers();
initDeviceFilterFactories();
initPanicErrorMessages();
initPropertyInitializers();
initGlobalDependencyManager();
initEmulatorProcessManager();
installBreakpointHack();
installResourceListener();
initBuildConfigurationTypes();
initLaunchers();
getPreferenceStore().addPropertyChangeListener(this);
initializeOnSeparateThread();
}
/**
* <p>For development & debugging purposes.</p>
* <p>Returns how this product's
* experimental mode was changed at startup (using the
* <code>-experimental:enable</code> or
* <code>-experimental:disable</code>
* command line arguments).
* @return <code>Boolean.TRUE</code> if experimental mode
* was enabled at startup, <code>Boolean.FALSE</code> if
* it was disabled, <code>null</code> if neither.
*/
public Boolean switchedToExperimental() {
if (Arrays.asList(Platform.getApplicationArgs()).contains("-experimental:enable")) {
return true;
}
if (Arrays.asList(Platform.getApplicationArgs()).contains("-experimental:disable")) {
return false;
}
return null;
}
private void initLaunchers() {
// Default always present
this.launchers.put(MoReLauncher.ID, new MoReLauncher());
// External emulators are only allowed in experimental mode
if(Boolean.TRUE.equals(switchedToExperimental())) {
IConfigurationElement[] launchers = Platform.getExtensionRegistry().getConfigurationElementsFor(IEmulatorLauncher.EXTENSION_POINT_ID);
for (int i = 0; i < launchers.length; i++) {
IConfigurationElement launcher = launchers[i];
String id = launcher.getAttribute("id");
this.launchers.put(id, new EmulatorLauncherProxy(launcher));
}
}
}
private void initBuildConfigurationTypes() {
IConfigurationElement[] types = Platform.getExtensionRegistry().getConfigurationElementsFor(
BuildConfiguration.TYPE_EXTENSION_POINT);
ArrayList<String> buildConfigurationTypes = new ArrayList<String>();
// Add defaults
buildConfigurationTypes.add(IBuildConfiguration.RELEASE_TYPE);
buildConfigurationTypes.add(IBuildConfiguration.DEBUG_TYPE);
// Add extensions
for (int i = 0; i < types.length; i++) {
String typeId = types[i].getAttribute("id");
if (typeId != null) {
buildConfigurationTypes.add(typeId);
}
}
this.buildConfigurationTypes = buildConfigurationTypes.toArray(new String[0]);
}
void initializeOnSeparateThread() {
// I think we should move this to the UI plugin!
Thread initializerThread = new Thread(new Runnable() {
public void run() {
checkAutoUpdate();
}
}, "Initializer");
initializerThread.setDaemon(true);
initializerThread.start();
}
/**
* Returns whether this app is running in headless mode.
* @return
*/
public static boolean isHeadless() {
return plugin.isHeadless;
}
/**
* Sets this app to headless/non-headless mode.
* Please note that this will trigger a bundle activation,
* so if you want to make sure headless is set before that
* use <code>System.setProperty("com.mobilesorcery.headless", true")</code>
* @param isHeadless
*/
public static void setHeadless(boolean isHeadless) {
plugin.isHeadless = isHeadless;
}
private void installBreakpointHack() {
bpSync = new MoSyncBreakpointSynchronizer();
bpSync.install();
}
private void initGlobalDependencyManager() {
// Currently, all workspaces share this guy -- fixme later.
this.projectDependencyManager = new DependencyManager<IProject>();
}
private void initRebuildListener() {
MoSyncProject.addGlobalPropertyChangeListener(new RebuildListener());
}
public void stop(BundleContext context) throws Exception {
plugin = null;
projectDependencyManager = null;
disposeUpdater();
MoSyncProject.removeGlobalPropertyChangeListener(reindexListener);
bpSync.uninstall();
deinstallResourceListener();
super.stop(context);
}
private void initPropertyInitializers() {
IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor(
IPropertyInitializerDelegate.EXTENSION_POINT);
propertyInitializers = new HashMap<String, Map<String, IPropertyInitializer>>();
for (int i = 0; i < elements.length; i++) {
String context = PropertyInitializerProxy.getContext(elements[i]);
String prefix = PropertyInitializerProxy.getPrefix(elements[i]);
if (context != null && prefix != null) {
Map<String, IPropertyInitializer> prefixMap = propertyInitializers.get(context);
if (prefixMap == null) {
prefixMap = new HashMap<String, IPropertyInitializer>();
propertyInitializers.put(context, prefixMap);
}
prefixMap.put(prefix, new PropertyInitializerProxy(elements[i]));
}
}
}
/**
* <p>
* From the registered <code>IPropertyInitializerDelegate</code>s, returns
* the default value for <code>key</code>, where <code>key</code> has the
* format <code>prefix:subkey</code>.
* </p>
* <p>
* <code>IPropertyInitializerDelegate</code>s are always registered with
* context and prefix, which are used for lookup.
* </p>
* <p>
* The context is the same as is returned from the <code>getContext()</code>
* method in <code>IPropertyOwner</code>.
*
* @param owner
* @param key
* @return May return <code>null</code>
*/
public String getDefaultValue(IPropertyOwner owner, String key) {
Map<String, IPropertyInitializer> prefixMap = propertyInitializers.get(owner.getContext());
if (prefixMap != null) {
String[] prefixAndSubkey = key.split(":", 2);
if (prefixAndSubkey.length == 2) {
IPropertyInitializer initializer = prefixMap.get(prefixAndSubkey[0]);
if (initializer != null) {
return initializer.getDefaultValue(owner, key);
}
}
}
return null;
}
private void initReIndexerListener() {
reindexListener = new ReindexListener();
MoSyncProject.addGlobalPropertyChangeListener(new ReindexListener());
}
private void initEmulatorProcessManager() {
this.emulatorProcessManager = new EmulatorProcessManager();
}
private void initPanicErrorMessages() {
try {
panicMessages = new Properties();
InputStream messagesStream =
new FileInputStream(MoSyncTool.getDefault().getMoSyncHome().
append("eclipse/paniccodes.properties").toFile());
try {
panicMessages.load(messagesStream);
} finally {
Util.safeClose(messagesStream);
}
} catch (Exception e) {
// Just ignore.
getLog().log(new Status(IStatus.WARNING, PLUGIN_ID, "Could not initialize panic messages", e));
}
TreeSet<Integer> result = new TreeSet<Integer>();
for (Enumeration errorCodes = panicMessages.keys(); errorCodes.hasMoreElements(); ) {
try {
String errorCode = (String) errorCodes.nextElement();
int errorCodeValue = Integer.parseInt(errorCode);
result.add(errorCodeValue);
} catch (Exception e) {
// Just ignore.
}
}
sortedPanicErrorCodes = result.toArray(new Integer[result.size()]);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static CoreMoSyncPlugin getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given plug-in
* relative path
*
* @param path
* the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
public void log(Throwable e) {
getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, e.getMessage(), e));
}
private void initNativeLibs(BundleContext context) {
try {
JNALibInitializer.init(this.getBundle(), "libpipe");
@SuppressWarnings("unused")
PROCESS dummy = PROCESS.INSTANCE; // Just to execute the .clinit.
JNALibInitializer.init(this.getBundle(), "libpid2");
if (isDebugging()) {
trace("Process id: " + getPid());
}
} catch (Throwable t) {
log(t);
t.printStackTrace();
}
}
private void initPackagers() {
IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor(IPackager.EXTENSION_POINT);
for (int i = 0; i < elements.length; i++) {
String pattern = elements[i].getAttribute(PackagerProxy.PATTERN);
Pattern platformPattern = Pattern.compile(pattern);
patterns.add(platformPattern);
packagers.add(new PackagerProxy(elements[i]));
}
}
/**
* Returns the packager for a specific platform.
* @param platform
* @return A non-null packager. If no packager is found,
* a default <code>ErrorPackager</code> is returned
* @see ErrorPackager
*/
public IPackager getPackager(String platform) {
for (int i = 0; i < patterns.size(); i++) {
Pattern pattern = patterns.get(i);
if (pattern.matcher(platform).matches()) {
return packagers.get(i);
}
}
return ErrorPackager.getDefault();
}
/**
* Returns a sorted list of all panic error codes.
* @return
*/
public Integer[] getAllPanicErrorCodes() {
return sortedPanicErrorCodes;
}
/**
* Returns the panic message corresponding to <code>errcode</code>
* @param errcode
* @return
*/
public String getPanicMessage(int errcode) {
return panicMessages.getProperty(Integer.toString(errcode));
}
/**
* @deprecated Do we really need this? It is never used outside
* the builder + recalculated every time...
* @return
*/
public DependencyManager<IProject> getProjectDependencyManager() {
return getProjectDependencyManager(ResourcesPlugin.getWorkspace());
}
/**
* @deprecated Do we really need this? It is never used outside
* the builder + recalculated every time...
* @param ws
* @return
*/
public DependencyManager<IProject> getProjectDependencyManager(IWorkspace ws) {
return projectDependencyManager;
}
/**
* Returns the Eclipse OS Process ID.
* @return
*/
public static String getPid() {
return "" + PID.INSTANCE.pid();
}
public IProcessUtil getProcessUtil() {
return PROCESS.INSTANCE;
}
/**
* <p>Outputs a trace message.</p>
* <p>Please use this pattern:
* <blockquote><code>
* if (CoreMoSyncPlugin.getDefault().isDebugging()) {
* trace("A trace message");
* }
* </code></blockquote>
* </p>
* @param msg
*/
public static void trace(Object msg) {
System.out.println(msg);
}
/**
* <p>Outputs a trace message.</p>
* <p>The arguments match those of <code>MessageFormat.format</code>.</p>
* @see {@link CoreMoSyncPlugin#trace(Object)};
*/
public static void trace(String msg, Object... args) {
trace(MessageFormat.format(msg, args));
}
private void initDeviceFilterFactories() {
factories = new HashMap<String, IDeviceFilterFactory>();
// We'll just add some of them explicitly
factories.put(ConstantFilterFactory.ID, new ConstantFilterFactory());
factories.put(VendorFilterFactory.ID, new VendorFilterFactory());
factories.put(FeatureFilterFactory.ID, new FeatureFilterFactory());
factories.put(ProfileFilterFactory.ID, new ProfileFilterFactory());
IConfigurationElement[] factoryCEs = Platform.getExtensionRegistry().getConfigurationElementsFor(PLUGIN_ID + ".filter.factories");
for (int i = 0; i < factoryCEs.length; i++) {
IConfigurationElement factoryCE = factoryCEs[i];
String id = factoryCE.getAttribute("id");
DeviceFilterFactoryProxy factory = new DeviceFilterFactoryProxy(factoryCE);
registerDeviceFilterFactory(id, factory);
}
}
private void registerDeviceFilterFactory(String id, IDeviceFilterFactory factory) {
if (factories.containsKey(id)) {
throw new IllegalStateException("Id already used");
}
factories.put(id, factory);
}
private void installResourceListener() {
ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.PRE_BUILD);
}
private void deinstallResourceListener() {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
}
/**
* <p>Returns an <code>IDeviceFilterFactory</code>.</p>
* <p>Examples of <code>IDeviceFilterFactories</code> are
* <code>ConstantFilterFactory</code> and <code>VenderFilterFactory</code>.
* @param factoryId
* @return
*/
public IDeviceFilterFactory getDeviceFilterFactory(String factoryId) {
if (factoryId == null) {
return null;
}
// Kind of an IElementFactory, but without the UI deps.
return factories.get(factoryId);
}
public IProcessConsole createConsole(String consoleName) {
if (isHeadless) {
return new LogProcessConsole(consoleName);
} else {
return ideProcessConsoleProvider == null ? new LogProcessConsole(consoleName) : ideProcessConsoleProvider.get(consoleName);
}
}
public IEmulatorLauncher getEmulatorLauncher(String launcherId) {
return launchers.get(launcherId);
}
public Set<String> getEmulatorLauncherIds() {
return Collections.unmodifiableSet(launchers.keySet());
}
public IUpdater getUpdater() {
if (!updaterInitialized) {
IExtensionRegistry registry = Platform.getExtensionRegistry();
IConfigurationElement[] elements = registry
.getConfigurationElementsFor("com.mobilesorcery.sdk.updater");
if (elements.length > 0) {
try {
updater = (IUpdater) elements[0]
.createExecutableExtension("implementation");
} catch (CoreException e) {
getLog().log(e.getStatus());
}
}
updaterInitialized = true;
}
return updater;
}
private void disposeUpdater() {
if (updater != null) {
updater.dispose();
}
}
private void checkAutoUpdate() {
if (CoreMoSyncPlugin.isHeadless()) {
return;
}
String[] args = Platform.getApplicationArgs();
if (suppressUpdating(args)) {
return;
}
IUpdater updater = getUpdater();
if (updater != null) {
updater.update(false);
}
}
private boolean suppressUpdating(String[] args) {
for (int i = 0; i < args.length; i++) {
if ("-suppress-updates".equals(args[i])) {
return true;
}
}
return false;
}
/**
* <p>Returns the (single) emulator process manager</p>
* @return
*/
public EmulatorProcessManager getEmulatorProcessManager() {
return emulatorProcessManager;
}
/**
* INTERNAL: Clients should not call this method.
*/
public void setIDEProcessConsoleProvider(IProvider<IProcessConsole, String> ideProcessConsoleProvider) {
// I'm lazy - Instead of extension points...
this.ideProcessConsoleProvider = ideProcessConsoleProvider;
}
public void propertyChange(PropertyChangeEvent event) {
if (MoSyncTool.MOSYNC_HOME_PREF.equals(event.getProperty()) || MoSyncTool.MO_SYNC_HOME_FROM_ENV_PREF.equals(event.getProperty())) {
initPanicErrorMessages();
}
}
/**
* Tries to derive a mosync project from whatever object is passed
* as the <code>receiver</code>; this method will accept <code>List</code>s,
* <code>IAdaptable</code>s, <code>IResource</code>s, as well as <code>IStructuredSelection</code>s
* and then if the project
* associated with these is compatible with a MoSyncProject, return that project.
*/
// Should it be here?
public MoSyncProject extractProject(Object receiver) {
if (receiver instanceof IStructuredSelection) {
return extractProject(((IStructuredSelection) receiver).toList());
}
if (receiver instanceof IAdaptable) {
receiver = ((IAdaptable) receiver).getAdapter(IResource.class);
}
if (receiver instanceof List) {
if (((List)(receiver)).size() == 0) {
return null;
}
return extractProject(((List)receiver).get(0));
}
if(receiver == null) {
return null;
}
if (receiver instanceof IResource) {
IProject project = ((IResource)receiver).getProject();
try {
return MoSyncNature.isCompatible(project) ? MoSyncProject.create(project) : null;
} catch (CoreException e) {
return null;
}
}
return null;
}
public void resourceChanged(IResourceChangeEvent event) {
if (event.getType() == IResourceChangeEvent.PRE_DELETE) {
IResource resource = event.getResource();
IProject project = (resource != null && resource.getType() == IResource.PROJECT) ? (IProject) resource : null;
MoSyncProject mosyncProject = MoSyncProject.create(project);
if (mosyncProject != null) {
// So we do not keep any old references to this project
mosyncProject.dispose();
- // And we make sure to clear the privileged access state
- PrivilegedAccess.getInstance().grantAccess(mosyncProject, false);
}
} else if (event.getType() == IResourceChangeEvent.PRE_BUILD && event.getBuildKind() != IncrementalProjectBuilder.CLEAN_BUILD && event.getBuildKind() != IncrementalProjectBuilder.AUTO_BUILD) {
Object source = event.getSource();
ArrayList<IResource> mosyncProjects = new ArrayList<IResource>();
IProject[] projects = null;
if (source instanceof IWorkspace) {
projects = ((IWorkspace) source).getRoot().getProjects();
} else if (source instanceof IProject) {
projects = new IProject[] { (IProject) source };
}
for (int i = 0; projects != null && i < projects.length; i++) {
IProject project = projects[i];
try {
if (MoSyncNature.isCompatible(project)) {
mosyncProjects.add(projects[i]);
}
} catch (CoreException e) {
CoreMoSyncPlugin.getDefault().log(e);
}
}
IJobManager jm = Job.getJobManager();
Job currentJob = jm.currentJob();
if (!MoSyncBuilder.saveAllEditors(mosyncProjects)) {
// If this thread is a build job, then cancel.
// TODO: Could this somewhere or some day cease to work!
if (currentJob != null) {
currentJob.cancel();
}
}
}
}
public String[] getBuildConfigurationTypes() {
return buildConfigurationTypes;
}
/**
* <p>Returns a working copy of an <code>IApplicationPermissions</code>
* with default permissions.</p>
* @param project
* @return
*/
public IApplicationPermissions getDefaultPermissions(MoSyncProject project) {
return ApplicationPermissions.getDefaultPermissions(project);
}
/**
* Logs a specified method ONCE
* @param e
* @param token Used to distinguish the source of log messages
*/
public void logOnce(Exception e, String token) {
Integer logCount = logCounts.get(token);
if (logCount == null) {
logCount = 0;
}
if (logCount < 1) {
log(e);
}
logCount++;
logCounts.put(token, logCount);
}
/**
* <p>Returns a secure property. If not running
* in headless mode, this may entail launching [master] password dialogs, etc.</p>
* <p>This method makes use of the internal eclipse secure storage.
* @param key
* @return
* @throws StorageException
*/
public String getSecureProperty(String key, String def) throws StorageException {
return SecurePreferencesFactory.getDefault().node(SECURE_ROOT_NODE).get(key, def);
}
public void setSecureProperty(String key, String value) throws StorageException {
SecurePreferencesFactory.getDefault().node(SECURE_ROOT_NODE).put(key, value, true);
}
}
| true | true | public void resourceChanged(IResourceChangeEvent event) {
if (event.getType() == IResourceChangeEvent.PRE_DELETE) {
IResource resource = event.getResource();
IProject project = (resource != null && resource.getType() == IResource.PROJECT) ? (IProject) resource : null;
MoSyncProject mosyncProject = MoSyncProject.create(project);
if (mosyncProject != null) {
// So we do not keep any old references to this project
mosyncProject.dispose();
// And we make sure to clear the privileged access state
PrivilegedAccess.getInstance().grantAccess(mosyncProject, false);
}
} else if (event.getType() == IResourceChangeEvent.PRE_BUILD && event.getBuildKind() != IncrementalProjectBuilder.CLEAN_BUILD && event.getBuildKind() != IncrementalProjectBuilder.AUTO_BUILD) {
Object source = event.getSource();
ArrayList<IResource> mosyncProjects = new ArrayList<IResource>();
IProject[] projects = null;
if (source instanceof IWorkspace) {
projects = ((IWorkspace) source).getRoot().getProjects();
} else if (source instanceof IProject) {
projects = new IProject[] { (IProject) source };
}
for (int i = 0; projects != null && i < projects.length; i++) {
IProject project = projects[i];
try {
if (MoSyncNature.isCompatible(project)) {
mosyncProjects.add(projects[i]);
}
} catch (CoreException e) {
CoreMoSyncPlugin.getDefault().log(e);
}
}
IJobManager jm = Job.getJobManager();
Job currentJob = jm.currentJob();
if (!MoSyncBuilder.saveAllEditors(mosyncProjects)) {
// If this thread is a build job, then cancel.
// TODO: Could this somewhere or some day cease to work!
if (currentJob != null) {
currentJob.cancel();
}
}
}
}
| public void resourceChanged(IResourceChangeEvent event) {
if (event.getType() == IResourceChangeEvent.PRE_DELETE) {
IResource resource = event.getResource();
IProject project = (resource != null && resource.getType() == IResource.PROJECT) ? (IProject) resource : null;
MoSyncProject mosyncProject = MoSyncProject.create(project);
if (mosyncProject != null) {
// So we do not keep any old references to this project
mosyncProject.dispose();
}
} else if (event.getType() == IResourceChangeEvent.PRE_BUILD && event.getBuildKind() != IncrementalProjectBuilder.CLEAN_BUILD && event.getBuildKind() != IncrementalProjectBuilder.AUTO_BUILD) {
Object source = event.getSource();
ArrayList<IResource> mosyncProjects = new ArrayList<IResource>();
IProject[] projects = null;
if (source instanceof IWorkspace) {
projects = ((IWorkspace) source).getRoot().getProjects();
} else if (source instanceof IProject) {
projects = new IProject[] { (IProject) source };
}
for (int i = 0; projects != null && i < projects.length; i++) {
IProject project = projects[i];
try {
if (MoSyncNature.isCompatible(project)) {
mosyncProjects.add(projects[i]);
}
} catch (CoreException e) {
CoreMoSyncPlugin.getDefault().log(e);
}
}
IJobManager jm = Job.getJobManager();
Job currentJob = jm.currentJob();
if (!MoSyncBuilder.saveAllEditors(mosyncProjects)) {
// If this thread is a build job, then cancel.
// TODO: Could this somewhere or some day cease to work!
if (currentJob != null) {
currentJob.cancel();
}
}
}
}
|
diff --git a/src/com/allplayers/android/PhotoPager.java b/src/com/allplayers/android/PhotoPager.java
index c45d44c..fdf9cfd 100644
--- a/src/com/allplayers/android/PhotoPager.java
+++ b/src/com/allplayers/android/PhotoPager.java
@@ -1,225 +1,225 @@
package com.allplayers.android;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.util.LruCache;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import com.allplayers.android.activities.AllplayersSherlockActivity;
import com.allplayers.objects.PhotoData;
import com.allplayers.rest.RestApiV1;
import com.devspark.sidenavigation.SideNavigationView;
import com.devspark.sidenavigation.SideNavigationView.Mode;
public class PhotoPager extends AllplayersSherlockActivity {
private ViewPager mViewPager;
private PhotoPagerAdapter mPhotoAdapter;
private PhotoData mCurrentPhoto;
private int mCurrentPhotoIndex;
/**
* Called when the activity is first created, this sets up some variables,
* creates the Action Bar, and sets up the Side Navigation Menu.
* @param savedInstanceState: Saved data from the last instance of the
* activity.
* @TODO The side navigation menu does NOT work due to conflicting views.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
if (savedInstanceState != null) {
mCurrentPhotoIndex = savedInstanceState.getInt("photoToStart");
}
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_pager);
mCurrentPhoto = (new Router(this)).getIntentPhoto();
mViewPager = new ViewPager(this);
mPhotoAdapter = new PhotoPagerAdapter(this, mCurrentPhoto);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setAdapter(mPhotoAdapter);
mViewPager.setCurrentItem(mCurrentPhotoIndex);
actionbar.setTitle(getIntent().getStringExtra("album title"));
sideNavigationView = (SideNavigationView)findViewById(R.id.side_navigation_view);
sideNavigationView.setMenuItems(R.menu.side_navigation_menu);
sideNavigationView.setMenuClickCallback(this);
sideNavigationView.setMode(Mode.LEFT);
}
/**
* Called before placing the activity in a background state. Saves the
* instance data for the activity to be used the next time onCreate() is
* called.
* @param icicle: The bundle to add to.
*/
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
mCurrentPhotoIndex = mViewPager.getCurrentItem();
icicle.putInt("photoToStart", mCurrentPhotoIndex);
}
/**
* @TODO EDIT ME
*/
public class PhotoPagerAdapter extends PagerAdapter {
private LruCache<String, Bitmap> mImageCache;
private Context mContext;
private List<PhotoData> photos;
/**
* @TODO EDIT ME
* @param context:
* @param item:
*/
public PhotoPagerAdapter(Context context, PhotoData item) {
mContext = context;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
mImageCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
- return bitmap.getByteCount() / 1024;
+ return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024;
}
};
photos = new ArrayList<PhotoData>();
PhotoData temp = item;
while (temp.previousPhoto() != null) {
photos.add(0, temp.previousPhoto());
temp = temp.previousPhoto();
}
if (mCurrentPhotoIndex == 0) {
mCurrentPhotoIndex = photos.size();
}
photos.add(item);
temp = item;
while (temp.nextPhoto() != null) {
photos.add(temp.nextPhoto());
temp = temp.nextPhoto();
}
}
/**
* @TODO EDIT ME
* @param collection:
* @param position:
*/
@Override
public Object instantiateItem(View collection, int position) {
ImageView image = new ImageView(mContext);
image.setImageResource(R.drawable.backgroundstate);
if (mImageCache.get(position+"") != null) {
image.setImageBitmap(mImageCache.get(position+""));
((ViewPager) collection).addView(image, 0);
return image;
}
new GetRemoteImageTask(image, position).execute(photos.get(position).getPhotoFull());
((ViewPager) collection).addView(image, 0);
return image;
}
/**
* @TODO EDIT ME
* @param container:
* @param position:
* @param object:
*/
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
/**
* @TODO Returns the size of the list of photos.
*/
@Override
public int getCount() {
return photos.size();
}
/**
* @TODO EDIT ME
* @param view:
* @param obj:
*/
@Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
/**
* Get's a user's image using a rest call and displays it.
*/
public class GetRemoteImageTask extends AsyncTask<Object, Void, Bitmap> {
private final WeakReference<ImageView> viewReference;
private int index;
GetRemoteImageTask(ImageView im, int ind) {
viewReference = new WeakReference<ImageView>(im);
index = ind;
}
@Override
protected void onPreExecute() {
((Activity) mContext).setProgressBarIndeterminateVisibility(true);
}
/**
* Gets the requested image using a REST call.
* @param photoUrl: The URL of the photo to fetch.
*/
protected Bitmap doInBackground(Object... photoUrl) {
Bitmap b = RestApiV1.getRemoteImage((String) photoUrl[0]);
mImageCache.put(index+"", b);
return b;
}
/**
* Adds the fetched image to an array of the album's images.
* @param image: The image to be added.
*/
protected void onPostExecute(Bitmap bm) {
((Activity) mContext).setProgressBarIndeterminateVisibility(false);
ImageView imageView = viewReference.get();
if( imageView != null ) {
imageView.setImageBitmap(bm);
}
}
}
}
}
| true | true | public PhotoPagerAdapter(Context context, PhotoData item) {
mContext = context;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
mImageCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
photos = new ArrayList<PhotoData>();
PhotoData temp = item;
while (temp.previousPhoto() != null) {
photos.add(0, temp.previousPhoto());
temp = temp.previousPhoto();
}
if (mCurrentPhotoIndex == 0) {
mCurrentPhotoIndex = photos.size();
}
photos.add(item);
temp = item;
while (temp.nextPhoto() != null) {
photos.add(temp.nextPhoto());
temp = temp.nextPhoto();
}
}
| public PhotoPagerAdapter(Context context, PhotoData item) {
mContext = context;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
mImageCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024;
}
};
photos = new ArrayList<PhotoData>();
PhotoData temp = item;
while (temp.previousPhoto() != null) {
photos.add(0, temp.previousPhoto());
temp = temp.previousPhoto();
}
if (mCurrentPhotoIndex == 0) {
mCurrentPhotoIndex = photos.size();
}
photos.add(item);
temp = item;
while (temp.nextPhoto() != null) {
photos.add(temp.nextPhoto());
temp = temp.nextPhoto();
}
}
|
diff --git a/framework/freedomotic/src/it/freedomotic/bus/AbstractBusConnector.java b/framework/freedomotic/src/it/freedomotic/bus/AbstractBusConnector.java
index 8e581954..fa417746 100644
--- a/framework/freedomotic/src/it/freedomotic/bus/AbstractBusConnector.java
+++ b/framework/freedomotic/src/it/freedomotic/bus/AbstractBusConnector.java
@@ -1,105 +1,105 @@
/*Copyright 2009 Enrico Nicoletti
eMail: [email protected]
This file is part of Freedomotic.
Freedomotic is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
any later version.
Freedomotic 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 EventEngine; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package it.freedomotic.bus;
import it.freedomotic.app.Freedomotic;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
/**
*
* @author enrico
*/
public class AbstractBusConnector {
protected static final String DEFAULT_USER = "user";
protected static final String DEFAULT_BROKER = "vm://freedomotic";
protected static final String DEFAULT_PASSWORD = "password";
protected Connection connection;
protected MessageConsumer receiver;
protected MessageProducer sender;
private static Session sharedSession;
private static Session unlistenedSession;
private static MessageProducer emptySharedWriter;
private static final BrokerService BROKER = new BrokerService();
public AbstractBusConnector() {
connect(DEFAULT_BROKER, DEFAULT_USER, DEFAULT_PASSWORD);
}
private void connect(String brokerString, String username, String password) {
//create a connection
if (emptySharedWriter == null) { //not already connected to the bus
try {
//create an embedded messaging broker
BROKER.setBrokerName("freedomotic");
//use always 0.0.0.0 not localhost. localhost allows connections
//only on the local machine not from LAN IPs
BROKER.addConnector("stomp://0.0.0.0:61666");
// //websocket connector for javascript apps
-// broker.addConnector("ws://0.0.0.0:61614");
+ BROKER.addConnector("ws://0.0.0.0:61614");
BROKER.setPersistent(false); //we don't need to save messages on disk
//start the broker
BROKER.start();
//connect to the embedded broker defined above
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(Freedomotic.config.getStringProperty("vm://freedomotic", DEFAULT_BROKER));
//tuned for performances http://activemq.apache.org/performance-tuning.html
factory.setUseAsyncSend(true);
factory.setOptimizeAcknowledge(true);
factory.setAlwaysSessionAsync(false);
connection = factory.createConnection(username, password);
sharedSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
unlistenedSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); //an unlistened session
emptySharedWriter = unlistenedSession.createProducer(null); //a shared bus writer for all freedomotic classes
emptySharedWriter.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
new StompDispatcher(); //just for testing, don't mind it
connection.start();
} catch (JMSException jMSException) {
Freedomotic.logger.severe(Freedomotic.getStackTraceInfo(jMSException));
} catch (Exception ex) {
Logger.getLogger(AbstractBusConnector.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
protected Session getBusUnlistenedSession() {
return unlistenedSession;
}
protected Session getBusSharedSession() {
return sharedSession;
}
protected MessageProducer getBusSharedWriter() {
return emptySharedWriter;
}
public void disconnect() {
try {
connection.close();
} catch (JMSException jMSException) {
}
}
}
| true | true | private void connect(String brokerString, String username, String password) {
//create a connection
if (emptySharedWriter == null) { //not already connected to the bus
try {
//create an embedded messaging broker
BROKER.setBrokerName("freedomotic");
//use always 0.0.0.0 not localhost. localhost allows connections
//only on the local machine not from LAN IPs
BROKER.addConnector("stomp://0.0.0.0:61666");
// //websocket connector for javascript apps
// broker.addConnector("ws://0.0.0.0:61614");
BROKER.setPersistent(false); //we don't need to save messages on disk
//start the broker
BROKER.start();
//connect to the embedded broker defined above
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(Freedomotic.config.getStringProperty("vm://freedomotic", DEFAULT_BROKER));
//tuned for performances http://activemq.apache.org/performance-tuning.html
factory.setUseAsyncSend(true);
factory.setOptimizeAcknowledge(true);
factory.setAlwaysSessionAsync(false);
connection = factory.createConnection(username, password);
sharedSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
unlistenedSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); //an unlistened session
emptySharedWriter = unlistenedSession.createProducer(null); //a shared bus writer for all freedomotic classes
emptySharedWriter.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
new StompDispatcher(); //just for testing, don't mind it
connection.start();
} catch (JMSException jMSException) {
Freedomotic.logger.severe(Freedomotic.getStackTraceInfo(jMSException));
} catch (Exception ex) {
Logger.getLogger(AbstractBusConnector.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| private void connect(String brokerString, String username, String password) {
//create a connection
if (emptySharedWriter == null) { //not already connected to the bus
try {
//create an embedded messaging broker
BROKER.setBrokerName("freedomotic");
//use always 0.0.0.0 not localhost. localhost allows connections
//only on the local machine not from LAN IPs
BROKER.addConnector("stomp://0.0.0.0:61666");
// //websocket connector for javascript apps
BROKER.addConnector("ws://0.0.0.0:61614");
BROKER.setPersistent(false); //we don't need to save messages on disk
//start the broker
BROKER.start();
//connect to the embedded broker defined above
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(Freedomotic.config.getStringProperty("vm://freedomotic", DEFAULT_BROKER));
//tuned for performances http://activemq.apache.org/performance-tuning.html
factory.setUseAsyncSend(true);
factory.setOptimizeAcknowledge(true);
factory.setAlwaysSessionAsync(false);
connection = factory.createConnection(username, password);
sharedSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
unlistenedSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); //an unlistened session
emptySharedWriter = unlistenedSession.createProducer(null); //a shared bus writer for all freedomotic classes
emptySharedWriter.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
new StompDispatcher(); //just for testing, don't mind it
connection.start();
} catch (JMSException jMSException) {
Freedomotic.logger.severe(Freedomotic.getStackTraceInfo(jMSException));
} catch (Exception ex) {
Logger.getLogger(AbstractBusConnector.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
diff --git a/src/edu/kit/asa/alloy2key/key/TermUnary.java b/src/edu/kit/asa/alloy2key/key/TermUnary.java
index 9bca586..fa919dd 100644
--- a/src/edu/kit/asa/alloy2key/key/TermUnary.java
+++ b/src/edu/kit/asa/alloy2key/key/TermUnary.java
@@ -1,86 +1,86 @@
/**
* Created on 13.02.2011
*/
package edu.kit.asa.alloy2key.key;
import java.util.List;
import edu.mit.csail.sdg.alloy4.Pair;
/**
* term constructed from a unary operator
*
* @author Ulrich Geilmann
*
*/
public class TermUnary extends Term {
public enum Op {
NOT
};
// the operator
private Op operator;
// the sub term
private Term sub;
public TermUnary (Op op, Term sub) {
this.operator = op;
this.sub = sub;
}
/** {@inheritDoc} */
@Override
public List<Pair<String,String>> getQuantVars() {
return sub.getQuantVars();
}
/** {@inheritDoc} */
@Override
public String toString() {
switch (operator) {
case NOT:
- return comment == null ? "" : "; " + this.comment + "\n" +
+ return (comment == null ? "" : "; " + this.comment + "\n") +
"(not "+sub.toString()+")"; // smt ok
default:
return "";
}
}
/** {@inheritDoc} */
@Override
public String toStringTaclet() { // todo: remove taclets
switch (operator) {
case NOT:
return "!("+sub.toStringTaclet()+")";
default:
return "";
}
}
/** {@inheritDoc} */
@Override
public boolean occurs (String id) {
return sub.occurs(id);
}
/** {@inheritDoc} */
@Override
public Term substitute (String a, String b) {
return new TermUnary(operator,sub.substitute(a,b));
}
/** {@inheritDoc}
* @throws ModelException */
@Override
public Term fill(Term t) throws ModelException {
return new TermUnary(operator,sub.fill(t));
}
/** {@inheritDoc} */
@Override
public boolean isInt() {
return false;
}
}
| true | true | public String toString() {
switch (operator) {
case NOT:
return comment == null ? "" : "; " + this.comment + "\n" +
"(not "+sub.toString()+")"; // smt ok
default:
return "";
}
}
| public String toString() {
switch (operator) {
case NOT:
return (comment == null ? "" : "; " + this.comment + "\n") +
"(not "+sub.toString()+")"; // smt ok
default:
return "";
}
}
|
diff --git a/app/external/InstagramParser.java b/app/external/InstagramParser.java
index 1b22a28..e60b282 100644
--- a/app/external/InstagramParser.java
+++ b/app/external/InstagramParser.java
@@ -1,374 +1,374 @@
package external;
import static play.libs.Json.toJson;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import data.Images;
import geometry.Geometry;
import geometry.Point;
import models.*;
public class InstagramParser {
/**
* This method is used to get the pois from a service and return a GeoJSON
* document with the data retrieved given a lnggitude, latitude and a radius
* in meters.
*
* @param id
* The id of the service
* @param lng
* The lnggitude
* @param lat
* The latitude
* @param distanceInMeters
* The distance in meters from the lng, lat
* @return The GeoJSON response from the original service response
* @throws Exception
*/
// public static Result getPOIs(String lng1, String lat1,String lng2, String lat2) throws Exception
// {
// List<Feature> features = searchInstaPOIsByBBox(Double.parseDouble(lng1), Double.parseDouble(lat1),
// Double.parseDouble(lng2), Double.parseDouble(lat2));
// return ok(toJson(features));
//
// }
public static Feature getInstaByMediaId(String id) throws Exception
{
String url = "https://api.instagram.com/v1/media/"+id+"?client_id=a80dd450be84452a91527609a4eae97b";
String file = doRequest(url);
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(file);
//TODO: add validation if the response type is not 200 then skip the rest process
if (actualObj.findPath("meta").get("code").toString().equalsIgnoreCase("200")) {
Feature geoJSON = instaToGeoJson(actualObj.findValue("data"));
return geoJSON;
}
else {
return new Feature();
}
}
public static List<Feature> searchInstaPOIsByBBox(double lng1, double lat1,double lng2, double lat2) throws Exception
{
String describeService = "https://api.instagram.com/v1/media/search";
String url = buildRequest(describeService, lng1,lat1,lng2,lat2);
String file = doRequest(url);
//TODO: need to optimize for speed
// return async(
// WS.url(url).get().map(
// new Function<WS.Response, Result>() {
// public Result apply(WS.Response response) {
// return ok(response.asJson());
// }
// }
// )
// );
//return redirect(url);
//return ok(url.toString());
//List<Feature> geoJSON = new Arr
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(file);
// TODO: add validation if the response type is not 200 then skip the
// rest process
if (actualObj.findPath("meta").get("code").toString()
.equalsIgnoreCase("200"))
{
List<Feature> geoJSON = onResponseReceived(actualObj);
return geoJSON;
} else {
return new ArrayList<Feature>();
}
}
public static List<Feature> onResponseReceived(JsonNode json)
{
JsonNode insta_feeds = json.findValue("data");
List<Feature>features = new ArrayList<Feature>();
for (int i = 0; i < insta_feeds.size(); i++)
{
JsonNode childNode = insta_feeds.get(i);
Feature feature = instaToGeoJson(childNode);
features.add(feature);
}
return features;
}
public static List<Feature> searchInstaPOIsByTag(String tag) throws Exception
{
String url = "https://api.instagram.com/v1/tags/"+tag+"/media/recent?client_id=a80dd450be84452a91527609a4eae97b";
String file = doRequest(url);
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(file);
// TODO: add validation if the response type is not 200 then skip the
// rest process
if (actualObj.findPath("meta").get("code").toString()
.equalsIgnoreCase("200"))
{
List<Feature> geoJSON = onResponseReceived(actualObj);
return geoJSON;
} else {
return new ArrayList<Feature>();
}
}
/**
* @param jsonNode
* @return
*/
private static Feature instaToGeoJson(JsonNode jsonNode)
{
//String type = jsonNode.findValue("type").asText();
String id = jsonNode.get("id").asText();
JsonNode location = jsonNode.findValue("location");
Geometry geometry;
//check if location node is not null
if (!location.isNull()) {
double latitude = location.findValue("latitude").asDouble();
double longitude = location.findValue("longitude").asDouble();
geometry = new Point(longitude, latitude);
}
else {
geometry = new Point();
}
Feature feature = new Feature(geometry);
feature.id = id;
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("created_time", jsonNode.get("created_time").asLong());
properties.put("source_type", "Instagram");
//save url to both standard and instagram image
JsonNode image = jsonNode.findPath("images");
properties.put("images", image);
JsonNode caption = jsonNode.findPath("caption");
properties.put("description", caption.findValue("text"));
- if (caption.findValue("text").asText() != null) {
+ if (!(caption.isNull())) {
String description = caption.findValue("text").asText();
//Formulate the label of the POI, using first sentence in the description
String delims = "[.,?!]+";
String[] tokens = description.split(delims);
String name = tokens[0];
properties.put("name", name);
}
JsonNode tags = jsonNode.findValue("tags");
properties.put("tags", tags);
JsonNode user = jsonNode.findValue("user");
properties.put("user", user);
feature.setProperties(properties);
//Save instagram features to local db
/*if (Feature.find().byId(id) == null) {
feature.insert();
}*/
return feature;
}
public static String buildRequest(String describeService, double lng1,
double lat1, double lng2, double lat2) throws UnsupportedEncodingException
{
double center[] = new double[2];
center[0] = (lat1 + lat2) / 2;
center[1] = (lng1 + lng2) / 2;
double radius_outer_circle_of_reactangle = radius(lat1,lng1,lat2,lng2);
HashMap<String, String> params = new HashMap<String, String>();
params.put(Param.LAT, String.valueOf(center[0]));
params.put(Param.LNG, String.valueOf(center[1]));
params.put(Param.DIST, String.valueOf(radius_outer_circle_of_reactangle));
params.put(Param.CLIENTID, "a80dd450be84452a91527609a4eae97b");
//Set<String> keys = params.keySet();
// construct URL
StringBuffer paramsBuffer = new StringBuffer();
if (params.keySet().size() > 0) {
boolean isFirstParam = true;
for (Iterator<String> keys = params.keySet().iterator(); keys.hasNext();) {
String key = (String) keys.next();
if (isFirstParam) {
paramsBuffer.append("?" + key);
isFirstParam = false;
} else {
paramsBuffer.append("&" + key);
}
paramsBuffer.append("="
+ URLEncoder.encode(
(String) params.get(key),
"UTF-8"));
}
}
StringBuffer url = new StringBuffer();
url.append(describeService);
url.append(paramsBuffer);
return url.toString();
}
/**
* Calculates the area of the extent
*
* @return The radius of outer circle of BoundingBox
*/
public static double radius(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 6371; // km
double distant = Math.acos(Math.sin(lat1)*Math.sin(lat2) +
Math.cos(lat1)*Math.cos(lat2) *
Math.cos(lng2-lng1)) * earthRadius;
return distant;
}
/**
* Calculates the width of the extent
*
* @return The width of the extent
*/
public static double getWidth(double maxX, double minX) {
return Math.abs(maxX - minX);
}
/**
* Calculates the height of the extent
*
* @return The height of the extent
*/
public static double getHeight(double maxY, double minY) {
return Math.abs(maxY - minY);
}
/**
* Calculates the area of the extent
*
* @return The area
*/
public double area(double maxX, double minX,double maxY, double minY) {
return this.getWidth(maxX,minX) * this.getHeight(maxY,minY);
}
/**
* Calls
* {@link Downloader#downloadFromUrl(String, es.prodevelop.gvsig.mini.utiles.Cancellable)}
*
* @param url
* The url to request to
* @return The data downloaded
* @throws Exception
*/
public static String doRequest(String url) throws Exception {
// hacer peticion en segundo plano
Downloader d = new Downloader();
System.out.println(url);
d.downloadFromUrl(url);
return new String(d.getData());
}
}
| true | true | private static Feature instaToGeoJson(JsonNode jsonNode)
{
//String type = jsonNode.findValue("type").asText();
String id = jsonNode.get("id").asText();
JsonNode location = jsonNode.findValue("location");
Geometry geometry;
//check if location node is not null
if (!location.isNull()) {
double latitude = location.findValue("latitude").asDouble();
double longitude = location.findValue("longitude").asDouble();
geometry = new Point(longitude, latitude);
}
else {
geometry = new Point();
}
Feature feature = new Feature(geometry);
feature.id = id;
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("created_time", jsonNode.get("created_time").asLong());
properties.put("source_type", "Instagram");
//save url to both standard and instagram image
JsonNode image = jsonNode.findPath("images");
properties.put("images", image);
JsonNode caption = jsonNode.findPath("caption");
properties.put("description", caption.findValue("text"));
if (caption.findValue("text").asText() != null) {
String description = caption.findValue("text").asText();
//Formulate the label of the POI, using first sentence in the description
String delims = "[.,?!]+";
String[] tokens = description.split(delims);
String name = tokens[0];
properties.put("name", name);
}
JsonNode tags = jsonNode.findValue("tags");
properties.put("tags", tags);
JsonNode user = jsonNode.findValue("user");
properties.put("user", user);
feature.setProperties(properties);
//Save instagram features to local db
/*if (Feature.find().byId(id) == null) {
feature.insert();
}*/
| private static Feature instaToGeoJson(JsonNode jsonNode)
{
//String type = jsonNode.findValue("type").asText();
String id = jsonNode.get("id").asText();
JsonNode location = jsonNode.findValue("location");
Geometry geometry;
//check if location node is not null
if (!location.isNull()) {
double latitude = location.findValue("latitude").asDouble();
double longitude = location.findValue("longitude").asDouble();
geometry = new Point(longitude, latitude);
}
else {
geometry = new Point();
}
Feature feature = new Feature(geometry);
feature.id = id;
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("created_time", jsonNode.get("created_time").asLong());
properties.put("source_type", "Instagram");
//save url to both standard and instagram image
JsonNode image = jsonNode.findPath("images");
properties.put("images", image);
JsonNode caption = jsonNode.findPath("caption");
properties.put("description", caption.findValue("text"));
if (!(caption.isNull())) {
String description = caption.findValue("text").asText();
//Formulate the label of the POI, using first sentence in the description
String delims = "[.,?!]+";
String[] tokens = description.split(delims);
String name = tokens[0];
properties.put("name", name);
}
JsonNode tags = jsonNode.findValue("tags");
properties.put("tags", tags);
JsonNode user = jsonNode.findValue("user");
properties.put("user", user);
feature.setProperties(properties);
//Save instagram features to local db
/*if (Feature.find().byId(id) == null) {
feature.insert();
}*/
|
diff --git a/Main.java b/Main.java
index a9012d0..d669e6e 100644
--- a/Main.java
+++ b/Main.java
@@ -1,43 +1,45 @@
import java.io.*;
import java.util.*;
class Main {
Scanner sc;
public Main()
{
sc = new Scanner(System.in);
}
void run()
{
// read 'find $C_i$ to $C_j$ clusters'
// read '$n$ points'
// read '$x$ $y$' for each point
sc.next(); // find
int ci = sc.nextInt();
- sc.next(); // to
- int cj = sc.nextInt();
- sc.next(); // clusters
+ int cj = ci;
+ if (sc.next().equals("to")) { // otherwise, it is clusters
+ cj = sc.nextInt();
+ sc.next(); // clusters
+ }
int n = sc.nextInt();
sc.next(); // points
int[] points_x = new int[n];
int[] points_y = new int[n];
for (int i = 0; i < n; i++) {
points_x[i] = sc.nextInt();
points_y[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
System.out.println(points_x[i] + " " + points_y[i] + " " + (i % cj));
}
}
public static void main(String args[])
{
new Main().run();
}
}
| true | true | void run()
{
// read 'find $C_i$ to $C_j$ clusters'
// read '$n$ points'
// read '$x$ $y$' for each point
sc.next(); // find
int ci = sc.nextInt();
sc.next(); // to
int cj = sc.nextInt();
sc.next(); // clusters
int n = sc.nextInt();
sc.next(); // points
int[] points_x = new int[n];
int[] points_y = new int[n];
for (int i = 0; i < n; i++) {
points_x[i] = sc.nextInt();
points_y[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
System.out.println(points_x[i] + " " + points_y[i] + " " + (i % cj));
}
}
| void run()
{
// read 'find $C_i$ to $C_j$ clusters'
// read '$n$ points'
// read '$x$ $y$' for each point
sc.next(); // find
int ci = sc.nextInt();
int cj = ci;
if (sc.next().equals("to")) { // otherwise, it is clusters
cj = sc.nextInt();
sc.next(); // clusters
}
int n = sc.nextInt();
sc.next(); // points
int[] points_x = new int[n];
int[] points_y = new int[n];
for (int i = 0; i < n; i++) {
points_x[i] = sc.nextInt();
points_y[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
System.out.println(points_x[i] + " " + points_y[i] + " " + (i % cj));
}
}
|
diff --git a/spring-integration-redis/src/main/java/org/springframework/integration/redis/inbound/RedisQueueMessageDrivenEndpoint.java b/spring-integration-redis/src/main/java/org/springframework/integration/redis/inbound/RedisQueueMessageDrivenEndpoint.java
index 8435439974..1d7b3a7ee8 100644
--- a/spring-integration-redis/src/main/java/org/springframework/integration/redis/inbound/RedisQueueMessageDrivenEndpoint.java
+++ b/spring-integration-redis/src/main/java/org/springframework/integration/redis/inbound/RedisQueueMessageDrivenEndpoint.java
@@ -1,301 +1,306 @@
/*
* Copyright 2013 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.redis.inbound;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.MessagingException;
import org.springframework.integration.channel.MessagePublishingErrorHandler;
import org.springframework.integration.endpoint.MessageProducerSupport;
import org.springframework.integration.redis.event.RedisExceptionEvent;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.support.channel.BeanFactoryChannelResolver;
import org.springframework.integration.util.ErrorHandlingTaskExecutor;
import org.springframework.jmx.export.annotation.ManagedMetric;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.util.Assert;
/**
* @author Mark Fisher
* @author Gunnar Hillert
* @author Artem Bilan
* @since 3.0
*/
@ManagedResource
public class RedisQueueMessageDrivenEndpoint extends MessageProducerSupport implements ApplicationEventPublisherAware {
public static final long DEFAULT_RECEIVE_TIMEOUT = 1000;
public static final long DEFAULT_RECOVERY_INTERVAL = 5000;
private final BoundListOperations<String, byte[]> boundListOperations;
private volatile ApplicationEventPublisher applicationEventPublisher;
private volatile MessageChannel errorChannel;
private volatile Executor taskExecutor;
private volatile RedisSerializer<?> serializer = new JdkSerializationRedisSerializer();
private volatile boolean expectMessage = false;
private volatile long receiveTimeout = DEFAULT_RECEIVE_TIMEOUT;
private volatile long recoveryInterval = DEFAULT_RECOVERY_INTERVAL;
private volatile boolean active;
private volatile boolean listening;
/**
* @param queueName Must not be an empty String
* @param connectionFactory Must not be null
*/
public RedisQueueMessageDrivenEndpoint(String queueName, RedisConnectionFactory connectionFactory) {
Assert.hasText(queueName, "'queueName' is required");
Assert.notNull(connectionFactory, "'connectionFactory' must not be null");
RedisTemplate<String, byte[]> template = new RedisTemplate<String, byte[]>();
template.setConnectionFactory(connectionFactory);
template.setEnableDefaultSerializer(false);
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
this.boundListOperations = template.boundListOps(queueName);
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void setSerializer(RedisSerializer<?> serializer) {
this.serializer = serializer;
}
/**
* When data is retrieved from the Redis queue, does the returned data represent
* just the payload for a Message, or does the data represent a serialized
* {@link Message}?. {@code expectMessage} defaults to false. This means
* the retrieved data will be used as the payload for a new Spring Integration
* Message. Otherwise, the data is deserialized as Spring Integration
* Message.
*
* @param expectMessage Defaults to false
*/
public void setExpectMessage(boolean expectMessage) {
this.expectMessage = expectMessage;
}
/**
* This timeout (milliseconds) is used when retrieving elements from the queue
* specified by {@link #boundListOperations}.
* <p/>
* If the queue does contain elements, the data is retrieved immediately. However,
* if the queue is empty, the Redis connection is blocked until either an element
* can be retrieved from the queue or until the specified timeout passes.
* <p/>
* A timeout of zero can be used to block indefinitely. If not set explicitly
* the timeout value will default to {@code 1000}
* <p/>
* See also: http://redis.io/commands/brpop
*
* @param receiveTimeout Must be non-negative. Specified in milliseconds.
*/
public void setReceiveTimeout(long receiveTimeout) {
Assert.isTrue(receiveTimeout > 0, "'receiveTimeout' must be > 0.");
this.receiveTimeout = receiveTimeout;
}
public void setTaskExecutor(Executor taskExecutor) {
this.taskExecutor = taskExecutor;
}
@Override
public void setErrorChannel(MessageChannel errorChannel) {
super.setErrorChannel(errorChannel);
this.errorChannel = errorChannel;
}
public void setRecoveryInterval(long recoveryInterval) {
this.recoveryInterval = recoveryInterval;
}
@Override
protected void onInit() {
super.onInit();
if (this.expectMessage) {
Assert.notNull(this.serializer, "'serializer' has to be provided where 'expectMessage == true'.");
}
if (this.taskExecutor == null) {
String beanName = this.getComponentName();
this.taskExecutor = new SimpleAsyncTaskExecutor((beanName == null ? "" : beanName + "-") + this.getComponentType());
}
if (!(this.taskExecutor instanceof ErrorHandlingTaskExecutor) && this.getBeanFactory() != null) {
MessagePublishingErrorHandler errorHandler =
new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(this.getBeanFactory()));
errorHandler.setDefaultErrorChannel(this.errorChannel);
this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, errorHandler);
}
}
@Override
public String getComponentType() {
return "redis:queue-inbound-channel-adapter";
}
@SuppressWarnings("unchecked")
private void popMessageAndSend() {
Message<Object> message = null;
byte[] value = null;
try {
value = this.boundListOperations.rightPop(this.receiveTimeout, TimeUnit.MILLISECONDS);
}
catch (Exception e) {
- logger.error("Failed to execute listening task. Will attempt to resubmit in " + this.recoveryInterval + " milliseconds.", e);
this.listening = false;
- this.sleepBeforeRecoveryAttempt();
- this.publishException(e);
+ if (this.active) {
+ logger.error("Failed to execute listening task. Will attempt to resubmit in " + this.recoveryInterval + " milliseconds.", e);
+ this.publishException(e);
+ this.sleepBeforeRecoveryAttempt();
+ }
+ else {
+ logger.debug("Failed to execute listening task. " + e.getClass() + ": " + e.getMessage());
+ }
return;
}
if (value != null) {
if (this.expectMessage) {
try {
message = (Message<Object>) this.serializer.deserialize(value);
}
catch (Exception e) {
throw new MessagingException("Deserialization of Message failed.", e);
}
}
else {
Object payload = value;
if (this.serializer != null) {
payload = this.serializer.deserialize(value);
}
message = MessageBuilder.withPayload(payload).build();
}
}
if (message != null) {
this.sendMessage(message);
}
}
@Override
protected void doStart() {
if (!this.active) {
this.active = true;
this.restart();
}
}
/**
* Sleep according to the specified recovery interval.
* Called between recovery attempts.
*/
private void sleepBeforeRecoveryAttempt() {
if (this.recoveryInterval > 0) {
try {
Thread.sleep(this.recoveryInterval);
}
catch (InterruptedException e) {
logger.debug("Thread interrupted while sleeping the recovery interval");
}
}
}
private void publishException(Exception e) {
if (this.applicationEventPublisher != null) {
this.applicationEventPublisher.publishEvent(new RedisExceptionEvent(this, e));
}
else {
if (logger.isDebugEnabled()) {
logger.debug("No application event publisher for exception: " + e.getMessage());
}
}
}
private void restart() {
this.taskExecutor.execute(new ListenerTask());
}
@Override
protected void doStop() {
this.active = false;
}
public boolean isListening() {
return listening;
}
/**
* Returns the size of the Queue specified by {@link #boundListOperations}. The queue is
* represented by a Redis list. If the queue does not exist <code>0</code>
* is returned. See also http://redis.io/commands/llen
*
* @return Size of the queue. Never negative.
*/
@ManagedMetric
public long getQueueSize() {
return this.boundListOperations.size();
}
/**
* Clear the Redis Queue specified by {@link #boundListOperations}.
*/
@ManagedOperation
public void clearQueue() {
this.boundListOperations.getOperations().delete(this.boundListOperations.getKey());
}
private class ListenerTask implements Runnable {
@Override
public void run() {
RedisQueueMessageDrivenEndpoint.this.listening = true;
try {
while (RedisQueueMessageDrivenEndpoint.this.active) {
RedisQueueMessageDrivenEndpoint.this.popMessageAndSend();
}
}
finally {
if (RedisQueueMessageDrivenEndpoint.this.active) {
RedisQueueMessageDrivenEndpoint.this.restart();
}
else {
RedisQueueMessageDrivenEndpoint.this.listening = false;
}
}
}
}
}
| false | true | private void popMessageAndSend() {
Message<Object> message = null;
byte[] value = null;
try {
value = this.boundListOperations.rightPop(this.receiveTimeout, TimeUnit.MILLISECONDS);
}
catch (Exception e) {
logger.error("Failed to execute listening task. Will attempt to resubmit in " + this.recoveryInterval + " milliseconds.", e);
this.listening = false;
this.sleepBeforeRecoveryAttempt();
this.publishException(e);
return;
}
if (value != null) {
if (this.expectMessage) {
try {
message = (Message<Object>) this.serializer.deserialize(value);
}
catch (Exception e) {
throw new MessagingException("Deserialization of Message failed.", e);
}
}
else {
Object payload = value;
if (this.serializer != null) {
payload = this.serializer.deserialize(value);
}
message = MessageBuilder.withPayload(payload).build();
}
}
if (message != null) {
this.sendMessage(message);
}
}
| private void popMessageAndSend() {
Message<Object> message = null;
byte[] value = null;
try {
value = this.boundListOperations.rightPop(this.receiveTimeout, TimeUnit.MILLISECONDS);
}
catch (Exception e) {
this.listening = false;
if (this.active) {
logger.error("Failed to execute listening task. Will attempt to resubmit in " + this.recoveryInterval + " milliseconds.", e);
this.publishException(e);
this.sleepBeforeRecoveryAttempt();
}
else {
logger.debug("Failed to execute listening task. " + e.getClass() + ": " + e.getMessage());
}
return;
}
if (value != null) {
if (this.expectMessage) {
try {
message = (Message<Object>) this.serializer.deserialize(value);
}
catch (Exception e) {
throw new MessagingException("Deserialization of Message failed.", e);
}
}
else {
Object payload = value;
if (this.serializer != null) {
payload = this.serializer.deserialize(value);
}
message = MessageBuilder.withPayload(payload).build();
}
}
if (message != null) {
this.sendMessage(message);
}
}
|
diff --git a/src/main/java/org/asciidoc/maven/AsciidoctorMojo.java b/src/main/java/org/asciidoc/maven/AsciidoctorMojo.java
index 7f2ab63..25c4599 100644
--- a/src/main/java/org/asciidoc/maven/AsciidoctorMojo.java
+++ b/src/main/java/org/asciidoc/maven/AsciidoctorMojo.java
@@ -1,89 +1,89 @@
/*
* 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.asciidoc.maven;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
/**
* Basic maven plugin to render asciidoc files using asciidoctor, a ruby port.
*
* Uses jRuby to invoke a small script to process the asciidoc files.
*/
@Mojo(name = "process-asciidoc")
public class AsciidoctorMojo extends AbstractMojo {
@Parameter(property = "sourceDir", defaultValue = "${basedir}/src/asciidoc", required = true)
protected File sourceDirectory;
@Parameter(property = "outputDir", defaultValue = "${project.build.directory}", required = true)
protected File outputDirectory;
@Parameter(property = "backend", defaultValue = "docbook", required = true)
protected String backend;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
final ScriptEngineManager engineManager = new ScriptEngineManager();
final ScriptEngine rubyEngine = engineManager.getEngineByName("jruby");
final Bindings bindings = new SimpleBindings();
bindings.put("srcDir", sourceDirectory.getAbsolutePath());
bindings.put("outputDir", outputDirectory.getAbsolutePath());
bindings.put("backend", backend);
try {
- final InputStream script = AbstractMojo.class.getClassLoader().getResourceAsStream("execute_asciidoctor.rb");
+ final InputStream script = getClass().getClassLoader().getResourceAsStream("execute_asciidoctor.rb");
final InputStreamReader streamReader = new InputStreamReader(script);
rubyEngine.eval(streamReader, bindings);
} catch (ScriptException e) {
getLog().error("Error running ruby script", e);
}
}
public File getSourceDirectory() {
return sourceDirectory;
}
public void setSourceDirectory(File sourceDirectory) {
this.sourceDirectory = sourceDirectory;
}
public File getOutputDirectory() {
return outputDirectory;
}
public void setOutputDirectory(File outputDirectory) {
this.outputDirectory = outputDirectory;
}
public String getBackend() {
return backend;
}
public void setBackend(String backend) {
this.backend = backend;
}
}
| true | true | public void execute() throws MojoExecutionException, MojoFailureException {
final ScriptEngineManager engineManager = new ScriptEngineManager();
final ScriptEngine rubyEngine = engineManager.getEngineByName("jruby");
final Bindings bindings = new SimpleBindings();
bindings.put("srcDir", sourceDirectory.getAbsolutePath());
bindings.put("outputDir", outputDirectory.getAbsolutePath());
bindings.put("backend", backend);
try {
final InputStream script = AbstractMojo.class.getClassLoader().getResourceAsStream("execute_asciidoctor.rb");
final InputStreamReader streamReader = new InputStreamReader(script);
rubyEngine.eval(streamReader, bindings);
} catch (ScriptException e) {
getLog().error("Error running ruby script", e);
}
}
| public void execute() throws MojoExecutionException, MojoFailureException {
final ScriptEngineManager engineManager = new ScriptEngineManager();
final ScriptEngine rubyEngine = engineManager.getEngineByName("jruby");
final Bindings bindings = new SimpleBindings();
bindings.put("srcDir", sourceDirectory.getAbsolutePath());
bindings.put("outputDir", outputDirectory.getAbsolutePath());
bindings.put("backend", backend);
try {
final InputStream script = getClass().getClassLoader().getResourceAsStream("execute_asciidoctor.rb");
final InputStreamReader streamReader = new InputStreamReader(script);
rubyEngine.eval(streamReader, bindings);
} catch (ScriptException e) {
getLog().error("Error running ruby script", e);
}
}
|
diff --git a/WorldWindRad/src/panels/other/ExaggerationPanel.java b/WorldWindRad/src/panels/other/ExaggerationPanel.java
index bc44bdd3..e658edc5 100644
--- a/WorldWindRad/src/panels/other/ExaggerationPanel.java
+++ b/WorldWindRad/src/panels/other/ExaggerationPanel.java
@@ -1,157 +1,158 @@
package panels.other;
import gov.nasa.worldwind.WorldWindow;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import settings.Settings;
public class ExaggerationPanel extends JPanel
{
public ExaggerationPanel(final WorldWindow wwd)
{
super(new GridBagLayout());
GridBagConstraints c;
+ double settingsExaggeration = Settings.get().getVerticalExaggeration();
final JSlider slider = new JSlider(0, 200,
- exaggerationToSlider(Settings.get().getVerticalExaggeration()));
+ exaggerationToSlider(settingsExaggeration));
Dimension size = slider.getPreferredSize();
size.width = 50;
slider.setPreferredSize(size);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
c.weightx = 1;
add(slider, c);
final JLabel label = new JLabel();
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
add(label, c);
class Setter
{
public void set(double exaggeration)
{
label.setText(String
.valueOf(Math.round(exaggeration * 10d) / 10d));
Settings.get().setVerticalExaggeration(exaggeration);
wwd.getSceneController().setVerticalExaggeration(exaggeration);
wwd.redraw();
}
}
final Setter setter = new Setter();
+ setter.set(settingsExaggeration);
final ChangeListener listener = new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
double exaggeration = sliderToExaggeration(slider.getValue());
setter.set(exaggeration);
}
};
slider.addChangeListener(listener);
- listener.stateChanged(null);
JPanel buttons = new JPanel(new GridLayout(1, 0));
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
add(buttons, c);
class ScaleListener implements ActionListener
{
private double exaggeration;
public ScaleListener(double exaggeration)
{
this.exaggeration = exaggeration;
}
public void actionPerformed(ActionEvent e)
{
slider.setValue(exaggerationToSlider(exaggeration));
setter.set(exaggeration);
}
}
JButton button = new JButton("1:1");
button.addActionListener(new ScaleListener(1d));
size = button.getMinimumSize();
size.width = 0;
button.setMinimumSize(size);
buttons.add(button);
button = new JButton("2:1");
button.addActionListener(new ScaleListener(2d));
button.setMinimumSize(size);
buttons.add(button);
button = new JButton("10:1");
button.addActionListener(new ScaleListener(10d));
button.setMinimumSize(size);
buttons.add(button);
/*button = new JButton("100:1");
button.addActionListener(new ScaleListener(100d));
button.setMinimumSize(size);
buttons.add(button);*/
/*final JCheckBox useTerrain = new JCheckBox("Use GA terrain");
useTerrain.setSelected(Settings.get().isUseTerrain());
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
add(useTerrain, c);
useTerrain.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Settings.get().setUseTerrain(useTerrain.isSelected());
LayerList layers = wwd.getModel().getLayers();
Model model = new BasicModel();
model.setLayers(layers);
wwd.setModel(model);
listener.stateChanged(null);
listener.stateChanged(null);
}
});*/
}
//logarithmic vertical exaggeration slider
private int exaggerationToSlider(double exaggeration)
{
double y = exaggeration;
double x = Math.log10(y + (100 - y) / 100);
return (int) (x * 100);
}
private double sliderToExaggeration(int slider)
{
double x = slider / 100d;
double y = Math.pow(10d, x) - (2 - x) / 2;
return y;
}
}
| false | true | public ExaggerationPanel(final WorldWindow wwd)
{
super(new GridBagLayout());
GridBagConstraints c;
final JSlider slider = new JSlider(0, 200,
exaggerationToSlider(Settings.get().getVerticalExaggeration()));
Dimension size = slider.getPreferredSize();
size.width = 50;
slider.setPreferredSize(size);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
c.weightx = 1;
add(slider, c);
final JLabel label = new JLabel();
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
add(label, c);
class Setter
{
public void set(double exaggeration)
{
label.setText(String
.valueOf(Math.round(exaggeration * 10d) / 10d));
Settings.get().setVerticalExaggeration(exaggeration);
wwd.getSceneController().setVerticalExaggeration(exaggeration);
wwd.redraw();
}
}
final Setter setter = new Setter();
final ChangeListener listener = new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
double exaggeration = sliderToExaggeration(slider.getValue());
setter.set(exaggeration);
}
};
slider.addChangeListener(listener);
listener.stateChanged(null);
JPanel buttons = new JPanel(new GridLayout(1, 0));
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
add(buttons, c);
class ScaleListener implements ActionListener
{
private double exaggeration;
public ScaleListener(double exaggeration)
{
this.exaggeration = exaggeration;
}
public void actionPerformed(ActionEvent e)
{
slider.setValue(exaggerationToSlider(exaggeration));
setter.set(exaggeration);
}
}
JButton button = new JButton("1:1");
button.addActionListener(new ScaleListener(1d));
size = button.getMinimumSize();
size.width = 0;
button.setMinimumSize(size);
buttons.add(button);
button = new JButton("2:1");
button.addActionListener(new ScaleListener(2d));
button.setMinimumSize(size);
buttons.add(button);
button = new JButton("10:1");
button.addActionListener(new ScaleListener(10d));
button.setMinimumSize(size);
buttons.add(button);
/*button = new JButton("100:1");
button.addActionListener(new ScaleListener(100d));
button.setMinimumSize(size);
buttons.add(button);*/
/*final JCheckBox useTerrain = new JCheckBox("Use GA terrain");
useTerrain.setSelected(Settings.get().isUseTerrain());
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
add(useTerrain, c);
useTerrain.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Settings.get().setUseTerrain(useTerrain.isSelected());
LayerList layers = wwd.getModel().getLayers();
Model model = new BasicModel();
model.setLayers(layers);
wwd.setModel(model);
listener.stateChanged(null);
listener.stateChanged(null);
}
});*/
}
| public ExaggerationPanel(final WorldWindow wwd)
{
super(new GridBagLayout());
GridBagConstraints c;
double settingsExaggeration = Settings.get().getVerticalExaggeration();
final JSlider slider = new JSlider(0, 200,
exaggerationToSlider(settingsExaggeration));
Dimension size = slider.getPreferredSize();
size.width = 50;
slider.setPreferredSize(size);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
c.weightx = 1;
add(slider, c);
final JLabel label = new JLabel();
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
add(label, c);
class Setter
{
public void set(double exaggeration)
{
label.setText(String
.valueOf(Math.round(exaggeration * 10d) / 10d));
Settings.get().setVerticalExaggeration(exaggeration);
wwd.getSceneController().setVerticalExaggeration(exaggeration);
wwd.redraw();
}
}
final Setter setter = new Setter();
setter.set(settingsExaggeration);
final ChangeListener listener = new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
double exaggeration = sliderToExaggeration(slider.getValue());
setter.set(exaggeration);
}
};
slider.addChangeListener(listener);
JPanel buttons = new JPanel(new GridLayout(1, 0));
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
add(buttons, c);
class ScaleListener implements ActionListener
{
private double exaggeration;
public ScaleListener(double exaggeration)
{
this.exaggeration = exaggeration;
}
public void actionPerformed(ActionEvent e)
{
slider.setValue(exaggerationToSlider(exaggeration));
setter.set(exaggeration);
}
}
JButton button = new JButton("1:1");
button.addActionListener(new ScaleListener(1d));
size = button.getMinimumSize();
size.width = 0;
button.setMinimumSize(size);
buttons.add(button);
button = new JButton("2:1");
button.addActionListener(new ScaleListener(2d));
button.setMinimumSize(size);
buttons.add(button);
button = new JButton("10:1");
button.addActionListener(new ScaleListener(10d));
button.setMinimumSize(size);
buttons.add(button);
/*button = new JButton("100:1");
button.addActionListener(new ScaleListener(100d));
button.setMinimumSize(size);
buttons.add(button);*/
/*final JCheckBox useTerrain = new JCheckBox("Use GA terrain");
useTerrain.setSelected(Settings.get().isUseTerrain());
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
add(useTerrain, c);
useTerrain.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Settings.get().setUseTerrain(useTerrain.isSelected());
LayerList layers = wwd.getModel().getLayers();
Model model = new BasicModel();
model.setLayers(layers);
wwd.setModel(model);
listener.stateChanged(null);
listener.stateChanged(null);
}
});*/
}
|
diff --git a/src/Parser.java b/src/Parser.java
index 2cf1de7..c92bc0b 100644
--- a/src/Parser.java
+++ b/src/Parser.java
@@ -1,58 +1,58 @@
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import Token.Type;
public class Parser
{
private InputSource _in;
private String _line;
private Map<String, Token.Type> _tokens;
public Parser(InputSource source)
{
if (source == null)
throw new IllegalArgumentException("InputSource can't be null");
_in = source;
_line = _in.readLine();
this.initTokens();
}
private void initTokens()
{
_tokens = new HashMap<String, Token.Type>();
_tokens.put("(", Token.Type.OPEN_PARENTHESIS);
_tokens.put(")", Token.Type.CLOSE_PARENTHESIS);
_tokens.put("&", Token.Type.BIN_AND_OPERATOR);
_tokens.put("|", Token.Type.BIN_OR_OPERATOR);
_tokens.put("=>", Token.Type.EQUALS_OPERATOR);
_tokens.put("~", Token.Type.UNARY_NOT_OPERATOR);
}
public Token nextToken()
{
if (_line.length() == 0)
_line = _in.readLine();
if (_line.length() == 0)
return null;
Iterator<Entry<String, Token.Type>> it = _tokens.entrySet().iterator();
while (it.hasNext())
{
Entry<String, Token.Type> entry = it.next();
if (_line.startsWith(entry.getKey()))
{
String value = _line.substring(0, entry.getKey().length());
_line = _line.substring(value.length());
return new Token(entry.getValue(), value);
}
}
Character c = _line.charAt(0);
if (!Character.isLowerCase(c))
throw new IllegalLineException("`" + c + "' is not a valid token");
- return new Token(Token.Type.VARIABLE, c);
+ return new Token(Token.Type.VARIABLE, c.toString());
}
}
| true | true | public Token nextToken()
{
if (_line.length() == 0)
_line = _in.readLine();
if (_line.length() == 0)
return null;
Iterator<Entry<String, Token.Type>> it = _tokens.entrySet().iterator();
while (it.hasNext())
{
Entry<String, Token.Type> entry = it.next();
if (_line.startsWith(entry.getKey()))
{
String value = _line.substring(0, entry.getKey().length());
_line = _line.substring(value.length());
return new Token(entry.getValue(), value);
}
}
Character c = _line.charAt(0);
if (!Character.isLowerCase(c))
throw new IllegalLineException("`" + c + "' is not a valid token");
return new Token(Token.Type.VARIABLE, c);
}
| public Token nextToken()
{
if (_line.length() == 0)
_line = _in.readLine();
if (_line.length() == 0)
return null;
Iterator<Entry<String, Token.Type>> it = _tokens.entrySet().iterator();
while (it.hasNext())
{
Entry<String, Token.Type> entry = it.next();
if (_line.startsWith(entry.getKey()))
{
String value = _line.substring(0, entry.getKey().length());
_line = _line.substring(value.length());
return new Token(entry.getValue(), value);
}
}
Character c = _line.charAt(0);
if (!Character.isLowerCase(c))
throw new IllegalLineException("`" + c + "' is not a valid token");
return new Token(Token.Type.VARIABLE, c.toString());
}
|
diff --git a/src/java/com/cantstopthesignals/PicasaRelayServlet.java b/src/java/com/cantstopthesignals/PicasaRelayServlet.java
index 469004c..4af657a 100644
--- a/src/java/com/cantstopthesignals/PicasaRelayServlet.java
+++ b/src/java/com/cantstopthesignals/PicasaRelayServlet.java
@@ -1,51 +1,52 @@
package com.cantstopthesignals;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class PicasaRelayServlet extends HttpServlet {
private static final Pattern ALLOWED_URLS = Pattern.compile(
"^https://(picasaweb.google.com|lh[0-9]+.googleusercontent.com)/.*$");
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String urlParam = req.getParameter("url");
URL url = new URL(urlParam);
if (!ALLOWED_URLS.matcher(url.toString()).matches()) {
throw new RuntimeException("Url not in whitelist");
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String method = req.getParameter("method");
if (method != null) {
connection.setRequestMethod(method);
}
String[] headers = req.getParameterValues("header");
if (headers != null) {
for (String header : headers) {
String[] headerPieces = header.split("=", 2);
connection.addRequestProperty(headerPieces[0], headerPieces[1]);
}
}
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
resp.setContentType(connection.getContentType());
+ resp.setStatus(connection.getResponseCode());
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer, 0, 1024)) > 0) {
resp.getOutputStream().write(buffer, 0, bytesRead);
}
}
}
| true | true | public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String urlParam = req.getParameter("url");
URL url = new URL(urlParam);
if (!ALLOWED_URLS.matcher(url.toString()).matches()) {
throw new RuntimeException("Url not in whitelist");
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String method = req.getParameter("method");
if (method != null) {
connection.setRequestMethod(method);
}
String[] headers = req.getParameterValues("header");
if (headers != null) {
for (String header : headers) {
String[] headerPieces = header.split("=", 2);
connection.addRequestProperty(headerPieces[0], headerPieces[1]);
}
}
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
resp.setContentType(connection.getContentType());
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer, 0, 1024)) > 0) {
resp.getOutputStream().write(buffer, 0, bytesRead);
}
}
| public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String urlParam = req.getParameter("url");
URL url = new URL(urlParam);
if (!ALLOWED_URLS.matcher(url.toString()).matches()) {
throw new RuntimeException("Url not in whitelist");
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String method = req.getParameter("method");
if (method != null) {
connection.setRequestMethod(method);
}
String[] headers = req.getParameterValues("header");
if (headers != null) {
for (String header : headers) {
String[] headerPieces = header.split("=", 2);
connection.addRequestProperty(headerPieces[0], headerPieces[1]);
}
}
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
resp.setContentType(connection.getContentType());
resp.setStatus(connection.getResponseCode());
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer, 0, 1024)) > 0) {
resp.getOutputStream().write(buffer, 0, bytesRead);
}
}
|
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
index 7b53cd70..d76e0260 100644
--- a/src/com/android/launcher2/LauncherModel.java
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -1,1186 +1,1187 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import android.os.Process;
import android.os.SystemClock;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = true;
static final String TAG = "Launcher.Model";
private final LauncherApplication mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private Loader mLoader = new Loader();
private boolean mBeforeFirstLoad = true;
private WeakReference<Callbacks> mCallbacks;
private AllAppsList mAllAppsList = new AllAppsList();
public interface Callbacks {
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems();
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindPackageAdded(ArrayList<ApplicationInfo> apps);
public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps);
public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps);
}
LauncherModel(LauncherApplication app) {
mApp = app;
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screen, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screen, cellX, cellY);
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen,
int cellX, int cellY) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive intent=" + intent);
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.d(TAG, "nobody to tell about the new app");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
//Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
// + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
+ mAppWidgets.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
info.title = c.getString(titleIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
| true | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive intent=" + intent);
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.d(TAG, "nobody to tell about the new app");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
//Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
// + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
info.title = c.getString(titleIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive intent=" + intent);
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.d(TAG, "nobody to tell about the new app");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
//Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
// + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
mAppWidgets.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
info.title = c.getString(titleIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
|
diff --git a/calendar-createcomponent/src/main/java/org/exoplatform/cs/event/UICreateEvent.java b/calendar-createcomponent/src/main/java/org/exoplatform/cs/event/UICreateEvent.java
index 3fadb238..ccc318af 100644
--- a/calendar-createcomponent/src/main/java/org/exoplatform/cs/event/UICreateEvent.java
+++ b/calendar-createcomponent/src/main/java/org/exoplatform/cs/event/UICreateEvent.java
@@ -1,575 +1,575 @@
package org.exoplatform.cs.event;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TimeZone;
import org.exoplatform.calendar.service.CalendarEvent;
import org.exoplatform.calendar.service.CalendarService;
import org.exoplatform.calendar.service.CalendarSetting;
import org.exoplatform.calendar.service.GroupCalendarData;
import org.exoplatform.calendar.service.Utils;
import org.exoplatform.calendar.service.impl.NewUserListener;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.portal.application.PortalRequestContext;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.services.security.ConversationState;
import org.exoplatform.services.security.Identity;
import org.exoplatform.services.security.MembershipEntry;
import org.exoplatform.web.application.ApplicationMessage;
import org.exoplatform.webui.application.WebuiRequestContext;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.UIComponent;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.core.model.SelectItem;
import org.exoplatform.webui.core.model.SelectItemOption;
import org.exoplatform.webui.core.model.SelectOption;
import org.exoplatform.webui.core.model.SelectOptionGroup;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.webui.form.UIForm;
import org.exoplatform.webui.form.UIFormDateTimeInput;
import org.exoplatform.webui.form.UIFormRadioBoxInput;
import org.exoplatform.webui.form.UIFormSelectBox;
import org.exoplatform.webui.form.UIFormSelectBoxWithGroups;
import org.exoplatform.webui.form.UIFormStringInput;
/**
* Created with IntelliJ IDEA.
* User: Racha
* Date: 01/11/12
* Time: 11:08
* To change this template use File | Settings | File Templates.
*/
@ComponentConfig(
lifecycle = UIFormLifecycle.class,
template = "classpath:groovy/webui/create/UICreateEvent.gtmpl",
events = {
@EventConfig(
listeners = UICreateEvent.NextActionListener.class,
phase = Event.Phase.DECODE
),
@EventConfig(
listeners = UICreateEvent.CancelActionListener.class,
phase = Event.Phase.DECODE
)
}
)
public class UICreateEvent extends UIForm {
public static final String PRIVATE_CALENDARS = "privateCalendar";
public static final String SHARED_CALENDARS = "sharedCalendar";
public static final String PUBLIC_CALENDARS = "publicCalendar";
public static final String PRIVATE_TYPE = "0";
public static final String SHARED_TYPE = "1";
public static final String PUBLIC_TYPE = "2";
public static final String COLON = ":";
public static final String COMMA = ",";
public static final String ANY = "*.*";
public static final String ANY_OF = "*.";
public static final String DOT = ".";
public static final String SLASH_COLON = "/:";
public static final String OPEN_PARENTHESIS = "(";
public static final String CLOSE_PARENTHESIS = ")";
static List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>();
private static Log log = ExoLogger.getLogger(UICreateEvent.class);
static String CHOIX = "Choix";
static String TITLE = "Title";
public static String END_EVENT = "EndEvent";
public static String CALENDAR = "Calendar";
public static String Start_EVENT = "StartEvent";
public static String START_TIME = "start_time";
public static String END_TIME = "end_time";
public static String ALL_DAY = "all-day";
private String calType_ = "0";
public static final String TIMEFORMAT = "HH:mm";
public static final String DISPLAY_TIMEFORMAT = "hh:mm a";
public static final long DEFAULT_TIME_INTERVAL = 30;
public UICreateEvent() throws Exception {
addUIFormInput(new UIFormRadioBoxInput(CHOIX, "Event", options));
addUIFormInput(new UIFormStringInput(TITLE, TITLE, null));
addUIFormInput(new UIFormDateTimeInput(Start_EVENT, Start_EVENT, getInstanceOfCurrentCalendar().getTime(), false));
addUIFormInput(new UIFormDateTimeInput(END_EVENT, END_EVENT, getInstanceOfCurrentCalendar().getTime(), false));
addUIFormInput(new UIFormSelectBoxWithGroups(CALENDAR, CALENDAR, getCalendarOption()));
addUIFormInput(new UIFormSelectBox(START_TIME, START_TIME, getTimesSelectBoxOptions(DISPLAY_TIMEFORMAT)));
addUIFormInput(new UIFormSelectBox(END_TIME, END_TIME, getTimesSelectBoxOptions(DISPLAY_TIMEFORMAT)));
}
protected String getDateTimeFormat(){
UIFormDateTimeInput fromField = getChildById(Start_EVENT);
return fromField.getDatePattern_();
}
static public class NextActionListener extends EventListener<UICreateEvent> {
public void execute(Event<UICreateEvent> event)
throws Exception {
UICreateEvent uiForm = event.getSource();
String summary = uiForm.getEventSummary();
if (summary == null || summary.trim().length() <= 0) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId()
+ ".msg.summary-field-required", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
summary = summary.trim();
summary = enCodeTitle(summary);
UIFormDateTimeInput fromField = uiForm.getChildById(Start_EVENT);
UIFormDateTimeInput toField = uiForm.getChildById(END_EVENT);
Date from = uiForm.getDateTime(fromField, UICreateEvent.START_TIME);
Date to = uiForm.getDateTime(toField, UICreateEvent.END_TIME);
if (from == null) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.fromDate-format", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
if (to == null) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.toDate-format", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
if (from.after(to) || from.equals(to)) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.logic-required", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
CalendarService calService = getCalendarService();
if (calService.isRemoteCalendar(getCurrentUser(), uiForm.getEventCalendar())) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() +".msg.cant-add-event-on-remote-calendar", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
try {
CalendarEvent calEvent = new CalendarEvent();
calEvent.setSummary(summary);
calEvent.setCalendarId(uiForm.getEventCalendar());
String username = getCurrentUser();
boolean isEvent = "Event".equals(((UIFormRadioBoxInput) uiForm.getUIInput(CHOIX)).getValue());
if (isEvent) {
calEvent.setEventType(CalendarEvent.TYPE_EVENT);
calEvent.setEventState(CalendarEvent.ST_BUSY);
calEvent.setRepeatType(CalendarEvent.RP_NOREPEAT);
} else {
calEvent.setEventType(CalendarEvent.TYPE_TASK);
calEvent.setEventState(CalendarEvent.NEEDS_ACTION);
calEvent.setTaskDelegator(event.getRequestContext().getRemoteUser());
}
calEvent.setFromDateTime(from);
calEvent.setToDateTime(to);
calEvent.setCalType(uiForm.calType_);
String calName="";
if(calService.getUserCalendar(username,uiForm.getEventCalendar())!=null){
if (calService.getUserCalendar(username,uiForm.getEventCalendar()).getId().equals(Utils.getDefaultCalendarId(username)) && calService.getUserCalendar(username,uiForm.getEventCalendar()).getName().equals(NewUserListener.defaultCalendarName)) {
calName = getResourceBundle("UICreateEvent.label." + NewUserListener.defaultCalendarId, NewUserListener.defaultCalendarId);
}
}else {
if(calService.getGroupCalendar(uiForm.getEventCalendar())!=null){
calName= getGroupCalendarName(calService.getGroupCalendar(uiForm.getEventCalendar()).getGroups()[0].substring(calService.getGroupCalendar(uiForm.getEventCalendar()).getGroups()[0].lastIndexOf("/") + 1),
calService.getGroupCalendar(uiForm.getEventCalendar()).getName()) ;
} else{
if( calService.getSharedCalendars(username,true).getCalendarById(uiForm.getEventCalendar())!=null){
if (calService.getUserCalendar(username,uiForm.getEventCalendar()).getId().equals(Utils.getDefaultCalendarId(calService.getUserCalendar(username,uiForm.getEventCalendar()).getCalendarOwner())) && calService.getUserCalendar(username,uiForm.getEventCalendar()).getName().equals(NewUserListener.defaultCalendarName)) {
calName = getResourceBundle("UICreateEvent.label." + NewUserListener.defaultCalendarId, NewUserListener.defaultCalendarId);
}
String owner = "";
if (calService.getUserCalendar(username,uiForm.getEventCalendar()).getCalendarOwner() != null) owner = calService.getUserCalendar(username,uiForm.getEventCalendar()).getCalendarOwner() + " - ";
calName=owner+calName;
}
}
}
if (uiForm.calType_.equals(PRIVATE_TYPE)) {
calService.saveUserEvent(username, calEvent.getCalendarId(), calEvent, true);
} else if (uiForm.calType_.equals(SHARED_TYPE)) {
calService.saveEventToSharedCalendar(username, calEvent.getCalendarId(), calEvent, true);
} else if (uiForm.calType_.equals(PUBLIC_TYPE)) {
calService.savePublicEvent(calEvent.getCalendarId(), calEvent, true);
}
String defaultMsg = "The {0} added to the {1}.";
String message = UICreateEvent.getResourceBundle(uiForm.getId()+".msg.add-successfully",defaultMsg);
- message.replace("{0}", calEvent.getEventType()).replace("{1}", calName);
+ message = message.replace("{0}", calEvent.getEventType()).replace("{1}", calName);
Event<UIComponent> cancelEvent = uiForm.<UIComponent>getParent().createEvent("Cancel", Event.Phase.PROCESS, event.getRequestContext());
if (cancelEvent != null) {
cancelEvent.broadcast();
}
event.getRequestContext().getJavascriptManager().require("SHARED/navigation-toolbar", "toolbarnav").addScripts("toolbarnav.UIPortalNavigation.cancelNextClick('UICreateList','UICreatePlatformToolBarPortlet','" + message + "');");
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Fail to quick add event to the calendar", e);
}
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.add-unsuccessfully", null));
}
}
}
public Date getDateTime(UIFormDateTimeInput input, String selectId) throws Exception {
String timeField = getUIFormSelectBox(selectId).getValue();
boolean isAllDate = ALL_DAY.equals(timeField);
if (END_TIME.equals(selectId)) {
return getEndDate(isAllDate, input.getDatePattern_(), input.getValue(), TIMEFORMAT, timeField);
} else return getBeginDate(isAllDate, input.getDatePattern_(), input.getValue(), TIMEFORMAT, timeField);
}
public static Date getBeginDate(boolean isAllDate, String dateFormat, String fromField, String timeFormat, String timeField) throws Exception {
try {
WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
Locale locale = context.getParentAppRequestContext().getLocale();
if (isAllDate) {
DateFormat df = new SimpleDateFormat(dateFormat, locale);
df.setCalendar(getInstanceOfCurrentCalendar());
return getBeginDay(df.parse(fromField)).getTime();
}
DateFormat df = new SimpleDateFormat(dateFormat + Utils.SPACE + timeFormat, locale);
df.setCalendar(getInstanceOfCurrentCalendar());
return df.parse(fromField + Utils.SPACE + timeField);
} catch (Exception e) {
return null;
}
}
public static Date getEndDate(boolean isAllDate, String dateFormat, String fromField, String timeFormat, String timeField) throws Exception {
try {
WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
Locale locale = context.getParentAppRequestContext().getLocale();
if (isAllDate) {
DateFormat df = new SimpleDateFormat(dateFormat, locale);
df.setCalendar(getInstanceOfCurrentCalendar());
return getEndDay(df.parse(fromField)).getTime();
}
DateFormat df = new SimpleDateFormat(dateFormat + Utils.SPACE + timeFormat, locale);
df.setCalendar(getInstanceOfCurrentCalendar());
return df.parse(fromField + Utils.SPACE + timeField);
} catch (Exception e) {
return null;
}
}
public static CalendarSetting getCurrentUserCalendarSetting() {
try {
String user = getCurrentUser();
CalendarSetting setting = getCalendarService().getCalendarSetting(user);
return setting;
} catch (Exception e) {
log.warn("could not get calendar setting of user", e);
return null;
}
}
public static Calendar getInstanceOfCurrentCalendar() {
try {
CalendarSetting setting = getCurrentUserCalendarSetting();
return getCalendarInstanceBySetting(setting);
} catch (Exception e) {
if (log.isWarnEnabled()) log.warn("Could not get calendar setting!", e);
Calendar calendar = GregorianCalendar.getInstance();
calendar.setLenient(false);
return calendar;
}
}
public static Calendar getCalendarInstanceBySetting(final CalendarSetting calendarSetting) {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setLenient(false);
calendar.setTimeZone(TimeZone.getTimeZone(calendarSetting.getTimeZone()));
calendar.setFirstDayOfWeek(Integer.parseInt(calendarSetting.getWeekStartOn()));
// fix CS-4725
calendar.setMinimalDaysInFirstWeek(4);
return calendar;
}
public static Calendar getBeginDay(Calendar cal) {
Calendar newCal = (Calendar) cal.clone();
newCal.set(Calendar.HOUR_OF_DAY, 0);
newCal.set(Calendar.MINUTE, 0);
newCal.set(Calendar.SECOND, 0);
newCal.set(Calendar.MILLISECOND, 0);
return newCal;
}
public static Calendar getEndDay(Calendar cal) {
Calendar newCal = (Calendar) cal.clone();
newCal.set(Calendar.HOUR_OF_DAY, 0);
newCal.set(Calendar.MINUTE, 0);
newCal.set(Calendar.SECOND, 0);
newCal.set(Calendar.MILLISECOND, 0);
newCal.add(Calendar.HOUR_OF_DAY, 24);
return newCal;
}
public static Calendar getBeginDay(Date date) {
Calendar cal = getInstanceOfCurrentCalendar();
cal.setTime(date);
return getBeginDay(cal);
}
public static Calendar getEndDay(Date date) {
Calendar cal = getInstanceOfCurrentCalendar();
cal.setTime(date);
return getEndDay(cal);
}
static public class CancelActionListener extends EventListener<UICreateEvent> {
public void execute(Event<UICreateEvent> event)
throws Exception {
UICreateEvent uisource = event.getSource();
WebuiRequestContext ctx = event.getRequestContext();
Event<UIComponent> cancelEvent = uisource.<UIComponent>getParent().createEvent("Cancel", Event.Phase.DECODE, ctx);
if (cancelEvent != null) {
cancelEvent.broadcast();
}
}
}
static {
options.add(new SelectItemOption("Event"));
options.add(new SelectItemOption("Task"));
}
public static List<SelectItemOption<String>> getTimesSelectBoxOptions(String timeFormat) {
WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
Locale locale = context.getParentAppRequestContext().getLocale();
return getTimesSelectBoxOptions(timeFormat, TIMEFORMAT, DEFAULT_TIME_INTERVAL, locale);
}
public static List<SelectItemOption<String>> getTimesSelectBoxOptions(String labelFormat, String valueFormat, long timeInteval) {
WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
Locale locale = context.getParentAppRequestContext().getLocale();
return getTimesSelectBoxOptions(labelFormat, valueFormat, timeInteval, locale);
}
public static List<SelectItemOption<String>> getTimesSelectBoxOptions(String labelFormat, String valueFormat, long timeInteval, Locale locale) {
List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>();
options.add(new SelectItemOption<String>(getResourceBundle("UICreateEvent.label."+ALL_DAY,"All Day"), ALL_DAY));
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("")); // get a GMT calendar
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
DateFormat dfLabel = new SimpleDateFormat(labelFormat, locale);
dfLabel.setCalendar(cal);
DateFormat dfValue = new SimpleDateFormat(valueFormat, locale);
dfValue.setCalendar(cal);
int day = cal.get(Calendar.DAY_OF_MONTH);
while (day == cal.get(Calendar.DAY_OF_MONTH)) {
options.add(new SelectItemOption<String>(dfLabel.format(cal.getTime()), dfValue.format(cal.getTime())));
cal.add(java.util.Calendar.MINUTE, (int) timeInteval);
}
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.MILLISECOND, 59);
options.add(new SelectItemOption<String>(dfLabel.format(cal.getTime()), dfValue.format(cal.getTime())));
return options;
}
public static List<SelectItem> getCalendarOption() throws Exception {
List<SelectItem> options = new ArrayList<SelectItem>();
CalendarService calendarService = getCalendarService();
String username = getCurrentUser();
Map<String, String> hash = new HashMap<String, String>();
// private calendars group
SelectOptionGroup privGrp = new SelectOptionGroup(PRIVATE_CALENDARS);
List<org.exoplatform.calendar.service.Calendar> calendars = calendarService.getUserCalendars(username, true);
for (org.exoplatform.calendar.service.Calendar c : calendars) {
if (c.getId().equals(Utils.getDefaultCalendarId(username)) && c.getName().equals(NewUserListener.defaultCalendarName)) {
String newName = getResourceBundle("UICreateEvent.label." + NewUserListener.defaultCalendarId, NewUserListener.defaultCalendarId);
c.setName(newName);
}
if (!hash.containsKey(c.getId())) {
hash.put(c.getId(), "");
privGrp.addOption(new SelectOption(c.getName(), PRIVATE_TYPE + COLON + c.getId()));
}
}
if (privGrp.getOptions().size() > 0) options.add(privGrp);
// shared calendars group
GroupCalendarData gcd = calendarService.getSharedCalendars(username, true);
if (gcd != null) {
SelectOptionGroup sharedGrp = new SelectOptionGroup(SHARED_CALENDARS);
for (org.exoplatform.calendar.service.Calendar c : gcd.getCalendars()) {
if (canEdit(null, Utils.getEditPerUsers(c), username)) {
if (c.getId().equals(Utils.getDefaultCalendarId(c.getCalendarOwner())) && c.getName().equals(NewUserListener.defaultCalendarName)) {
String newName = getResourceBundle("UICreateEvent.label." + NewUserListener.defaultCalendarId, NewUserListener.defaultCalendarId);
c.setName(newName);
}
String owner = "";
if (c.getCalendarOwner() != null) owner = c.getCalendarOwner() + " - ";
if (!hash.containsKey(c.getId())) {
hash.put(c.getId(), "");
sharedGrp.addOption(new SelectOption(owner + c.getName(), SHARED_TYPE + COLON + c.getId()));
}
}
}
if (sharedGrp.getOptions().size() > 0) options.add(sharedGrp);
}
// public calendars group
List<GroupCalendarData> lgcd = calendarService.getGroupCalendars(getUserGroups(username), true, username);
if (lgcd != null) {
SelectOptionGroup pubGrp = new SelectOptionGroup(PUBLIC_CALENDARS);
String[] checkPerms = getCheckPermissionString().split(COMMA);
for (GroupCalendarData g : lgcd) {
String groupName = g.getName();
for (org.exoplatform.calendar.service.Calendar c : g.getCalendars()) {
if (hasEditPermission(c.getEditPermission(), checkPerms)) {
if (!hash.containsKey(c.getId())) {
hash.put(c.getId(), "");
pubGrp.addOption(new SelectOption(getGroupCalendarName(groupName.substring(groupName.lastIndexOf("/") + 1),
c.getName()), PUBLIC_TYPE + COLON + c.getId()));
}
}
}
}
if (pubGrp.getOptions().size() > 0) options.add(pubGrp);
}
return options;
}
static public CalendarService getCalendarService() throws Exception {
return (CalendarService) PortalContainer.getInstance().getComponentInstance(CalendarService.class);
}
@SuppressWarnings("unchecked")
public static String getCheckPermissionString() throws Exception {
Identity identity = ConversationState.getCurrent().getIdentity();
StringBuffer sb = new StringBuffer(identity.getUserId());
Set<String> groupsId = identity.getGroups();
for (String groupId : groupsId) {
sb.append(COMMA).append(groupId).append(SLASH_COLON).append(ANY);
sb.append(COMMA).append(groupId).append(SLASH_COLON).append(identity.getUserId());
}
Collection<MembershipEntry> memberships = identity.getMemberships();
for (MembershipEntry membership : memberships) {
sb.append(COMMA).append(membership.getGroup()).append(SLASH_COLON).append(ANY_OF + membership.getMembershipType());
}
return sb.toString();
}
public static boolean hasEditPermission(String[] savePerms, String[] checkPerms) {
if (savePerms != null)
for (String sp : savePerms) {
for (String cp : checkPerms) {
if (sp.equals(cp)) {
return true;
}
}
}
return false;
}
public static String getResourceBundle(String key, String defaultValue) {
WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
ResourceBundle res = context.getApplicationResourceBundle();
try {
return res.getString(key);
} catch (MissingResourceException e) {
log.warn("Can not find the resource for key: " + key);
return defaultValue;
}
}
static public String getCurrentUser() throws Exception {
return Util.getPortalRequestContext().getRemoteUser();
}
public static boolean canEdit(OrganizationService oService, String[] savePerms, String username) throws Exception {
String checkPerms = getCheckPermissionString();
return hasEditPermission(savePerms, checkPerms.toString().split(COMMA));
}
public static final String[] getUserGroups(String username) throws Exception {
ConversationState conversationState = ConversationState.getCurrent();
Identity identity = conversationState.getIdentity();
Set<String> objs = identity.getGroups();
String[] groups = new String[objs.size()];
int i = 0;
for (String obj : objs) {
groups[i++] = obj;
}
return groups;
}
public static String getGroupCalendarName(String groupName, String calendarName) {
return calendarName + Utils.SPACE + OPEN_PARENTHESIS + groupName + CLOSE_PARENTHESIS;
}
private String getEventSummary() {
return getUIStringInput(TITLE).getValue();
}
public static String enCodeTitle(String s) {
StringBuffer buffer = new StringBuffer();
if (s != null) {
s = s.replaceAll("(<p>((\\ )*)(\\s*)?</p>)|(<p>((\\ )*)?(\\s*)</p>)", "<br/>").trim();
s = s.replaceFirst("(<br/>)*", "");
s = s.replaceAll("(\\w|\\$)(>?,?\\.?\\*?\\!?\\&?\\%?\\]?\\)?\\}?)(<br/><br/>)*", "$1$2");
s.replaceAll("&", "&").replaceAll("'", "'");
for (int j = 0; j < s.trim().length(); j++) {
char c = s.charAt(j);
if ((int) c == 60) {
buffer.append("<");
} else if ((int) c == 62) {
buffer.append(">");
} else if (c == '\'') {
buffer.append("'");
} else {
buffer.append(c);
}
}
}
return buffer.toString();
}
private String getEventCalendar() {
String values = getUIFormSelectBoxGroup(CALENDAR).getValue();
if (values != null && values.trim().length() > 0 && values.split(COLON).length > 0) {
calType_ = values.split(COLON)[0];
return values.split(COLON)[1];
}
return null;
}
public UIFormSelectBoxWithGroups getUIFormSelectBoxGroup(String id) {
return findComponentById(id);
}
}
| true | true | public void execute(Event<UICreateEvent> event)
throws Exception {
UICreateEvent uiForm = event.getSource();
String summary = uiForm.getEventSummary();
if (summary == null || summary.trim().length() <= 0) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId()
+ ".msg.summary-field-required", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
summary = summary.trim();
summary = enCodeTitle(summary);
UIFormDateTimeInput fromField = uiForm.getChildById(Start_EVENT);
UIFormDateTimeInput toField = uiForm.getChildById(END_EVENT);
Date from = uiForm.getDateTime(fromField, UICreateEvent.START_TIME);
Date to = uiForm.getDateTime(toField, UICreateEvent.END_TIME);
if (from == null) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.fromDate-format", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
if (to == null) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.toDate-format", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
if (from.after(to) || from.equals(to)) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.logic-required", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
CalendarService calService = getCalendarService();
if (calService.isRemoteCalendar(getCurrentUser(), uiForm.getEventCalendar())) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() +".msg.cant-add-event-on-remote-calendar", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
try {
CalendarEvent calEvent = new CalendarEvent();
calEvent.setSummary(summary);
calEvent.setCalendarId(uiForm.getEventCalendar());
String username = getCurrentUser();
boolean isEvent = "Event".equals(((UIFormRadioBoxInput) uiForm.getUIInput(CHOIX)).getValue());
if (isEvent) {
calEvent.setEventType(CalendarEvent.TYPE_EVENT);
calEvent.setEventState(CalendarEvent.ST_BUSY);
calEvent.setRepeatType(CalendarEvent.RP_NOREPEAT);
} else {
calEvent.setEventType(CalendarEvent.TYPE_TASK);
calEvent.setEventState(CalendarEvent.NEEDS_ACTION);
calEvent.setTaskDelegator(event.getRequestContext().getRemoteUser());
}
calEvent.setFromDateTime(from);
calEvent.setToDateTime(to);
calEvent.setCalType(uiForm.calType_);
String calName="";
if(calService.getUserCalendar(username,uiForm.getEventCalendar())!=null){
if (calService.getUserCalendar(username,uiForm.getEventCalendar()).getId().equals(Utils.getDefaultCalendarId(username)) && calService.getUserCalendar(username,uiForm.getEventCalendar()).getName().equals(NewUserListener.defaultCalendarName)) {
calName = getResourceBundle("UICreateEvent.label." + NewUserListener.defaultCalendarId, NewUserListener.defaultCalendarId);
}
}else {
if(calService.getGroupCalendar(uiForm.getEventCalendar())!=null){
calName= getGroupCalendarName(calService.getGroupCalendar(uiForm.getEventCalendar()).getGroups()[0].substring(calService.getGroupCalendar(uiForm.getEventCalendar()).getGroups()[0].lastIndexOf("/") + 1),
calService.getGroupCalendar(uiForm.getEventCalendar()).getName()) ;
} else{
if( calService.getSharedCalendars(username,true).getCalendarById(uiForm.getEventCalendar())!=null){
if (calService.getUserCalendar(username,uiForm.getEventCalendar()).getId().equals(Utils.getDefaultCalendarId(calService.getUserCalendar(username,uiForm.getEventCalendar()).getCalendarOwner())) && calService.getUserCalendar(username,uiForm.getEventCalendar()).getName().equals(NewUserListener.defaultCalendarName)) {
calName = getResourceBundle("UICreateEvent.label." + NewUserListener.defaultCalendarId, NewUserListener.defaultCalendarId);
}
String owner = "";
if (calService.getUserCalendar(username,uiForm.getEventCalendar()).getCalendarOwner() != null) owner = calService.getUserCalendar(username,uiForm.getEventCalendar()).getCalendarOwner() + " - ";
calName=owner+calName;
}
}
}
if (uiForm.calType_.equals(PRIVATE_TYPE)) {
calService.saveUserEvent(username, calEvent.getCalendarId(), calEvent, true);
} else if (uiForm.calType_.equals(SHARED_TYPE)) {
calService.saveEventToSharedCalendar(username, calEvent.getCalendarId(), calEvent, true);
} else if (uiForm.calType_.equals(PUBLIC_TYPE)) {
calService.savePublicEvent(calEvent.getCalendarId(), calEvent, true);
}
String defaultMsg = "The {0} added to the {1}.";
String message = UICreateEvent.getResourceBundle(uiForm.getId()+".msg.add-successfully",defaultMsg);
message.replace("{0}", calEvent.getEventType()).replace("{1}", calName);
Event<UIComponent> cancelEvent = uiForm.<UIComponent>getParent().createEvent("Cancel", Event.Phase.PROCESS, event.getRequestContext());
if (cancelEvent != null) {
cancelEvent.broadcast();
}
event.getRequestContext().getJavascriptManager().require("SHARED/navigation-toolbar", "toolbarnav").addScripts("toolbarnav.UIPortalNavigation.cancelNextClick('UICreateList','UICreatePlatformToolBarPortlet','" + message + "');");
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Fail to quick add event to the calendar", e);
}
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.add-unsuccessfully", null));
}
}
| public void execute(Event<UICreateEvent> event)
throws Exception {
UICreateEvent uiForm = event.getSource();
String summary = uiForm.getEventSummary();
if (summary == null || summary.trim().length() <= 0) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId()
+ ".msg.summary-field-required", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
summary = summary.trim();
summary = enCodeTitle(summary);
UIFormDateTimeInput fromField = uiForm.getChildById(Start_EVENT);
UIFormDateTimeInput toField = uiForm.getChildById(END_EVENT);
Date from = uiForm.getDateTime(fromField, UICreateEvent.START_TIME);
Date to = uiForm.getDateTime(toField, UICreateEvent.END_TIME);
if (from == null) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.fromDate-format", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
if (to == null) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.toDate-format", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
if (from.after(to) || from.equals(to)) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.logic-required", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
CalendarService calService = getCalendarService();
if (calService.isRemoteCalendar(getCurrentUser(), uiForm.getEventCalendar())) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() +".msg.cant-add-event-on-remote-calendar", null, ApplicationMessage.WARNING));
((PortalRequestContext) event.getRequestContext().getParentAppRequestContext()).setFullRender(true);
return;
}
try {
CalendarEvent calEvent = new CalendarEvent();
calEvent.setSummary(summary);
calEvent.setCalendarId(uiForm.getEventCalendar());
String username = getCurrentUser();
boolean isEvent = "Event".equals(((UIFormRadioBoxInput) uiForm.getUIInput(CHOIX)).getValue());
if (isEvent) {
calEvent.setEventType(CalendarEvent.TYPE_EVENT);
calEvent.setEventState(CalendarEvent.ST_BUSY);
calEvent.setRepeatType(CalendarEvent.RP_NOREPEAT);
} else {
calEvent.setEventType(CalendarEvent.TYPE_TASK);
calEvent.setEventState(CalendarEvent.NEEDS_ACTION);
calEvent.setTaskDelegator(event.getRequestContext().getRemoteUser());
}
calEvent.setFromDateTime(from);
calEvent.setToDateTime(to);
calEvent.setCalType(uiForm.calType_);
String calName="";
if(calService.getUserCalendar(username,uiForm.getEventCalendar())!=null){
if (calService.getUserCalendar(username,uiForm.getEventCalendar()).getId().equals(Utils.getDefaultCalendarId(username)) && calService.getUserCalendar(username,uiForm.getEventCalendar()).getName().equals(NewUserListener.defaultCalendarName)) {
calName = getResourceBundle("UICreateEvent.label." + NewUserListener.defaultCalendarId, NewUserListener.defaultCalendarId);
}
}else {
if(calService.getGroupCalendar(uiForm.getEventCalendar())!=null){
calName= getGroupCalendarName(calService.getGroupCalendar(uiForm.getEventCalendar()).getGroups()[0].substring(calService.getGroupCalendar(uiForm.getEventCalendar()).getGroups()[0].lastIndexOf("/") + 1),
calService.getGroupCalendar(uiForm.getEventCalendar()).getName()) ;
} else{
if( calService.getSharedCalendars(username,true).getCalendarById(uiForm.getEventCalendar())!=null){
if (calService.getUserCalendar(username,uiForm.getEventCalendar()).getId().equals(Utils.getDefaultCalendarId(calService.getUserCalendar(username,uiForm.getEventCalendar()).getCalendarOwner())) && calService.getUserCalendar(username,uiForm.getEventCalendar()).getName().equals(NewUserListener.defaultCalendarName)) {
calName = getResourceBundle("UICreateEvent.label." + NewUserListener.defaultCalendarId, NewUserListener.defaultCalendarId);
}
String owner = "";
if (calService.getUserCalendar(username,uiForm.getEventCalendar()).getCalendarOwner() != null) owner = calService.getUserCalendar(username,uiForm.getEventCalendar()).getCalendarOwner() + " - ";
calName=owner+calName;
}
}
}
if (uiForm.calType_.equals(PRIVATE_TYPE)) {
calService.saveUserEvent(username, calEvent.getCalendarId(), calEvent, true);
} else if (uiForm.calType_.equals(SHARED_TYPE)) {
calService.saveEventToSharedCalendar(username, calEvent.getCalendarId(), calEvent, true);
} else if (uiForm.calType_.equals(PUBLIC_TYPE)) {
calService.savePublicEvent(calEvent.getCalendarId(), calEvent, true);
}
String defaultMsg = "The {0} added to the {1}.";
String message = UICreateEvent.getResourceBundle(uiForm.getId()+".msg.add-successfully",defaultMsg);
message = message.replace("{0}", calEvent.getEventType()).replace("{1}", calName);
Event<UIComponent> cancelEvent = uiForm.<UIComponent>getParent().createEvent("Cancel", Event.Phase.PROCESS, event.getRequestContext());
if (cancelEvent != null) {
cancelEvent.broadcast();
}
event.getRequestContext().getJavascriptManager().require("SHARED/navigation-toolbar", "toolbarnav").addScripts("toolbarnav.UIPortalNavigation.cancelNextClick('UICreateList','UICreatePlatformToolBarPortlet','" + message + "');");
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Fail to quick add event to the calendar", e);
}
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.getId() + ".msg.add-unsuccessfully", null));
}
}
|
diff --git a/com/buglabs/bug/module/camera/CameraModlet.java b/com/buglabs/bug/module/camera/CameraModlet.java
index 21855e3..b1b5774 100644
--- a/com/buglabs/bug/module/camera/CameraModlet.java
+++ b/com/buglabs/bug/module/camera/CameraModlet.java
@@ -1,316 +1,311 @@
/* Copyright (c) 2007, 2008 Bug Labs, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* 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 version 2 for more details (a copy is
* included at http://www.gnu.org/licenses/old-licenses/gpl-2.0.html).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
package com.buglabs.bug.module.camera;
import java.awt.Rectangle;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
import com.buglabs.bug.input.pub.InputEventProvider;
import com.buglabs.bug.jni.camera.Camera;
import com.buglabs.bug.jni.camera.CameraControl;
import com.buglabs.bug.jni.common.CharDeviceUtils;
import com.buglabs.bug.menu.pub.StatusBarUtils;
import com.buglabs.bug.module.camera.pub.ICameraButtonEventProvider;
import com.buglabs.bug.module.camera.pub.ICameraDevice;
import com.buglabs.bug.module.camera.pub.ICameraModuleControl;
import com.buglabs.bug.module.pub.IModlet;
import com.buglabs.module.IModuleControl;
import com.buglabs.module.IModuleLEDController;
import com.buglabs.module.IModuleProperty;
import com.buglabs.module.ModuleProperty;
import com.buglabs.services.ws.IWSResponse;
import com.buglabs.services.ws.PublicWSDefinition;
import com.buglabs.services.ws.PublicWSProvider;
import com.buglabs.services.ws.WSResponse;
import com.buglabs.util.LogServiceUtil;
import com.buglabs.util.RemoteOSGiServiceConstants;
import com.buglabs.util.trackers.PublicWSAdminTracker;
/**
*
* @author kgilmer
*
*/
public class CameraModlet implements IModlet, ICameraDevice, PublicWSProvider, IModuleControl {
private static final String IMAGE_MIME_TYPE = "image/jpg";
private static final String DEVNODE_INPUT_DEVICE = "/dev/input/bmi_cam";
private static final String CAMERA_DEVICE_NODE = "/dev/v4l/video0";
private static final String CAMERA_CONTROL_DEVICE_NODE = "/dev/bug_camera_control";
private ServiceTracker wsTracker;
private int megapixels;
private List modProps;
private final BundleContext context;
private final int slotId;
private final String moduleName;
private ServiceRegistration moduleControl;
private ServiceRegistration cameraService;
private ServiceRegistration bepReg;
private LogService logService;
private Camera camera;
private String moduleId;
private String regionKey;
private static boolean icon[][] = { { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false },
{ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false },
{ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false },
{ false, false, true, true, true, true, true, true, true, true, true, true, true, true, false, false },
{ false, true, false, false, false, false, false, false, false, false, false, false, false, false, true, false },
{ false, true, false, false, false, false, false, false, false, false, false, true, true, false, true, false },
{ false, true, false, false, true, true, true, true, true, true, true, true, true, false, true, false },
{ false, true, false, true, false, false, false, false, false, false, false, false, true, false, true, false },
{ false, true, false, true, false, false, false, false, true, true, true, true, true, false, true, false },
{ false, true, false, true, false, false, true, true, false, true, true, true, true, false, true, false },
{ false, true, false, true, false, false, true, true, false, true, true, true, true, false, true, false },
{ false, true, false, true, false, true, false, false, true, true, true, true, true, false, true, false },
{ false, true, false, true, false, true, true, true, true, true, true, true, true, false, true, false },
{ false, true, false, true, true, true, true, true, true, true, true, true, true, false, true, false },
{ false, true, false, false, false, false, false, false, false, false, false, false, false, false, true, false },
{ false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false },
{ false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false },
{ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false },
{ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false },
{ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false } };
private CameraModuleControl cameraControl;
private ServiceRegistration cameraControlRef;
private CameraControl cc;
private InputEventProvider bep;
private ServiceRegistration ledRef;
public CameraModlet(BundleContext context, int slotId, String moduleId) {
this.context = context;
this.slotId = slotId;
this.moduleId = moduleId;
this.moduleName = "CAMERA";
// TODO See if we can get this from the Camera driver.
this.megapixels = 2;
}
public String getModuleId() {
return moduleId;
}
public int getSlotId() {
return slotId;
}
public void setup() throws Exception {
logService = LogServiceUtil.getLogService(context);
}
public void start() throws Exception {
modProps = new ArrayList();
camera = new Camera();
//TODO: Change this when we move to linux 2.6.22 or greater since
//BMI agent should listen to UDEV ACTION=="online" before starting modlets
try {
CharDeviceUtils.openDeviceWithRetry(camera, CAMERA_DEVICE_NODE, 2);
} catch (IOException e) {
String errormsg = "Unable to open camera device node: " + CAMERA_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
cc = new CameraControl();
try {
CharDeviceUtils.openDeviceWithRetry(cc, CAMERA_CONTROL_DEVICE_NODE, 2);
} catch (IOException e){
String errormsg = "Unable to open camera device node: " + CAMERA_CONTROL_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
- System.out.println("I'm here!");
- System.out.println("I'm here!");
- System.out.println("I'm here!");
- System.out.println("I'm here!");
- System.out.println("I'm here!");
cameraControl = new CameraModuleControl(cc);
cameraControlRef = context.registerService(ICameraModuleControl.class.getName(), cameraControl, createRemotableProperties(null));
moduleControl = context.registerService(IModuleControl.class.getName(), this, createRemotableProperties(null));
cameraService = context.registerService(ICameraDevice.class.getName(), this, createRemotableProperties(null));
ledRef = context.registerService(IModuleLEDController.class.getName(), cameraControl, createRemotableProperties(null));
bep = new CameraInputEventProvider(DEVNODE_INPUT_DEVICE, logService);
bep.start();
bepReg = context.registerService(ICameraButtonEventProvider.class.getName(), bep, createRemotableProperties(getButtonServiceProperties()));
// Display the camera icon
regionKey = StatusBarUtils.displayImage(context, icon, this.getModuleName());
List wsProviders = new ArrayList();
wsProviders.add(this);
wsTracker = PublicWSAdminTracker.createTracker(context, wsProviders);
}
/**
* @return A dictionary with R-OSGi enable property.
*/
private Dictionary createRemotableProperties(Dictionary ht) {
if (ht == null) {
ht = new Hashtable();
}
ht.put(RemoteOSGiServiceConstants.R_OSGi_REGISTRATION, "true");
return ht;
}
public void stop() throws Exception {
StatusBarUtils.releaseRegion(context, regionKey);
cameraControlRef.unregister();
cameraService.unregister();
moduleControl.unregister();
ledRef.unregister();
bep.tearDown();
bepReg.unregister();
wsTracker.close();
camera.close();
cc.close();
}
/**
* @return a dictionary of properties for the IButtonEventProvider service.
*/
private Dictionary getButtonServiceProperties() {
Dictionary props = new Hashtable();
props.put("ButtonEventProvider", this.getClass().getName());
props.put("ButtonsProvided", "Camera");
return props;
}
public PublicWSDefinition discover(int operation) {
if (operation == PublicWSProvider.GET) {
return new PublicWSDefinition() {
public List getParameters() {
return null;
}
public String getReturnType() {
return IMAGE_MIME_TYPE;
}
};
}
return null;
}
public IWSResponse execute(int operation, String input) {
if (operation == PublicWSProvider.GET) {
return new WSResponse(getImageInputStream(), IMAGE_MIME_TYPE);
}
return null;
}
public String getPublicName() {
return "Picture";
}
public List getModuleProperties() {
modProps.clear();
//Removing...this information needs to come from the device.
//modProps.add(new ModuleProperty("MP", "" + megapixels, "Number", false));
modProps.add(new ModuleProperty("Slot", "" + slotId));
return modProps;
}
public String getModuleName() {
return moduleName;
}
public boolean setModuleProperty(IModuleProperty property) {
return false;
}
public byte[] getImage() {
return camera.grabFrame();
}
public boolean initOverlay(Rectangle pbounds){
if (camera.overlayinit(pbounds.x, pbounds.y, pbounds.width, pbounds.height) < 0)
return false;
else
return true;
}
public boolean startOverlay(){
if (camera.overlaystart() < 0)
return false;
else
return true;
}
public boolean stopOverlay(){
if (camera.overlaystop() < 0)
return false;
else
return true;
}
public InputStream getImageInputStream() {
return new ByteArrayInputStream(camera.grabFrame());
}
public String getFormat() {
return IMAGE_MIME_TYPE;
}
public String getDescription() {
return "This service can return image data from a hardware camera.";
}
}
| true | true | public void start() throws Exception {
modProps = new ArrayList();
camera = new Camera();
//TODO: Change this when we move to linux 2.6.22 or greater since
//BMI agent should listen to UDEV ACTION=="online" before starting modlets
try {
CharDeviceUtils.openDeviceWithRetry(camera, CAMERA_DEVICE_NODE, 2);
} catch (IOException e) {
String errormsg = "Unable to open camera device node: " + CAMERA_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
cc = new CameraControl();
try {
CharDeviceUtils.openDeviceWithRetry(cc, CAMERA_CONTROL_DEVICE_NODE, 2);
} catch (IOException e){
String errormsg = "Unable to open camera device node: " + CAMERA_CONTROL_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
System.out.println("I'm here!");
System.out.println("I'm here!");
System.out.println("I'm here!");
System.out.println("I'm here!");
System.out.println("I'm here!");
cameraControl = new CameraModuleControl(cc);
cameraControlRef = context.registerService(ICameraModuleControl.class.getName(), cameraControl, createRemotableProperties(null));
moduleControl = context.registerService(IModuleControl.class.getName(), this, createRemotableProperties(null));
cameraService = context.registerService(ICameraDevice.class.getName(), this, createRemotableProperties(null));
ledRef = context.registerService(IModuleLEDController.class.getName(), cameraControl, createRemotableProperties(null));
bep = new CameraInputEventProvider(DEVNODE_INPUT_DEVICE, logService);
bep.start();
bepReg = context.registerService(ICameraButtonEventProvider.class.getName(), bep, createRemotableProperties(getButtonServiceProperties()));
// Display the camera icon
regionKey = StatusBarUtils.displayImage(context, icon, this.getModuleName());
List wsProviders = new ArrayList();
wsProviders.add(this);
wsTracker = PublicWSAdminTracker.createTracker(context, wsProviders);
}
| public void start() throws Exception {
modProps = new ArrayList();
camera = new Camera();
//TODO: Change this when we move to linux 2.6.22 or greater since
//BMI agent should listen to UDEV ACTION=="online" before starting modlets
try {
CharDeviceUtils.openDeviceWithRetry(camera, CAMERA_DEVICE_NODE, 2);
} catch (IOException e) {
String errormsg = "Unable to open camera device node: " + CAMERA_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
cc = new CameraControl();
try {
CharDeviceUtils.openDeviceWithRetry(cc, CAMERA_CONTROL_DEVICE_NODE, 2);
} catch (IOException e){
String errormsg = "Unable to open camera device node: " + CAMERA_CONTROL_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
cameraControl = new CameraModuleControl(cc);
cameraControlRef = context.registerService(ICameraModuleControl.class.getName(), cameraControl, createRemotableProperties(null));
moduleControl = context.registerService(IModuleControl.class.getName(), this, createRemotableProperties(null));
cameraService = context.registerService(ICameraDevice.class.getName(), this, createRemotableProperties(null));
ledRef = context.registerService(IModuleLEDController.class.getName(), cameraControl, createRemotableProperties(null));
bep = new CameraInputEventProvider(DEVNODE_INPUT_DEVICE, logService);
bep.start();
bepReg = context.registerService(ICameraButtonEventProvider.class.getName(), bep, createRemotableProperties(getButtonServiceProperties()));
// Display the camera icon
regionKey = StatusBarUtils.displayImage(context, icon, this.getModuleName());
List wsProviders = new ArrayList();
wsProviders.add(this);
wsTracker = PublicWSAdminTracker.createTracker(context, wsProviders);
}
|
diff --git a/rultor-conveyer/src/main/java/com/rultor/conveyer/XemblyReportingWallet.java b/rultor-conveyer/src/main/java/com/rultor/conveyer/XemblyReportingWallet.java
index 343690c2f..4afdde10c 100644
--- a/rultor-conveyer/src/main/java/com/rultor/conveyer/XemblyReportingWallet.java
+++ b/rultor-conveyer/src/main/java/com/rultor/conveyer/XemblyReportingWallet.java
@@ -1,90 +1,90 @@
/**
* Copyright (c) 2009-2013, rultor.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the rultor.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rultor.conveyer;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.urn.URN;
import com.rultor.snapshot.XemblyLine;
import com.rultor.spi.Wallet;
import com.rultor.tools.Dollars;
import lombok.EqualsAndHashCode;
import org.xembly.Directives;
/**
* Wallet logging every charge in Xembly.
*
* @author Evgeniy Nyavro ([email protected])
* @version $Id$
* @since 1.0
*/
@Immutable
@Loggable(Loggable.DEBUG)
@EqualsAndHashCode(of = { "wallet" })
final class XemblyReportingWallet implements Wallet {
/**
* Underlying wallet.
*/
private final transient Wallet wallet;
/**
* Public ctor.
* @param underlying Underlying wallet to wrap
*/
protected XemblyReportingWallet(final Wallet underlying) {
this.wallet = underlying;
}
/**
* {@inheritDoc}
*/
@Override
public void charge(final String details, final Dollars amount) {
this.wallet.charge(details, amount);
new XemblyLine(
new Directives()
.xpath("/snapshot")
- .add("cost")
+ .addIf("cost")
.xset(String.format(". + %d", amount.points()))
).log();
}
/**
* {@inheritDoc}
* @checkstyle RedundantThrows (5 lines)
*/
@Override
public Wallet delegate(final URN urn, final String name)
throws NotEnoughFundsException {
return this.wallet.delegate(urn, name);
}
}
| true | true | public void charge(final String details, final Dollars amount) {
this.wallet.charge(details, amount);
new XemblyLine(
new Directives()
.xpath("/snapshot")
.add("cost")
.xset(String.format(". + %d", amount.points()))
).log();
}
| public void charge(final String details, final Dollars amount) {
this.wallet.charge(details, amount);
new XemblyLine(
new Directives()
.xpath("/snapshot")
.addIf("cost")
.xset(String.format(". + %d", amount.points()))
).log();
}
|
diff --git a/src/net/contra/obfuscator/util/misc/Misc.java b/src/net/contra/obfuscator/util/misc/Misc.java
index 210f07d..9239af1 100644
--- a/src/net/contra/obfuscator/util/misc/Misc.java
+++ b/src/net/contra/obfuscator/util/misc/Misc.java
@@ -1,62 +1,62 @@
package net.contra.obfuscator.util.misc;
import net.contra.obfuscator.Settings;
import java.util.Random;
/**
* Created by IntelliJ IDEA.
* User: Contra
* Date: 2/7/11
* Time: 8:36 AM
*/
public class Misc {
public static String getRandomName() {
switch (Settings.ObfuscationLevel) {
case Light:
return getRandomString(5, true);
case Normal:
return getRandomString(8, true);
case Heavy:
return getRandomString(5, false);
case Insane:
return getRandomString(10, false);
default:
return getRandomString(5, true);
}
}
public static String getRandomClassName() {
switch (Settings.ObfuscationLevel) {
case Light:
return getRandomString(8, true);
case Normal:
return getRandomString(10, true);
case Heavy:
return getRandomString(15, true);
case Insane:
return getRandomString(20, true);
default:
return getRandomString(8, true);
}
}
private static String getRandomString(int length, boolean simple) {
if (!simple) {
- Random rand = new Random(System.currentTimeMillis());
+ Random rand = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append(new char[rand.nextInt(255)]);
}
return sb.toString();
} else {
String charset = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890$_";
- Random rand = new Random(System.currentTimeMillis());
+ Random rand = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append(charset.charAt(rand.nextInt(charset.length())));
}
- return "c" + sb.toString();
+ return "c" + sb.toString() + rand.nextInt(20);
}
}
}
| false | true | private static String getRandomString(int length, boolean simple) {
if (!simple) {
Random rand = new Random(System.currentTimeMillis());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append(new char[rand.nextInt(255)]);
}
return sb.toString();
} else {
String charset = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890$_";
Random rand = new Random(System.currentTimeMillis());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append(charset.charAt(rand.nextInt(charset.length())));
}
return "c" + sb.toString();
}
}
| private static String getRandomString(int length, boolean simple) {
if (!simple) {
Random rand = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append(new char[rand.nextInt(255)]);
}
return sb.toString();
} else {
String charset = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890$_";
Random rand = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append(charset.charAt(rand.nextInt(charset.length())));
}
return "c" + sb.toString() + rand.nextInt(20);
}
}
|
diff --git a/support/src/main/java/org/fourthline/cling/support/model/RecordMediumWriteStatus.java b/support/src/main/java/org/fourthline/cling/support/model/RecordMediumWriteStatus.java
index cbd8ecd..a15762e 100644
--- a/support/src/main/java/org/fourthline/cling/support/model/RecordMediumWriteStatus.java
+++ b/support/src/main/java/org/fourthline/cling/support/model/RecordMediumWriteStatus.java
@@ -1,36 +1,38 @@
/*
* Copyright (C) 2013 4th Line GmbH, Switzerland
*
* The contents of this file are subject to the terms of either the GNU
* Lesser General Public License Version 2 or later ("LGPL") or the
* Common Development and Distribution License Version 1 or later
* ("CDDL") (collectively, the "License"). You may not use this file
* except in compliance with the License. See LICENSE.txt for more
* information.
*
* 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.
*/
package org.fourthline.cling.support.model;
/**
*
*/
public enum RecordMediumWriteStatus {
WRITABLE,
PROTECTED,
NOT_WRITABLE,
UNKNOWN,
NOT_IMPLEMENTED;
static public RecordMediumWriteStatus valueOrUnknownOf(String s) {
+ if (s == null)
+ return UNKNOWN;
try {
return valueOf(s);
} catch (IllegalArgumentException ex) {
return UNKNOWN;
}
}
}
| true | true | static public RecordMediumWriteStatus valueOrUnknownOf(String s) {
try {
return valueOf(s);
} catch (IllegalArgumentException ex) {
return UNKNOWN;
}
}
| static public RecordMediumWriteStatus valueOrUnknownOf(String s) {
if (s == null)
return UNKNOWN;
try {
return valueOf(s);
} catch (IllegalArgumentException ex) {
return UNKNOWN;
}
}
|
diff --git a/gdx/src/com/badlogic/gdx/Version.java b/gdx/src/com/badlogic/gdx/Version.java
index d8a5ed275..e460f36f1 100644
--- a/gdx/src/com/badlogic/gdx/Version.java
+++ b/gdx/src/com/badlogic/gdx/Version.java
@@ -1,44 +1,41 @@
/*
* Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.badlogic.gdx;
import com.badlogic.gdx.utils.GdxNativesLoader;
/**
* The version of libgdx
*
* @author mzechner
*
*/
public class Version {
/** the current version of libgdx in the major.minor format **/
public static String VERSION = "0.81";
public static void loadLibrary () {
if(GdxNativesLoader.loadLibraries())
return;
String os = System.getProperty("os.name");
String arch = System.getProperty("os.arch");
if (!arch.equals("amd64") || os.contains("Mac")) {
System.loadLibrary("gdx");
}
else {
- if( arch.contains("Windows") )
- throw new UnsupportedOperationException("Libgdx applications only work with 32-bit VMs on Windows at the moment!");
- else
- System.loadLibrary("gdx-64");
+ System.loadLibrary("gdx-64");
}
}
}
| true | true | public static void loadLibrary () {
if(GdxNativesLoader.loadLibraries())
return;
String os = System.getProperty("os.name");
String arch = System.getProperty("os.arch");
if (!arch.equals("amd64") || os.contains("Mac")) {
System.loadLibrary("gdx");
}
else {
if( arch.contains("Windows") )
throw new UnsupportedOperationException("Libgdx applications only work with 32-bit VMs on Windows at the moment!");
else
System.loadLibrary("gdx-64");
}
}
| public static void loadLibrary () {
if(GdxNativesLoader.loadLibraries())
return;
String os = System.getProperty("os.name");
String arch = System.getProperty("os.arch");
if (!arch.equals("amd64") || os.contains("Mac")) {
System.loadLibrary("gdx");
}
else {
System.loadLibrary("gdx-64");
}
}
|
diff --git a/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/api/DocumentModelComparator.java b/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/api/DocumentModelComparator.java
index 739bc8423..11086ce03 100644
--- a/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/api/DocumentModelComparator.java
+++ b/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/api/DocumentModelComparator.java
@@ -1,146 +1,146 @@
/*
* (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* <a href="mailto:[email protected]">Anahide Tchertchian</a>
*
* $Id$
*/
package org.nuxeo.ecm.core.api;
import java.text.Collator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.nuxeo.ecm.core.api.model.PropertyException;
/**
* DocumentModel comparator. Uses ordering independent of case or accent. If two
* values are integers/longs, numbering comparison is used.
*
* @author Florent Guillaume
* @author Anahide Tchertchian
*/
public class DocumentModelComparator implements Sorter {
private static final long serialVersionUID = 1L;
public static final String ORDER_ASC = "asc";
static final Collator collator = Collator.getInstance();
static {
collator.setStrength(Collator.PRIMARY); // case+accent independent
}
final String schemaName;
final Map<String, String> orderBy;
/**
* Constructor using a map of property names to compare on.
*
* @param orderBy map using property names as keys, and "asc" or "desc" as
* values. Should be a {@link LinkedHashMap} if order of criteria
* matters.
*/
public DocumentModelComparator(Map<String, String> orderBy) {
this.schemaName = null;
this.orderBy = orderBy;
}
/**
* Constructor using a schema and a map of field names to compare on.
*
* @param schemaName the schema name
* @param orderBy map using property names as keys, and "asc" or "desc" as
* values. Should be a {@link LinkedHashMap} if order of criteria
* matters.
*/
public DocumentModelComparator(String schemaName,
Map<String, String> orderBy) {
this.schemaName = schemaName;
this.orderBy = orderBy;
}
protected int compare(Object v1, Object v2, boolean asc) {
if (v1 == null && v2 == null) {
return 0;
} else if (v1 == null) {
return asc ? -1 : 1;
} else if (v2 == null) {
return asc ? 1 : -1;
}
final int cmp;
if (v1 instanceof Long && v2 instanceof Long) {
cmp = ((Long) v1).compareTo((Long) v2);
} else if (v1 instanceof Integer && v2 instanceof Integer) {
cmp = ((Integer) v1).compareTo((Integer) v2);
} else {
cmp = collator.compare(v1.toString(), v2.toString());
}
return asc ? cmp : -cmp;
}
public int compare(DocumentModel doc1, DocumentModel doc2) {
int cmp = 0;
if (schemaName != null) {
final DataModel d1 = doc1.getDataModel(schemaName);
final DataModel d2 = doc2.getDataModel(schemaName);
for (Entry<String, String> e : orderBy.entrySet()) {
final String fieldName = e.getKey();
final boolean asc = ORDER_ASC.equals(e.getValue());
final Object v1 = d1.getData(fieldName);
final Object v2 = d2.getData(fieldName);
cmp = compare(v1, v2, asc);
- if (cmp == 0) {
- continue;
+ if (cmp != 0) {
+ break;
}
}
} else {
for (Entry<String, String> e : orderBy.entrySet()) {
final String propertyName = e.getKey();
final boolean asc = ORDER_ASC.equals(e.getValue());
Object v1;
try {
v1 = doc1.getPropertyValue(propertyName);
} catch (PropertyException pe) {
v1 = null;
}
Object v2;
try {
v2 = doc2.getPropertyValue(propertyName);
} catch (PropertyException pe) {
v2 = null;
}
cmp = compare(v1, v2, asc);
- if (cmp == 0) {
- continue;
+ if (cmp != 0) {
+ break;
}
}
}
if (cmp == 0) {
// everything being equal, provide consistent ordering
if (doc1.hashCode() == doc2.hashCode()) {
cmp = 0;
} else if (doc1.hashCode() < doc2.hashCode()) {
cmp = -1;
} else {
cmp = 1;
}
}
return cmp;
}
}
| false | true | public int compare(DocumentModel doc1, DocumentModel doc2) {
int cmp = 0;
if (schemaName != null) {
final DataModel d1 = doc1.getDataModel(schemaName);
final DataModel d2 = doc2.getDataModel(schemaName);
for (Entry<String, String> e : orderBy.entrySet()) {
final String fieldName = e.getKey();
final boolean asc = ORDER_ASC.equals(e.getValue());
final Object v1 = d1.getData(fieldName);
final Object v2 = d2.getData(fieldName);
cmp = compare(v1, v2, asc);
if (cmp == 0) {
continue;
}
}
} else {
for (Entry<String, String> e : orderBy.entrySet()) {
final String propertyName = e.getKey();
final boolean asc = ORDER_ASC.equals(e.getValue());
Object v1;
try {
v1 = doc1.getPropertyValue(propertyName);
} catch (PropertyException pe) {
v1 = null;
}
Object v2;
try {
v2 = doc2.getPropertyValue(propertyName);
} catch (PropertyException pe) {
v2 = null;
}
cmp = compare(v1, v2, asc);
if (cmp == 0) {
continue;
}
}
}
if (cmp == 0) {
// everything being equal, provide consistent ordering
if (doc1.hashCode() == doc2.hashCode()) {
cmp = 0;
} else if (doc1.hashCode() < doc2.hashCode()) {
cmp = -1;
} else {
cmp = 1;
}
}
return cmp;
}
| public int compare(DocumentModel doc1, DocumentModel doc2) {
int cmp = 0;
if (schemaName != null) {
final DataModel d1 = doc1.getDataModel(schemaName);
final DataModel d2 = doc2.getDataModel(schemaName);
for (Entry<String, String> e : orderBy.entrySet()) {
final String fieldName = e.getKey();
final boolean asc = ORDER_ASC.equals(e.getValue());
final Object v1 = d1.getData(fieldName);
final Object v2 = d2.getData(fieldName);
cmp = compare(v1, v2, asc);
if (cmp != 0) {
break;
}
}
} else {
for (Entry<String, String> e : orderBy.entrySet()) {
final String propertyName = e.getKey();
final boolean asc = ORDER_ASC.equals(e.getValue());
Object v1;
try {
v1 = doc1.getPropertyValue(propertyName);
} catch (PropertyException pe) {
v1 = null;
}
Object v2;
try {
v2 = doc2.getPropertyValue(propertyName);
} catch (PropertyException pe) {
v2 = null;
}
cmp = compare(v1, v2, asc);
if (cmp != 0) {
break;
}
}
}
if (cmp == 0) {
// everything being equal, provide consistent ordering
if (doc1.hashCode() == doc2.hashCode()) {
cmp = 0;
} else if (doc1.hashCode() < doc2.hashCode()) {
cmp = -1;
} else {
cmp = 1;
}
}
return cmp;
}
|
diff --git a/components/dotnet-dao-project/src/main/java/npanday/dao/impl/ProjectDaoImpl.java b/components/dotnet-dao-project/src/main/java/npanday/dao/impl/ProjectDaoImpl.java
index 37ddbd75..db606159 100644
--- a/components/dotnet-dao-project/src/main/java/npanday/dao/impl/ProjectDaoImpl.java
+++ b/components/dotnet-dao-project/src/main/java/npanday/dao/impl/ProjectDaoImpl.java
@@ -1,1268 +1,1271 @@
/*
* 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 npanday.dao.impl;
import npanday.ArtifactType;
import npanday.ArtifactTypeHelper;
import npanday.dao.ProjectDao;
import npanday.dao.ProjectUri;
import npanday.dao.ProjectFactory;
import npanday.dao.Project;
import npanday.dao.ProjectDependency;
import npanday.dao.Requirement;
import npanday.registry.RepositoryRegistry;
import npanday.PathUtil;
import org.apache.maven.project.MavenProject;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.DefaultArtifactRepository;
import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.manager.WagonManager;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.wagon.TransferFailedException;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.model.Model;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.Repository;
import org.openrdf.OpenRDFException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.BindingSet;
import org.openrdf.query.Binding;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.DefaultConsumer;
import org.codehaus.plexus.util.cli.StreamConsumer;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.codehaus.plexus.util.FileUtils;
import java.util.logging.Logger;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.EOFException;
import java.lang.ExceptionInInitializerError;
import java.net.URISyntaxException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public final class ProjectDaoImpl
implements ProjectDao
{
private String className;
private String id;
private static Logger logger = Logger.getAnonymousLogger();
private org.openrdf.repository.Repository rdfRepository;
/**
* The artifact factory component, which is used for creating artifacts.
*/
private org.apache.maven.artifact.factory.ArtifactFactory artifactFactory;
private int getProjectForCounter = 0;
private int storeCounter = 0;
private RepositoryConnection repositoryConnection;
private String dependencyQuery;
private String projectQuery;
private ArtifactResolver artifactResolver;
public void init( ArtifactFactory artifactFactory, ArtifactResolver artifactResolver )
{
this.artifactFactory = artifactFactory;
this.artifactResolver = artifactResolver;
List<ProjectUri> projectUris = new ArrayList<ProjectUri>();
projectUris.add( ProjectUri.GROUP_ID );
projectUris.add( ProjectUri.ARTIFACT_ID );
projectUris.add( ProjectUri.VERSION );
projectUris.add( ProjectUri.ARTIFACT_TYPE );
projectUris.add( ProjectUri.IS_RESOLVED );
projectUris.add( ProjectUri.DEPENDENCY );
projectUris.add( ProjectUri.CLASSIFIER );
dependencyQuery = "SELECT * FROM " + this.constructQueryFragmentFor( "{x}", projectUris );
projectUris = new ArrayList<ProjectUri>();
projectUris.add( ProjectUri.GROUP_ID );
projectUris.add( ProjectUri.ARTIFACT_ID );
projectUris.add( ProjectUri.VERSION );
projectUris.add( ProjectUri.ARTIFACT_TYPE );
projectUris.add( ProjectUri.IS_RESOLVED );
projectUris.add( ProjectUri.DEPENDENCY );
projectUris.add( ProjectUri.CLASSIFIER );
projectUris.add( ProjectUri.PARENT );
projectQuery = "SELECT * FROM " + this.constructQueryFragmentFor( "{x}", projectUris );
}
public Set<Project> getAllProjects()
throws IOException
{
Set<Project> projects = new HashSet<Project>();
TupleQueryResult result = null;
try
{
TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, projectQuery );
result = tupleQuery.evaluate();
while ( result.hasNext() )
{
BindingSet set = result.next();
String groupId = set.getBinding( ProjectUri.GROUP_ID.getObjectBinding() ).getValue().toString();
String version = set.getBinding( ProjectUri.VERSION.getObjectBinding() ).getValue().toString();
String artifactId = set.getBinding( ProjectUri.ARTIFACT_ID.getObjectBinding() ).getValue().toString();
String artifactType =
set.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString();
String classifier = null;
if ( set.hasBinding( ProjectUri.CLASSIFIER.getObjectBinding() ) )
{
classifier = set.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() ).getValue().toString();
}
// Project project = getProjectFor( groupId, artifactId, version, artifactType, null );
/*
* for ( Iterator<Binding> i = set.iterator(); i.hasNext(); ) { Binding b = i.next();
* System.out.println( b.getName() + ":" + b.getValue() ); }
*/
projects.add( getProjectFor( groupId, artifactId, version, artifactType, classifier ) );
}
}
catch ( RepositoryException e )
{
throw new IOException( "NPANDAY-180-000: Message = " + e.getMessage() );
}
catch ( MalformedQueryException e )
{
throw new IOException( "NPANDAY-180-001: Message = " + e.getMessage() );
}
catch ( QueryEvaluationException e )
{
throw new IOException( "NPANDAY-180-002: Message = " + e.getMessage() );
}
finally
{
if ( result != null )
{
try
{
result.close();
}
catch ( QueryEvaluationException e )
{
}
}
}
return projects;
}
public void setRdfRepository( Repository repository )
{
this.rdfRepository = repository;
}
public boolean openConnection()
{
try
{
repositoryConnection = rdfRepository.getConnection();
repositoryConnection.setAutoCommit( false );
}
catch ( RepositoryException e )
{
return false;
}
return true;
}
public boolean closeConnection()
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.commit();
repositoryConnection.close();
}
catch ( RepositoryException e )
{
return false;
}
}
return true;
}
public void removeProjectFor( String groupId, String artifactId, String version, String artifactType )
throws IOException
{
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id = valueFactory.createURI( groupId + ":" + artifactId + ":" + version + ":" + artifactType );
try
{
repositoryConnection.remove( repositoryConnection.getStatements( id, null, null, true ) );
}
catch ( RepositoryException e )
{
throw new IOException( e.getMessage() );
}
}
public Project getProjectFor( String groupId, String artifactId, String version, String artifactType,
String publicKeyTokenId )
throws IOException
{
long startTime = System.currentTimeMillis();
ValueFactory valueFactory = rdfRepository.getValueFactory();
Project project = new ProjectDependency();
project.setArtifactId( artifactId );
project.setGroupId( groupId );
project.setVersion( version );
project.setArtifactType( artifactType );
project.setPublicKeyTokenId( publicKeyTokenId );
TupleQueryResult result = null;
try
{
TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, projectQuery );
tupleQuery.setBinding( ProjectUri.GROUP_ID.getObjectBinding(), valueFactory.createLiteral( groupId ) );
tupleQuery.setBinding( ProjectUri.ARTIFACT_ID.getObjectBinding(), valueFactory.createLiteral( artifactId ) );
tupleQuery.setBinding( ProjectUri.VERSION.getObjectBinding(), valueFactory.createLiteral( version ) );
tupleQuery.setBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding(),
valueFactory.createLiteral( artifactType ) );
if ( publicKeyTokenId != null )
{
tupleQuery.setBinding( ProjectUri.CLASSIFIER.getObjectBinding(),
valueFactory.createLiteral( publicKeyTokenId ) );
project.setPublicKeyTokenId( publicKeyTokenId.replace( ":", "" ) );
}
result = tupleQuery.evaluate();
if ( !result.hasNext() )
{
if ( artifactType != null && ArtifactTypeHelper.isDotnetAnyGac( artifactType ) )
{
Artifact artifact =
ProjectFactory.createArtifactFrom( (ProjectDependency) project, artifactFactory );
if ( !artifact.getFile().exists() )
{
throw new IOException( "NPANDAY-180-003: Could not find GAC assembly: Group ID = " + groupId
+ ", Artifact ID = " + artifactId + ", Version = " + version + ", Artifact Type = "
+ artifactType + ", File Path = " + artifact.getFile().getAbsolutePath() );
}
project.setResolved( true );
return project;
}
throw new IOException( "NPANDAY-180-004: Could not find the project: Group ID = " + groupId
+ ", Artifact ID = " + artifactId + ", Version = " + version + ", Artifact Type = " + artifactType );
}
while ( result.hasNext() )
{
BindingSet set = result.next();
/*
* for ( Iterator<Binding> i = set.iterator(); i.hasNext(); ) { Binding b = i.next();
* System.out.println( b.getName() + ":" + b.getValue() ); }
*/
if ( set.hasBinding( ProjectUri.IS_RESOLVED.getObjectBinding() )
&& set.getBinding( ProjectUri.IS_RESOLVED.getObjectBinding() ).getValue().toString().equalsIgnoreCase(
"true" ) )
{
project.setResolved( true );
}
project.setArtifactType( set.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString() );
/*
* if ( set.hasBinding( ProjectUri.PARENT.getObjectBinding() ) ) { String pid = set.getBinding(
* ProjectUri.PARENT.getObjectBinding() ).getValue().toString(); String[] tokens = pid.split( "[:]" );
* Project parentProject = getProjectFor( tokens[0], tokens[1], tokens[2], null, null );
* project.setParentProject( parentProject ); }
*/
if ( set.hasBinding( ProjectUri.DEPENDENCY.getObjectBinding() ) )
{
Binding binding = set.getBinding( ProjectUri.DEPENDENCY.getObjectBinding() );
addDependenciesToProject( project, repositoryConnection, binding.getValue() );
}
if ( set.hasBinding( ProjectUri.CLASSIFIER.getObjectBinding() ) )
{
Binding binding = set.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() );
addClassifiersToProject( project, repositoryConnection, binding.getValue() );
}
}
}
catch ( QueryEvaluationException e )
{
throw new IOException( "NPANDAY-180-005: Message = " + e.getMessage() );
}
catch ( RepositoryException e )
{
throw new IOException( "NPANDAY-180-006: Message = " + e.getMessage() );
}
catch ( MalformedQueryException e )
{
throw new IOException( "NPANDAY-180-007: Message = " + e.getMessage() );
}
finally
{
if ( result != null )
{
try
{
result.close();
}
catch ( QueryEvaluationException e )
{
}
}
}
// TODO: If has parent, then need to modify dependencies, etc of returned project
logger.finest( "NPANDAY-180-008: ProjectDao.GetProjectFor - Artifact Id = " + project.getArtifactId()
+ ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = " + getProjectForCounter++ );
return project;
}
public Project getProjectFor( MavenProject mavenProject )
throws IOException
{
return getProjectFor( mavenProject.getGroupId(), mavenProject.getArtifactId(), mavenProject.getVersion(),
mavenProject.getArtifact().getType(), mavenProject.getArtifact().getClassifier() );
}
public void storeProject( Project project, File localRepository, List<ArtifactRepository> artifactRepositories )
throws IOException
{
}
/**
* Generates the system path for gac dependencies.
*/
private String generateDependencySystemPath( ProjectDependency projectDependency )
{
return new File( System.getenv( "SystemRoot" ), "/assembly/"
+ projectDependency.getArtifactType().toUpperCase() + "/" + projectDependency.getArtifactId() + "/"
+ projectDependency.getVersion() + "__" + projectDependency.getPublicKeyTokenId() + "/"
+ projectDependency.getArtifactId() + ".dll" ).getAbsolutePath();
}
public Set<Artifact> storeProjectAndResolveDependencies( Project project, File localRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException, IllegalArgumentException
{
long startTime = System.currentTimeMillis();
String snapshotVersion;
if ( project == null )
{
throw new IllegalArgumentException( "NPANDAY-180-009: Project is null" );
}
if ( project.getGroupId() == null || project.getArtifactId() == null || project.getVersion() == null )
{
throw new IllegalArgumentException( "NPANDAY-180-010: Project value is null: Group Id ="
+ project.getGroupId() + ", Artifact Id = " + project.getArtifactId() + ", Version = "
+ project.getVersion() );
}
Set<Artifact> artifactDependencies = new HashSet<Artifact>();
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id =
valueFactory.createURI( project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()
+ ":" + project.getArtifactType() );
URI groupId = valueFactory.createURI( ProjectUri.GROUP_ID.getPredicate() );
URI artifactId = valueFactory.createURI( ProjectUri.ARTIFACT_ID.getPredicate() );
URI version = valueFactory.createURI( ProjectUri.VERSION.getPredicate() );
URI artifactType = valueFactory.createURI( ProjectUri.ARTIFACT_TYPE.getPredicate() );
URI classifier = valueFactory.createURI( ProjectUri.CLASSIFIER.getPredicate() );
URI isResolved = valueFactory.createURI( ProjectUri.IS_RESOLVED.getPredicate() );
URI artifact = valueFactory.createURI( ProjectUri.ARTIFACT.getPredicate() );
URI dependency = valueFactory.createURI( ProjectUri.DEPENDENCY.getPredicate() );
URI parent = valueFactory.createURI( ProjectUri.PARENT.getPredicate() );
Set<Model> modelDependencies = new HashSet<Model>();
try
{
repositoryConnection.add( id, RDF.TYPE, artifact );
repositoryConnection.add( id, groupId, valueFactory.createLiteral( project.getGroupId() ) );
repositoryConnection.add( id, artifactId, valueFactory.createLiteral( project.getArtifactId() ) );
repositoryConnection.add( id, version, valueFactory.createLiteral( project.getVersion() ) );
repositoryConnection.add( id, artifactType, valueFactory.createLiteral( project.getArtifactType() ) );
if ( project.getPublicKeyTokenId() != null )
{
URI classifierNode = valueFactory.createURI( project.getPublicKeyTokenId() + ":" );
for ( Requirement requirement : project.getRequirements() )
{
URI uri = valueFactory.createURI( requirement.getUri().toString() );
repositoryConnection.add( classifierNode, uri, valueFactory.createLiteral( requirement.getValue() ) );
}
repositoryConnection.add( id, classifier, classifierNode );
}
if ( project.getParentProject() != null )
{
Project parentProject = project.getParentProject();
URI pid =
valueFactory.createURI( parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":"
+ parentProject.getVersion() + ":" + project.getArtifactType() );
repositoryConnection.add( id, parent, pid );
artifactDependencies.addAll( storeProjectAndResolveDependencies( parentProject, null,
artifactRepositories ) );
}
for ( ProjectDependency projectDependency : project.getProjectDependencies() )
{
snapshotVersion = null;
logger.finest( "NPANDAY-180-011: Project Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Artifact Type = "
+ projectDependency.getArtifactType() );
// If artifact has been deleted, then re-resolve
if ( projectDependency.isResolved() && !ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
File dependencyFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
if ( !dependencyFile.exists() )
{
projectDependency.setResolved( false );
}
}
// resolve system scope dependencies
if ( projectDependency.getScope() != null && projectDependency.getScope().equals( "system" ) )
{
if ( projectDependency.getSystemPath() == null )
{
throw new IOException( "systemPath required for System Scoped dependencies " + "in Group ID = "
+ projectDependency.getGroupId() + ", Artiract ID = " + projectDependency.getArtifactId() );
}
File f = new File( projectDependency.getSystemPath() );
if ( !f.exists() )
{
throw new IOException( "Dependency systemPath File not found:"
+ projectDependency.getSystemPath() + "in Group ID = " + projectDependency.getGroupId()
+ ", Artiract ID = " + projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve com reference
// flow:
// 1. generate the interop dll in temp folder and resolve to that path during dependency resolution
// 2. cut and paste the dll to buildDirectory and update the paths once we grab the reference of
// MavenProject (CompilerContext.java)
if ( projectDependency.getArtifactType().equals( "com_reference" ) )
{
String tokenId = projectDependency.getPublicKeyTokenId();
String interopPath = generateInteropDll( projectDependency.getArtifactId(), tokenId );
File f = new File( interopPath );
if ( !f.exists() )
{
throw new IOException( "Dependency com_reference File not found:" + interopPath
+ "in Group ID = " + projectDependency.getGroupId() + ", Artiract ID = "
+ projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve gac references
// note: the old behavior of gac references, used to have system path properties in the pom of the
// project
// now we need to generate the system path of the gac references so we can use
// System.getenv("SystemRoot")
if ( !projectDependency.isResolved() )
{
if ( ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
try
{
projectDependency.setResolved( true );
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
File f = new File( projectDependency.getSystemPath() );
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
}
catch ( ExceptionInInitializerError e )
{
logger.warning( "NPANDAY-180-516.82: Project Failed to Resolve Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = "
+ projectDependency.getScope() + "SystemPath = " + projectDependency.getSystemPath() );
}
}
else
{
try
{
Project dep =
this.getProjectFor( projectDependency.getGroupId(), projectDependency.getArtifactId(),
projectDependency.getVersion(),
projectDependency.getArtifactType(),
projectDependency.getPublicKeyTokenId() );
if ( dep.isResolved() )
{
Artifact assembly =
ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
// re-resolve snapshots
if ( !assembly.isSnapshot() )
{
projectDependency = (ProjectDependency) dep;
artifactDependencies.add( assembly );
Set<Artifact> deps = this.storeProjectAndResolveDependencies( projectDependency,
localRepository,
artifactRepositories );
artifactDependencies.addAll( deps );
}
}
}
catch ( IOException e )
{
// safe to ignore: dependency not found
}
}
}
if ( !projectDependency.isResolved() )
{
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
if ( assembly.getType().equals( "jar" ) )
{
logger.info( "Detected jar dependency - skipping: Artifact Dependency ID = "
+ assembly.getArtifactId() );
continue;
}
ArtifactType type = ArtifactType.getArtifactTypeForPackagingName( assembly.getType() );
logger.info( "NPANDAY-180-012: Resolving artifact for unresolved dependency: "
+ assembly.getId());
ArtifactRepository localArtifactRepository =
new DefaultArtifactRepository( "local", "file://" + localRepository,
new DefaultRepositoryLayout() );
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ))// TODO: Generalize to any attached artifact
{
Artifact pomArtifact =
artifactFactory.createProjectArtifact( projectDependency.getGroupId(),
projectDependency.getArtifactId(),
projectDependency.getVersion() );
try
{
artifactResolver.resolve( pomArtifact, artifactRepositories,
localArtifactRepository );
logger.info( "NPANDAY-180-024: resolving pom artifact: " + pomArtifact.toString() );
snapshotVersion = pomArtifact.getVersion();
}
catch ( ArtifactNotFoundException e )
{
logger.info( "NPANDAY-180-025: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.info( "NPANDAY-180-026: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
if ( pomArtifact.getFile() != null && pomArtifact.getFile().exists() )
{
FileReader fileReader = new FileReader( pomArtifact.getFile() );
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model;
try
{
model = reader.read( fileReader ); // TODO: interpolate values
}
catch ( XmlPullParserException e )
{
throw new IOException( "NPANDAY-180-015: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
catch ( EOFException e )
{
throw new IOException( "NPANDAY-180-016: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
// small hack for not doing inheritence
String g = model.getGroupId();
if ( g == null )
{
g = model.getParent().getGroupId();
}
String v = model.getVersion();
if ( v == null )
{
v = model.getParent().getVersion();
}
if ( !( g.equals( projectDependency.getGroupId() )
&& model.getArtifactId().equals( projectDependency.getArtifactId() ) && v.equals( projectDependency.getVersion() ) ) )
{
throw new IOException(
"NPANDAY-180-017: Model parameters do not match project dependencies parameters: Model: "
+ g + ":" + model.getArtifactId() + ":" + v + ", Project: "
+ projectDependency.getGroupId() + ":"
+ projectDependency.getArtifactId() + ":"
+ projectDependency.getVersion() );
}
modelDependencies.add( model );
}
}
if ( snapshotVersion != null )
{
assembly.setVersion( snapshotVersion );
}
File uacFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
logger.info( "NPANDAY-180-018: Not found in UAC, now retrieving artifact from wagon:"
+ assembly.getId()
+ ", Failed UAC Path Check = " + uacFile.getAbsolutePath());
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ) || !uacFile.exists() )// TODO: Generalize to any attached artifact
{
try
{
artifactResolver.resolve( assembly, artifactRepositories,
localArtifactRepository );
if ( assembly != null && assembly.getFile().exists() )
{
uacFile.getParentFile().mkdirs();
FileUtils.copyFile( assembly.getFile(), uacFile );
assembly.setFile( uacFile );
}
}
catch ( ArtifactNotFoundException e )
{
throw new IOException(
"NPANDAY-180-020: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
+ logger.error( "NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ + assembly.getId()
+ + ", Message = " + e.getMessage(), e );
throw new IOException(
"NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ assembly.getId()
- + ", Message = " + e.getMessage(), e );
+ + ", Message = " + e.getMessage() );
}
}
artifactDependencies.add( assembly );
}// end if dependency not resolved
URI did =
valueFactory.createURI( projectDependency.getGroupId() + ":" + projectDependency.getArtifactId()
+ ":" + projectDependency.getVersion() + ":" + projectDependency.getArtifactType() );
repositoryConnection.add( did, RDF.TYPE, artifact );
repositoryConnection.add( did, groupId, valueFactory.createLiteral( projectDependency.getGroupId() ) );
repositoryConnection.add( did, artifactId,
valueFactory.createLiteral( projectDependency.getArtifactId() ) );
repositoryConnection.add( did, version, valueFactory.createLiteral( projectDependency.getVersion() ) );
repositoryConnection.add( did, artifactType,
valueFactory.createLiteral( projectDependency.getArtifactType() ) );
if ( projectDependency.getPublicKeyTokenId() != null )
{
repositoryConnection.add(
did,
classifier,
valueFactory.createLiteral( projectDependency.getPublicKeyTokenId() + ":" ) );
}
repositoryConnection.add( id, dependency, did );
}// end for
repositoryConnection.add( id, isResolved, valueFactory.createLiteral( true ) );
repositoryConnection.commit();
}
catch ( OpenRDFException e )
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.rollback();
}
catch ( RepositoryException e1 )
{
}
}
throw new IOException( "NPANDAY-180-021: Could not open RDF Repository: Message =" + e.getMessage() );
}
for ( Model model : modelDependencies )
{
// System.out.println( "Storing dependency: Artifact Id = " + model.getArtifactId() );
artifactDependencies.addAll( storeProjectAndResolveDependencies( ProjectFactory.createProjectFrom( model,
null ),
localRepository, artifactRepositories ) );
}
logger.finest( "NPANDAY-180-022: ProjectDao.storeProjectAndResolveDependencies - Artifact Id = "
+ project.getArtifactId() + ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = "
+ storeCounter++ );
return artifactDependencies;
}
public Set<Artifact> storeModelAndResolveDependencies( Model model, File pomFileDirectory,
File localArtifactRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException
{
return storeProjectAndResolveDependencies( ProjectFactory.createProjectFrom( model, pomFileDirectory ),
localArtifactRepository, artifactRepositories );
}
public String getClassName()
{
return className;
}
public String getID()
{
return id;
}
public void init( Object dataStoreObject, String id, String className )
throws IllegalArgumentException
{
if ( dataStoreObject == null || !( dataStoreObject instanceof org.openrdf.repository.Repository ) )
{
throw new IllegalArgumentException(
"NPANDAY-180-023: Must initialize with an instance of org.openrdf.repository.Repository" );
}
this.id = id;
this.className = className;
this.rdfRepository = (org.openrdf.repository.Repository) dataStoreObject;
}
public void setRepositoryRegistry( RepositoryRegistry repositoryRegistry )
{
}
protected void initForUnitTest( Object dataStoreObject, String id, String className,
ArtifactResolver artifactResolver, ArtifactFactory artifactFactory )
{
this.init( dataStoreObject, id, className );
init( artifactFactory, artifactResolver );
}
private void addClassifiersToProject( Project project, RepositoryConnection repositoryConnection,
Value classifierUri )
throws RepositoryException, MalformedQueryException, QueryEvaluationException
{
String query = "SELECT * FROM {x} p {y}";
TupleQuery tq = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, query );
tq.setBinding( "x", classifierUri );
TupleQueryResult result = tq.evaluate();
while ( result.hasNext() )
{
BindingSet set = result.next();
for ( Iterator<Binding> i = set.iterator(); i.hasNext(); )
{
Binding binding = i.next();
if ( binding.getValue().toString().startsWith( "http://maven.apache.org/artifact/requirement" ) )
{
try
{
project.addRequirement( Requirement.Factory.createDefaultRequirement(
new java.net.URI(
binding.getValue().toString() ),
set.getValue( "y" ).toString() ) );
}
catch ( URISyntaxException e )
{
e.printStackTrace();
}
}
}
}
}
private void addDependenciesToProject( Project project, RepositoryConnection repositoryConnection,
Value dependencyUri )
throws RepositoryException, MalformedQueryException, QueryEvaluationException
{
TupleQuery tq = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, dependencyQuery );
tq.setBinding( "x", dependencyUri );
TupleQueryResult dependencyResult = tq.evaluate();
try
{
while ( dependencyResult.hasNext() )
{
ProjectDependency projectDependency = new ProjectDependency();
BindingSet bs = dependencyResult.next();
projectDependency.setGroupId( bs.getBinding( ProjectUri.GROUP_ID.getObjectBinding() ).getValue().toString() );
projectDependency.setArtifactId( bs.getBinding( ProjectUri.ARTIFACT_ID.getObjectBinding() ).getValue().toString() );
projectDependency.setVersion( bs.getBinding( ProjectUri.VERSION.getObjectBinding() ).getValue().toString() );
projectDependency.setArtifactType( bs.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString() );
Binding classifierBinding = bs.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() );
if ( classifierBinding != null )
{
projectDependency.setPublicKeyTokenId( classifierBinding.getValue().toString().replace( ":", "" ) );
}
project.addProjectDependency( projectDependency );
if ( bs.hasBinding( ProjectUri.DEPENDENCY.getObjectBinding() ) )
{
addDependenciesToProject( projectDependency, repositoryConnection,
bs.getValue( ProjectUri.DEPENDENCY.getObjectBinding() ) );
}
}
}
finally
{
dependencyResult.close();
}
}
private String constructQueryFragmentFor( String subject, List<ProjectUri> projectUris )
{
// ProjectUri nonOptionalUri = this.getNonOptionalUriFrom( projectUris );
// projectUris.remove( nonOptionalUri );
StringBuffer buffer = new StringBuffer();
buffer.append( subject );
for ( Iterator<ProjectUri> i = projectUris.iterator(); i.hasNext(); )
{
ProjectUri projectUri = i.next();
buffer.append( " " );
if ( projectUri.isOptional() )
{
buffer.append( "[" );
}
buffer.append( "<" ).append( projectUri.getPredicate() ).append( "> {" ).append(
projectUri.getObjectBinding() ).append(
"}" );
if ( projectUri.isOptional() )
{
buffer.append( "]" );
}
if ( i.hasNext() )
{
buffer.append( ";" );
}
}
return buffer.toString();
}
private ProjectUri getNonOptionalUriFrom( List<ProjectUri> projectUris )
{
for ( ProjectUri projectUri : projectUris )
{
if ( !projectUri.isOptional() )
{
return projectUri;
}
}
return null;
}
// TODO: move generateInteropDll, getInteropParameters, getTempDirectory, and execute methods to another class
private String generateInteropDll( String name, String classifier )
throws IOException
{
File tmpDir;
String comReferenceAbsolutePath = "";
try
{
tmpDir = getTempDirectory();
}
catch ( IOException e )
{
throw new IOException( "Unable to create temporary directory" );
}
try
{
comReferenceAbsolutePath = resolveComReferencePath( name, classifier );
}
catch ( Exception e )
{
throw new IOException( e.getMessage() );
}
String interopAbsolutePath = tmpDir.getAbsolutePath() + File.separator + "Interop." + name + ".dll";
List<String> params = getInteropParameters( interopAbsolutePath, comReferenceAbsolutePath, name );
try
{
execute( "tlbimp", params );
}
catch ( Exception e )
{
throw new IOException( e.getMessage() );
}
return interopAbsolutePath;
}
private String resolveComReferencePath( String name, String classifier )
throws Exception
{
String[] classTokens = classifier.split( "}" );
classTokens[1] = classTokens[1].replace( "-", "\\" );
String newClassifier = classTokens[0] + "}" + classTokens[1];
String registryPath = "HKEY_CLASSES_ROOT\\TypeLib\\" + newClassifier + "\\win32\\";
int lineNoOfPath = 1;
List<String> parameters = new ArrayList<String>();
parameters.add( "query" );
parameters.add( registryPath );
parameters.add( "/ve" );
StreamConsumer outConsumer = new StreamConsumerImpl();
StreamConsumer errorConsumer = new StreamConsumerImpl();
try
{
// TODO: investigate why outConsumer ignores newline
execute( "reg", parameters, outConsumer, errorConsumer );
}
catch ( Exception e )
{
throw new Exception( "Cannot find information of [" + name
+ "] ActiveX component in your system, you need to install this component first to continue." );
}
// parse outConsumer
String out = outConsumer.toString();
String tokens[] = out.split( "\n" );
String lineResult = "";
String[] result;
if ( tokens.length >= lineNoOfPath - 1 )
{
lineResult = tokens[lineNoOfPath - 1];
}
result = lineResult.split( "REG_SZ" );
if ( result.length > 1 )
{
return result[1].trim();
}
return null;
}
private List<String> readPomAttribute( String pomFileLoc, String tag )
{
List<String> attributes = new ArrayList<String>();
try
{
File file = new File( pomFileLoc );
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse( file );
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName( tag );
for ( int s = 0; s < nodeLst.getLength(); s++ )
{
Node currentNode = nodeLst.item( s );
NodeList childrenList = currentNode.getChildNodes();
for ( int i = 0; i < childrenList.getLength(); i++ )
{
Node child = childrenList.item( i );
attributes.add( child.getNodeValue() );
}
}
}
catch ( Exception e )
{
}
return attributes;
}
private List<String> getInteropParameters( String interopAbsolutePath, String comRerefenceAbsolutePath,
String namespace )
{
List<String> parameters = new ArrayList<String>();
parameters.add( comRerefenceAbsolutePath );
parameters.add( "/out:" + interopAbsolutePath );
parameters.add( "/namespace:" + namespace );
try
{
// beginning code for checking of strong name key or signing of projects
String key = "";
String keyfile = "";
String currentWorkingDir = System.getProperty( "user.dir" );
// Check if Parent pom
List<String> modules = readPomAttribute( currentWorkingDir + File.separator + "pom.xml", "module" );
if ( !modules.isEmpty() )
{
// check if there is a matching dependency with the namespace
for ( String child : modules )
{
// check each module pom file if there is existing keyfile
String tempDir = currentWorkingDir + File.separator + child;
try
{
List<String> keyfiles = readPomAttribute( tempDir + "\\pom.xml", "keyfile" );
if ( keyfiles.get( 0 ) != null )
{
// PROBLEM WITH MULTIMODULES
boolean hasComRef = false;
List<String> dependencies = readPomAttribute( tempDir + "\\pom.xml", "groupId" );
for ( String item : dependencies )
{
if ( item.equals( namespace ) )
{
hasComRef = true;
break;
}
}
if ( hasComRef )
{
key = keyfiles.get( 0 );
currentWorkingDir = tempDir;
}
}
}
catch ( Exception e )
{
}
}
}
else
{
// not a parent pom, so read project pom file for keyfile value
List<String> keyfiles = readPomAttribute( currentWorkingDir + File.separator + "pom.xml", "keyfile" );
key = keyfiles.get( 0 );
}
if ( key != "" )
{
keyfile = currentWorkingDir + File.separator + key;
parameters.add( "/keyfile:" + keyfile );
}
// end code for checking of strong name key or signing of projects
}
catch ( Exception ex )
{
}
return parameters;
}
private File getTempDirectory()
throws IOException
{
File tempFile = File.createTempFile( "interop-dll-", "" );
File tmpDir = new File( tempFile.getParentFile(), tempFile.getName() );
tempFile.delete();
tmpDir.mkdir();
return tmpDir;
}
// can't use dotnet-executable due to cyclic dependency.
private void execute( String executable, List<String> commands )
throws Exception
{
execute( executable, commands, null, null );
}
private void execute( String executable, List<String> commands, StreamConsumer systemOut, StreamConsumer systemError )
throws Exception
{
int result = 0;
Commandline commandline = new Commandline();
commandline.setExecutable( executable );
commandline.addArguments( commands.toArray( new String[commands.size()] ) );
try
{
result = CommandLineUtils.executeCommandLine( commandline, systemOut, systemError );
System.out.println( "NPANDAY-040-000: Executed command: Commandline = " + commandline + ", Result = "
+ result );
if ( result != 0 )
{
throw new Exception( "NPANDAY-040-001: Could not execute: Command = " + commandline.toString()
+ ", Result = " + result );
}
}
catch ( CommandLineException e )
{
throw new Exception( "NPANDAY-040-002: Could not execute: Command = " + commandline.toString() );
}
}
/**
* TODO: refactor this to another class and all methods concerning com_reference StreamConsumer instance that
* buffers the entire output
*/
class StreamConsumerImpl
implements StreamConsumer
{
private DefaultConsumer consumer;
private StringBuffer sb = new StringBuffer();
public StreamConsumerImpl()
{
consumer = new DefaultConsumer();
}
public void consumeLine( String line )
{
sb.append( line );
if ( logger != null )
{
consumer.consumeLine( line );
}
}
/**
* Returns the stream
*
* @return the stream
*/
public String toString()
{
return sb.toString();
}
}
}
| false | true | public Set<Artifact> storeProjectAndResolveDependencies( Project project, File localRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException, IllegalArgumentException
{
long startTime = System.currentTimeMillis();
String snapshotVersion;
if ( project == null )
{
throw new IllegalArgumentException( "NPANDAY-180-009: Project is null" );
}
if ( project.getGroupId() == null || project.getArtifactId() == null || project.getVersion() == null )
{
throw new IllegalArgumentException( "NPANDAY-180-010: Project value is null: Group Id ="
+ project.getGroupId() + ", Artifact Id = " + project.getArtifactId() + ", Version = "
+ project.getVersion() );
}
Set<Artifact> artifactDependencies = new HashSet<Artifact>();
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id =
valueFactory.createURI( project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()
+ ":" + project.getArtifactType() );
URI groupId = valueFactory.createURI( ProjectUri.GROUP_ID.getPredicate() );
URI artifactId = valueFactory.createURI( ProjectUri.ARTIFACT_ID.getPredicate() );
URI version = valueFactory.createURI( ProjectUri.VERSION.getPredicate() );
URI artifactType = valueFactory.createURI( ProjectUri.ARTIFACT_TYPE.getPredicate() );
URI classifier = valueFactory.createURI( ProjectUri.CLASSIFIER.getPredicate() );
URI isResolved = valueFactory.createURI( ProjectUri.IS_RESOLVED.getPredicate() );
URI artifact = valueFactory.createURI( ProjectUri.ARTIFACT.getPredicate() );
URI dependency = valueFactory.createURI( ProjectUri.DEPENDENCY.getPredicate() );
URI parent = valueFactory.createURI( ProjectUri.PARENT.getPredicate() );
Set<Model> modelDependencies = new HashSet<Model>();
try
{
repositoryConnection.add( id, RDF.TYPE, artifact );
repositoryConnection.add( id, groupId, valueFactory.createLiteral( project.getGroupId() ) );
repositoryConnection.add( id, artifactId, valueFactory.createLiteral( project.getArtifactId() ) );
repositoryConnection.add( id, version, valueFactory.createLiteral( project.getVersion() ) );
repositoryConnection.add( id, artifactType, valueFactory.createLiteral( project.getArtifactType() ) );
if ( project.getPublicKeyTokenId() != null )
{
URI classifierNode = valueFactory.createURI( project.getPublicKeyTokenId() + ":" );
for ( Requirement requirement : project.getRequirements() )
{
URI uri = valueFactory.createURI( requirement.getUri().toString() );
repositoryConnection.add( classifierNode, uri, valueFactory.createLiteral( requirement.getValue() ) );
}
repositoryConnection.add( id, classifier, classifierNode );
}
if ( project.getParentProject() != null )
{
Project parentProject = project.getParentProject();
URI pid =
valueFactory.createURI( parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":"
+ parentProject.getVersion() + ":" + project.getArtifactType() );
repositoryConnection.add( id, parent, pid );
artifactDependencies.addAll( storeProjectAndResolveDependencies( parentProject, null,
artifactRepositories ) );
}
for ( ProjectDependency projectDependency : project.getProjectDependencies() )
{
snapshotVersion = null;
logger.finest( "NPANDAY-180-011: Project Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Artifact Type = "
+ projectDependency.getArtifactType() );
// If artifact has been deleted, then re-resolve
if ( projectDependency.isResolved() && !ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
File dependencyFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
if ( !dependencyFile.exists() )
{
projectDependency.setResolved( false );
}
}
// resolve system scope dependencies
if ( projectDependency.getScope() != null && projectDependency.getScope().equals( "system" ) )
{
if ( projectDependency.getSystemPath() == null )
{
throw new IOException( "systemPath required for System Scoped dependencies " + "in Group ID = "
+ projectDependency.getGroupId() + ", Artiract ID = " + projectDependency.getArtifactId() );
}
File f = new File( projectDependency.getSystemPath() );
if ( !f.exists() )
{
throw new IOException( "Dependency systemPath File not found:"
+ projectDependency.getSystemPath() + "in Group ID = " + projectDependency.getGroupId()
+ ", Artiract ID = " + projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve com reference
// flow:
// 1. generate the interop dll in temp folder and resolve to that path during dependency resolution
// 2. cut and paste the dll to buildDirectory and update the paths once we grab the reference of
// MavenProject (CompilerContext.java)
if ( projectDependency.getArtifactType().equals( "com_reference" ) )
{
String tokenId = projectDependency.getPublicKeyTokenId();
String interopPath = generateInteropDll( projectDependency.getArtifactId(), tokenId );
File f = new File( interopPath );
if ( !f.exists() )
{
throw new IOException( "Dependency com_reference File not found:" + interopPath
+ "in Group ID = " + projectDependency.getGroupId() + ", Artiract ID = "
+ projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve gac references
// note: the old behavior of gac references, used to have system path properties in the pom of the
// project
// now we need to generate the system path of the gac references so we can use
// System.getenv("SystemRoot")
if ( !projectDependency.isResolved() )
{
if ( ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
try
{
projectDependency.setResolved( true );
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
File f = new File( projectDependency.getSystemPath() );
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
}
catch ( ExceptionInInitializerError e )
{
logger.warning( "NPANDAY-180-516.82: Project Failed to Resolve Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = "
+ projectDependency.getScope() + "SystemPath = " + projectDependency.getSystemPath() );
}
}
else
{
try
{
Project dep =
this.getProjectFor( projectDependency.getGroupId(), projectDependency.getArtifactId(),
projectDependency.getVersion(),
projectDependency.getArtifactType(),
projectDependency.getPublicKeyTokenId() );
if ( dep.isResolved() )
{
Artifact assembly =
ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
// re-resolve snapshots
if ( !assembly.isSnapshot() )
{
projectDependency = (ProjectDependency) dep;
artifactDependencies.add( assembly );
Set<Artifact> deps = this.storeProjectAndResolveDependencies( projectDependency,
localRepository,
artifactRepositories );
artifactDependencies.addAll( deps );
}
}
}
catch ( IOException e )
{
// safe to ignore: dependency not found
}
}
}
if ( !projectDependency.isResolved() )
{
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
if ( assembly.getType().equals( "jar" ) )
{
logger.info( "Detected jar dependency - skipping: Artifact Dependency ID = "
+ assembly.getArtifactId() );
continue;
}
ArtifactType type = ArtifactType.getArtifactTypeForPackagingName( assembly.getType() );
logger.info( "NPANDAY-180-012: Resolving artifact for unresolved dependency: "
+ assembly.getId());
ArtifactRepository localArtifactRepository =
new DefaultArtifactRepository( "local", "file://" + localRepository,
new DefaultRepositoryLayout() );
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ))// TODO: Generalize to any attached artifact
{
Artifact pomArtifact =
artifactFactory.createProjectArtifact( projectDependency.getGroupId(),
projectDependency.getArtifactId(),
projectDependency.getVersion() );
try
{
artifactResolver.resolve( pomArtifact, artifactRepositories,
localArtifactRepository );
logger.info( "NPANDAY-180-024: resolving pom artifact: " + pomArtifact.toString() );
snapshotVersion = pomArtifact.getVersion();
}
catch ( ArtifactNotFoundException e )
{
logger.info( "NPANDAY-180-025: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.info( "NPANDAY-180-026: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
if ( pomArtifact.getFile() != null && pomArtifact.getFile().exists() )
{
FileReader fileReader = new FileReader( pomArtifact.getFile() );
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model;
try
{
model = reader.read( fileReader ); // TODO: interpolate values
}
catch ( XmlPullParserException e )
{
throw new IOException( "NPANDAY-180-015: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
catch ( EOFException e )
{
throw new IOException( "NPANDAY-180-016: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
// small hack for not doing inheritence
String g = model.getGroupId();
if ( g == null )
{
g = model.getParent().getGroupId();
}
String v = model.getVersion();
if ( v == null )
{
v = model.getParent().getVersion();
}
if ( !( g.equals( projectDependency.getGroupId() )
&& model.getArtifactId().equals( projectDependency.getArtifactId() ) && v.equals( projectDependency.getVersion() ) ) )
{
throw new IOException(
"NPANDAY-180-017: Model parameters do not match project dependencies parameters: Model: "
+ g + ":" + model.getArtifactId() + ":" + v + ", Project: "
+ projectDependency.getGroupId() + ":"
+ projectDependency.getArtifactId() + ":"
+ projectDependency.getVersion() );
}
modelDependencies.add( model );
}
}
if ( snapshotVersion != null )
{
assembly.setVersion( snapshotVersion );
}
File uacFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
logger.info( "NPANDAY-180-018: Not found in UAC, now retrieving artifact from wagon:"
+ assembly.getId()
+ ", Failed UAC Path Check = " + uacFile.getAbsolutePath());
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ) || !uacFile.exists() )// TODO: Generalize to any attached artifact
{
try
{
artifactResolver.resolve( assembly, artifactRepositories,
localArtifactRepository );
if ( assembly != null && assembly.getFile().exists() )
{
uacFile.getParentFile().mkdirs();
FileUtils.copyFile( assembly.getFile(), uacFile );
assembly.setFile( uacFile );
}
}
catch ( ArtifactNotFoundException e )
{
throw new IOException(
"NPANDAY-180-020: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
throw new IOException(
"NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage(), e );
}
}
artifactDependencies.add( assembly );
}// end if dependency not resolved
URI did =
valueFactory.createURI( projectDependency.getGroupId() + ":" + projectDependency.getArtifactId()
+ ":" + projectDependency.getVersion() + ":" + projectDependency.getArtifactType() );
repositoryConnection.add( did, RDF.TYPE, artifact );
repositoryConnection.add( did, groupId, valueFactory.createLiteral( projectDependency.getGroupId() ) );
repositoryConnection.add( did, artifactId,
valueFactory.createLiteral( projectDependency.getArtifactId() ) );
repositoryConnection.add( did, version, valueFactory.createLiteral( projectDependency.getVersion() ) );
repositoryConnection.add( did, artifactType,
valueFactory.createLiteral( projectDependency.getArtifactType() ) );
if ( projectDependency.getPublicKeyTokenId() != null )
{
repositoryConnection.add(
did,
classifier,
valueFactory.createLiteral( projectDependency.getPublicKeyTokenId() + ":" ) );
}
repositoryConnection.add( id, dependency, did );
}// end for
repositoryConnection.add( id, isResolved, valueFactory.createLiteral( true ) );
repositoryConnection.commit();
}
catch ( OpenRDFException e )
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.rollback();
}
catch ( RepositoryException e1 )
{
}
}
throw new IOException( "NPANDAY-180-021: Could not open RDF Repository: Message =" + e.getMessage() );
}
for ( Model model : modelDependencies )
{
// System.out.println( "Storing dependency: Artifact Id = " + model.getArtifactId() );
artifactDependencies.addAll( storeProjectAndResolveDependencies( ProjectFactory.createProjectFrom( model,
null ),
localRepository, artifactRepositories ) );
}
logger.finest( "NPANDAY-180-022: ProjectDao.storeProjectAndResolveDependencies - Artifact Id = "
+ project.getArtifactId() + ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = "
+ storeCounter++ );
return artifactDependencies;
}
| public Set<Artifact> storeProjectAndResolveDependencies( Project project, File localRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException, IllegalArgumentException
{
long startTime = System.currentTimeMillis();
String snapshotVersion;
if ( project == null )
{
throw new IllegalArgumentException( "NPANDAY-180-009: Project is null" );
}
if ( project.getGroupId() == null || project.getArtifactId() == null || project.getVersion() == null )
{
throw new IllegalArgumentException( "NPANDAY-180-010: Project value is null: Group Id ="
+ project.getGroupId() + ", Artifact Id = " + project.getArtifactId() + ", Version = "
+ project.getVersion() );
}
Set<Artifact> artifactDependencies = new HashSet<Artifact>();
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id =
valueFactory.createURI( project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()
+ ":" + project.getArtifactType() );
URI groupId = valueFactory.createURI( ProjectUri.GROUP_ID.getPredicate() );
URI artifactId = valueFactory.createURI( ProjectUri.ARTIFACT_ID.getPredicate() );
URI version = valueFactory.createURI( ProjectUri.VERSION.getPredicate() );
URI artifactType = valueFactory.createURI( ProjectUri.ARTIFACT_TYPE.getPredicate() );
URI classifier = valueFactory.createURI( ProjectUri.CLASSIFIER.getPredicate() );
URI isResolved = valueFactory.createURI( ProjectUri.IS_RESOLVED.getPredicate() );
URI artifact = valueFactory.createURI( ProjectUri.ARTIFACT.getPredicate() );
URI dependency = valueFactory.createURI( ProjectUri.DEPENDENCY.getPredicate() );
URI parent = valueFactory.createURI( ProjectUri.PARENT.getPredicate() );
Set<Model> modelDependencies = new HashSet<Model>();
try
{
repositoryConnection.add( id, RDF.TYPE, artifact );
repositoryConnection.add( id, groupId, valueFactory.createLiteral( project.getGroupId() ) );
repositoryConnection.add( id, artifactId, valueFactory.createLiteral( project.getArtifactId() ) );
repositoryConnection.add( id, version, valueFactory.createLiteral( project.getVersion() ) );
repositoryConnection.add( id, artifactType, valueFactory.createLiteral( project.getArtifactType() ) );
if ( project.getPublicKeyTokenId() != null )
{
URI classifierNode = valueFactory.createURI( project.getPublicKeyTokenId() + ":" );
for ( Requirement requirement : project.getRequirements() )
{
URI uri = valueFactory.createURI( requirement.getUri().toString() );
repositoryConnection.add( classifierNode, uri, valueFactory.createLiteral( requirement.getValue() ) );
}
repositoryConnection.add( id, classifier, classifierNode );
}
if ( project.getParentProject() != null )
{
Project parentProject = project.getParentProject();
URI pid =
valueFactory.createURI( parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":"
+ parentProject.getVersion() + ":" + project.getArtifactType() );
repositoryConnection.add( id, parent, pid );
artifactDependencies.addAll( storeProjectAndResolveDependencies( parentProject, null,
artifactRepositories ) );
}
for ( ProjectDependency projectDependency : project.getProjectDependencies() )
{
snapshotVersion = null;
logger.finest( "NPANDAY-180-011: Project Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Artifact Type = "
+ projectDependency.getArtifactType() );
// If artifact has been deleted, then re-resolve
if ( projectDependency.isResolved() && !ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
File dependencyFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
if ( !dependencyFile.exists() )
{
projectDependency.setResolved( false );
}
}
// resolve system scope dependencies
if ( projectDependency.getScope() != null && projectDependency.getScope().equals( "system" ) )
{
if ( projectDependency.getSystemPath() == null )
{
throw new IOException( "systemPath required for System Scoped dependencies " + "in Group ID = "
+ projectDependency.getGroupId() + ", Artiract ID = " + projectDependency.getArtifactId() );
}
File f = new File( projectDependency.getSystemPath() );
if ( !f.exists() )
{
throw new IOException( "Dependency systemPath File not found:"
+ projectDependency.getSystemPath() + "in Group ID = " + projectDependency.getGroupId()
+ ", Artiract ID = " + projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve com reference
// flow:
// 1. generate the interop dll in temp folder and resolve to that path during dependency resolution
// 2. cut and paste the dll to buildDirectory and update the paths once we grab the reference of
// MavenProject (CompilerContext.java)
if ( projectDependency.getArtifactType().equals( "com_reference" ) )
{
String tokenId = projectDependency.getPublicKeyTokenId();
String interopPath = generateInteropDll( projectDependency.getArtifactId(), tokenId );
File f = new File( interopPath );
if ( !f.exists() )
{
throw new IOException( "Dependency com_reference File not found:" + interopPath
+ "in Group ID = " + projectDependency.getGroupId() + ", Artiract ID = "
+ projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve gac references
// note: the old behavior of gac references, used to have system path properties in the pom of the
// project
// now we need to generate the system path of the gac references so we can use
// System.getenv("SystemRoot")
if ( !projectDependency.isResolved() )
{
if ( ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
try
{
projectDependency.setResolved( true );
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
File f = new File( projectDependency.getSystemPath() );
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
}
catch ( ExceptionInInitializerError e )
{
logger.warning( "NPANDAY-180-516.82: Project Failed to Resolve Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = "
+ projectDependency.getScope() + "SystemPath = " + projectDependency.getSystemPath() );
}
}
else
{
try
{
Project dep =
this.getProjectFor( projectDependency.getGroupId(), projectDependency.getArtifactId(),
projectDependency.getVersion(),
projectDependency.getArtifactType(),
projectDependency.getPublicKeyTokenId() );
if ( dep.isResolved() )
{
Artifact assembly =
ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
// re-resolve snapshots
if ( !assembly.isSnapshot() )
{
projectDependency = (ProjectDependency) dep;
artifactDependencies.add( assembly );
Set<Artifact> deps = this.storeProjectAndResolveDependencies( projectDependency,
localRepository,
artifactRepositories );
artifactDependencies.addAll( deps );
}
}
}
catch ( IOException e )
{
// safe to ignore: dependency not found
}
}
}
if ( !projectDependency.isResolved() )
{
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
if ( assembly.getType().equals( "jar" ) )
{
logger.info( "Detected jar dependency - skipping: Artifact Dependency ID = "
+ assembly.getArtifactId() );
continue;
}
ArtifactType type = ArtifactType.getArtifactTypeForPackagingName( assembly.getType() );
logger.info( "NPANDAY-180-012: Resolving artifact for unresolved dependency: "
+ assembly.getId());
ArtifactRepository localArtifactRepository =
new DefaultArtifactRepository( "local", "file://" + localRepository,
new DefaultRepositoryLayout() );
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ))// TODO: Generalize to any attached artifact
{
Artifact pomArtifact =
artifactFactory.createProjectArtifact( projectDependency.getGroupId(),
projectDependency.getArtifactId(),
projectDependency.getVersion() );
try
{
artifactResolver.resolve( pomArtifact, artifactRepositories,
localArtifactRepository );
logger.info( "NPANDAY-180-024: resolving pom artifact: " + pomArtifact.toString() );
snapshotVersion = pomArtifact.getVersion();
}
catch ( ArtifactNotFoundException e )
{
logger.info( "NPANDAY-180-025: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.info( "NPANDAY-180-026: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
if ( pomArtifact.getFile() != null && pomArtifact.getFile().exists() )
{
FileReader fileReader = new FileReader( pomArtifact.getFile() );
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model;
try
{
model = reader.read( fileReader ); // TODO: interpolate values
}
catch ( XmlPullParserException e )
{
throw new IOException( "NPANDAY-180-015: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
catch ( EOFException e )
{
throw new IOException( "NPANDAY-180-016: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
// small hack for not doing inheritence
String g = model.getGroupId();
if ( g == null )
{
g = model.getParent().getGroupId();
}
String v = model.getVersion();
if ( v == null )
{
v = model.getParent().getVersion();
}
if ( !( g.equals( projectDependency.getGroupId() )
&& model.getArtifactId().equals( projectDependency.getArtifactId() ) && v.equals( projectDependency.getVersion() ) ) )
{
throw new IOException(
"NPANDAY-180-017: Model parameters do not match project dependencies parameters: Model: "
+ g + ":" + model.getArtifactId() + ":" + v + ", Project: "
+ projectDependency.getGroupId() + ":"
+ projectDependency.getArtifactId() + ":"
+ projectDependency.getVersion() );
}
modelDependencies.add( model );
}
}
if ( snapshotVersion != null )
{
assembly.setVersion( snapshotVersion );
}
File uacFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
logger.info( "NPANDAY-180-018: Not found in UAC, now retrieving artifact from wagon:"
+ assembly.getId()
+ ", Failed UAC Path Check = " + uacFile.getAbsolutePath());
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ) || !uacFile.exists() )// TODO: Generalize to any attached artifact
{
try
{
artifactResolver.resolve( assembly, artifactRepositories,
localArtifactRepository );
if ( assembly != null && assembly.getFile().exists() )
{
uacFile.getParentFile().mkdirs();
FileUtils.copyFile( assembly.getFile(), uacFile );
assembly.setFile( uacFile );
}
}
catch ( ArtifactNotFoundException e )
{
throw new IOException(
"NPANDAY-180-020: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.error( "NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage(), e );
throw new IOException(
"NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
}
artifactDependencies.add( assembly );
}// end if dependency not resolved
URI did =
valueFactory.createURI( projectDependency.getGroupId() + ":" + projectDependency.getArtifactId()
+ ":" + projectDependency.getVersion() + ":" + projectDependency.getArtifactType() );
repositoryConnection.add( did, RDF.TYPE, artifact );
repositoryConnection.add( did, groupId, valueFactory.createLiteral( projectDependency.getGroupId() ) );
repositoryConnection.add( did, artifactId,
valueFactory.createLiteral( projectDependency.getArtifactId() ) );
repositoryConnection.add( did, version, valueFactory.createLiteral( projectDependency.getVersion() ) );
repositoryConnection.add( did, artifactType,
valueFactory.createLiteral( projectDependency.getArtifactType() ) );
if ( projectDependency.getPublicKeyTokenId() != null )
{
repositoryConnection.add(
did,
classifier,
valueFactory.createLiteral( projectDependency.getPublicKeyTokenId() + ":" ) );
}
repositoryConnection.add( id, dependency, did );
}// end for
repositoryConnection.add( id, isResolved, valueFactory.createLiteral( true ) );
repositoryConnection.commit();
}
catch ( OpenRDFException e )
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.rollback();
}
catch ( RepositoryException e1 )
{
}
}
throw new IOException( "NPANDAY-180-021: Could not open RDF Repository: Message =" + e.getMessage() );
}
for ( Model model : modelDependencies )
{
// System.out.println( "Storing dependency: Artifact Id = " + model.getArtifactId() );
artifactDependencies.addAll( storeProjectAndResolveDependencies( ProjectFactory.createProjectFrom( model,
null ),
localRepository, artifactRepositories ) );
}
logger.finest( "NPANDAY-180-022: ProjectDao.storeProjectAndResolveDependencies - Artifact Id = "
+ project.getArtifactId() + ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = "
+ storeCounter++ );
return artifactDependencies;
}
|
diff --git a/hw5/list/DListNode.java b/hw5/list/DListNode.java
index cc0b581..88af7c9 100644
--- a/hw5/list/DListNode.java
+++ b/hw5/list/DListNode.java
@@ -1,169 +1,170 @@
/* DListNode.java */
package hw5.list;
/**
* A DListNode is a mutable node in a DList (doubly-linked list).
**/
public class DListNode extends ListNode {
/**
* (inherited) item references the item stored in the current node.
* (inherited) myList references the List that contains this node.
* prev references the previous node in the DList.
* next references the next node in the DList.
*
* DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
**/
protected DListNode prev;
protected DListNode next;
protected DList myList;
/**
* DListNode() constructor.
* @param i the item to store in the node.
* @param l the list this node is in.
* @param p the node previous to this node.
* @param n the node following this node.
*/
DListNode(Object i, DList l, DListNode p, DListNode n) {
item = i;
myList = l;
prev = p;
next = n;
}
/**
* isValidNode returns true if this node is valid; false otherwise.
* An invalid node is represented by a `myList' field with the value null.
* Sentinel nodes are invalid, and nodes that don't belong to a list are
* also invalid.
*
* @return true if this node is valid; false otherwise.
*
* Performance: runs in O(1) time.
*/
public boolean isValidNode() {
return myList != null;
}
/**
* next() returns the node following this node. If this node is invalid,
* throws an exception.
*
* @return the node following this node.
* @exception InvalidNodeException if this node is not valid.
*
* Performance: runs in O(1) time.
*/
public ListNode next() throws InvalidNodeException {
if (!isValidNode()) {
throw new InvalidNodeException("next() called on invalid node");
}
return next;
}
/**
* prev() returns the node preceding this node. If this node is invalid,
* throws an exception.
*
* @param node the node whose predecessor is sought.
* @return the node preceding this node.
* @exception InvalidNodeException if this node is not valid.
*
* Performance: runs in O(1) time.
*/
public ListNode prev() throws InvalidNodeException {
if (!isValidNode()) {
throw new InvalidNodeException("prev() called on invalid node");
}
return prev;
}
/**
* insertAfter() inserts an item immediately following this node. If this
* node is invalid, throws an exception.
*
* @param item the item to be inserted.
* @exception InvalidNodeException if this node is not valid.
*
* Performance: runs in O(1) time.
*/
public void insertAfter(Object item) throws InvalidNodeException {
if (!isValidNode()) {
throw new InvalidNodeException("insertAfter() called on invalid node");
}else{
DList a = this.myList;
DListNode b = a.newNode(item, this.myList, null, null);
DListNode c = this.next;
b.next = c;
c.prev = b;
this.next = b;
b.prev = this;
}
// Your solution here. Will look something like your Homework 4 solution,
// but changes are necessary. For instance, there is no need to check if
// "this" is null. Remember that this node's "myList" field tells you
// what DList it's in. You should use myList.newNode() to create the
// new node.
}
/**
* insertBefore() inserts an item immediately preceding this node. If this
* node is invalid, throws an exception.
*
* @param item the item to be inserted.
* @exception InvalidNodeException if this node is not valid.
*
* Performance: runs in O(1) time.
*/
public void insertBefore(Object item) throws InvalidNodeException {
if (!isValidNode()) {
throw new InvalidNodeException("insertBefore() called on invalid node");
}else{
DList a = this.myList;
DListNode b = a.newNode(item, this.myList, null, null);
DListNode c = this.prev;
b.prev = c;
c.next = b;
this.prev = b;
b.next = this;
}
// Your solution here. Will look something like your Homework 4 solution,
// but changes are necessary. For instance, there is no need to check if
// "this" is null. Remember that this node's "myList" field tells you
// what DList it's in. You should use myList.newNode() to create the
// new node.
}
/**
* remove() removes this node from its DList. If this node is invalid,
* throws an exception.
*
* @exception InvalidNodeException if this node is not valid.
*
* Performance: runs in O(1) time.
*/
public void remove() throws InvalidNodeException {
if (!isValidNode()) {
throw new InvalidNodeException("remove() called on invalid node");
}else{
DListNode before = this.prev;
DListNode after = this.next;
before.next = after;
after.prev = before;
// Your solution here. Will look something like your Homework 4 solution,
// but changes are necessary. For instance, there is no need to check if
// "this" is null. Remember that this node's "myList" field tells you
// what DList it's in.
// Make this node an invalid node, so it cannot be used to corrupt myList.
+ myList.size--;
myList = null;
// Set other references to null to improve garbage collection.
next = null;
prev = null;
}
}
}
| true | true | public void remove() throws InvalidNodeException {
if (!isValidNode()) {
throw new InvalidNodeException("remove() called on invalid node");
}else{
DListNode before = this.prev;
DListNode after = this.next;
before.next = after;
after.prev = before;
// Your solution here. Will look something like your Homework 4 solution,
// but changes are necessary. For instance, there is no need to check if
// "this" is null. Remember that this node's "myList" field tells you
// what DList it's in.
// Make this node an invalid node, so it cannot be used to corrupt myList.
myList = null;
// Set other references to null to improve garbage collection.
next = null;
prev = null;
}
}
| public void remove() throws InvalidNodeException {
if (!isValidNode()) {
throw new InvalidNodeException("remove() called on invalid node");
}else{
DListNode before = this.prev;
DListNode after = this.next;
before.next = after;
after.prev = before;
// Your solution here. Will look something like your Homework 4 solution,
// but changes are necessary. For instance, there is no need to check if
// "this" is null. Remember that this node's "myList" field tells you
// what DList it's in.
// Make this node an invalid node, so it cannot be used to corrupt myList.
myList.size--;
myList = null;
// Set other references to null to improve garbage collection.
next = null;
prev = null;
}
}
|
diff --git a/src/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java b/src/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
index d6c2a20..9295773 100644
--- a/src/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
+++ b/src/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
@@ -1,471 +1,479 @@
/*
* Copyright (C) 2006 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.internal.telephony.gsm;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Intent;
import android.os.AsyncResult;
import android.os.Message;
import android.os.SystemProperties;
import android.provider.Telephony.Sms;
import android.provider.Telephony.Sms.Intents;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsCbLocation;
import android.telephony.SmsCbMessage;
import android.telephony.SmsManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import com.android.internal.telephony.CommandsInterface;
import com.android.internal.telephony.GsmAlphabet;
import com.android.internal.telephony.IccUtils;
import com.android.internal.telephony.PhoneBase;
import com.android.internal.telephony.SmsConstants;
import com.android.internal.telephony.SMSDispatcher;
import com.android.internal.telephony.SmsHeader;
import com.android.internal.telephony.SmsMessageBase;
import com.android.internal.telephony.SmsStorageMonitor;
import com.android.internal.telephony.SmsUsageMonitor;
import com.android.internal.telephony.TelephonyProperties;
import java.util.HashMap;
import java.util.Iterator;
public final class GsmSMSDispatcher extends SMSDispatcher {
private static final String TAG = "GSM";
/** Status report received */
private static final int EVENT_NEW_SMS_STATUS_REPORT = 100;
/** New broadcast SMS */
private static final int EVENT_NEW_BROADCAST_SMS = 101;
/** Result of writing SM to UICC (when SMS-PP service is not available). */
private static final int EVENT_WRITE_SMS_COMPLETE = 102;
/** Handler for SMS-PP data download messages to UICC. */
private final UsimDataDownloadHandler mDataDownloadHandler;
public GsmSMSDispatcher(PhoneBase phone, SmsStorageMonitor storageMonitor,
SmsUsageMonitor usageMonitor) {
super(phone, storageMonitor, usageMonitor);
mDataDownloadHandler = new UsimDataDownloadHandler(mCm);
mCm.setOnNewGsmSms(this, EVENT_NEW_SMS, null);
mCm.setOnSmsStatus(this, EVENT_NEW_SMS_STATUS_REPORT, null);
mCm.setOnNewGsmBroadcastSms(this, EVENT_NEW_BROADCAST_SMS, null);
}
@Override
public void dispose() {
mCm.unSetOnNewGsmSms(this);
mCm.unSetOnSmsStatus(this);
mCm.unSetOnNewGsmBroadcastSms(this);
}
@Override
protected String getFormat() {
return SmsConstants.FORMAT_3GPP;
}
/**
* Handles 3GPP format-specific events coming from the phone stack.
* Other events are handled by {@link SMSDispatcher#handleMessage}.
*
* @param msg the message to handle
*/
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_NEW_SMS_STATUS_REPORT:
handleStatusReport((AsyncResult) msg.obj);
break;
case EVENT_NEW_BROADCAST_SMS:
handleBroadcastSms((AsyncResult)msg.obj);
break;
case EVENT_WRITE_SMS_COMPLETE:
AsyncResult ar = (AsyncResult) msg.obj;
if (ar.exception == null) {
Log.d(TAG, "Successfully wrote SMS-PP message to UICC");
mCm.acknowledgeLastIncomingGsmSms(true, 0, null);
} else {
Log.d(TAG, "Failed to write SMS-PP message to UICC", ar.exception);
mCm.acknowledgeLastIncomingGsmSms(false,
CommandsInterface.GSM_SMS_FAIL_CAUSE_UNSPECIFIED_ERROR, null);
}
break;
default:
super.handleMessage(msg);
}
}
/**
* Called when a status report is received. This should correspond to
* a previously successful SEND.
*
* @param ar AsyncResult passed into the message handler. ar.result should
* be a String representing the status report PDU, as ASCII hex.
*/
private void handleStatusReport(AsyncResult ar) {
String pduString = (String) ar.result;
SmsMessage sms = SmsMessage.newFromCDS(pduString);
if (sms != null) {
int tpStatus = sms.getStatus();
int messageRef = sms.messageRef;
for (int i = 0, count = deliveryPendingList.size(); i < count; i++) {
SmsTracker tracker = deliveryPendingList.get(i);
if (tracker.mMessageRef == messageRef) {
// Found it. Remove from list and broadcast.
if(tpStatus >= Sms.STATUS_FAILED || tpStatus < Sms.STATUS_PENDING ) {
deliveryPendingList.remove(i);
}
PendingIntent intent = tracker.mDeliveryIntent;
Intent fillIn = new Intent();
fillIn.putExtra("pdu", IccUtils.hexStringToBytes(pduString));
fillIn.putExtra("format", SmsConstants.FORMAT_3GPP);
try {
intent.send(mContext, Activity.RESULT_OK, fillIn);
} catch (CanceledException ex) {}
// Only expect to see one tracker matching this messageref
break;
}
}
}
acknowledgeLastIncomingSms(true, Intents.RESULT_SMS_HANDLED, null);
}
/** {@inheritDoc} */
@Override
public int dispatchMessage(SmsMessageBase smsb) {
// If sms is null, means there was a parsing error.
if (smsb == null) {
Log.e(TAG, "dispatchMessage: message is null");
return Intents.RESULT_SMS_GENERIC_ERROR;
}
SmsMessage sms = (SmsMessage) smsb;
if (sms.isTypeZero()) {
// As per 3GPP TS 23.040 9.2.3.9, Type Zero messages should not be
// Displayed/Stored/Notified. They should only be acknowledged.
Log.d(TAG, "Received short message type 0, Don't display or store it. Send Ack");
return Intents.RESULT_SMS_HANDLED;
}
// Send SMS-PP data download messages to UICC. See 3GPP TS 31.111 section 7.1.1.
if (sms.isUsimDataDownload()) {
UsimServiceTable ust = mPhone.getUsimServiceTable();
// If we receive an SMS-PP message before the UsimServiceTable has been loaded,
// assume that the data download service is not present. This is very unlikely to
// happen because the IMS connection will not be established until after the ISIM
// records have been loaded, after the USIM service table has been loaded.
if (ust != null && ust.isAvailable(
UsimServiceTable.UsimService.DATA_DL_VIA_SMS_PP)) {
Log.d(TAG, "Received SMS-PP data download, sending to UICC.");
return mDataDownloadHandler.startDataDownload(sms);
} else {
Log.d(TAG, "DATA_DL_VIA_SMS_PP service not available, storing message to UICC.");
String smsc = IccUtils.bytesToHexString(
PhoneNumberUtils.networkPortionToCalledPartyBCDWithLength(
sms.getServiceCenterAddress()));
mCm.writeSmsToSim(SmsManager.STATUS_ON_ICC_UNREAD, smsc,
IccUtils.bytesToHexString(sms.getPdu()),
obtainMessage(EVENT_WRITE_SMS_COMPLETE));
return Activity.RESULT_OK; // acknowledge after response from write to USIM
}
}
if (mSmsReceiveDisabled) {
// Device doesn't support SMS service,
Log.d(TAG, "Received short message on device which doesn't support "
+ "SMS service. Ignored.");
return Intents.RESULT_SMS_HANDLED;
}
// Special case the message waiting indicator messages
boolean handled = false;
if (sms.isMWISetMessage()) {
mPhone.setVoiceMessageWaiting(1, -1); // line 1: unknown number of msgs waiting
handled = sms.isMwiDontStore();
if (false) {
Log.d(TAG, "Received voice mail indicator set SMS shouldStore=" + !handled);
}
} else if (sms.isMWIClearMessage()) {
mPhone.setVoiceMessageWaiting(1, 0); // line 1: no msgs waiting
handled = sms.isMwiDontStore();
if (false) {
Log.d(TAG, "Received voice mail indicator clear SMS shouldStore=" + !handled);
}
}
if (handled) {
return Intents.RESULT_SMS_HANDLED;
}
if (!mStorageMonitor.isStorageAvailable() &&
sms.getMessageClass() != SmsConstants.MessageClass.CLASS_0) {
// It's a storable message and there's no storage available. Bail.
// (See TS 23.038 for a description of class 0 messages.)
return Intents.RESULT_SMS_OUT_OF_MEMORY;
}
return dispatchNormalMessage(smsb);
}
/** {@inheritDoc} */
@Override
protected void sendData(String destAddr, String scAddr, int destPort,
byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent) {
SmsMessage.SubmitPdu pdu = SmsMessage.getSubmitPdu(
scAddr, destAddr, destPort, data, (deliveryIntent != null));
if (pdu != null) {
sendRawPdu(pdu.encodedScAddress, pdu.encodedMessage, sentIntent, deliveryIntent,
destAddr);
} else {
Log.e(TAG, "GsmSMSDispatcher.sendData(): getSubmitPdu() returned null");
}
}
/** {@inheritDoc} */
@Override
protected void sendText(String destAddr, String scAddr, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent) {
SmsMessage.SubmitPdu pdu = SmsMessage.getSubmitPdu(
scAddr, destAddr, text, (deliveryIntent != null));
if (pdu != null) {
sendRawPdu(pdu.encodedScAddress, pdu.encodedMessage, sentIntent, deliveryIntent,
destAddr);
} else {
Log.e(TAG, "GsmSMSDispatcher.sendText(): getSubmitPdu() returned null");
}
}
/** {@inheritDoc} */
@Override
protected GsmAlphabet.TextEncodingDetails calculateLength(CharSequence messageBody,
boolean use7bitOnly) {
return SmsMessage.calculateLength(messageBody, use7bitOnly);
}
/** {@inheritDoc} */
@Override
protected void sendNewSubmitPdu(String destinationAddress, String scAddress,
String message, SmsHeader smsHeader, int encoding,
PendingIntent sentIntent, PendingIntent deliveryIntent, boolean lastPart) {
SmsMessage.SubmitPdu pdu = SmsMessage.getSubmitPdu(scAddress, destinationAddress,
message, deliveryIntent != null, SmsHeader.toByteArray(smsHeader),
encoding, smsHeader.languageTable, smsHeader.languageShiftTable);
if (pdu != null) {
sendRawPdu(pdu.encodedScAddress, pdu.encodedMessage, sentIntent, deliveryIntent,
destinationAddress);
} else {
Log.e(TAG, "GsmSMSDispatcher.sendNewSubmitPdu(): getSubmitPdu() returned null");
}
}
/** {@inheritDoc} */
@Override
protected void sendSms(SmsTracker tracker) {
HashMap<String, Object> map = tracker.mData;
byte smsc[] = (byte[]) map.get("smsc");
byte pdu[] = (byte[]) map.get("pdu");
Message reply = obtainMessage(EVENT_SEND_SMS_COMPLETE, tracker);
mCm.sendSMS(IccUtils.bytesToHexString(smsc), IccUtils.bytesToHexString(pdu), reply);
}
/** {@inheritDoc} */
@Override
protected void acknowledgeLastIncomingSms(boolean success, int result, Message response) {
mCm.acknowledgeLastIncomingGsmSms(success, resultToCause(result), response);
}
private static int resultToCause(int rc) {
switch (rc) {
case Activity.RESULT_OK:
case Intents.RESULT_SMS_HANDLED:
// Cause code is ignored on success.
return 0;
case Intents.RESULT_SMS_OUT_OF_MEMORY:
return CommandsInterface.GSM_SMS_FAIL_CAUSE_MEMORY_CAPACITY_EXCEEDED;
case Intents.RESULT_SMS_GENERIC_ERROR:
default:
return CommandsInterface.GSM_SMS_FAIL_CAUSE_UNSPECIFIED_ERROR;
}
}
/**
* Holds all info about a message page needed to assemble a complete
* concatenated message
*/
private static final class SmsCbConcatInfo {
private final SmsCbHeader mHeader;
private final SmsCbLocation mLocation;
public SmsCbConcatInfo(SmsCbHeader header, SmsCbLocation location) {
mHeader = header;
mLocation = location;
}
@Override
public int hashCode() {
return (mHeader.getSerialNumber() * 31) + mLocation.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SmsCbConcatInfo) {
SmsCbConcatInfo other = (SmsCbConcatInfo)obj;
// Two pages match if they have the same serial number (which includes the
// geographical scope and update number), and both pages belong to the same
// location (PLMN, plus LAC and CID if these are part of the geographical scope).
return mHeader.getSerialNumber() == other.mHeader.getSerialNumber()
&& mLocation.equals(other.mLocation);
}
return false;
}
/**
* Compare the location code for this message to the current location code. The match is
* relative to the geographical scope of the message, which determines whether the LAC
* and Cell ID are saved in mLocation or set to -1 to match all values.
*
* @param plmn the current PLMN
* @param lac the current Location Area (GSM) or Service Area (UMTS)
* @param cid the current Cell ID
* @return true if this message is valid for the current location; false otherwise
*/
public boolean matchesLocation(String plmn, int lac, int cid) {
return mLocation.isInLocationArea(plmn, lac, cid);
}
}
// This map holds incomplete concatenated messages waiting for assembly
private final HashMap<SmsCbConcatInfo, byte[][]> mSmsCbPageMap =
new HashMap<SmsCbConcatInfo, byte[][]>();
/**
* Handle 3GPP format SMS-CB message.
* @param ar the AsyncResult containing the received PDUs
*/
private void handleBroadcastSms(AsyncResult ar) {
try {
byte[] receivedPdu = (byte[])ar.result;
if (false) {
for (int i = 0; i < receivedPdu.length; i += 8) {
StringBuilder sb = new StringBuilder("SMS CB pdu data: ");
for (int j = i; j < i + 8 && j < receivedPdu.length; j++) {
int b = receivedPdu[j] & 0xff;
if (b < 0x10) {
sb.append('0');
}
sb.append(Integer.toHexString(b)).append(' ');
}
Log.d(TAG, sb.toString());
}
}
SmsCbHeader header = new SmsCbHeader(receivedPdu);
String plmn = SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC);
- GsmCellLocation cellLocation = (GsmCellLocation) mPhone.getCellLocation();
- int lac = cellLocation.getLac();
- int cid = cellLocation.getCid();
+ int lac = -1;
+ int cid = -1;
+ android.telephony.CellLocation cl = mPhone.getCellLocation();
+ // Check if cell location is GsmCellLocation. This is required to support
+ // dual-mode devices such as CDMA/LTE devices that require support for
+ // both 3GPP and 3GPP2 format messages
+ if (cl instanceof GsmCellLocation) {
+ GsmCellLocation cellLocation = (GsmCellLocation)cl;
+ lac = cellLocation.getLac();
+ cid = cellLocation.getCid();
+ }
SmsCbLocation location;
switch (header.getGeographicalScope()) {
case SmsCbMessage.GEOGRAPHICAL_SCOPE_LA_WIDE:
location = new SmsCbLocation(plmn, lac, -1);
break;
case SmsCbMessage.GEOGRAPHICAL_SCOPE_CELL_WIDE:
case SmsCbMessage.GEOGRAPHICAL_SCOPE_CELL_WIDE_IMMEDIATE:
location = new SmsCbLocation(plmn, lac, cid);
break;
case SmsCbMessage.GEOGRAPHICAL_SCOPE_PLMN_WIDE:
default:
location = new SmsCbLocation(plmn);
break;
}
byte[][] pdus;
int pageCount = header.getNumberOfPages();
if (pageCount > 1) {
// Multi-page message
SmsCbConcatInfo concatInfo = new SmsCbConcatInfo(header, location);
// Try to find other pages of the same message
pdus = mSmsCbPageMap.get(concatInfo);
if (pdus == null) {
// This is the first page of this message, make room for all
// pages and keep until complete
pdus = new byte[pageCount][];
mSmsCbPageMap.put(concatInfo, pdus);
}
// Page parameter is one-based
pdus[header.getPageIndex() - 1] = receivedPdu;
for (int i = 0; i < pdus.length; i++) {
if (pdus[i] == null) {
// Still missing pages, exit
return;
}
}
// Message complete, remove and dispatch
mSmsCbPageMap.remove(concatInfo);
} else {
// Single page message
pdus = new byte[1][];
pdus[0] = receivedPdu;
}
SmsCbMessage message = GsmSmsCbMessage.createSmsCbMessage(header, location, pdus);
dispatchBroadcastMessage(message);
// Remove messages that are out of scope to prevent the map from
// growing indefinitely, containing incomplete messages that were
// never assembled
Iterator<SmsCbConcatInfo> iter = mSmsCbPageMap.keySet().iterator();
while (iter.hasNext()) {
SmsCbConcatInfo info = iter.next();
if (!info.matchesLocation(plmn, lac, cid)) {
iter.remove();
}
}
} catch (RuntimeException e) {
Log.e(TAG, "Error in decoding SMS CB pdu", e);
}
}
}
| true | true | private void handleBroadcastSms(AsyncResult ar) {
try {
byte[] receivedPdu = (byte[])ar.result;
if (false) {
for (int i = 0; i < receivedPdu.length; i += 8) {
StringBuilder sb = new StringBuilder("SMS CB pdu data: ");
for (int j = i; j < i + 8 && j < receivedPdu.length; j++) {
int b = receivedPdu[j] & 0xff;
if (b < 0x10) {
sb.append('0');
}
sb.append(Integer.toHexString(b)).append(' ');
}
Log.d(TAG, sb.toString());
}
}
SmsCbHeader header = new SmsCbHeader(receivedPdu);
String plmn = SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC);
GsmCellLocation cellLocation = (GsmCellLocation) mPhone.getCellLocation();
int lac = cellLocation.getLac();
int cid = cellLocation.getCid();
SmsCbLocation location;
switch (header.getGeographicalScope()) {
case SmsCbMessage.GEOGRAPHICAL_SCOPE_LA_WIDE:
location = new SmsCbLocation(plmn, lac, -1);
break;
case SmsCbMessage.GEOGRAPHICAL_SCOPE_CELL_WIDE:
case SmsCbMessage.GEOGRAPHICAL_SCOPE_CELL_WIDE_IMMEDIATE:
location = new SmsCbLocation(plmn, lac, cid);
break;
case SmsCbMessage.GEOGRAPHICAL_SCOPE_PLMN_WIDE:
default:
location = new SmsCbLocation(plmn);
break;
}
byte[][] pdus;
int pageCount = header.getNumberOfPages();
if (pageCount > 1) {
// Multi-page message
SmsCbConcatInfo concatInfo = new SmsCbConcatInfo(header, location);
// Try to find other pages of the same message
pdus = mSmsCbPageMap.get(concatInfo);
if (pdus == null) {
// This is the first page of this message, make room for all
// pages and keep until complete
pdus = new byte[pageCount][];
mSmsCbPageMap.put(concatInfo, pdus);
}
// Page parameter is one-based
pdus[header.getPageIndex() - 1] = receivedPdu;
for (int i = 0; i < pdus.length; i++) {
if (pdus[i] == null) {
// Still missing pages, exit
return;
}
}
// Message complete, remove and dispatch
mSmsCbPageMap.remove(concatInfo);
} else {
// Single page message
pdus = new byte[1][];
pdus[0] = receivedPdu;
}
SmsCbMessage message = GsmSmsCbMessage.createSmsCbMessage(header, location, pdus);
dispatchBroadcastMessage(message);
// Remove messages that are out of scope to prevent the map from
// growing indefinitely, containing incomplete messages that were
// never assembled
Iterator<SmsCbConcatInfo> iter = mSmsCbPageMap.keySet().iterator();
while (iter.hasNext()) {
SmsCbConcatInfo info = iter.next();
if (!info.matchesLocation(plmn, lac, cid)) {
iter.remove();
}
}
} catch (RuntimeException e) {
Log.e(TAG, "Error in decoding SMS CB pdu", e);
}
}
| private void handleBroadcastSms(AsyncResult ar) {
try {
byte[] receivedPdu = (byte[])ar.result;
if (false) {
for (int i = 0; i < receivedPdu.length; i += 8) {
StringBuilder sb = new StringBuilder("SMS CB pdu data: ");
for (int j = i; j < i + 8 && j < receivedPdu.length; j++) {
int b = receivedPdu[j] & 0xff;
if (b < 0x10) {
sb.append('0');
}
sb.append(Integer.toHexString(b)).append(' ');
}
Log.d(TAG, sb.toString());
}
}
SmsCbHeader header = new SmsCbHeader(receivedPdu);
String plmn = SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC);
int lac = -1;
int cid = -1;
android.telephony.CellLocation cl = mPhone.getCellLocation();
// Check if cell location is GsmCellLocation. This is required to support
// dual-mode devices such as CDMA/LTE devices that require support for
// both 3GPP and 3GPP2 format messages
if (cl instanceof GsmCellLocation) {
GsmCellLocation cellLocation = (GsmCellLocation)cl;
lac = cellLocation.getLac();
cid = cellLocation.getCid();
}
SmsCbLocation location;
switch (header.getGeographicalScope()) {
case SmsCbMessage.GEOGRAPHICAL_SCOPE_LA_WIDE:
location = new SmsCbLocation(plmn, lac, -1);
break;
case SmsCbMessage.GEOGRAPHICAL_SCOPE_CELL_WIDE:
case SmsCbMessage.GEOGRAPHICAL_SCOPE_CELL_WIDE_IMMEDIATE:
location = new SmsCbLocation(plmn, lac, cid);
break;
case SmsCbMessage.GEOGRAPHICAL_SCOPE_PLMN_WIDE:
default:
location = new SmsCbLocation(plmn);
break;
}
byte[][] pdus;
int pageCount = header.getNumberOfPages();
if (pageCount > 1) {
// Multi-page message
SmsCbConcatInfo concatInfo = new SmsCbConcatInfo(header, location);
// Try to find other pages of the same message
pdus = mSmsCbPageMap.get(concatInfo);
if (pdus == null) {
// This is the first page of this message, make room for all
// pages and keep until complete
pdus = new byte[pageCount][];
mSmsCbPageMap.put(concatInfo, pdus);
}
// Page parameter is one-based
pdus[header.getPageIndex() - 1] = receivedPdu;
for (int i = 0; i < pdus.length; i++) {
if (pdus[i] == null) {
// Still missing pages, exit
return;
}
}
// Message complete, remove and dispatch
mSmsCbPageMap.remove(concatInfo);
} else {
// Single page message
pdus = new byte[1][];
pdus[0] = receivedPdu;
}
SmsCbMessage message = GsmSmsCbMessage.createSmsCbMessage(header, location, pdus);
dispatchBroadcastMessage(message);
// Remove messages that are out of scope to prevent the map from
// growing indefinitely, containing incomplete messages that were
// never assembled
Iterator<SmsCbConcatInfo> iter = mSmsCbPageMap.keySet().iterator();
while (iter.hasNext()) {
SmsCbConcatInfo info = iter.next();
if (!info.matchesLocation(plmn, lac, cid)) {
iter.remove();
}
}
} catch (RuntimeException e) {
Log.e(TAG, "Error in decoding SMS CB pdu", e);
}
}
|
diff --git a/src/hk/reality/stock/view/IndexAdapter.java b/src/hk/reality/stock/view/IndexAdapter.java
index d9ea313..19c9049 100644
--- a/src/hk/reality/stock/view/IndexAdapter.java
+++ b/src/hk/reality/stock/view/IndexAdapter.java
@@ -1,81 +1,81 @@
package hk.reality.stock.view;
import hk.reality.stock.R;
import hk.reality.stock.model.Index;
import android.content.Context;
import android.graphics.Color;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class IndexAdapter extends ArrayAdapter<Index> {
private static final String TAG = "IndexAdapter";
private java.text.DateFormat formatter;
public IndexAdapter(Context context) {
super(context, 0);
formatter = DateFormat.getTimeFormat(context);
}
@Override
public View getView(int position, View view, ViewGroup parent) {
View v = view;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = (View) vi.inflate(R.layout.index_item, null);
}
Log.d(TAG, "prepare view for indexes");
// prepare views
TextView name = (TextView) v.findViewById(R.id.name);
TextView price = (TextView) v.findViewById(R.id.price);
TextView change = (TextView) v.findViewById(R.id.change);
TextView volume = (TextView) v.findViewById(R.id.volume);
TextView time = (TextView) v.findViewById(R.id.time);
// set data
Index index = getItem(position);
- if (index != null && index.getUpdatedAt() != null) {
+ if (index != null) {
volume.setText("");
name.setText(index.getName());
price.setText(String.format("%.02f", index.getValue().doubleValue()));
if (index.getUpdatedAt() != null) {
time.setText(formatter.format(index.getUpdatedAt().getTime()));
} else {
- time.setText("-----");
+ time.setText("");
}
if (index.getChange() != null) {
change.setText(String.format("%+.02f (%.02f%%)",
index.getChange().doubleValue(),
index.getChangePercent().doubleValue()));
} else {
change.setText("---- (---)");
}
if (index.getChange() != null && index.getChange().floatValue() > 0) {
price.setTextColor(Color.rgb(0, 213, 65));
change.setTextColor(Color.rgb(0, 213, 65));
} else if (index.getChange() != null && index.getChange().floatValue() < 0) {
price.setTextColor(Color.rgb(238, 30, 0));
change.setTextColor(Color.rgb(238, 30, 0));
} else {
price.setTextColor(Color.WHITE);
change.setTextColor(Color.WHITE);
}
} else {
time.setText("");
volume.setText("---");
- name.setText(index.getName());
+ name.setText("");
price.setText("----");
change.setText("---- (---)");
}
return v;
}
}
| false | true | public View getView(int position, View view, ViewGroup parent) {
View v = view;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = (View) vi.inflate(R.layout.index_item, null);
}
Log.d(TAG, "prepare view for indexes");
// prepare views
TextView name = (TextView) v.findViewById(R.id.name);
TextView price = (TextView) v.findViewById(R.id.price);
TextView change = (TextView) v.findViewById(R.id.change);
TextView volume = (TextView) v.findViewById(R.id.volume);
TextView time = (TextView) v.findViewById(R.id.time);
// set data
Index index = getItem(position);
if (index != null && index.getUpdatedAt() != null) {
volume.setText("");
name.setText(index.getName());
price.setText(String.format("%.02f", index.getValue().doubleValue()));
if (index.getUpdatedAt() != null) {
time.setText(formatter.format(index.getUpdatedAt().getTime()));
} else {
time.setText("-----");
}
if (index.getChange() != null) {
change.setText(String.format("%+.02f (%.02f%%)",
index.getChange().doubleValue(),
index.getChangePercent().doubleValue()));
} else {
change.setText("---- (---)");
}
if (index.getChange() != null && index.getChange().floatValue() > 0) {
price.setTextColor(Color.rgb(0, 213, 65));
change.setTextColor(Color.rgb(0, 213, 65));
} else if (index.getChange() != null && index.getChange().floatValue() < 0) {
price.setTextColor(Color.rgb(238, 30, 0));
change.setTextColor(Color.rgb(238, 30, 0));
} else {
price.setTextColor(Color.WHITE);
change.setTextColor(Color.WHITE);
}
} else {
time.setText("");
volume.setText("---");
name.setText(index.getName());
price.setText("----");
change.setText("---- (---)");
}
return v;
}
| public View getView(int position, View view, ViewGroup parent) {
View v = view;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = (View) vi.inflate(R.layout.index_item, null);
}
Log.d(TAG, "prepare view for indexes");
// prepare views
TextView name = (TextView) v.findViewById(R.id.name);
TextView price = (TextView) v.findViewById(R.id.price);
TextView change = (TextView) v.findViewById(R.id.change);
TextView volume = (TextView) v.findViewById(R.id.volume);
TextView time = (TextView) v.findViewById(R.id.time);
// set data
Index index = getItem(position);
if (index != null) {
volume.setText("");
name.setText(index.getName());
price.setText(String.format("%.02f", index.getValue().doubleValue()));
if (index.getUpdatedAt() != null) {
time.setText(formatter.format(index.getUpdatedAt().getTime()));
} else {
time.setText("");
}
if (index.getChange() != null) {
change.setText(String.format("%+.02f (%.02f%%)",
index.getChange().doubleValue(),
index.getChangePercent().doubleValue()));
} else {
change.setText("---- (---)");
}
if (index.getChange() != null && index.getChange().floatValue() > 0) {
price.setTextColor(Color.rgb(0, 213, 65));
change.setTextColor(Color.rgb(0, 213, 65));
} else if (index.getChange() != null && index.getChange().floatValue() < 0) {
price.setTextColor(Color.rgb(238, 30, 0));
change.setTextColor(Color.rgb(238, 30, 0));
} else {
price.setTextColor(Color.WHITE);
change.setTextColor(Color.WHITE);
}
} else {
time.setText("");
volume.setText("---");
name.setText("");
price.setText("----");
change.setText("---- (---)");
}
return v;
}
|
diff --git a/src/webapp/src/java/org/wyona/yanel/servlet/About.java b/src/webapp/src/java/org/wyona/yanel/servlet/About.java
index af0749fd6..34249523a 100644
--- a/src/webapp/src/java/org/wyona/yanel/servlet/About.java
+++ b/src/webapp/src/java/org/wyona/yanel/servlet/About.java
@@ -1,18 +1,18 @@
package org.wyona.yanel.servlet;
/**
* Yanel about statement
*/
public class About {
/**
* Get XHTML of about statement
*/
public static String toHTML(String version, String revision) {
StringBuilder sb = new StringBuilder("<html>");
sb.append("<head><title>About Yanel</title></head>");
- sb.append("<body><h1>About Yanel</h1><p>Version " + version + "-r" + revision + "</p><p>Copyright © 2005 - 2009 Wyona. All rights reserved.</p></body>");
+ sb.append("<body><h1>About Yanel</h1><p>Version " + version + "-r" + revision + "</p><p>Copyright © 2005 - 2010 Wyona. All rights reserved.</p></body>");
sb.append("</html>");
return sb.toString();
}
}
| true | true | public static String toHTML(String version, String revision) {
StringBuilder sb = new StringBuilder("<html>");
sb.append("<head><title>About Yanel</title></head>");
sb.append("<body><h1>About Yanel</h1><p>Version " + version + "-r" + revision + "</p><p>Copyright © 2005 - 2009 Wyona. All rights reserved.</p></body>");
sb.append("</html>");
return sb.toString();
}
| public static String toHTML(String version, String revision) {
StringBuilder sb = new StringBuilder("<html>");
sb.append("<head><title>About Yanel</title></head>");
sb.append("<body><h1>About Yanel</h1><p>Version " + version + "-r" + revision + "</p><p>Copyright © 2005 - 2010 Wyona. All rights reserved.</p></body>");
sb.append("</html>");
return sb.toString();
}
|
diff --git a/src/main/scala/thirdparty/misc/ThistleFilter.java b/src/main/scala/thirdparty/misc/ThistleFilter.java
index 681f31b..aa44be9 100644
--- a/src/main/scala/thirdparty/misc/ThistleFilter.java
+++ b/src/main/scala/thirdparty/misc/ThistleFilter.java
@@ -1,59 +1,59 @@
package thirdparty.misc;
import thirdparty.romainguy.BlendComposite;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.IOException;
/**
* @author Sarah Schölzel
*/
public class ThistleFilter {
public BufferedImage filter(BufferedImage bi) {
if (bi.getSampleModel().getDataType() != DataBuffer.TYPE_INT)
throw new UnsupportedOperationException();
BufferedImage dstImg = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
BufferedImage tmp = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
Graphics2D gtmp = tmp.createGraphics();
gtmp.setColor(new Color(17, 24, 66));
gtmp.fill(new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
BufferedImage tmp2 = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
Graphics2D gtmp2 = tmp2.createGraphics();
gtmp2.setColor(new Color(220, 227, 84));
gtmp2.fill(new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
//Blending Mode: Lighten, 55%
gtmp2.setComposite(BlendComposite.getInstance(BlendComposite.BlendingMode.LIGHTEN, 0.55f));
gtmp2.drawImage(tmp, 0, 0, bi.getWidth(), bi.getHeight(), null);
//texture
BufferedImage texture;
try {
- texture = ImageIO.read(getClass().getResource("/texture_old_square.jpg"));
+ texture = ImageIO.read(getClass().getResource("/com/sksamuel/scrimage/filter/texture_old_square.jpg"));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
//Blending Mode: Multiply, 75%
tmp = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
gtmp = tmp.createGraphics();
gtmp.drawImage(texture, 0, 0, bi.getWidth(), bi.getHeight(), null);
gtmp.setComposite(BlendComposite.getInstance(BlendComposite.BlendingMode.MULTIPLY, 0.75f));
gtmp.drawImage(tmp2, 0, 0, bi.getWidth(), bi.getHeight(), null);
//Blending Mode: Overlay, 65%
Graphics2D gdst = dstImg.createGraphics();
gdst.drawImage(bi, 0, 0, null);
gdst.setComposite(BlendComposite.getInstance(BlendComposite.BlendingMode.OVERLAY, 1f));
gdst.drawImage(tmp, 0, 0, bi.getWidth(), bi.getHeight(), null);
return dstImg;
}
}
| true | true | public BufferedImage filter(BufferedImage bi) {
if (bi.getSampleModel().getDataType() != DataBuffer.TYPE_INT)
throw new UnsupportedOperationException();
BufferedImage dstImg = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
BufferedImage tmp = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
Graphics2D gtmp = tmp.createGraphics();
gtmp.setColor(new Color(17, 24, 66));
gtmp.fill(new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
BufferedImage tmp2 = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
Graphics2D gtmp2 = tmp2.createGraphics();
gtmp2.setColor(new Color(220, 227, 84));
gtmp2.fill(new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
//Blending Mode: Lighten, 55%
gtmp2.setComposite(BlendComposite.getInstance(BlendComposite.BlendingMode.LIGHTEN, 0.55f));
gtmp2.drawImage(tmp, 0, 0, bi.getWidth(), bi.getHeight(), null);
//texture
BufferedImage texture;
try {
texture = ImageIO.read(getClass().getResource("/texture_old_square.jpg"));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
//Blending Mode: Multiply, 75%
tmp = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
gtmp = tmp.createGraphics();
gtmp.drawImage(texture, 0, 0, bi.getWidth(), bi.getHeight(), null);
gtmp.setComposite(BlendComposite.getInstance(BlendComposite.BlendingMode.MULTIPLY, 0.75f));
gtmp.drawImage(tmp2, 0, 0, bi.getWidth(), bi.getHeight(), null);
//Blending Mode: Overlay, 65%
Graphics2D gdst = dstImg.createGraphics();
gdst.drawImage(bi, 0, 0, null);
gdst.setComposite(BlendComposite.getInstance(BlendComposite.BlendingMode.OVERLAY, 1f));
gdst.drawImage(tmp, 0, 0, bi.getWidth(), bi.getHeight(), null);
return dstImg;
}
| public BufferedImage filter(BufferedImage bi) {
if (bi.getSampleModel().getDataType() != DataBuffer.TYPE_INT)
throw new UnsupportedOperationException();
BufferedImage dstImg = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
BufferedImage tmp = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
Graphics2D gtmp = tmp.createGraphics();
gtmp.setColor(new Color(17, 24, 66));
gtmp.fill(new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
BufferedImage tmp2 = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
Graphics2D gtmp2 = tmp2.createGraphics();
gtmp2.setColor(new Color(220, 227, 84));
gtmp2.fill(new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
//Blending Mode: Lighten, 55%
gtmp2.setComposite(BlendComposite.getInstance(BlendComposite.BlendingMode.LIGHTEN, 0.55f));
gtmp2.drawImage(tmp, 0, 0, bi.getWidth(), bi.getHeight(), null);
//texture
BufferedImage texture;
try {
texture = ImageIO.read(getClass().getResource("/com/sksamuel/scrimage/filter/texture_old_square.jpg"));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
//Blending Mode: Multiply, 75%
tmp = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
gtmp = tmp.createGraphics();
gtmp.drawImage(texture, 0, 0, bi.getWidth(), bi.getHeight(), null);
gtmp.setComposite(BlendComposite.getInstance(BlendComposite.BlendingMode.MULTIPLY, 0.75f));
gtmp.drawImage(tmp2, 0, 0, bi.getWidth(), bi.getHeight(), null);
//Blending Mode: Overlay, 65%
Graphics2D gdst = dstImg.createGraphics();
gdst.drawImage(bi, 0, 0, null);
gdst.setComposite(BlendComposite.getInstance(BlendComposite.BlendingMode.OVERLAY, 1f));
gdst.drawImage(tmp, 0, 0, bi.getWidth(), bi.getHeight(), null);
return dstImg;
}
|
diff --git a/src/main/java/com/github/kpacha/jkata/primeFactors/PrimeFactors.java b/src/main/java/com/github/kpacha/jkata/primeFactors/PrimeFactors.java
index cebf1a5..81840b9 100644
--- a/src/main/java/com/github/kpacha/jkata/primeFactors/PrimeFactors.java
+++ b/src/main/java/com/github/kpacha/jkata/primeFactors/PrimeFactors.java
@@ -1,11 +1,15 @@
package com.github.kpacha.jkata.primeFactors;
import java.util.ArrayList;
import java.util.List;
public class PrimeFactors {
public static List<Integer> generate(final int number) {
- return new ArrayList<Integer>();
+ List<Integer> primes = new ArrayList<Integer>();
+ if (number > 1) {
+ primes.add(2);
+ }
+ return primes;
}
}
| true | true | public static List<Integer> generate(final int number) {
return new ArrayList<Integer>();
}
| public static List<Integer> generate(final int number) {
List<Integer> primes = new ArrayList<Integer>();
if (number > 1) {
primes.add(2);
}
return primes;
}
|
diff --git a/modules/extra/jetty-runner/src/main/java/org/mortbay/jetty/runner/Runner.java b/modules/extra/jetty-runner/src/main/java/org/mortbay/jetty/runner/Runner.java
index 218f38619..c759d252a 100644
--- a/modules/extra/jetty-runner/src/main/java/org/mortbay/jetty/runner/Runner.java
+++ b/modules/extra/jetty-runner/src/main/java/org/mortbay/jetty/runner/Runner.java
@@ -1,249 +1,252 @@
package org.mortbay.jetty.runner;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.NCSARequestLog;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.jetty.handler.ContextHandlerCollection;
import org.mortbay.jetty.handler.DefaultHandler;
import org.mortbay.jetty.handler.HandlerCollection;
import org.mortbay.jetty.handler.RequestLogHandler;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.log.Log;
import org.mortbay.resource.Resource;
import org.mortbay.xml.XmlConfiguration;
public class Runner
{
protected Server _server;
protected URLClassLoader _classLoader;
protected List<URL> _classpath=new ArrayList<URL>();
protected ContextHandlerCollection _contexts;
protected RequestLogHandler _logHandler;
protected String logFile;
public Runner()
{
}
public void configure(String[] args) throws Exception
{
// handle classpath bits first so we can initialize the log mechanism.
for (int i=0;i<args.length;i++)
{
if ("--lib".equals(args[i]))
{
Resource lib = Resource.newResource(args[++i]);
if (!lib.exists() || !lib.isDirectory())
usage("No such lib directory "+lib);
expandJars(lib);
}
else if ("--jar".equals(args[i]))
{
Resource jar = Resource.newResource(args[++i]);
if (!jar.exists() || jar.isDirectory())
usage("No such jar "+jar);
_classpath.add(jar.getURL());
}
else if ("--classes".equals(args[i]))
{
Resource classes = Resource.newResource(args[++i]);
if (!classes.exists() || !classes.isDirectory())
usage("No such classes directory "+classes);
_classpath.add(classes.getURL());
}
else if (args[i].startsWith("--"))
i++;
}
initClassLoader();
Log.initialize();
if (System.getProperties().containsKey("DEBUG"))
Log.getLog().setDebugEnabled(true);
Log.info("Runner");
Log.debug("Runner classpath {}",_classpath);
String contextPath="/";
boolean contextPathSet=false;
int port=8080;
for (int i=0;i<args.length;i++)
{
if ("--port".equals(args[i]))
port=Integer.parseInt(args[++i]);
else if ("--log".equals(args[i]))
logFile=args[++i];
else if ("--path".equals(args[i]))
{
contextPath=args[++i];
contextPathSet=true;
}
else if ("--lib".equals(args[i]))
{
}
+ else if ("--jar".equals(args[i]))
+ {
+ }
else if ("--classes".equals(args[i]))
{
}
else
{
if (_server==null)
{
// build the server
_server = new Server(port);
HandlerCollection handlers = new HandlerCollection();
_contexts = new ContextHandlerCollection();
_logHandler = new RequestLogHandler();
handlers.setHandlers(new Handler[]{_contexts,new DefaultHandler(),_logHandler});
_server.setHandler(handlers);
}
// Create a context
Resource ctx = Resource.newResource(args[i]);
if (!ctx.exists())
usage("Context '"+ctx+"' does not exist");
// Configure the context
if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml"))
{
// It is a context config file
XmlConfiguration xmlConfiguration=new XmlConfiguration(ctx.getURL());
HashMap<String,Object> properties = new HashMap<String,Object>();
properties.put("Server", _server);
xmlConfiguration.setProperties(properties);
ContextHandler handler=(ContextHandler)xmlConfiguration.configure();
_contexts.addHandler(handler);
if (contextPathSet)
handler.setContextPath(contextPath);
}
else
{
// assume it is a WAR file
WebAppContext webapp = new WebAppContext(_contexts,ctx.toString(),contextPath);
}
}
}
if (_server==null)
usage("No Contexts defined");
_server.setStopAtShutdown(true);
_server.setSendServerVersion(true);
if (logFile!=null)
{
NCSARequestLog requestLog = new NCSARequestLog(logFile);
requestLog.setExtended(false);
_logHandler.setRequestLog(requestLog);
}
}
public void run() throws Exception
{
_server.start();
_server.join();
}
protected void expandJars(Resource lib) throws IOException
{
String[] list = lib.list();
if (list==null)
return;
for (String path : list)
{
if (".".equals(path) || "..".equals(path))
continue;
Resource item = lib.addPath(path);
if (item.isDirectory())
expandJars(item);
else
{
if (path.toLowerCase().endsWith(".jar") ||
path.toLowerCase().endsWith(".zip"))
{
URL url = item.getURL();
_classpath.add(url);
}
}
}
}
protected void initClassLoader()
{
if (_classLoader==null && _classpath!=null && _classpath.size()>0)
{
ClassLoader context=Thread.currentThread().getContextClassLoader();
if (context==null)
_classLoader=new URLClassLoader(_classpath.toArray(new URL[_classpath.size()]));
else
_classLoader=new URLClassLoader(_classpath.toArray(new URL[_classpath.size()]),context);
Thread.currentThread().setContextClassLoader(_classLoader);
}
}
public void usage(String error)
{
if (error!=null)
System.err.println("ERROR: "+error);
System.err.println("Usage: java [-DDEBUG] [-Djetty.home=dir] -jar jetty-runner.jar [--help|--version] [ server opts] [[ context opts] context ...] ");
System.err.println("Server Options:");
System.err.println(" --log file - request log filename (with optional 'yyyy_mm_dd' wildcard");
System.err.println(" --port n - port to listen on (default 8080)");
System.err.println(" --jar file - a jar to be added to the classloader");
System.err.println(" --lib dir - a directory of jars to be added to the classloader");
System.err.println(" --classes dir - a directory of classes to be added to the classloader");
System.err.println("Context Options:");
System.err.println(" --path /path - context path (default /)");
System.err.println(" context - WAR file, web app dir or context.xml file");
System.exit(1);
}
public static void main(String[] args)
{
Runner runner = new Runner();
try
{
if (args.length>0&&args[0].equalsIgnoreCase("--help"))
{
runner.usage(null);
}
else if (args.length>0&&args[0].equalsIgnoreCase("--version"))
{
System.err.println("org.mortbay.jetty.Server: "+Server.getVersion());
System.exit(1);
}
runner.configure(args);
runner.run();
}
catch (Exception e)
{
e.printStackTrace();
runner.usage(null);
}
}
}
| true | true | public void configure(String[] args) throws Exception
{
// handle classpath bits first so we can initialize the log mechanism.
for (int i=0;i<args.length;i++)
{
if ("--lib".equals(args[i]))
{
Resource lib = Resource.newResource(args[++i]);
if (!lib.exists() || !lib.isDirectory())
usage("No such lib directory "+lib);
expandJars(lib);
}
else if ("--jar".equals(args[i]))
{
Resource jar = Resource.newResource(args[++i]);
if (!jar.exists() || jar.isDirectory())
usage("No such jar "+jar);
_classpath.add(jar.getURL());
}
else if ("--classes".equals(args[i]))
{
Resource classes = Resource.newResource(args[++i]);
if (!classes.exists() || !classes.isDirectory())
usage("No such classes directory "+classes);
_classpath.add(classes.getURL());
}
else if (args[i].startsWith("--"))
i++;
}
initClassLoader();
Log.initialize();
if (System.getProperties().containsKey("DEBUG"))
Log.getLog().setDebugEnabled(true);
Log.info("Runner");
Log.debug("Runner classpath {}",_classpath);
String contextPath="/";
boolean contextPathSet=false;
int port=8080;
for (int i=0;i<args.length;i++)
{
if ("--port".equals(args[i]))
port=Integer.parseInt(args[++i]);
else if ("--log".equals(args[i]))
logFile=args[++i];
else if ("--path".equals(args[i]))
{
contextPath=args[++i];
contextPathSet=true;
}
else if ("--lib".equals(args[i]))
{
}
else if ("--classes".equals(args[i]))
{
}
else
{
if (_server==null)
{
// build the server
_server = new Server(port);
HandlerCollection handlers = new HandlerCollection();
_contexts = new ContextHandlerCollection();
_logHandler = new RequestLogHandler();
handlers.setHandlers(new Handler[]{_contexts,new DefaultHandler(),_logHandler});
_server.setHandler(handlers);
}
// Create a context
Resource ctx = Resource.newResource(args[i]);
if (!ctx.exists())
usage("Context '"+ctx+"' does not exist");
// Configure the context
if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml"))
{
// It is a context config file
XmlConfiguration xmlConfiguration=new XmlConfiguration(ctx.getURL());
HashMap<String,Object> properties = new HashMap<String,Object>();
properties.put("Server", _server);
xmlConfiguration.setProperties(properties);
ContextHandler handler=(ContextHandler)xmlConfiguration.configure();
_contexts.addHandler(handler);
if (contextPathSet)
handler.setContextPath(contextPath);
}
else
{
// assume it is a WAR file
WebAppContext webapp = new WebAppContext(_contexts,ctx.toString(),contextPath);
}
}
}
if (_server==null)
usage("No Contexts defined");
_server.setStopAtShutdown(true);
_server.setSendServerVersion(true);
if (logFile!=null)
{
NCSARequestLog requestLog = new NCSARequestLog(logFile);
requestLog.setExtended(false);
_logHandler.setRequestLog(requestLog);
}
}
| public void configure(String[] args) throws Exception
{
// handle classpath bits first so we can initialize the log mechanism.
for (int i=0;i<args.length;i++)
{
if ("--lib".equals(args[i]))
{
Resource lib = Resource.newResource(args[++i]);
if (!lib.exists() || !lib.isDirectory())
usage("No such lib directory "+lib);
expandJars(lib);
}
else if ("--jar".equals(args[i]))
{
Resource jar = Resource.newResource(args[++i]);
if (!jar.exists() || jar.isDirectory())
usage("No such jar "+jar);
_classpath.add(jar.getURL());
}
else if ("--classes".equals(args[i]))
{
Resource classes = Resource.newResource(args[++i]);
if (!classes.exists() || !classes.isDirectory())
usage("No such classes directory "+classes);
_classpath.add(classes.getURL());
}
else if (args[i].startsWith("--"))
i++;
}
initClassLoader();
Log.initialize();
if (System.getProperties().containsKey("DEBUG"))
Log.getLog().setDebugEnabled(true);
Log.info("Runner");
Log.debug("Runner classpath {}",_classpath);
String contextPath="/";
boolean contextPathSet=false;
int port=8080;
for (int i=0;i<args.length;i++)
{
if ("--port".equals(args[i]))
port=Integer.parseInt(args[++i]);
else if ("--log".equals(args[i]))
logFile=args[++i];
else if ("--path".equals(args[i]))
{
contextPath=args[++i];
contextPathSet=true;
}
else if ("--lib".equals(args[i]))
{
}
else if ("--jar".equals(args[i]))
{
}
else if ("--classes".equals(args[i]))
{
}
else
{
if (_server==null)
{
// build the server
_server = new Server(port);
HandlerCollection handlers = new HandlerCollection();
_contexts = new ContextHandlerCollection();
_logHandler = new RequestLogHandler();
handlers.setHandlers(new Handler[]{_contexts,new DefaultHandler(),_logHandler});
_server.setHandler(handlers);
}
// Create a context
Resource ctx = Resource.newResource(args[i]);
if (!ctx.exists())
usage("Context '"+ctx+"' does not exist");
// Configure the context
if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml"))
{
// It is a context config file
XmlConfiguration xmlConfiguration=new XmlConfiguration(ctx.getURL());
HashMap<String,Object> properties = new HashMap<String,Object>();
properties.put("Server", _server);
xmlConfiguration.setProperties(properties);
ContextHandler handler=(ContextHandler)xmlConfiguration.configure();
_contexts.addHandler(handler);
if (contextPathSet)
handler.setContextPath(contextPath);
}
else
{
// assume it is a WAR file
WebAppContext webapp = new WebAppContext(_contexts,ctx.toString(),contextPath);
}
}
}
if (_server==null)
usage("No Contexts defined");
_server.setStopAtShutdown(true);
_server.setSendServerVersion(true);
if (logFile!=null)
{
NCSARequestLog requestLog = new NCSARequestLog(logFile);
requestLog.setExtended(false);
_logHandler.setRequestLog(requestLog);
}
}
|
diff --git a/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/presentation/aggregation/layout/RequesterFragment.java b/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/presentation/aggregation/layout/RequesterFragment.java
index 807b1d5c..ca0ce55f 100644
--- a/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/presentation/aggregation/layout/RequesterFragment.java
+++ b/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/presentation/aggregation/layout/RequesterFragment.java
@@ -1,31 +1,32 @@
package org.eclipse.birt.report.presentation.aggregation.layout;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.birt.report.presentation.aggregation.BirtBaseFragment;
public class RequesterFragment extends BirtBaseFragment
{
/**
* Override implementation of doPostService.
*/
protected String doPostService( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
+ request.setAttribute( "ServletPath", request.getServletPath( ) ); //$NON-NLS-1$
String className = getClass( ).getName( )
.substring( getClass( ).getName( ).lastIndexOf( '.' ) + 1 );
return JSPRootPath + "/pages/layout/" + className + ".jsp"; //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Override build method.
*/
protected void build( )
{
addChild( new ParameterFragment( ) );
}
}
| true | true | protected String doPostService( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
String className = getClass( ).getName( )
.substring( getClass( ).getName( ).lastIndexOf( '.' ) + 1 );
return JSPRootPath + "/pages/layout/" + className + ".jsp"; //$NON-NLS-1$ //$NON-NLS-2$
}
| protected String doPostService( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
request.setAttribute( "ServletPath", request.getServletPath( ) ); //$NON-NLS-1$
String className = getClass( ).getName( )
.substring( getClass( ).getName( ).lastIndexOf( '.' ) + 1 );
return JSPRootPath + "/pages/layout/" + className + ".jsp"; //$NON-NLS-1$ //$NON-NLS-2$
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/server/CommunicationManager.java b/src/com/itmill/toolkit/terminal/gwt/server/CommunicationManager.java
index 33fab1312..bb4e76c09 100644
--- a/src/com/itmill/toolkit/terminal/gwt/server/CommunicationManager.java
+++ b/src/com/itmill/toolkit/terminal/gwt/server/CommunicationManager.java
@@ -1,1154 +1,1155 @@
/* *************************************************************************
IT Mill Toolkit
Development of Browser User Interfaces Made Easy
Copyright (C) 2000-2006 IT Mill Ltd
*************************************************************************
This product is distributed under commercial license that can be found
from the product package on license.pdf. Use of this product might
require purchasing a commercial license from IT Mill Ltd. For guidelines
on usage, see licensing-guidelines.html
*************************************************************************
For more information, contact:
IT Mill Ltd phone: +358 2 4802 7180
Ruukinkatu 2-4 fax: +358 2 4802 7181
20540, Turku email: [email protected]
Finland company www: www.itmill.com
Primary source for information and releases: www.itmill.com
********************************************************************** */
package com.itmill.toolkit.terminal.gwt.server;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// wrapped to prevent conflicts with possible developer required Apache JARs
import com.itmill.toolkit.external.org.apache.commons.fileupload.FileItemIterator;
import com.itmill.toolkit.external.org.apache.commons.fileupload.FileItemStream;
import com.itmill.toolkit.external.org.apache.commons.fileupload.FileUploadException;
import com.itmill.toolkit.external.org.apache.commons.fileupload.ProgressListener;
import com.itmill.toolkit.external.org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.itmill.toolkit.Application;
import com.itmill.toolkit.Log;
import com.itmill.toolkit.Application.WindowAttachEvent;
import com.itmill.toolkit.Application.WindowDetachEvent;
import com.itmill.toolkit.terminal.DownloadStream;
import com.itmill.toolkit.terminal.Paintable;
import com.itmill.toolkit.terminal.URIHandler;
import com.itmill.toolkit.terminal.UploadStream;
import com.itmill.toolkit.terminal.VariableOwner;
import com.itmill.toolkit.terminal.Paintable.RepaintRequestEvent;
import com.itmill.toolkit.ui.Component;
import com.itmill.toolkit.ui.FrameWindow;
import com.itmill.toolkit.ui.Upload;
import com.itmill.toolkit.ui.Window;
/**
* Application manager processes changes and paints for single application
* instance.
*
* @author IT Mill Ltd.
* @version
* @VERSION@
* @since 5.0
*/
public class CommunicationManager implements Paintable.RepaintRequestListener,
Application.WindowAttachListener, Application.WindowDetachListener {
private static String GET_PARAM_REPAINT_ALL = "repaintAll";
private static int DEFAULT_BUFFER_SIZE = 32 * 1024;
private static int MAX_BUFFER_SIZE = 64 * 1024;
private HashSet dirtyPaintabletSet = new HashSet();
private WeakHashMap paintableIdMap = new WeakHashMap();
private WeakHashMap idPaintableMap = new WeakHashMap();
private int idSequence = 0;
private Application application;
private Set removedWindows = new HashSet();
private JsonPaintTarget paintTarget;
private List locales;
private int pendingLocalesIndex;
private ApplicationServlet applicationServlet;
public CommunicationManager(Application application,
ApplicationServlet applicationServlet) {
this.application = application;
this.applicationServlet = applicationServlet;
requireLocale(application.getLocale().toString());
}
/**
*
*
*/
public void takeControl() {
application.addListener((Application.WindowAttachListener) this);
application.addListener((Application.WindowDetachListener) this);
}
/**
*
*
*/
public void releaseControl() {
application.removeListener((Application.WindowAttachListener) this);
application.removeListener((Application.WindowDetachListener) this);
}
/**
* Handles file upload request submitted via Upload component.
*
* @param request
* @param response
* @throws IOException
*/
public void handleFileUpload(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
UploadProgressListener pl = new UploadProgressListener();
upload.setProgressListener(pl);
// Parse the request
FileItemIterator iter;
try {
iter = upload.getItemIterator(request);
/*
* ATM this loop is run only once as we are uploading one file per
* request.
*/
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
final String filename = item.getName();
final String mimeType = item.getContentType();
final InputStream stream = item.openStream();
if (item.isFormField()) {
// ignored, upload requests contian only files
} else {
String pid = name.split("_")[0];
Upload uploadComponent = (Upload) idPaintableMap.get(pid);
if (uploadComponent == null) {
throw new FileUploadException(
"Upload component not found");
}
synchronized (application) {
// put upload component into receiving state
uploadComponent.startUpload();
}
UploadStream upstream = new UploadStream() {
public String getContentName() {
return filename;
}
public String getContentType() {
return mimeType;
}
public InputStream getStream() {
return stream;
}
public String getStreamName() {
return "stream";
}
};
// tell UploadProgressListener which component is receiving
// file
pl.setUpload(uploadComponent);
uploadComponent.receiveUpload(upstream);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
// Send short response to acknowledge client that request was done
response.setContentType("text/html");
OutputStream out = response.getOutputStream();
PrintWriter outWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(out, "UTF-8")));
outWriter.print("<html><body>download handled</body></html>");
outWriter.flush();
out.close();
}
/**
* Handles UIDL request
*
* @param request
* @param response
* @throws IOException
*/
public void handleUidlRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// repaint requested or session has timed out and new one is created
boolean repaintAll = (request.getParameter(GET_PARAM_REPAINT_ALL) != null)
|| request.getSession().isNew();
// If repaint is requested, clean all ids
if (repaintAll) {
idPaintableMap.clear();
paintableIdMap.clear();
}
OutputStream out = response.getOutputStream();
PrintWriter outWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(out, "UTF-8")));
try {
// Is this a download request from application
DownloadStream download = null;
// The rest of the process is synchronized with the application
// in order to guarantee that no parallel variable handling is
// made
synchronized (application) {
// Change all variables based on request parameters
Map unhandledParameters = handleVariables(request, application);
// Handles the URI if the application is still running
if (application.isRunning())
download = handleURI(application, request, response);
// If this is not a download request
if (download == null) {
// Finds the window within the application
Window window = null;
if (application.isRunning())
window = getApplicationWindow(request, application);
// Handles the unhandled parameters if the application is
// still running
if (window != null && unhandledParameters != null
&& !unhandledParameters.isEmpty())
window.handleParameters(unhandledParameters);
// Removes application if it has stopped
if (!application.isRunning()) {
endApplication(request, response, application);
return;
}
// Returns if no window found
if (window == null)
return;
// Sets the response type
response.setContentType("application/json; charset=UTF-8");
// some dirt to prevent cross site scripting
outWriter.print(")/*{");
outWriter.print("\"changes\":[");
paintTarget = new JsonPaintTarget(this, outWriter,
!repaintAll);
// Paints components
Set paintables;
if (repaintAll) {
paintables = new LinkedHashSet();
paintables.add(window);
// Reset sent locales
locales = null;
requireLocale(application.getLocale().toString());
} else
paintables = getDirtyComponents();
if (paintables != null) {
// Creates "working copy" of the current state.
List currentPaintables = new ArrayList(paintables);
// Sorts the paintable so that parent windows
// are always painted before child windows
Collections.sort(currentPaintables, new Comparator() {
public int compare(Object o1, Object o2) {
// If first argumement is now window
// the second is "smaller" if it is.
if (!(o1 instanceof Window)) {
return (o2 instanceof Window) ? 1 : 0;
}
// Now, if second is not window the
// first is smaller.
if (!(o2 instanceof Window)) {
return -1;
}
// Both are windows.
String n1 = ((Window) o1).getName();
String n2 = ((Window) o2).getName();
if (o1 instanceof FrameWindow) {
if (((FrameWindow) o1).getFrameset()
.getFrame(n2) != null) {
return -1;
} else if (!(o2 instanceof FrameWindow)) {
return -1;
}
}
if (o2 instanceof FrameWindow) {
if (((FrameWindow) o2).getFrameset()
.getFrame(n1) != null) {
return 1;
} else if (!(o1 instanceof FrameWindow)) {
return 1;
}
}
return 0;
}
});
for (Iterator i = currentPaintables.iterator(); i
.hasNext();) {
Paintable p = (Paintable) i.next();
// TODO CLEAN
if (p instanceof Window) {
Window w = (Window) p;
if (w.getTerminal() == null)
w.setTerminal(application.getMainWindow()
.getTerminal());
}
/*
* This does not seem to happen in tk5, but remember
* this case: else if (p instanceof Component) { if
* (((Component) p).getParent() == null ||
* ((Component) p).getApplication() == null) { //
* Component requested repaint, but is no // longer
* attached: skip paintablePainted(p); continue; } }
*/
paintTarget.startTag("change");
paintTarget.addAttribute("format", "uidl");
String pid = getPaintableId(p);
paintTarget.addAttribute("pid", pid);
// Track paints to identify empty paints
paintTarget.setTrackPaints(true);
p.paint(paintTarget);
// If no paints add attribute empty
if (paintTarget.getNumberOfPaints() <= 0) {
paintTarget.addAttribute("visible", false);
}
paintTarget.endTag("change");
paintablePainted(p);
}
}
paintTarget.close();
outWriter.print("]"); // close changes
outWriter.print(", \"meta\" : {");
boolean metaOpen = false;
// add meta instruction for client to set focus if it is set
Paintable f = (Paintable) application.consumeFocus();
if (f != null) {
if (metaOpen)
outWriter.write(",");
outWriter.write("\"focus\":\"" + getPaintableId(f)
+ "\"");
}
outWriter.print("}, \"resources\" : {");
// Precache custom layouts
String themeName = window.getTheme();
if (request.getParameter("theme") != null) {
themeName = request.getParameter("theme");
}
if (themeName == null)
themeName = "default";
// TODO We should only precache the layouts that are not
// cached already
int resourceIndex = 0;
for (Iterator i = paintTarget.getPreCachedResources()
.iterator(); i.hasNext();) {
String resource = (String) i.next();
InputStream is = null;
try {
is = applicationServlet
.getServletContext()
.getResourceAsStream(
"/"
+ ApplicationServlet.THEME_DIRECTORY_PATH
+ themeName + "/"
+ resource);
} catch (Exception e) {
e.printStackTrace();
Log.info(e.getMessage());
}
if (is != null) {
outWriter.print((resourceIndex++ > 0 ? ", " : "")
+ "\"" + resource + "\" : ");
StringBuffer layout = new StringBuffer();
try {
InputStreamReader r = new InputStreamReader(is);
char[] buffer = new char[20000];
int charsRead = 0;
while ((charsRead = r.read(buffer)) > 0)
layout.append(buffer, 0, charsRead);
r.close();
} catch (java.io.IOException e) {
Log.info("Resource transfer failed: "
+ request.getRequestURI() + ". ("
+ e.getMessage() + ")");
}
outWriter.print("\""
+ JsonPaintTarget.escapeJSON(layout
.toString()) + "\"");
}
}
outWriter.print("}");
printLocaleDeclarations(outWriter);
outWriter.flush();
outWriter.close();
out.flush();
} else {
// For download request, transfer the downloaded data
handleDownload(download, request, response);
}
}
out.flush();
out.close();
} catch (Throwable e) {
+ e.printStackTrace();
// Writes the error report to client
OutputStreamWriter w = new OutputStreamWriter(out);
PrintWriter err = new PrintWriter(w);
err
.write("<html><head><title>Application Internal Error</title></head><body>");
err.write("<h1>" + e.toString() + "</h1><pre>\n");
e.printStackTrace(new PrintWriter(err));
err.write("\n</pre></body></html>");
err.close();
} finally {
}
}
private Map handleVariables(HttpServletRequest request,
Application application2) {
Map params = new HashMap(request.getParameterMap());
String changes = (String) ((params.get("changes") instanceof String[]) ? ((String[]) params
.get("changes"))[0]
: params.get("changes"));
params.remove("changes");
if (changes != null) {
String[] ca = changes.split("\u0001");
for (int i = 0; i < ca.length; i++) {
String[] vid = ca[i].split("_");
VariableOwner owner = (VariableOwner) idPaintableMap
.get(vid[0]);
if (owner != null) {
Map m;
if (i + 2 >= ca.length
|| !vid[0].equals(ca[i + 2].split("_")[0])) {
if (ca.length > i + 1) {
m = new SingleValueMap(vid[1],
convertVariableValue(vid[2].charAt(0),
ca[++i]));
} else {
m = new SingleValueMap(vid[1],
convertVariableValue(vid[2].charAt(0), ""));
}
} else {
m = new HashMap();
m.put(vid[1], convertVariableValue(vid[2].charAt(0),
ca[++i]));
}
while (i + 1 < ca.length
&& vid[0].equals(ca[i + 1].split("_")[0])) {
vid = ca[++i].split("_");
m.put(vid[1], convertVariableValue(vid[2].charAt(0),
ca[++i]));
}
owner.changeVariables(request, m);
}
}
}
return params;
}
private Object convertVariableValue(char variableType, String strValue) {
Object val = null;
switch (variableType) {
case 'a':
val = strValue.split(",");
break;
case 's':
val = strValue;
break;
case 'i':
val = Integer.valueOf(strValue);
break;
case 'l':
val = Long.valueOf(strValue);
case 'f':
val = Float.valueOf(strValue);
break;
case 'd':
val = Double.valueOf(strValue);
break;
case 'b':
val = Boolean.valueOf(strValue);
break;
}
return val;
}
private void printLocaleDeclarations(PrintWriter outWriter) {
/*
* ----------------------------- Sending Locale sensitive date
* -----------------------------
*/
// Store JVM default locale for later restoration
// (we'll have to change the default locale for a while)
Locale jvmDefault = Locale.getDefault();
// Send locale informations to client
outWriter.print(", \"locales\":[");
for (; pendingLocalesIndex < locales.size(); pendingLocalesIndex++) {
Locale l = generateLocale((String) locales.get(pendingLocalesIndex));
// Locale name
outWriter.print("{\"name\":\"" + l.toString() + "\",");
/*
* Month names (both short and full)
*/
DateFormatSymbols dfs = new DateFormatSymbols(l);
String[] short_months = dfs.getShortMonths();
String[] months = dfs.getMonths();
outWriter.print("\"smn\":[\""
+ // ShortMonthNames
short_months[0] + "\",\"" + short_months[1] + "\",\""
+ short_months[2] + "\",\"" + short_months[3] + "\",\""
+ short_months[4] + "\",\"" + short_months[5] + "\",\""
+ short_months[6] + "\",\"" + short_months[7] + "\",\""
+ short_months[8] + "\",\"" + short_months[9] + "\",\""
+ short_months[10] + "\",\"" + short_months[11] + "\""
+ "],");
outWriter.print("\"mn\":[\""
+ // MonthNames
months[0] + "\",\"" + months[1] + "\",\"" + months[2]
+ "\",\"" + months[3] + "\",\"" + months[4] + "\",\""
+ months[5] + "\",\"" + months[6] + "\",\"" + months[7]
+ "\",\"" + months[8] + "\",\"" + months[9] + "\",\""
+ months[10] + "\",\"" + months[11] + "\"" + "],");
/*
* Weekday names (both short and full)
*/
String[] short_days = dfs.getShortWeekdays();
String[] days = dfs.getWeekdays();
outWriter.print("\"sdn\":[\""
+ // ShortDayNames
short_days[1] + "\",\"" + short_days[2] + "\",\""
+ short_days[3] + "\",\"" + short_days[4] + "\",\""
+ short_days[5] + "\",\"" + short_days[6] + "\",\""
+ short_days[7] + "\"" + "],");
outWriter.print("\"dn\":[\""
+ // DayNames
days[1] + "\",\"" + days[2] + "\",\"" + days[3] + "\",\""
+ days[4] + "\",\"" + days[5] + "\",\"" + days[6] + "\",\""
+ days[7] + "\"" + "],");
/*
* First day of week (0 = sunday, 1 = monday)
*/
Calendar cal = new GregorianCalendar(l);
outWriter.print("\"fdow\":" + (cal.getFirstDayOfWeek() - 1) + ",");
/*
* Date formatting (MM/DD/YYYY etc.)
*/
// Force our locale as JVM default for a while (SimpleDateFormat
// uses JVM default)
Locale.setDefault(l);
String df = new SimpleDateFormat().toPattern();
int timeStart = df.indexOf("H");
if (timeStart < 0)
timeStart = df.indexOf("h");
int ampm_first = df.indexOf("a");
// E.g. in Korean locale AM/PM is before h:mm
// TODO should take that into consideration on client-side as well,
// now always h:mm a
if (ampm_first > 0 && ampm_first < timeStart)
timeStart = ampm_first;
String dateformat = df.substring(0, timeStart - 1);
outWriter.print("\"df\":\"" + dateformat.trim() + "\",");
/*
* Time formatting (24 or 12 hour clock and AM/PM suffixes)
*/
String timeformat = df.substring(timeStart, df.length()); // Doesn't
// return
// second
// or
// milliseconds
// We use timeformat to determine 12/24-hour clock
boolean twelve_hour_clock = timeformat.indexOf("a") > -1;
// TODO there are other possibilities as well, like 'h' in french
// (ignore them, too complicated)
String hour_min_delimiter = timeformat.indexOf(".") > -1 ? "."
: ":";
// outWriter.print("\"tf\":\"" + timeformat + "\",");
outWriter.print("\"thc\":" + twelve_hour_clock + ",");
outWriter.print("\"hmd\":\"" + hour_min_delimiter + "\"");
if (twelve_hour_clock) {
String[] ampm = dfs.getAmPmStrings();
outWriter.print(",\"ampm\":[\"" + ampm[0] + "\",\"" + ampm[1]
+ "\"]");
}
outWriter.print("}");
if (pendingLocalesIndex < locales.size() - 1)
outWriter.print(",");
}
outWriter.print("]"); // Close locales
// Restore JVM default locale
Locale.setDefault(jvmDefault);
}
/**
* Gets the existing application or create a new one. Get a window within an
* application based on the requested URI.
*
* @param request
* the HTTP Request.
* @param application
* the Application to query for window.
* @return Window mathing the given URI or null if not found.
* @throws ServletException
* if an exception has occurred that interferes with the
* servlet's normal operation.
*/
private Window getApplicationWindow(HttpServletRequest request,
Application application) throws ServletException {
Window window = null;
// Find the window where the request is handled
String path = request.getPathInfo();
// Remove UIDL from the path
path = path.substring("/UIDL".length());
// Main window as the URI is empty
if (path == null || path.length() == 0 || path.equals("/"))
window = application.getMainWindow();
// Try to search by window name
else {
String windowName = null;
if (path.charAt(0) == '/')
path = path.substring(1);
int index = path.indexOf('/');
if (index < 0) {
windowName = path;
path = "";
} else {
windowName = path.substring(0, index);
path = path.substring(index + 1);
}
window = application.getWindow(windowName);
// By default, we use main window
if (window == null)
window = application.getMainWindow();
}
return window;
}
/**
* Handles the requested URI. An application can add handlers to do special
* processing, when a certain URI is requested. The handlers are invoked
* before any windows URIs are processed and if a DownloadStream is returned
* it is sent to the client.
*
* @param application
* the Application owning the URI.
* @param request
* the HTTP request instance.
* @param response
* the HTTP response to write to.
* @return boolean <code>true</code> if the request was handled and
* further processing should be suppressed, otherwise
* <code>false</code>.
* @see com.itmill.toolkit.terminal.URIHandler
*/
private DownloadStream handleURI(Application application,
HttpServletRequest request, HttpServletResponse response) {
String uri = request.getPathInfo();
// If no URI is available
if (uri == null || uri.length() == 0 || uri.equals("/"))
return null;
// Remove the leading /
while (uri.startsWith("/") && uri.length() > 0)
uri = uri.substring(1);
// Handle the uri
DownloadStream stream = null;
try {
stream = application.handleURI(application.getURL(), uri);
} catch (Throwable t) {
application.terminalError(new URIHandlerErrorImpl(application, t));
}
return stream;
}
/**
* Handles the requested URI. An application can add handlers to do special
* processing, when a certain URI is requested. The handlers are invoked
* before any windows URIs are processed and if a DownloadStream is returned
* it is sent to the client.
*
* @param stream
* the downloadable stream.
*
* @param request
* the HTTP request instance.
* @param response
* the HTTP response to write to.
*
* @see com.itmill.toolkit.terminal.URIHandler
*/
private void handleDownload(DownloadStream stream,
HttpServletRequest request, HttpServletResponse response) {
// Download from given stream
InputStream data = stream.getStream();
if (data != null) {
// Sets content type
response.setContentType(stream.getContentType());
// Sets cache headers
long cacheTime = stream.getCacheTime();
if (cacheTime <= 0) {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
} else {
response.setHeader("Cache-Control", "max-age=" + cacheTime
/ 1000);
response.setDateHeader("Expires", System.currentTimeMillis()
+ cacheTime);
response.setHeader("Pragma", "cache"); // Required to apply
// caching in some
// Tomcats
}
// Copy download stream parameters directly
// to HTTP headers.
Iterator i = stream.getParameterNames();
if (i != null) {
while (i.hasNext()) {
String param = (String) i.next();
response.setHeader((String) param, stream
.getParameter(param));
}
}
int bufferSize = stream.getBufferSize();
if (bufferSize <= 0 || bufferSize > MAX_BUFFER_SIZE)
bufferSize = DEFAULT_BUFFER_SIZE;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
try {
OutputStream out = response.getOutputStream();
while ((bytesRead = data.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
out.flush();
}
out.close();
} catch (IOException ignored) {
}
}
}
/**
* Ends the Application.
*
* @param request
* the HTTP request instance.
* @param response
* the HTTP response to write to.
* @param application
* the Application to end.
* @throws IOException
* if the writing failed due to input/output error.
*/
private void endApplication(HttpServletRequest request,
HttpServletResponse response, Application application)
throws IOException {
String logoutUrl = application.getLogoutURL();
if (logoutUrl == null)
logoutUrl = application.getURL().toString();
// clients JS app is still running, send a special json file to
// tell client that application has quit and where to point browser now
// Set the response type
response.setContentType("application/json; charset=UTF-8");
ServletOutputStream out = response.getOutputStream();
PrintWriter outWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(out, "UTF-8")));
outWriter.print(")/*{");
outWriter.print("\"redirect\":{");
outWriter.write("\"url\":\"" + logoutUrl + "\"}");
outWriter.flush();
outWriter.close();
out.flush();
}
/**
* Gets the Paintable Id.
*
* @param paintable
* @return the paintable Id.
*/
public synchronized String getPaintableId(Paintable paintable) {
String id = (String) paintableIdMap.get(paintable);
if (id == null) {
id = "PID" + Integer.toString(idSequence++);
paintableIdMap.put(paintable, id);
idPaintableMap.put(id, paintable);
}
return id;
}
public synchronized boolean hasPaintableId(Paintable paintable) {
return paintableIdMap.containsKey(paintable);
}
/**
*
* @return
*/
public synchronized Set getDirtyComponents() {
HashSet resultset = new HashSet(dirtyPaintabletSet);
// The following algorithm removes any components that would be painted
// as
// a direct descendant of other components from the dirty components
// list.
// The result is that each component should be painted exactly once and
// any unmodified components will be painted as "cached=true".
for (Iterator i = dirtyPaintabletSet.iterator(); i.hasNext();) {
Paintable p = (Paintable) i.next();
if (p instanceof Component) {
if (dirtyPaintabletSet.contains(((Component) p).getParent()))
resultset.remove(p);
}
}
return resultset;
}
/**
* @see com.itmill.toolkit.terminal.Paintable.RepaintRequestListener#repaintRequested(com.itmill.toolkit.terminal.Paintable.RepaintRequestEvent)
*/
public void repaintRequested(RepaintRequestEvent event) {
Paintable p = event.getPaintable();
dirtyPaintabletSet.add(p);
}
/**
*
* @param p
*/
public void paintablePainted(Paintable p) {
dirtyPaintabletSet.remove(p);
p.requestRepaintRequests();
}
/**
* @see com.itmill.toolkit.Application.WindowAttachListener#windowAttached(com.itmill.toolkit.Application.WindowAttachEvent)
*/
public void windowAttached(WindowAttachEvent event) {
event.getWindow().addListener(this);
dirtyPaintabletSet.add(event.getWindow());
}
/**
* @see com.itmill.toolkit.Application.WindowDetachListener#windowDetached(com.itmill.toolkit.Application.WindowDetachEvent)
*/
public void windowDetached(WindowDetachEvent event) {
event.getWindow().removeListener(this);
// Notify client of the close operation
removedWindows.add(event.getWindow());
}
/**
*
* @return
*/
public synchronized Set getRemovedWindows() {
return Collections.unmodifiableSet(removedWindows);
}
/**
*
* @param w
*/
private void removedWindowNotified(Window w) {
this.removedWindows.remove(w);
}
private final class SingleValueMap implements Map {
private final String name;
private final Object value;
private SingleValueMap(String name, Object value) {
this.name = name;
this.value = value;
}
public void clear() {
throw new UnsupportedOperationException();
}
public boolean containsKey(Object key) {
if (name == null)
return key == null;
return name.equals(key);
}
public boolean containsValue(Object v) {
if (value == null)
return v == null;
return value.equals(v);
}
public Set entrySet() {
Set s = new HashSet();
s.add(new Map.Entry() {
public Object getKey() {
return name;
}
public Object getValue() {
return value;
}
public Object setValue(Object value) {
throw new UnsupportedOperationException();
}
});
return s;
}
public Object get(Object key) {
if (!name.equals(key))
return null;
return value;
}
public boolean isEmpty() {
return false;
}
public Set keySet() {
Set s = new HashSet();
s.add(name);
return s;
}
public Object put(Object key, Object value) {
throw new UnsupportedOperationException();
}
public void putAll(Map t) {
throw new UnsupportedOperationException();
}
public Object remove(Object key) {
throw new UnsupportedOperationException();
}
public int size() {
return 1;
}
public Collection values() {
LinkedList s = new LinkedList();
s.add(value);
return s;
}
}
/**
* Implementation of URIHandler.ErrorEvent interface.
*/
public class URIHandlerErrorImpl implements URIHandler.ErrorEvent {
private URIHandler owner;
private Throwable throwable;
/**
*
* @param owner
* @param throwable
*/
private URIHandlerErrorImpl(URIHandler owner, Throwable throwable) {
this.owner = owner;
this.throwable = throwable;
}
/**
* @see com.itmill.toolkit.terminal.Terminal.ErrorEvent#getThrowable()
*/
public Throwable getThrowable() {
return this.throwable;
}
/**
* @see com.itmill.toolkit.terminal.URIHandler.ErrorEvent#getURIHandler()
*/
public URIHandler getURIHandler() {
return this.owner;
}
}
public void requireLocale(String value) {
if (locales == null) {
locales = new ArrayList();
locales.add(application.getLocale().toString());
pendingLocalesIndex = 0;
}
if (!locales.contains(value))
locales.add(value);
}
private Locale generateLocale(String value) {
String[] temp = value.split("_");
if (temp.length == 1)
return new Locale(temp[0]);
else if (temp.length == 2)
return new Locale(temp[0], temp[1]);
else
return new Locale(temp[0], temp[1], temp[2]);
}
/*
* Upload progress listener notifies upload component once when Jakarta
* FileUpload can determine content length. Used to detect files total size,
* uploads progress can be tracked inside upload.
*/
private class UploadProgressListener implements ProgressListener {
Upload uploadComponent;
boolean updated = false;
public void setUpload(Upload u) {
uploadComponent = u;
}
public void update(long bytesRead, long contentLength, int items) {
if (!updated && uploadComponent != null) {
uploadComponent.setUploadSize(contentLength);
updated = true;
}
}
}
}
| true | true | public void handleUidlRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// repaint requested or session has timed out and new one is created
boolean repaintAll = (request.getParameter(GET_PARAM_REPAINT_ALL) != null)
|| request.getSession().isNew();
// If repaint is requested, clean all ids
if (repaintAll) {
idPaintableMap.clear();
paintableIdMap.clear();
}
OutputStream out = response.getOutputStream();
PrintWriter outWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(out, "UTF-8")));
try {
// Is this a download request from application
DownloadStream download = null;
// The rest of the process is synchronized with the application
// in order to guarantee that no parallel variable handling is
// made
synchronized (application) {
// Change all variables based on request parameters
Map unhandledParameters = handleVariables(request, application);
// Handles the URI if the application is still running
if (application.isRunning())
download = handleURI(application, request, response);
// If this is not a download request
if (download == null) {
// Finds the window within the application
Window window = null;
if (application.isRunning())
window = getApplicationWindow(request, application);
// Handles the unhandled parameters if the application is
// still running
if (window != null && unhandledParameters != null
&& !unhandledParameters.isEmpty())
window.handleParameters(unhandledParameters);
// Removes application if it has stopped
if (!application.isRunning()) {
endApplication(request, response, application);
return;
}
// Returns if no window found
if (window == null)
return;
// Sets the response type
response.setContentType("application/json; charset=UTF-8");
// some dirt to prevent cross site scripting
outWriter.print(")/*{");
outWriter.print("\"changes\":[");
paintTarget = new JsonPaintTarget(this, outWriter,
!repaintAll);
// Paints components
Set paintables;
if (repaintAll) {
paintables = new LinkedHashSet();
paintables.add(window);
// Reset sent locales
locales = null;
requireLocale(application.getLocale().toString());
} else
paintables = getDirtyComponents();
if (paintables != null) {
// Creates "working copy" of the current state.
List currentPaintables = new ArrayList(paintables);
// Sorts the paintable so that parent windows
// are always painted before child windows
Collections.sort(currentPaintables, new Comparator() {
public int compare(Object o1, Object o2) {
// If first argumement is now window
// the second is "smaller" if it is.
if (!(o1 instanceof Window)) {
return (o2 instanceof Window) ? 1 : 0;
}
// Now, if second is not window the
// first is smaller.
if (!(o2 instanceof Window)) {
return -1;
}
// Both are windows.
String n1 = ((Window) o1).getName();
String n2 = ((Window) o2).getName();
if (o1 instanceof FrameWindow) {
if (((FrameWindow) o1).getFrameset()
.getFrame(n2) != null) {
return -1;
} else if (!(o2 instanceof FrameWindow)) {
return -1;
}
}
if (o2 instanceof FrameWindow) {
if (((FrameWindow) o2).getFrameset()
.getFrame(n1) != null) {
return 1;
} else if (!(o1 instanceof FrameWindow)) {
return 1;
}
}
return 0;
}
});
for (Iterator i = currentPaintables.iterator(); i
.hasNext();) {
Paintable p = (Paintable) i.next();
// TODO CLEAN
if (p instanceof Window) {
Window w = (Window) p;
if (w.getTerminal() == null)
w.setTerminal(application.getMainWindow()
.getTerminal());
}
/*
* This does not seem to happen in tk5, but remember
* this case: else if (p instanceof Component) { if
* (((Component) p).getParent() == null ||
* ((Component) p).getApplication() == null) { //
* Component requested repaint, but is no // longer
* attached: skip paintablePainted(p); continue; } }
*/
paintTarget.startTag("change");
paintTarget.addAttribute("format", "uidl");
String pid = getPaintableId(p);
paintTarget.addAttribute("pid", pid);
// Track paints to identify empty paints
paintTarget.setTrackPaints(true);
p.paint(paintTarget);
// If no paints add attribute empty
if (paintTarget.getNumberOfPaints() <= 0) {
paintTarget.addAttribute("visible", false);
}
paintTarget.endTag("change");
paintablePainted(p);
}
}
paintTarget.close();
outWriter.print("]"); // close changes
outWriter.print(", \"meta\" : {");
boolean metaOpen = false;
// add meta instruction for client to set focus if it is set
Paintable f = (Paintable) application.consumeFocus();
if (f != null) {
if (metaOpen)
outWriter.write(",");
outWriter.write("\"focus\":\"" + getPaintableId(f)
+ "\"");
}
outWriter.print("}, \"resources\" : {");
// Precache custom layouts
String themeName = window.getTheme();
if (request.getParameter("theme") != null) {
themeName = request.getParameter("theme");
}
if (themeName == null)
themeName = "default";
// TODO We should only precache the layouts that are not
// cached already
int resourceIndex = 0;
for (Iterator i = paintTarget.getPreCachedResources()
.iterator(); i.hasNext();) {
String resource = (String) i.next();
InputStream is = null;
try {
is = applicationServlet
.getServletContext()
.getResourceAsStream(
"/"
+ ApplicationServlet.THEME_DIRECTORY_PATH
+ themeName + "/"
+ resource);
} catch (Exception e) {
e.printStackTrace();
Log.info(e.getMessage());
}
if (is != null) {
outWriter.print((resourceIndex++ > 0 ? ", " : "")
+ "\"" + resource + "\" : ");
StringBuffer layout = new StringBuffer();
try {
InputStreamReader r = new InputStreamReader(is);
char[] buffer = new char[20000];
int charsRead = 0;
while ((charsRead = r.read(buffer)) > 0)
layout.append(buffer, 0, charsRead);
r.close();
} catch (java.io.IOException e) {
Log.info("Resource transfer failed: "
+ request.getRequestURI() + ". ("
+ e.getMessage() + ")");
}
outWriter.print("\""
+ JsonPaintTarget.escapeJSON(layout
.toString()) + "\"");
}
}
outWriter.print("}");
printLocaleDeclarations(outWriter);
outWriter.flush();
outWriter.close();
out.flush();
} else {
// For download request, transfer the downloaded data
handleDownload(download, request, response);
}
}
out.flush();
out.close();
} catch (Throwable e) {
// Writes the error report to client
OutputStreamWriter w = new OutputStreamWriter(out);
PrintWriter err = new PrintWriter(w);
err
.write("<html><head><title>Application Internal Error</title></head><body>");
err.write("<h1>" + e.toString() + "</h1><pre>\n");
e.printStackTrace(new PrintWriter(err));
err.write("\n</pre></body></html>");
err.close();
} finally {
}
}
| public void handleUidlRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// repaint requested or session has timed out and new one is created
boolean repaintAll = (request.getParameter(GET_PARAM_REPAINT_ALL) != null)
|| request.getSession().isNew();
// If repaint is requested, clean all ids
if (repaintAll) {
idPaintableMap.clear();
paintableIdMap.clear();
}
OutputStream out = response.getOutputStream();
PrintWriter outWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(out, "UTF-8")));
try {
// Is this a download request from application
DownloadStream download = null;
// The rest of the process is synchronized with the application
// in order to guarantee that no parallel variable handling is
// made
synchronized (application) {
// Change all variables based on request parameters
Map unhandledParameters = handleVariables(request, application);
// Handles the URI if the application is still running
if (application.isRunning())
download = handleURI(application, request, response);
// If this is not a download request
if (download == null) {
// Finds the window within the application
Window window = null;
if (application.isRunning())
window = getApplicationWindow(request, application);
// Handles the unhandled parameters if the application is
// still running
if (window != null && unhandledParameters != null
&& !unhandledParameters.isEmpty())
window.handleParameters(unhandledParameters);
// Removes application if it has stopped
if (!application.isRunning()) {
endApplication(request, response, application);
return;
}
// Returns if no window found
if (window == null)
return;
// Sets the response type
response.setContentType("application/json; charset=UTF-8");
// some dirt to prevent cross site scripting
outWriter.print(")/*{");
outWriter.print("\"changes\":[");
paintTarget = new JsonPaintTarget(this, outWriter,
!repaintAll);
// Paints components
Set paintables;
if (repaintAll) {
paintables = new LinkedHashSet();
paintables.add(window);
// Reset sent locales
locales = null;
requireLocale(application.getLocale().toString());
} else
paintables = getDirtyComponents();
if (paintables != null) {
// Creates "working copy" of the current state.
List currentPaintables = new ArrayList(paintables);
// Sorts the paintable so that parent windows
// are always painted before child windows
Collections.sort(currentPaintables, new Comparator() {
public int compare(Object o1, Object o2) {
// If first argumement is now window
// the second is "smaller" if it is.
if (!(o1 instanceof Window)) {
return (o2 instanceof Window) ? 1 : 0;
}
// Now, if second is not window the
// first is smaller.
if (!(o2 instanceof Window)) {
return -1;
}
// Both are windows.
String n1 = ((Window) o1).getName();
String n2 = ((Window) o2).getName();
if (o1 instanceof FrameWindow) {
if (((FrameWindow) o1).getFrameset()
.getFrame(n2) != null) {
return -1;
} else if (!(o2 instanceof FrameWindow)) {
return -1;
}
}
if (o2 instanceof FrameWindow) {
if (((FrameWindow) o2).getFrameset()
.getFrame(n1) != null) {
return 1;
} else if (!(o1 instanceof FrameWindow)) {
return 1;
}
}
return 0;
}
});
for (Iterator i = currentPaintables.iterator(); i
.hasNext();) {
Paintable p = (Paintable) i.next();
// TODO CLEAN
if (p instanceof Window) {
Window w = (Window) p;
if (w.getTerminal() == null)
w.setTerminal(application.getMainWindow()
.getTerminal());
}
/*
* This does not seem to happen in tk5, but remember
* this case: else if (p instanceof Component) { if
* (((Component) p).getParent() == null ||
* ((Component) p).getApplication() == null) { //
* Component requested repaint, but is no // longer
* attached: skip paintablePainted(p); continue; } }
*/
paintTarget.startTag("change");
paintTarget.addAttribute("format", "uidl");
String pid = getPaintableId(p);
paintTarget.addAttribute("pid", pid);
// Track paints to identify empty paints
paintTarget.setTrackPaints(true);
p.paint(paintTarget);
// If no paints add attribute empty
if (paintTarget.getNumberOfPaints() <= 0) {
paintTarget.addAttribute("visible", false);
}
paintTarget.endTag("change");
paintablePainted(p);
}
}
paintTarget.close();
outWriter.print("]"); // close changes
outWriter.print(", \"meta\" : {");
boolean metaOpen = false;
// add meta instruction for client to set focus if it is set
Paintable f = (Paintable) application.consumeFocus();
if (f != null) {
if (metaOpen)
outWriter.write(",");
outWriter.write("\"focus\":\"" + getPaintableId(f)
+ "\"");
}
outWriter.print("}, \"resources\" : {");
// Precache custom layouts
String themeName = window.getTheme();
if (request.getParameter("theme") != null) {
themeName = request.getParameter("theme");
}
if (themeName == null)
themeName = "default";
// TODO We should only precache the layouts that are not
// cached already
int resourceIndex = 0;
for (Iterator i = paintTarget.getPreCachedResources()
.iterator(); i.hasNext();) {
String resource = (String) i.next();
InputStream is = null;
try {
is = applicationServlet
.getServletContext()
.getResourceAsStream(
"/"
+ ApplicationServlet.THEME_DIRECTORY_PATH
+ themeName + "/"
+ resource);
} catch (Exception e) {
e.printStackTrace();
Log.info(e.getMessage());
}
if (is != null) {
outWriter.print((resourceIndex++ > 0 ? ", " : "")
+ "\"" + resource + "\" : ");
StringBuffer layout = new StringBuffer();
try {
InputStreamReader r = new InputStreamReader(is);
char[] buffer = new char[20000];
int charsRead = 0;
while ((charsRead = r.read(buffer)) > 0)
layout.append(buffer, 0, charsRead);
r.close();
} catch (java.io.IOException e) {
Log.info("Resource transfer failed: "
+ request.getRequestURI() + ". ("
+ e.getMessage() + ")");
}
outWriter.print("\""
+ JsonPaintTarget.escapeJSON(layout
.toString()) + "\"");
}
}
outWriter.print("}");
printLocaleDeclarations(outWriter);
outWriter.flush();
outWriter.close();
out.flush();
} else {
// For download request, transfer the downloaded data
handleDownload(download, request, response);
}
}
out.flush();
out.close();
} catch (Throwable e) {
e.printStackTrace();
// Writes the error report to client
OutputStreamWriter w = new OutputStreamWriter(out);
PrintWriter err = new PrintWriter(w);
err
.write("<html><head><title>Application Internal Error</title></head><body>");
err.write("<h1>" + e.toString() + "</h1><pre>\n");
e.printStackTrace(new PrintWriter(err));
err.write("\n</pre></body></html>");
err.close();
} finally {
}
}
|
diff --git a/fi/hu/cs/titokone/Compiler.java b/fi/hu/cs/titokone/Compiler.java
index 13a5701..c4e07a3 100755
--- a/fi/hu/cs/titokone/Compiler.java
+++ b/fi/hu/cs/titokone/Compiler.java
@@ -1,997 +1,996 @@
package fi.hu.cs.titokone;
import fi.hu.cs.ttk91.TTK91CompileException;
import java.util.HashMap;
import java.util.Vector;
/** This class knows everything about the relation between symbolic
code and binary code. It can transform a full source to binary or
one symbolic command to binary or vice versa. Empty out all compiler
commands and empty lines at the start
of round 2.*/
public class Compiler {
/** This field contains the source code as a String array. */
private String[] source;
/** This field holds the declared variables, labels and other
symbols. It acts as a pointer to the symbolTable Vector where
the actual data is stored. */
private HashMap symbols;
/** This field holds the invalid values to be introduced
(i.e. already used labels can't be re-used. */
private HashMap invalidLabels;
/** This field tells the next line to be checked. */
private int nextLine;
/** This field holds all the valid symbols on a label. */
private final String VALIDLABELCHARS = "0123456789abcdefghijklmnopqrstuvwxyz���_";
private final int NOTVALID = -1;
private final int EMPTY = -1;
/** Maximum value of the address part. */
private final int MAXINT = 32767;
/** Minimum value of the address part. */
private final int MININT = -32767;
/** This field holds the value of Stdin if it was set with DEF command. */
private String defStdin;
/** This field holds the value of Stdout if it was set with DEF command. */
private String defStdout;
/** This field keeps track of whether we are in the first round of
compilation or the second. It is set by compile() and updated
by compileLine(). */
private boolean firstRound;
/** This field counts the number of actual command lines found
during the first round. */
private int commandLineCount;
/** This array contains the code. During the first round this
field holds the clean version of the code (stripped of
compiler commands like def, ds, dc etc.)
*/
private Vector code;
/** This field acts as a symboltable, it is a String array vector
where 1:st position holds the name of the symbol and the
second either it's value (label, equ) or the command (ds 10,
dc 10) */
private Vector symbolTable;
/** This array contains the data. */
private String[] data;
// Second Round
/** This field holds the Memoryline objects for the code. These
are passed to the Application constructor at the end of the
compile process, and are gathered during the second round from
first round commands in code-array
*/
private MemoryLine[] codeMemoryLines;
/** This field holds the Memoryline objects for the data
area. Much like the code part, this is gathered during the
second round and passed to the Application when
getApplication() method is called.
*/
private MemoryLine[] dataMemoryLines;
/** This value tells if all the lines are processed twice and
getApplication can be run.
*/
private boolean compileFinished;
/** This field contains the CompileDebugger instance to inform of
any compilation happenings. */
private CompileDebugger compileDebugger;
/** This field contains the SymbolicInterpreter instance to use as
part of the compilation.
*/
private SymbolicInterpreter symbolicInterpreter;
/*---------- Constructor ----------*/
/** This constructor sets up the class. It also initializes an
instance of CompileDebugger. */
public Compiler() {
compileDebugger = new CompileDebugger();
symbolicInterpreter = new SymbolicInterpreter();
}
/** This function initializes transforms a symbolic source code into an
application class. After this, call compileLine() to actually compile
the application one line at a time, and finally getApplication() to get
the finished application.
@param source The symbolic source code to be compiled. */
public void compile(String source) {
firstRound = true;
compileFinished = false;
while (source.indexOf("\r\n") != -1) {
source = source.substring(0, source.indexOf("\r\n")) + source.substring(source.indexOf("\r\n") + 1);
}
source = source.toLowerCase();
this.source = source.split("[\n\r\f\u0085\u2028\u2029]");
// antti: removed + from the split and added the while loop (21.04.2004)
nextLine = 0;
defStdin = "";
defStdout = "";
code = new Vector();
symbols = new HashMap();
symbolTable = new Vector();
invalidLabels = new HashMap();
invalidLabels.put("crt", new Integer(0));
invalidLabels.put("kbd", new Integer(1));
invalidLabels.put("stdin", new Integer(6));
invalidLabels.put("stdout", new Integer(7));
invalidLabels.put("halt", new Integer(11));
invalidLabels.put("read", new Integer(12));
invalidLabels.put("write", new Integer(13));
invalidLabels.put("time", new Integer(14));
invalidLabels.put("date", new Integer(15));
}
/** This function goes through one line of the code. On the first
round, it gathers the symbols and their definitions to a
symbol table and conducts syntax-checking, on the second round
it transforms each command to its binary format. For the
transformations, the CompileConstants class is used. It calls
the private methods firstRoundProcess() and
secondRoundProcess() to do the actual work, if there is any to
do. The transfer from first round of compilation to the
second is done automatically; during it,
initializeSecondRound() is called.
@return A CompileInfo debug information object, describing
what happened during the compilation of this line and whether
this is the first or second round of compilation or null if
there are no more lines left to process.
@throws TTK91CompileException If a) there is a syntax error
during the first round of checking (error code 101) or b) a
symbol is still undefined after the first round of compilation
is finished. */
public CompileInfo compileLine() throws TTK91CompileException {
CompileInfo info;
if (firstRound) {
if (nextLine == source.length) {
compileDebugger.firstPhase();
info = initializeSecondRound();
return info;
} else {
compileDebugger.firstPhase(nextLine, source[nextLine]);
info = firstRoundProcess(source[nextLine]);
++nextLine;
return info;
}
} else {
if (nextLine == code.size()) {
compileDebugger.finalPhase();
compileFinished = true;
return null;
} else {
compileDebugger.secondPhase(nextLine, source[nextLine]);
info = secondRoundProcess((String)code.get(nextLine));
++nextLine;
return info;
}
}
}
/** This method returns the readily-compiled application if the
compilation is complete, or null otherwise. */
public Application getApplication() throws IllegalStateException {
if (compileFinished) {
dataMemoryLines = new MemoryLine[data.length];
for (int i = 0; i < data.length; ++i) {
dataMemoryLines[i] = new MemoryLine(Integer.parseInt(data[i]), "");
}
SymbolTable st = new SymbolTable();
String[] tempSTLine;
String symbolName;
int symbolValue;
for (int i = 0; i < symbolTable.size(); ++i) {
tempSTLine = (String[])symbolTable.get(i);
symbolName = tempSTLine[0];
symbolValue = Integer.parseInt(tempSTLine[1]);
st.addSymbol(symbolName, symbolValue);
}
if (!defStdin.equals("")) { st.addDefinition("stdin", defStdin); }
if (!defStdout.equals("")) { st.addDefinition("stdout", defStdout); }
return new Application(codeMemoryLines, dataMemoryLines, st);
} else {
throw new IllegalStateException(new Message("Compilation is not " +
"finished " +
"yet.").toString());
}
}
/** This function transforms a binary command number to a MemoryLine
containing both the binary and the symbolic command corresponding
to it.
@param binary The command to be translated as binary.
@return A MemoryLine instance containing both the information
about the symbolic command and the binary version of it. */
public MemoryLine getSymbolicAndBinary(int binary) {
BinaryInterpreter bi = new BinaryInterpreter();
return new MemoryLine(binary, bi.binaryToString(binary));
}
/** This function transforms a MemoryLine containing only the binary
command to a MemoryLine containing both the binary and the
symbolic command corresponding to it.
@param binaryOnly A MemoryLine containing the binary only of the
command to be translated as binary. If the MemoryLine contains
both, the pre-set symbolic value is ignored.
@return A MemoryLine instance containing both the information
about the symbolic command and the binary version of it. */
public MemoryLine getSymbolicAndBinary(MemoryLine binaryOnly) {
BinaryInterpreter bi = new BinaryInterpreter();
return new MemoryLine(binaryOnly.getBinary(),
bi.binaryToString(binaryOnly.getBinary()));
}
/** This function gathers new symbol information from the given line
and checks its syntax. If a data reservation is detected, the
dataAreaSize is incremented accordingly. If the line contains
an actual command, commandLineCount is incremented.
@param line The line of code to process.
@return A CompileInfo object describing what was done, or null if
the first round has been completed. This will be the sign for
the compiler to prepare for the second round and start it. */
private CompileInfo firstRoundProcess(String line)
throws TTK91CompileException {
String[] lineTemp = parseCompilerCommandLine(line);
boolean nothingFound = true;
String comment = "";
String[] commentParameters;
int intValue = 0;
String[] symbolTableEntry = new String[2];
boolean labelFound = false;
boolean variableUsed = false;
if (lineTemp == null) {
lineTemp = parseLine(line);
if (lineTemp == null) {
// not a valid command
comment = new Message("Invalid command.").toString();
throw new TTK91CompileException(comment);
} else {
if (lineTemp[1].equals("")) {
// line empty;
} else {
code.add(line);
if (!lineTemp[0].equals("")) {
nothingFound = false;
labelFound = true;
// label found
if (invalidLabels.containsKey(lineTemp[0])) {
// not a valid label
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
} else {
invalidLabels.put(lineTemp[0], null);
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = "" +
(code.size() - 1);
/* MUUTETTU 23.04. (OLLI)
*/
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone());
} else {
- symbols.put(lineTemp[0],
- new Integer(code.size() - 1));
+ symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = "" +
(code.size() - 1);
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundLabel(lineTemp[0],
code.size() -1);
}
}
try {
if (!lineTemp[4].equals(""))
Integer.parseInt(lineTemp[4]);
} catch(NumberFormatException e) {
// variable used
if (symbolicInterpreter.getRegisterId(lineTemp[4]) == -1) {
nothingFound = false;
variableUsed = true;
compileDebugger.foundSymbol(lineTemp[4]);
if (!symbols.containsKey(lineTemp[4])) {
if (invalidLabels.get(lineTemp[4]) == null) {
symbols.put(lineTemp[4], new
Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[4];
symbolTableEntry[1] = "";
symbolTable.add(symbolTableEntry.clone());
} else {
// predefined word (halt etc) was used
symbols.put(lineTemp[4],
new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[4];
symbolTableEntry[1] = "" +
(Integer) invalidLabels.get(lineTemp[4]);
symbolTable.add(symbolTableEntry.clone());
}
}
}
}
if (variableUsed && labelFound) {
commentParameters = new String[2];
commentParameters[0] = lineTemp[0];
commentParameters[1] = lineTemp[4];
comment = new Message("Found label {0} and variable " +
"{1}.",
commentParameters).toString();
compileDebugger.setComment(comment);
} else {
if (variableUsed) {
comment = new Message("Variable {0} used.",
lineTemp[4]).toString();
compileDebugger.setComment(comment);
} else {
if (labelFound) {
comment = new Message("Label {0} found.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
}
}
}
}
} else {
// compiler command
boolean allCharsValid = true;
boolean atLeastOneNonNumber = false;
if (invalidLabels.containsKey(lineTemp[0])) {
// not a valid label
if (!(lineTemp[1].equalsIgnoreCase("def") &&
(lineTemp[0].equalsIgnoreCase("stdin") ||
lineTemp[0].equalsIgnoreCase("stdout"))
)) {
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
}
}
if(!validLabelName(lineTemp[0])) {
// not a valid label;
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
} else {
if (lineTemp[1].equalsIgnoreCase("ds")) {
intValue = 0;
try {
intValue = Integer.parseInt(lineTemp[2]);
} catch(NumberFormatException e) {
comment = new Message("Invalid size for a " +
"DS.").toString();
throw new TTK91CompileException(comment);
}
if (intValue < 0 || intValue > MAXINT) {
comment = new Message("Invalid size for a " +
"DS.").toString();
throw new TTK91CompileException(comment);
}
}
if (lineTemp[1].equalsIgnoreCase("dc")) {
intValue = 0;
if (lineTemp[2].trim().length() > 0) {
try {
intValue = Integer.parseInt(lineTemp[2]);
} catch(NumberFormatException e) {
comment = new Message("Invalid value for a " +
"DC.").toString();
throw new TTK91CompileException(comment);
}
if (intValue < MININT || intValue > MAXINT) {
comment = new Message("Invalid value for a " +
"DC.").toString();
throw new TTK91CompileException(comment);
}
}
}
if (lineTemp[1].equalsIgnoreCase("equ")) {
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[2];
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone());
} else {
symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[2];
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundEQU(lineTemp[0], intValue);
commentParameters = new String[2];
commentParameters[0] = lineTemp[0];
commentParameters[1] = lineTemp[2];
comment = new Message("Variable {0} defined as {1}.",
commentParameters).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equals("ds")) {
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone()
);
} else {
symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundDS(lineTemp[0]);
comment = new Message("Found variable {0}.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equals("dc")) {
compileDebugger.foundDC(lineTemp[0]);
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone());
} else {
symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundDC(lineTemp[0]);
comment = new Message("Found variable {0}.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equalsIgnoreCase("def")) {
if (lineTemp[0].equals("stdin") ||
lineTemp[0].equals("stdout")) {
if (lineTemp[0].equals("stdin")) {
defStdin = lineTemp[2];
} else {
defStdout = lineTemp[2];
}
compileDebugger.foundDEF(lineTemp[0], lineTemp[2]);
commentParameters = new String[2];
commentParameters[0] = lineTemp[0].toUpperCase();
commentParameters[1] = lineTemp[2];
comment = new Message("{0} defined as {1}.",
commentParameters).toString();
compileDebugger.setComment(comment);
} else {
comment = new Message("Invalid DEF " +
"operation.").toString();
throw new TTK91CompileException(comment);
}
}
}
}
return compileDebugger.lineCompiled();
}
/** This method initializes the code and data area arrays for the
second round processing according to the dataAreaSize and
commandLineCount variables. It also resets the StringTokenizer
by calling tokenize(). Before entering the second round we
must clear all the empty lines like compiler-codes
(pseudo-codes) and lines with nothing but comments.
*/
private CompileInfo initializeSecondRound() {
nextLine = 0;
firstRound = false;
// copy the code.
String[] newCode = new String[code.size()];
for (int i= 0; i < newCode.length; ++i)
newCode[i] = (String)code.get(i);
String[] lineTemp;
int dataAreaSize = 0;
// calculate the size of data-area
for (int i = 0; i < symbolTable.size(); ++i) {
lineTemp = (String[])symbolTable.get(i);
if (lineTemp[1].trim().length() >= 2) {
if (lineTemp[1].substring(0,2).equalsIgnoreCase("ds")) {
dataAreaSize += Integer.parseInt(lineTemp[1].substring(3));
} else {
if (lineTemp[1].substring(0,2).equalsIgnoreCase("dc"))
++dataAreaSize;
}
}
}
/* OLLI: POISTETTU M��RITYKSET 26.4.04; ei DEF-m��rityksi� dataan!
if (!defStdin.equals("")) ++dataAreaSize;
if (!defStdout.equals("")) ++dataAreaSize;
*/
data = new String[dataAreaSize];
String[] newSymbolTableLine = new String[2];
newSymbolTableLine[0] = "";
newSymbolTableLine[1] = "";
int nextPosition = 0;
int nextMemorySlot = newCode.length;
int dsValue = 0;
// update variable values to symbolTable
for (int i = 0; i < symbolTable.size(); ++i) {
lineTemp = (String[])symbolTable.get(i);
if (lineTemp[1].trim().length() >= 2) {
if (lineTemp[1].substring(0,2).equalsIgnoreCase("ds")) {
dsValue = Integer.parseInt(lineTemp[1].substring(3));
newSymbolTableLine[0] = lineTemp[0];
newSymbolTableLine[1] = "" + nextMemorySlot;
symbolTable.set(i, newSymbolTableLine.clone());
++nextMemorySlot;
for (int j = 0; j < dsValue; ++j) {
data[j + nextPosition] = "" + 0;
}
nextPosition += dsValue;
} else {
if (lineTemp[1].substring(0,2).equalsIgnoreCase("dc")) {
if (lineTemp[1].trim().length() > 2) {
data[nextPosition] = lineTemp[1].substring(3);
} else { data[nextPosition] = "" + 0; }
newSymbolTableLine[0] = lineTemp[0];
newSymbolTableLine[1] = "" + nextMemorySlot;
symbolTable.set(i, newSymbolTableLine.clone());
++nextMemorySlot;
++nextPosition;
}
}
}
}
/* OLLI: POISTETTU M��RITYKSET 26.4.04; ei DEF-m��rityksi� dataan!
if (!defStdin.equals("")) {
data[nextPosition] = "STDIN " + defStdin;
++nextPosition;
}
if (!defStdout.equals("")) {
data[nextPosition] = "STDOUT " + defStdout;
}
*/
// make new SymbolTable
String[][] newSymbolTable = new String[symbolTable.size()][2];
for (int i = 0; i < newSymbolTable.length; ++i) {
newSymbolTable[i] = (String[])symbolTable.get(i);
}
// prepare for the second round.
codeMemoryLines = new MemoryLine[newCode.length];
compileDebugger.finalFirstPhase(newCode, data, newSymbolTable);
return compileDebugger.lineCompiled();
}
/** This function transforms any commands to binary and stores both
forms in the code array, or sets any initial data values in the
data array. It uses CompileConstants as its aid.
@param line The line of code to process.
@return A CompileInfo object describing what was done, or
null if the second round and thus the compilation has been
completed. */
private CompileInfo secondRoundProcess(String line)
throws TTK91CompileException {
/* Antti: 04.03.04
Do a pure binary translation first, then when all sections are
complete, convert the binary to an integer. Needs variables for
opcode(8bit), first operand(3 bit)(r0 to r7), m-part(memory format,
direct, indirect or from code), possible index register (3 bit) and 16
bits for the address. Once STORE is converted to a 00000001 and the
rest of the code processed we get 32bit binary that is the opcode from
symbolic opcode.
Antti 08.03.04 Teemu said that we should support the machine
spec instead of Koksi with this one. No need to support opcodes like
Muumuu LOAD R1, 100 kissa etc. Only tabs and extra spacing. So we need
to support opcodes like LOAD R1, 100 but not codes like LOAD R1, =R2.
Basic functionality: (Trim between each phase.) Check if there is a
label (8 first are the meaningful ones also must have one
non-number)) Convert opcode (8bit) check which register (0 to
7) =, Rj/addr or @ (00, 01 or 10) if addr(Ri) or Rj(Ri)(0 to
7) convert address (16bit) check if the rest is fine (empty or
starts with ;)
Store both formats to a data array (symbolic and binary).
*/
// check if variable is set!
int addressAsInt = 0;
int lineAsBinary;
String comment;
String[] symbolTableEntry;
String[] lineTemp = parseLine(line);
if (!lineTemp[4].equals("")) {
try {
addressAsInt = Integer.parseInt(lineTemp[4]);
} catch (NumberFormatException e) {
Object tempObject = symbolTable.get((((Integer)symbols.get(lineTemp[4]))).intValue());
symbolTableEntry = (String[])tempObject;
if (symbolTableEntry[1].equals("")) {
String missing = lineTemp[4];
//OLLI: Kommentti lis�tty 26.4.
comment = new Message("Missing referred label {0}", missing).toString();
throw new TTK91CompileException(comment);
}
addressAsInt = Integer.parseInt((String)symbolTableEntry[1]);
}
}
lineAsBinary = symbolicInterpreter.stringToBinary(lineTemp[1],
lineTemp[2],
lineTemp[3],
addressAsInt + "",
lineTemp[5]);
compileDebugger.setBinary(lineAsBinary);
codeMemoryLines[nextLine] = new MemoryLine(lineAsBinary, line);
// comment
String lineAsZerosAndOnes = symbolicInterpreter.intToBinary(lineAsBinary, 32);
String binaryByPositions =
symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(0, 8),
true) + ":" +
symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(8, 11),
false) + ":" +
symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(11, 13),
false) + ":" +
symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(13, 16),
false) + ":" +
symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(16),
true);
String[] commentParameters = {line, "" + lineAsBinary, binaryByPositions};
comment = new Message("{0} --> {1} ({2}) ", commentParameters).toString();
compileDebugger.setComment(comment);
return compileDebugger.lineCompiled();
}
/** This method parses a String and tries to find a label, opCode
and all the other parts of a Command line.
@param symbolicOpCode Symbolic form of an operation code. */
public String[] parseLine(String symbolicOpcode) {
String label = "";
String opcode = "";
String firstRegister = "";
String addressingMode = "";
String secondRegister = "";
String address = "";
String[] parsedLine;
String wordTemp = "";
int nextToCheck = 0; // for looping out the spacing
int fieldEnd = 0; // searches the end of a field (' ', ',')
boolean spaceBetweenMemorymodeAndAddress = false;
fieldEnd = symbolicOpcode.indexOf(";");
if (fieldEnd != -1) { symbolicOpcode = symbolicOpcode.substring(0, fieldEnd); }
symbolicOpcode = symbolicOpcode.replace('\t',' ');
symbolicOpcode = symbolicOpcode.replace('�', ' '); // Not stupid!
symbolicOpcode = symbolicOpcode.toLowerCase();
symbolicOpcode = symbolicOpcode.trim();
if (symbolicOpcode.length() == 0) {
parsedLine = new String[6];
for (int i = 0; i < parsedLine.length; ++i) parsedLine[i] = "";
return parsedLine;
}
String[] lineAsArray = symbolicOpcode.split("[ \t,]+");
int lineAsArrayIndex = 0;
/* label */
wordTemp = lineAsArray[lineAsArrayIndex];
if (symbolicInterpreter.getOpcode(wordTemp) == -1) {
if(!validLabelName(wordTemp))
return null;
label = wordTemp;
++lineAsArrayIndex;
}
/* opcode */
if (lineAsArrayIndex < lineAsArray.length) {
opcode = lineAsArray[lineAsArrayIndex];
++lineAsArrayIndex;
if (symbolicInterpreter.getOpcode(opcode) < 0) { return null; }
} else { return null; }
/*first register*/
if (lineAsArrayIndex < lineAsArray.length) {
// first register might end with a ','. Not when push Sp etc.
if (lineAsArray[lineAsArrayIndex].charAt(
lineAsArray[lineAsArrayIndex].length() -1) == ',') {
if (symbolicInterpreter.getRegisterId(
lineAsArray[lineAsArrayIndex].substring(0,
lineAsArray[lineAsArrayIndex].length() - 1)
) != -1) {
firstRegister = lineAsArray[lineAsArrayIndex].substring(0,
lineAsArray[lineAsArrayIndex].length() -1);
++lineAsArrayIndex;
}
} else {
if (symbolicInterpreter.getRegisterId(
lineAsArray[lineAsArrayIndex]) != -1) {
firstRegister = lineAsArray[lineAsArrayIndex];
++lineAsArrayIndex;
}
}
}
/* addressingMode */
if (lineAsArrayIndex < lineAsArray.length) {
if (lineAsArray[lineAsArrayIndex].charAt(0) == '=' ||
lineAsArray[lineAsArrayIndex].charAt(0) == '@') {
addressingMode = "" + lineAsArray[lineAsArrayIndex].charAt(0);
if (lineAsArray[lineAsArrayIndex].length() == 1) {
spaceBetweenMemorymodeAndAddress = true;
++lineAsArrayIndex;
}
} else { addressingMode = ""; }
}
/*address and second register*/
if (lineAsArrayIndex < lineAsArray.length) {
if (lineAsArray[lineAsArrayIndex].indexOf("(") != -1) {
if (lineAsArray[lineAsArrayIndex].indexOf(")") <
lineAsArray[lineAsArrayIndex].indexOf("(")) {
return null;
} else {
if (spaceBetweenMemorymodeAndAddress) {
address = lineAsArray[lineAsArrayIndex].substring(
0, lineAsArray[lineAsArrayIndex].indexOf("(")
);
} else {
address = lineAsArray[lineAsArrayIndex].substring(
addressingMode.length(),
lineAsArray[lineAsArrayIndex].indexOf("(")
);
}
secondRegister = lineAsArray[lineAsArrayIndex].substring(
lineAsArray[lineAsArrayIndex].indexOf("(") + 1,
lineAsArray[lineAsArrayIndex].indexOf(")")
);
if (symbolicInterpreter.getRegisterId(secondRegister) == -1) {
return null;
}
}
} else {
if (spaceBetweenMemorymodeAndAddress) {
address = lineAsArray[lineAsArrayIndex];
} else {
address = lineAsArray[lineAsArrayIndex].substring(addressingMode.length());
}
}
++lineAsArrayIndex;
}
if (symbolicInterpreter.getRegisterId(address) != -1) {
secondRegister = address;
address = "";
}
if (lineAsArrayIndex < lineAsArray.length) { return null; }
if (opcode.length() > 0) {
if (opcode.charAt(0) == 'j' || opcode.charAt(0) == 'J') {
// Opcode matches jneg/jzer/jpos or the negations
// jnneg/jnzer/jnpos.
if(opcode.toLowerCase().matches("j" + "n?" +
"((neg)|(zer)|(pos))")) {
if (firstRegister.equals("")) return null;
}
if (addressingMode.equals("=") || address.equals("")) return null;
} else {
if (opcode.equalsIgnoreCase("nop")) {
// (do nothing)
} else {
if (opcode.equalsIgnoreCase("pop")) {
if (addressingMode.equals("@") ||
addressingMode.equals("=") || !address.equals(""))
return null;
} else {
if (opcode.equalsIgnoreCase("pushr") ||
opcode.equalsIgnoreCase("popr")) {
if (firstRegister.equals("")) return null;
} else {
if (firstRegister.equals("") ||
(address.equals("") && secondRegister.equals("")))
return null;
}
}
}
}
}
if (addressingMode.equals("=") && address.equals(""))
return null;
if (opcode.equalsIgnoreCase("store") && address.equals(""))
return null;
if (opcode.equalsIgnoreCase("store") && addressingMode.equals("="))
return null;
if (opcode.equals("") && (!label.equals("") ||
!firstRegister.equals("") ||
!addressingMode.equals("") ||
!address.equals("") ||
!secondRegister.equals(""))) {
return null;
}
parsedLine = new String[6];
parsedLine[0] = label.trim();
parsedLine[1] = opcode.trim();
parsedLine[2] = firstRegister.trim();
parsedLine[3] = addressingMode.trim();
parsedLine[4] = address.trim();
parsedLine[5] = secondRegister.trim();
return parsedLine;
}
/** This function tries to find a compiler command from the
line. Works much like parseLine but this time valid opcodes
are DEF, EQU, DC and DS.
@param line String representing one line from source code.
@return String array with label in position 0, command in the
position 1 and position 2 contains the parameter.
*/
public String[] parseCompilerCommandLine(String line) {
int fieldEnd = 0;
int nextToCheck = 0;
String label = "";
String opcode = "";
String value = "";
int intValue;
String[] parsedLine;
/* preprosessing */
line = line.toLowerCase();
line = line.replace('\t',' ');
fieldEnd = line.indexOf(";");
if (fieldEnd != -1) { line = line.substring(0, fieldEnd); }
//OLLI: 26.4., trim viimeiseksi preprocessingissa, k��nn�s menee nyt l�pi
line = line.trim();
/* LABEL opcode value */
fieldEnd = line.indexOf(" ");
if (fieldEnd == -1) {
label = line.substring(nextToCheck);
fieldEnd = line.length();
} else {
label = line.substring(nextToCheck, fieldEnd);
}
nextToCheck = fieldEnd + 1;
/* label OPCODE value */
if (nextToCheck < line.length()) {
while (line.charAt(nextToCheck) == ' ') { ++nextToCheck; }
fieldEnd = line.indexOf(' ', nextToCheck);
if (fieldEnd == -1) {
opcode = line.substring(nextToCheck);
fieldEnd = line.length();
} else {
opcode = line.substring(nextToCheck, fieldEnd);
}
if (!opcode.matches("((dc)|(ds)|(equ)|(def))")) {
return null;
}
nextToCheck = fieldEnd;
}
/* label opcode VALUE */
if (nextToCheck < line.length()) {
while (line.charAt(nextToCheck) == ' ') { ++nextToCheck; }
value = line.substring(nextToCheck);
if (opcode.equals("def")) {
if (value.length() < 1) return null;
} else {
if (value.length() > 0) {
try {
intValue = Integer.parseInt(value);
if (opcode.equalsIgnoreCase("ds") && intValue < 1) {
return null;
}
} catch (NumberFormatException e) { return null; }
}
}
} //OLLI: lis�ttiin ELSE 26.4., jotta rivit 'KISSA DC ' eiv�t mene l�pi
else { return null; }
if (!opcode.equalsIgnoreCase("dc") && value.equals("")) return null;
parsedLine = new String[3];
parsedLine[0] = label;
parsedLine[1] = opcode;
parsedLine[2] = value;
return parsedLine;
}
/** This method tests whether a label name contains at least one
non-number and consists of 0-9, A-� and _.
It does not check whether the label is in use already or if it
is a reserved word.
@param labelName The label name to test.
@return True if the label consists of valid characters, false
otherwise. */
private boolean validLabelName(String labelName) {
// It must have one non-number. Valid characters are A-�, 0-9 and _.
// Test 1: the word contains one or more of the following:
// a-z, A-Z, _, 0-9, ���, ���, in any order.
// Test 2: the word also contains one non-number (class \D
// means anything but 0-9) surrounded by any number of
// any character. All these 'anything buts' and 'anys' are
// also valid characters, since we check that in Test 1.
if(labelName.matches("[������\\w]+") &&
labelName.matches(".*\\D.*")) {
return true;
}
return false;
}
}
| true | true | private CompileInfo firstRoundProcess(String line)
throws TTK91CompileException {
String[] lineTemp = parseCompilerCommandLine(line);
boolean nothingFound = true;
String comment = "";
String[] commentParameters;
int intValue = 0;
String[] symbolTableEntry = new String[2];
boolean labelFound = false;
boolean variableUsed = false;
if (lineTemp == null) {
lineTemp = parseLine(line);
if (lineTemp == null) {
// not a valid command
comment = new Message("Invalid command.").toString();
throw new TTK91CompileException(comment);
} else {
if (lineTemp[1].equals("")) {
// line empty;
} else {
code.add(line);
if (!lineTemp[0].equals("")) {
nothingFound = false;
labelFound = true;
// label found
if (invalidLabels.containsKey(lineTemp[0])) {
// not a valid label
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
} else {
invalidLabels.put(lineTemp[0], null);
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = "" +
(code.size() - 1);
/* MUUTETTU 23.04. (OLLI)
*/
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone());
} else {
symbols.put(lineTemp[0],
new Integer(code.size() - 1));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = "" +
(code.size() - 1);
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundLabel(lineTemp[0],
code.size() -1);
}
}
try {
if (!lineTemp[4].equals(""))
Integer.parseInt(lineTemp[4]);
} catch(NumberFormatException e) {
// variable used
if (symbolicInterpreter.getRegisterId(lineTemp[4]) == -1) {
nothingFound = false;
variableUsed = true;
compileDebugger.foundSymbol(lineTemp[4]);
if (!symbols.containsKey(lineTemp[4])) {
if (invalidLabels.get(lineTemp[4]) == null) {
symbols.put(lineTemp[4], new
Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[4];
symbolTableEntry[1] = "";
symbolTable.add(symbolTableEntry.clone());
} else {
// predefined word (halt etc) was used
symbols.put(lineTemp[4],
new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[4];
symbolTableEntry[1] = "" +
(Integer) invalidLabels.get(lineTemp[4]);
symbolTable.add(symbolTableEntry.clone());
}
}
}
}
if (variableUsed && labelFound) {
commentParameters = new String[2];
commentParameters[0] = lineTemp[0];
commentParameters[1] = lineTemp[4];
comment = new Message("Found label {0} and variable " +
"{1}.",
commentParameters).toString();
compileDebugger.setComment(comment);
} else {
if (variableUsed) {
comment = new Message("Variable {0} used.",
lineTemp[4]).toString();
compileDebugger.setComment(comment);
} else {
if (labelFound) {
comment = new Message("Label {0} found.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
}
}
}
}
} else {
// compiler command
boolean allCharsValid = true;
boolean atLeastOneNonNumber = false;
if (invalidLabels.containsKey(lineTemp[0])) {
// not a valid label
if (!(lineTemp[1].equalsIgnoreCase("def") &&
(lineTemp[0].equalsIgnoreCase("stdin") ||
lineTemp[0].equalsIgnoreCase("stdout"))
)) {
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
}
}
if(!validLabelName(lineTemp[0])) {
// not a valid label;
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
} else {
if (lineTemp[1].equalsIgnoreCase("ds")) {
intValue = 0;
try {
intValue = Integer.parseInt(lineTemp[2]);
} catch(NumberFormatException e) {
comment = new Message("Invalid size for a " +
"DS.").toString();
throw new TTK91CompileException(comment);
}
if (intValue < 0 || intValue > MAXINT) {
comment = new Message("Invalid size for a " +
"DS.").toString();
throw new TTK91CompileException(comment);
}
}
if (lineTemp[1].equalsIgnoreCase("dc")) {
intValue = 0;
if (lineTemp[2].trim().length() > 0) {
try {
intValue = Integer.parseInt(lineTemp[2]);
} catch(NumberFormatException e) {
comment = new Message("Invalid value for a " +
"DC.").toString();
throw new TTK91CompileException(comment);
}
if (intValue < MININT || intValue > MAXINT) {
comment = new Message("Invalid value for a " +
"DC.").toString();
throw new TTK91CompileException(comment);
}
}
}
if (lineTemp[1].equalsIgnoreCase("equ")) {
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[2];
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone());
} else {
symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[2];
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundEQU(lineTemp[0], intValue);
commentParameters = new String[2];
commentParameters[0] = lineTemp[0];
commentParameters[1] = lineTemp[2];
comment = new Message("Variable {0} defined as {1}.",
commentParameters).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equals("ds")) {
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone()
);
} else {
symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundDS(lineTemp[0]);
comment = new Message("Found variable {0}.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equals("dc")) {
compileDebugger.foundDC(lineTemp[0]);
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone());
} else {
symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundDC(lineTemp[0]);
comment = new Message("Found variable {0}.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equalsIgnoreCase("def")) {
if (lineTemp[0].equals("stdin") ||
lineTemp[0].equals("stdout")) {
if (lineTemp[0].equals("stdin")) {
defStdin = lineTemp[2];
} else {
defStdout = lineTemp[2];
}
compileDebugger.foundDEF(lineTemp[0], lineTemp[2]);
commentParameters = new String[2];
commentParameters[0] = lineTemp[0].toUpperCase();
commentParameters[1] = lineTemp[2];
comment = new Message("{0} defined as {1}.",
commentParameters).toString();
compileDebugger.setComment(comment);
} else {
comment = new Message("Invalid DEF " +
"operation.").toString();
throw new TTK91CompileException(comment);
}
}
}
}
return compileDebugger.lineCompiled();
}
| private CompileInfo firstRoundProcess(String line)
throws TTK91CompileException {
String[] lineTemp = parseCompilerCommandLine(line);
boolean nothingFound = true;
String comment = "";
String[] commentParameters;
int intValue = 0;
String[] symbolTableEntry = new String[2];
boolean labelFound = false;
boolean variableUsed = false;
if (lineTemp == null) {
lineTemp = parseLine(line);
if (lineTemp == null) {
// not a valid command
comment = new Message("Invalid command.").toString();
throw new TTK91CompileException(comment);
} else {
if (lineTemp[1].equals("")) {
// line empty;
} else {
code.add(line);
if (!lineTemp[0].equals("")) {
nothingFound = false;
labelFound = true;
// label found
if (invalidLabels.containsKey(lineTemp[0])) {
// not a valid label
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
} else {
invalidLabels.put(lineTemp[0], null);
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = "" +
(code.size() - 1);
/* MUUTETTU 23.04. (OLLI)
*/
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone());
} else {
symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = "" +
(code.size() - 1);
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundLabel(lineTemp[0],
code.size() -1);
}
}
try {
if (!lineTemp[4].equals(""))
Integer.parseInt(lineTemp[4]);
} catch(NumberFormatException e) {
// variable used
if (symbolicInterpreter.getRegisterId(lineTemp[4]) == -1) {
nothingFound = false;
variableUsed = true;
compileDebugger.foundSymbol(lineTemp[4]);
if (!symbols.containsKey(lineTemp[4])) {
if (invalidLabels.get(lineTemp[4]) == null) {
symbols.put(lineTemp[4], new
Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[4];
symbolTableEntry[1] = "";
symbolTable.add(symbolTableEntry.clone());
} else {
// predefined word (halt etc) was used
symbols.put(lineTemp[4],
new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[4];
symbolTableEntry[1] = "" +
(Integer) invalidLabels.get(lineTemp[4]);
symbolTable.add(symbolTableEntry.clone());
}
}
}
}
if (variableUsed && labelFound) {
commentParameters = new String[2];
commentParameters[0] = lineTemp[0];
commentParameters[1] = lineTemp[4];
comment = new Message("Found label {0} and variable " +
"{1}.",
commentParameters).toString();
compileDebugger.setComment(comment);
} else {
if (variableUsed) {
comment = new Message("Variable {0} used.",
lineTemp[4]).toString();
compileDebugger.setComment(comment);
} else {
if (labelFound) {
comment = new Message("Label {0} found.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
}
}
}
}
} else {
// compiler command
boolean allCharsValid = true;
boolean atLeastOneNonNumber = false;
if (invalidLabels.containsKey(lineTemp[0])) {
// not a valid label
if (!(lineTemp[1].equalsIgnoreCase("def") &&
(lineTemp[0].equalsIgnoreCase("stdin") ||
lineTemp[0].equalsIgnoreCase("stdout"))
)) {
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
}
}
if(!validLabelName(lineTemp[0])) {
// not a valid label;
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
} else {
if (lineTemp[1].equalsIgnoreCase("ds")) {
intValue = 0;
try {
intValue = Integer.parseInt(lineTemp[2]);
} catch(NumberFormatException e) {
comment = new Message("Invalid size for a " +
"DS.").toString();
throw new TTK91CompileException(comment);
}
if (intValue < 0 || intValue > MAXINT) {
comment = new Message("Invalid size for a " +
"DS.").toString();
throw new TTK91CompileException(comment);
}
}
if (lineTemp[1].equalsIgnoreCase("dc")) {
intValue = 0;
if (lineTemp[2].trim().length() > 0) {
try {
intValue = Integer.parseInt(lineTemp[2]);
} catch(NumberFormatException e) {
comment = new Message("Invalid value for a " +
"DC.").toString();
throw new TTK91CompileException(comment);
}
if (intValue < MININT || intValue > MAXINT) {
comment = new Message("Invalid value for a " +
"DC.").toString();
throw new TTK91CompileException(comment);
}
}
}
if (lineTemp[1].equalsIgnoreCase("equ")) {
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[2];
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone());
} else {
symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[2];
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundEQU(lineTemp[0], intValue);
commentParameters = new String[2];
commentParameters[0] = lineTemp[0];
commentParameters[1] = lineTemp[2];
comment = new Message("Variable {0} defined as {1}.",
commentParameters).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equals("ds")) {
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone()
);
} else {
symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundDS(lineTemp[0]);
comment = new Message("Found variable {0}.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equals("dc")) {
compileDebugger.foundDC(lineTemp[0]);
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.set(((Integer)symbols.get(lineTemp[0])).intValue(),
symbolTableEntry.clone());
} else {
symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.add(symbolTableEntry.clone());
}
compileDebugger.foundDC(lineTemp[0]);
comment = new Message("Found variable {0}.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equalsIgnoreCase("def")) {
if (lineTemp[0].equals("stdin") ||
lineTemp[0].equals("stdout")) {
if (lineTemp[0].equals("stdin")) {
defStdin = lineTemp[2];
} else {
defStdout = lineTemp[2];
}
compileDebugger.foundDEF(lineTemp[0], lineTemp[2]);
commentParameters = new String[2];
commentParameters[0] = lineTemp[0].toUpperCase();
commentParameters[1] = lineTemp[2];
comment = new Message("{0} defined as {1}.",
commentParameters).toString();
compileDebugger.setComment(comment);
} else {
comment = new Message("Invalid DEF " +
"operation.").toString();
throw new TTK91CompileException(comment);
}
}
}
}
return compileDebugger.lineCompiled();
}
|
diff --git a/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/EntitiesVerifier.java b/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/EntitiesVerifier.java
index 173af61..4fd777f 100644
--- a/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/EntitiesVerifier.java
+++ b/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/EntitiesVerifier.java
@@ -1,192 +1,192 @@
package org.apache.maven.doxia.siterenderer;
/*
* 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 com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlHeading2;
import com.gargoylesoftware.htmlunit.html.HtmlHeading3;
import com.gargoylesoftware.htmlunit.html.HtmlHeading4;
import com.gargoylesoftware.htmlunit.html.HtmlMeta;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlParagraph;
import com.gargoylesoftware.htmlunit.html.HtmlPreformattedText;
import java.util.Iterator;
/**
* Verify the <code>site/xdoc/entityTest.xml</code>
*
* @author ltheussl
* @version $Id$
*/
public class EntitiesVerifier
extends AbstractVerifier
{
/** {@inheritDoc} */
public void verify( String file )
throws Exception
{
HtmlPage page = htmlPage( file );
assertNotNull( page );
HtmlMeta author = (HtmlMeta) page.getElementsByName( "author" ).get( 0 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Ligature Æ" ) > 0 );
assertEquals( "Ligature \u00C6", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 1 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Ampersand &" ) > 0 );
assertEquals( "Ampersand &", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 2 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Less than <" ) > 0 );
assertEquals( "Less than <", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 3 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Greater than >" ) > 0 );
assertEquals( "Greater than >", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 4 );
assertNotNull( author );
assertTrue( author.getContentAttribute().equals( "Apostrophe '" ) );
assertEquals( "Apostrophe '", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 5 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Quote "" ) > 0 );
assertEquals( "Quote \"", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 6 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "[email protected]" ) > 0 );
assertEquals( "[email protected]", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 7 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "test©email.com" ) > 0 );
- assertEquals( "test�email.com", author.getContentAttribute() );
+ assertEquals( "test\u00A9email.com", author.getContentAttribute() );
HtmlElement element = page.getHtmlElementById( "contentBox" );
assertNotNull( element );
HtmlDivision division = (HtmlDivision) element;
assertNotNull( division );
Iterator<HtmlElement> elementIterator = division.getAllHtmlChildElements().iterator();
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
HtmlDivision div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
HtmlHeading2 h2 = (HtmlHeading2) elementIterator.next();
assertNotNull( h2 );
assertEquals( h2.asText().trim(), "section name with entities: '&' '\u0391' ' ' '\uD7ED'" );
HtmlAnchor a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
assertEquals( a.getAttribute( "name" ), "section_name_with_entities:____" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
HtmlHeading4 h4 = (HtmlHeading4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "Entities" );
a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
assertEquals( a.getAttribute( "name" ), "Entities" );
div = (HtmlDivision) elementIterator.next();
HtmlHeading3 h3 = (HtmlHeading3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "Generic Entities: '&' '<' '>' '\"' '''" );
a = (HtmlAnchor) elementIterator.next();
HtmlParagraph p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "'&' '<' '>' '\"' '''" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeading3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "Local Entities: '\u0391' '\u0392' '\u0393' '\uD7ED'" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "'\u0391' '\u0392' '\u0393' '\uD7ED\uD7ED' '\u0159\u0159' '\u0159'" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeading3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "DTD Entities: ' ' '\u00A1' '\u00A2'" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '\u00A1' '\u00A2'" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
h4 = (HtmlHeading4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "CDATA" );
a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
assertEquals( a.getAttribute( "name" ), "CDATA" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "source" );
HtmlPreformattedText pre = (HtmlPreformattedText) elementIterator.next();
assertNotNull( pre );
assertEquals( pre.asText().trim(), "<project xmlns:ant=\"jelly:ant\">" );
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '¡'" );
assertFalse( elementIterator.hasNext() );
}
}
| true | true | public void verify( String file )
throws Exception
{
HtmlPage page = htmlPage( file );
assertNotNull( page );
HtmlMeta author = (HtmlMeta) page.getElementsByName( "author" ).get( 0 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Ligature Æ" ) > 0 );
assertEquals( "Ligature \u00C6", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 1 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Ampersand &" ) > 0 );
assertEquals( "Ampersand &", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 2 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Less than <" ) > 0 );
assertEquals( "Less than <", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 3 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Greater than >" ) > 0 );
assertEquals( "Greater than >", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 4 );
assertNotNull( author );
assertTrue( author.getContentAttribute().equals( "Apostrophe '" ) );
assertEquals( "Apostrophe '", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 5 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Quote "" ) > 0 );
assertEquals( "Quote \"", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 6 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "[email protected]" ) > 0 );
assertEquals( "[email protected]", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 7 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "test©email.com" ) > 0 );
assertEquals( "test�email.com", author.getContentAttribute() );
HtmlElement element = page.getHtmlElementById( "contentBox" );
assertNotNull( element );
HtmlDivision division = (HtmlDivision) element;
assertNotNull( division );
Iterator<HtmlElement> elementIterator = division.getAllHtmlChildElements().iterator();
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
HtmlDivision div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
HtmlHeading2 h2 = (HtmlHeading2) elementIterator.next();
assertNotNull( h2 );
assertEquals( h2.asText().trim(), "section name with entities: '&' '\u0391' ' ' '\uD7ED'" );
HtmlAnchor a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
assertEquals( a.getAttribute( "name" ), "section_name_with_entities:____" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
HtmlHeading4 h4 = (HtmlHeading4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "Entities" );
a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
assertEquals( a.getAttribute( "name" ), "Entities" );
div = (HtmlDivision) elementIterator.next();
HtmlHeading3 h3 = (HtmlHeading3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "Generic Entities: '&' '<' '>' '\"' '''" );
a = (HtmlAnchor) elementIterator.next();
HtmlParagraph p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "'&' '<' '>' '\"' '''" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeading3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "Local Entities: '\u0391' '\u0392' '\u0393' '\uD7ED'" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "'\u0391' '\u0392' '\u0393' '\uD7ED\uD7ED' '\u0159\u0159' '\u0159'" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeading3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "DTD Entities: ' ' '\u00A1' '\u00A2'" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '\u00A1' '\u00A2'" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
h4 = (HtmlHeading4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "CDATA" );
a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
assertEquals( a.getAttribute( "name" ), "CDATA" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "source" );
HtmlPreformattedText pre = (HtmlPreformattedText) elementIterator.next();
assertNotNull( pre );
assertEquals( pre.asText().trim(), "<project xmlns:ant=\"jelly:ant\">" );
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '¡'" );
assertFalse( elementIterator.hasNext() );
}
| public void verify( String file )
throws Exception
{
HtmlPage page = htmlPage( file );
assertNotNull( page );
HtmlMeta author = (HtmlMeta) page.getElementsByName( "author" ).get( 0 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Ligature Æ" ) > 0 );
assertEquals( "Ligature \u00C6", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 1 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Ampersand &" ) > 0 );
assertEquals( "Ampersand &", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 2 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Less than <" ) > 0 );
assertEquals( "Less than <", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 3 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Greater than >" ) > 0 );
assertEquals( "Greater than >", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 4 );
assertNotNull( author );
assertTrue( author.getContentAttribute().equals( "Apostrophe '" ) );
assertEquals( "Apostrophe '", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 5 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "Quote "" ) > 0 );
assertEquals( "Quote \"", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 6 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "[email protected]" ) > 0 );
assertEquals( "[email protected]", author.getContentAttribute() );
author = (HtmlMeta) page.getElementsByName( "author" ).get( 7 );
assertNotNull( author );
assertTrue( author.toString().indexOf( "test©email.com" ) > 0 );
assertEquals( "test\u00A9email.com", author.getContentAttribute() );
HtmlElement element = page.getHtmlElementById( "contentBox" );
assertNotNull( element );
HtmlDivision division = (HtmlDivision) element;
assertNotNull( division );
Iterator<HtmlElement> elementIterator = division.getAllHtmlChildElements().iterator();
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
HtmlDivision div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
HtmlHeading2 h2 = (HtmlHeading2) elementIterator.next();
assertNotNull( h2 );
assertEquals( h2.asText().trim(), "section name with entities: '&' '\u0391' ' ' '\uD7ED'" );
HtmlAnchor a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
assertEquals( a.getAttribute( "name" ), "section_name_with_entities:____" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
HtmlHeading4 h4 = (HtmlHeading4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "Entities" );
a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
assertEquals( a.getAttribute( "name" ), "Entities" );
div = (HtmlDivision) elementIterator.next();
HtmlHeading3 h3 = (HtmlHeading3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "Generic Entities: '&' '<' '>' '\"' '''" );
a = (HtmlAnchor) elementIterator.next();
HtmlParagraph p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "'&' '<' '>' '\"' '''" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeading3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "Local Entities: '\u0391' '\u0392' '\u0393' '\uD7ED'" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "'\u0391' '\u0392' '\u0393' '\uD7ED\uD7ED' '\u0159\u0159' '\u0159'" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeading3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "DTD Entities: ' ' '\u00A1' '\u00A2'" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '\u00A1' '\u00A2'" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "section" );
h4 = (HtmlHeading4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "CDATA" );
a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
assertEquals( a.getAttribute( "name" ), "CDATA" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttribute( "class" ), "source" );
HtmlPreformattedText pre = (HtmlPreformattedText) elementIterator.next();
assertNotNull( pre );
assertEquals( pre.asText().trim(), "<project xmlns:ant=\"jelly:ant\">" );
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '¡'" );
assertFalse( elementIterator.hasNext() );
}
|
diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java
index 9345a881bc..964b870823 100644
--- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java
+++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java
@@ -1,158 +1,158 @@
/*
* Copyright 2002-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.springframework.integration.endpoint;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.integration.Message;
import org.springframework.integration.MessagingException;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.config.SourcePollingChannelAdapterFactoryBean;
import org.springframework.integration.config.TestErrorHandler;
import org.springframework.integration.core.MessageHandler;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.scheduling.PollerMetadata;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.PeriodicTrigger;
/**
* @author Oleg Zhurakousky
*
*/
public class PollingLifecycleTests {
private ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
private TestErrorHandler errorHandler = new TestErrorHandler();
@Before
public void init() throws Exception {
taskScheduler.afterPropertiesSet();
}
@Test
public void ensurePollerTaskStops() throws Exception{
final CountDownLatch latch = new CountDownLatch(1);
QueueChannel channel = new QueueChannel();
channel.send(new GenericMessage<String>("foo"));
MessageHandler handler = Mockito.spy(new MessageHandler() {
public void handleMessage(Message<?> message) throws MessagingException {
latch.countDown();
}
});
PollingConsumer consumer = new PollingConsumer(channel, handler);
consumer.setTrigger(new PeriodicTrigger(0));
consumer.setErrorHandler(errorHandler);
consumer.setTaskScheduler(taskScheduler);
consumer.setBeanFactory(mock(BeanFactory.class));
consumer.afterPropertiesSet();
consumer.start();
assertTrue(latch.await(2, TimeUnit.SECONDS));
Mockito.verify(handler, times(1)).handleMessage(Mockito.any(Message.class));
consumer.stop();
for (int i = 0; i < 10; i++) {
channel.send(new GenericMessage<String>("foo"));
}
Thread.sleep(2000); // give enough time for poller to kick in if it didn't stop properly
// we'll still have a natural race condition between call to stop() and poller polling
// so what we really have to assert is that it doesn't poll for more then once after stop() was called
Mockito.reset(handler);
Mockito.verify(handler, atMost(1)).handleMessage(Mockito.any(Message.class));
}
@Test
public void ensurePollerTaskStopsForAdapter() throws Exception{
final CountDownLatch latch = new CountDownLatch(1);
QueueChannel channel = new QueueChannel();
SourcePollingChannelAdapterFactoryBean adapterFactory = new SourcePollingChannelAdapterFactoryBean();
PollerMetadata pollerMetadata = new PollerMetadata();
pollerMetadata.setTrigger(new PeriodicTrigger(2000));
adapterFactory.setPollerMetadata(pollerMetadata);
MessageSource<String> source = spy(new MessageSource<String>() {
public Message<String> receive() {
latch.countDown();
return new GenericMessage<String>("hello");
}
});
adapterFactory.setSource(source);
adapterFactory.setOutputChannel(channel);
adapterFactory.setBeanFactory(mock(ConfigurableBeanFactory.class));
SourcePollingChannelAdapter adapter = adapterFactory.getObject();
adapter.setTaskScheduler(taskScheduler);
adapter.afterPropertiesSet();
adapter.start();
assertTrue(latch.await(20, TimeUnit.SECONDS));
assertNotNull(channel.receive(100));
adapter.stop();
assertNull(channel.receive(1000));
Mockito.verify(source, times(1)).receive();
}
@Test
- public void ensurePollerTaskStopsForAdapterWithInteraptible() throws Exception{
+ public void ensurePollerTaskStopsForAdapterWithInterruptible() throws Exception{
final CountDownLatch latch = new CountDownLatch(2);
QueueChannel channel = new QueueChannel();
SourcePollingChannelAdapterFactoryBean adapterFactory = new SourcePollingChannelAdapterFactoryBean();
PollerMetadata pollerMetadata = new PollerMetadata();
pollerMetadata.setMaxMessagesPerPoll(-1);
pollerMetadata.setTrigger(new PeriodicTrigger(2000));
adapterFactory.setPollerMetadata(pollerMetadata);
final Runnable coughtInterrupted = mock(Runnable.class);
MessageSource<String> source = new MessageSource<String>() {
public Message<String> receive() {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
latch.countDown();
}
} catch (InterruptedException e) {
coughtInterrupted.run();
}
return new GenericMessage<String>("hello");
}
};
adapterFactory.setSource(source);
adapterFactory.setOutputChannel(channel);
adapterFactory.setBeanFactory(mock(ConfigurableBeanFactory.class));
SourcePollingChannelAdapter adapter = adapterFactory.getObject();
adapter.setTaskScheduler(taskScheduler);
adapter.afterPropertiesSet();
adapter.start();
assertTrue(latch.await(3000, TimeUnit.SECONDS));
//
adapter.stop();
Thread.sleep(1000);
Mockito.verify(coughtInterrupted, times(1)).run();
}
}
| true | true | public void ensurePollerTaskStopsForAdapterWithInteraptible() throws Exception{
final CountDownLatch latch = new CountDownLatch(2);
QueueChannel channel = new QueueChannel();
SourcePollingChannelAdapterFactoryBean adapterFactory = new SourcePollingChannelAdapterFactoryBean();
PollerMetadata pollerMetadata = new PollerMetadata();
pollerMetadata.setMaxMessagesPerPoll(-1);
pollerMetadata.setTrigger(new PeriodicTrigger(2000));
adapterFactory.setPollerMetadata(pollerMetadata);
final Runnable coughtInterrupted = mock(Runnable.class);
MessageSource<String> source = new MessageSource<String>() {
public Message<String> receive() {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
latch.countDown();
}
} catch (InterruptedException e) {
coughtInterrupted.run();
}
return new GenericMessage<String>("hello");
}
};
adapterFactory.setSource(source);
adapterFactory.setOutputChannel(channel);
adapterFactory.setBeanFactory(mock(ConfigurableBeanFactory.class));
SourcePollingChannelAdapter adapter = adapterFactory.getObject();
adapter.setTaskScheduler(taskScheduler);
adapter.afterPropertiesSet();
adapter.start();
assertTrue(latch.await(3000, TimeUnit.SECONDS));
//
adapter.stop();
Thread.sleep(1000);
Mockito.verify(coughtInterrupted, times(1)).run();
}
| public void ensurePollerTaskStopsForAdapterWithInterruptible() throws Exception{
final CountDownLatch latch = new CountDownLatch(2);
QueueChannel channel = new QueueChannel();
SourcePollingChannelAdapterFactoryBean adapterFactory = new SourcePollingChannelAdapterFactoryBean();
PollerMetadata pollerMetadata = new PollerMetadata();
pollerMetadata.setMaxMessagesPerPoll(-1);
pollerMetadata.setTrigger(new PeriodicTrigger(2000));
adapterFactory.setPollerMetadata(pollerMetadata);
final Runnable coughtInterrupted = mock(Runnable.class);
MessageSource<String> source = new MessageSource<String>() {
public Message<String> receive() {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
latch.countDown();
}
} catch (InterruptedException e) {
coughtInterrupted.run();
}
return new GenericMessage<String>("hello");
}
};
adapterFactory.setSource(source);
adapterFactory.setOutputChannel(channel);
adapterFactory.setBeanFactory(mock(ConfigurableBeanFactory.class));
SourcePollingChannelAdapter adapter = adapterFactory.getObject();
adapter.setTaskScheduler(taskScheduler);
adapter.afterPropertiesSet();
adapter.start();
assertTrue(latch.await(3000, TimeUnit.SECONDS));
//
adapter.stop();
Thread.sleep(1000);
Mockito.verify(coughtInterrupted, times(1)).run();
}
|
diff --git a/52n-wps-io-impl/src/main/java/org/n52/wps/io/datahandler/parser/GTBinZippedWKT64Parser.java b/52n-wps-io-impl/src/main/java/org/n52/wps/io/datahandler/parser/GTBinZippedWKT64Parser.java
index e678c96e..f00d06ba 100644
--- a/52n-wps-io-impl/src/main/java/org/n52/wps/io/datahandler/parser/GTBinZippedWKT64Parser.java
+++ b/52n-wps-io-impl/src/main/java/org/n52/wps/io/datahandler/parser/GTBinZippedWKT64Parser.java
@@ -1,185 +1,185 @@
/***************************************************************
Copyright � 2011 52�North Initiative for Geospatial Open Source Software GmbH
Author: Bastian Schaeffer; Matthias Mueller, TU Dresden
Contact: Andreas Wytzisk,
52�North Initiative for Geospatial Open Source SoftwareGmbH,
Martin-Luther-King-Weg 24,
48155 Muenster, Germany,
[email protected]
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; even without the implied WARRANTY OF
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program (see gnu-gpl v2.txt). If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA or visit the Free
Software Foundation�s web page, http://www.fsf.org.
***************************************************************/
package org.n52.wps.io.datahandler.parser;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureCollections;
import org.geotools.feature.NameImpl;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.WKTReader2;
import org.geotools.referencing.CRS;
import org.n52.wps.io.GTHelper;
import org.n52.wps.io.IOUtils;
import org.n52.wps.io.data.binding.complex.GTVectorDataBinding;
import org.opengis.feature.Feature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.Name;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
public class GTBinZippedWKT64Parser extends AbstractParser {
private static Logger LOGGER = Logger.getLogger(GTBinZippedWKT64Parser.class);
public GTBinZippedWKT64Parser() {
super();
supportedIDataTypes.add(GTVectorDataBinding.class);
}
/**
* @throws RuntimeException
* if an error occurs while writing the stream to disk or
* unzipping the written file
* @see org.n52.wps.io.IParser#parse(java.io.InputStream)
*/
@Override
public GTVectorDataBinding parse(InputStream stream, String mimeType, String schema) {
try {
String fileName = "tempfile" + UUID.randomUUID() + ".zip";
String tmpDirPath = System.getProperty("java.io.tmpdir");
File tempFile = new File(tmpDirPath + File.separatorChar + fileName);
finalizeFiles.add(tempFile); // mark tempFile for final delete
try {
FileOutputStream outputStream = new FileOutputStream(tempFile);
byte buf[] = new byte[4096];
int len;
while ((len = stream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
outputStream.close();
stream.close();
} catch (FileNotFoundException e) {
System.gc();
LOGGER.error(e);
throw new RuntimeException(e);
- } catch (IOException e1) {
+ } catch (IOException e) {
LOGGER.error(e);
System.gc();
- throw new RuntimeException(e1);
+ throw new RuntimeException(e);
}
finalizeFiles.add(tempFile); // mark for final delete
stream.close();
List<File> wktFiles = IOUtils.unzip(tempFile, "wkt");
finalizeFiles.addAll(wktFiles); // mark for final delete
if (wktFiles == null || wktFiles.size() == 0) {
throw new RuntimeException(
"Cannot find a shapefile inside the zipped file.");
}
//set namespace namespace
List<Geometry> geometries = new ArrayList<Geometry>();
//read wkt file
//please not that only 1 geometry is returned. If multiple geometries are included, perhaps use the read(String wktstring) method
for(int i = 0; i<wktFiles.size();i++){
File wktFile = wktFiles.get(i);
Reader fileReader = new FileReader(wktFile);
WKTReader2 wktReader = new WKTReader2();
com.vividsolutions.jts.geom.Geometry geometry = wktReader.read(fileReader);
geometries.add(geometry);
}
CoordinateReferenceSystem coordinateReferenceSystem = CRS.decode("EPSG:4326");
FeatureCollection inputFeatureCollection = createFeatureCollection(geometries, coordinateReferenceSystem);
return new GTVectorDataBinding(inputFeatureCollection);
} catch (IOException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
} catch (ParseException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
} catch (NoSuchAuthorityCodeException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
} catch (FactoryException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
}
}
private FeatureCollection createFeatureCollection(List<com.vividsolutions.jts.geom.Geometry> geometries, CoordinateReferenceSystem coordinateReferenceSystem){
FeatureCollection collection = FeatureCollections.newCollection();
SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
if(coordinateReferenceSystem==null){
try {
coordinateReferenceSystem = CRS.decode("EPSG:4326");
} catch (NoSuchAuthorityCodeException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while trying to decode CRS EPSG:4326", e);
} catch (FactoryException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while trying to decode CRS EPSG:432", e);
}
typeBuilder.setCRS(coordinateReferenceSystem);
}
String namespace = "http://www.opengis.net/gml";
typeBuilder.setNamespaceURI(namespace);
Name nameType = new NameImpl(namespace, "Feature");
typeBuilder.setName(nameType);
typeBuilder.add("GEOMETRY", geometries.get(0).getClass());
SimpleFeatureType featureType = typeBuilder.buildFeatureType();
for(int i = 0; i<geometries.size();i++){
Feature feature = GTHelper.createFeature(""+i, geometries.get(i), featureType, new ArrayList());
collection.add(feature);
}
return collection;
}
}
| false | true | public GTVectorDataBinding parse(InputStream stream, String mimeType, String schema) {
try {
String fileName = "tempfile" + UUID.randomUUID() + ".zip";
String tmpDirPath = System.getProperty("java.io.tmpdir");
File tempFile = new File(tmpDirPath + File.separatorChar + fileName);
finalizeFiles.add(tempFile); // mark tempFile for final delete
try {
FileOutputStream outputStream = new FileOutputStream(tempFile);
byte buf[] = new byte[4096];
int len;
while ((len = stream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
outputStream.close();
stream.close();
} catch (FileNotFoundException e) {
System.gc();
LOGGER.error(e);
throw new RuntimeException(e);
} catch (IOException e1) {
LOGGER.error(e);
System.gc();
throw new RuntimeException(e1);
}
finalizeFiles.add(tempFile); // mark for final delete
stream.close();
List<File> wktFiles = IOUtils.unzip(tempFile, "wkt");
finalizeFiles.addAll(wktFiles); // mark for final delete
if (wktFiles == null || wktFiles.size() == 0) {
throw new RuntimeException(
"Cannot find a shapefile inside the zipped file.");
}
//set namespace namespace
List<Geometry> geometries = new ArrayList<Geometry>();
//read wkt file
//please not that only 1 geometry is returned. If multiple geometries are included, perhaps use the read(String wktstring) method
for(int i = 0; i<wktFiles.size();i++){
File wktFile = wktFiles.get(i);
Reader fileReader = new FileReader(wktFile);
WKTReader2 wktReader = new WKTReader2();
com.vividsolutions.jts.geom.Geometry geometry = wktReader.read(fileReader);
geometries.add(geometry);
}
CoordinateReferenceSystem coordinateReferenceSystem = CRS.decode("EPSG:4326");
FeatureCollection inputFeatureCollection = createFeatureCollection(geometries, coordinateReferenceSystem);
return new GTVectorDataBinding(inputFeatureCollection);
} catch (IOException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
} catch (ParseException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
} catch (NoSuchAuthorityCodeException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
} catch (FactoryException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
}
}
| public GTVectorDataBinding parse(InputStream stream, String mimeType, String schema) {
try {
String fileName = "tempfile" + UUID.randomUUID() + ".zip";
String tmpDirPath = System.getProperty("java.io.tmpdir");
File tempFile = new File(tmpDirPath + File.separatorChar + fileName);
finalizeFiles.add(tempFile); // mark tempFile for final delete
try {
FileOutputStream outputStream = new FileOutputStream(tempFile);
byte buf[] = new byte[4096];
int len;
while ((len = stream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
outputStream.close();
stream.close();
} catch (FileNotFoundException e) {
System.gc();
LOGGER.error(e);
throw new RuntimeException(e);
} catch (IOException e) {
LOGGER.error(e);
System.gc();
throw new RuntimeException(e);
}
finalizeFiles.add(tempFile); // mark for final delete
stream.close();
List<File> wktFiles = IOUtils.unzip(tempFile, "wkt");
finalizeFiles.addAll(wktFiles); // mark for final delete
if (wktFiles == null || wktFiles.size() == 0) {
throw new RuntimeException(
"Cannot find a shapefile inside the zipped file.");
}
//set namespace namespace
List<Geometry> geometries = new ArrayList<Geometry>();
//read wkt file
//please not that only 1 geometry is returned. If multiple geometries are included, perhaps use the read(String wktstring) method
for(int i = 0; i<wktFiles.size();i++){
File wktFile = wktFiles.get(i);
Reader fileReader = new FileReader(wktFile);
WKTReader2 wktReader = new WKTReader2();
com.vividsolutions.jts.geom.Geometry geometry = wktReader.read(fileReader);
geometries.add(geometry);
}
CoordinateReferenceSystem coordinateReferenceSystem = CRS.decode("EPSG:4326");
FeatureCollection inputFeatureCollection = createFeatureCollection(geometries, coordinateReferenceSystem);
return new GTVectorDataBinding(inputFeatureCollection);
} catch (IOException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
} catch (ParseException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
} catch (NoSuchAuthorityCodeException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
} catch (FactoryException e) {
LOGGER.error(e);
throw new RuntimeException(
"An error has occurred while accessing provided data", e);
}
}
|
diff --git a/apps/seqos-test/src/test/java/org/seerc/seqos/dao/DummyObservationDAOImplTest.java b/apps/seqos-test/src/test/java/org/seerc/seqos/dao/DummyObservationDAOImplTest.java
index 9d2b445..6e445cb 100644
--- a/apps/seqos-test/src/test/java/org/seerc/seqos/dao/DummyObservationDAOImplTest.java
+++ b/apps/seqos-test/src/test/java/org/seerc/seqos/dao/DummyObservationDAOImplTest.java
@@ -1,18 +1,18 @@
package org.seerc.seqos.dao;
import static org.junit.Assert.*;
import junit.framework.Assert;
import org.junit.Test;
import org.seerc.seqos.to.ListObservationTO;
public class DummyObservationDAOImplTest {
@Test
public void testCreateObservations() {
ObservationDAO dao = new DummyObservationDAOImpl();
ListObservationTO status = dao.getObservations();
- Assert.assertEquals(10, status.getObservations().size());
+ Assert.assertEquals(2, status.getObservations().size());
}
}
| true | true | public void testCreateObservations() {
ObservationDAO dao = new DummyObservationDAOImpl();
ListObservationTO status = dao.getObservations();
Assert.assertEquals(10, status.getObservations().size());
}
| public void testCreateObservations() {
ObservationDAO dao = new DummyObservationDAOImpl();
ListObservationTO status = dao.getObservations();
Assert.assertEquals(2, status.getObservations().size());
}
|
diff --git a/src/org/iplant/pipeline/client/dnd/DragCreator.java b/src/org/iplant/pipeline/client/dnd/DragCreator.java
index 7847b82..8606977 100644
--- a/src/org/iplant/pipeline/client/dnd/DragCreator.java
+++ b/src/org/iplant/pipeline/client/dnd/DragCreator.java
@@ -1,216 +1,216 @@
/* * Copyright 2012 Oregon State University.
*
* 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.iplant.pipeline.client.dnd;
import org.iplant.pipeline.client.json.App;
import org.iplant.pipeline.client.json.IPCType;
import org.iplant.pipeline.client.json.Input;
import org.iplant.pipeline.client.json.Output;
import com.google.gwt.dom.client.Element;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.ui.Image;
public class DragCreator {
private static IPCType draggedRecord;
public static final int MOVE = 1;
public static final int COPY = 2;
public static final int DELETE = 3;
public static native void addDrag(Element element, IPCType rec, DragListener listener) /*-{
function handleDragStart(e) {
var dragIcon = [email protected]::getDragImage(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
e.dataTransfer.setDragImage(dragIcon, -10, -10);
- e.dataTransfer.effectAllowed = 'copy'; // only dropEffect='copy' will be dropable
+ e.dataTransfer.effectAllowed = 'copy';
@org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = rec;
[email protected]::dragStart(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
if (element.getAttribute("data-downloadurl") != null) {
e.dataTransfer.setData("DownloadURL", element.getAttribute("data-downloadurl"));
} else {
e.dataTransfer.setData('Text',[email protected]::getId()()); // required otherwise doesn't work
}
}
function handleDragOver(e) {
if (e.preventDefault)
e.preventDefault();
[email protected]::dragOver(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
//e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
//this.style.border="1px dashed #84B4EA";
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
[email protected]::dragEnter(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
return false;
}
function handleDragLeave(e) {
[email protected]::dragLeave(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
function handleDrop(e) {
// this / e.target is current target element.
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
if (e.preventDefault)
e.preventDefault();
var data = e.dataTransfer.getData('Text');
if (isNaN(data)) {
// //item is an json app from iplant
var obj = eval("(" + data + ")");
var app = @org.iplant.pipeline.client.dnd.DragCreator::createApp(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
@org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = app;
}
- [email protected]::drop(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
+ [email protected]::drop(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
function handleDragEnd(e) {
[email protected]::dragEnd(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
element.addEventListener('dragstart', handleDragStart, false);
element.addEventListener('dragenter', handleDragEnter, false);
element.addEventListener('dragover', handleDragOver, false);
element.addEventListener('dragleave', handleDragLeave, false);
element.addEventListener('drop', handleDrop, false);
element.addEventListener('dragend', handleDragEnd, false);
}-*/;
public static native void addDrop(Element element, IPCType rec, DropListener listener) /*-{
function handleDragOver(e) {
if (e.preventDefault)
e.preventDefault(); // allows us to drop
e.dataTransfer.dropEffect = 'copy';
[email protected]::dragOver(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
// return false;
}
function handleDragEnter(e) {
if (e.preventDefault)
e.preventDefault(); // allows us to drop
e.dataTransfer.dropEffect = 'copy';
// return false;
[email protected]::dragEnter(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
function handleDragLeave(e) {
[email protected]::dragLeave(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
function handleDrop(e) {
// this / e.target is current target element.
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
if (e.preventDefault)
e.preventDefault();
var data = e.dataTransfer.getData('Text');
if (isNaN(data)) {
// //item is an json app from iplant
var obj = eval("(" + data + ")");
var app = @org.iplant.pipeline.client.dnd.DragCreator::createApp(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
@org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = app;
}
[email protected]::drop(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
function addEvent(el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for ( var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
}
addEvent(element, 'dragenter', handleDragEnter);
addEvent(element, 'dragover', handleDragOver);
addEvent(element, 'dragleave', handleDragLeave);
addEvent(element, 'drop', handleDrop);
}-*/;
public static IPCType getDragSource() {
return draggedRecord;
}
private static App createApp(String name, String description, String id) {
App app = new App();
app.setName(name);
app.setDescription(description);
app.setId(1);
app.setID(id);
return app;
}
private static App createApp(com.google.gwt.core.client.JavaScriptObject json) {
return createApp(new JSONObject(json));
}
public static App createApp(JSONObject json) {
App app = new App();
app.setName(((JSONString) json.get("name")).stringValue());
app.setDescription(((JSONString) json.get("description")).stringValue());
app.setId(1);
app.setID(((JSONString) json.get("id")).stringValue());
JSONArray inputs = (JSONArray) json.get("inputs");
app.setInputJson(inputs);
for (int i = 0; i < inputs.size(); i++) {
Input input = new Input();
JSONObject obj = (JSONObject) inputs.get(i);
JSONObject dataObj = (JSONObject) obj.get("data_object");
if (dataObj != null) {
input.setName(((JSONString) dataObj.get("name")).stringValue());
input.setDescription(((JSONString) dataObj.get("description")).stringValue());
input.setId(1);
input.setRequired(((JSONBoolean) dataObj.get("required")).booleanValue());
input.setType("File:" + ((JSONString) dataObj.get("format")).stringValue());
input.setID(((JSONString) dataObj.get("id")).stringValue());
app.addInput(input);
}
}
JSONArray outputs = (JSONArray) json.get("outputs");
app.setOutputJson(outputs);
for (int i = 0; i < outputs.size(); i++) {
Output output = new Output();
JSONObject obj = (JSONObject) outputs.get(i);
JSONObject dataObj = (JSONObject) obj.get("data_object");
if (dataObj != null) {
output.setName(((JSONString) dataObj.get("name")).stringValue());
output.setDescription(((JSONString) dataObj.get("description")).stringValue());
output.setId(1);
output.setType(((JSONString) dataObj.get("format")).stringValue());
output.setID(((JSONString) dataObj.get("id")).stringValue());
app.addOutput(output);
}
}
return app;
}
public static Element getImageElement(String src) {
Image img = new Image(src);
img.setWidth("20px");
img.setHeight("20px");
return img.getElement();
}
}
| false | true | public static native void addDrag(Element element, IPCType rec, DragListener listener) /*-{
function handleDragStart(e) {
var dragIcon = [email protected]::getDragImage(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
e.dataTransfer.setDragImage(dragIcon, -10, -10);
e.dataTransfer.effectAllowed = 'copy'; // only dropEffect='copy' will be dropable
@org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = rec;
[email protected]::dragStart(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
if (element.getAttribute("data-downloadurl") != null) {
e.dataTransfer.setData("DownloadURL", element.getAttribute("data-downloadurl"));
} else {
e.dataTransfer.setData('Text',[email protected]::getId()()); // required otherwise doesn't work
}
}
function handleDragOver(e) {
if (e.preventDefault)
e.preventDefault();
[email protected]::dragOver(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
//e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
//this.style.border="1px dashed #84B4EA";
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
[email protected]::dragEnter(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
return false;
}
function handleDragLeave(e) {
[email protected]::dragLeave(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
function handleDrop(e) {
// this / e.target is current target element.
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
if (e.preventDefault)
e.preventDefault();
var data = e.dataTransfer.getData('Text');
if (isNaN(data)) {
// //item is an json app from iplant
var obj = eval("(" + data + ")");
var app = @org.iplant.pipeline.client.dnd.DragCreator::createApp(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
@org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = app;
}
[email protected]::drop(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
function handleDragEnd(e) {
[email protected]::dragEnd(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
element.addEventListener('dragstart', handleDragStart, false);
element.addEventListener('dragenter', handleDragEnter, false);
element.addEventListener('dragover', handleDragOver, false);
element.addEventListener('dragleave', handleDragLeave, false);
element.addEventListener('drop', handleDrop, false);
element.addEventListener('dragend', handleDragEnd, false);
}-*/;
| public static native void addDrag(Element element, IPCType rec, DragListener listener) /*-{
function handleDragStart(e) {
var dragIcon = [email protected]::getDragImage(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
e.dataTransfer.setDragImage(dragIcon, -10, -10);
e.dataTransfer.effectAllowed = 'copy';
@org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = rec;
[email protected]::dragStart(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
if (element.getAttribute("data-downloadurl") != null) {
e.dataTransfer.setData("DownloadURL", element.getAttribute("data-downloadurl"));
} else {
e.dataTransfer.setData('Text',[email protected]::getId()()); // required otherwise doesn't work
}
}
function handleDragOver(e) {
if (e.preventDefault)
e.preventDefault();
[email protected]::dragOver(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
//e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
//this.style.border="1px dashed #84B4EA";
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
[email protected]::dragEnter(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
return false;
}
function handleDragLeave(e) {
[email protected]::dragLeave(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
function handleDrop(e) {
// this / e.target is current target element.
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
if (e.preventDefault)
e.preventDefault();
var data = e.dataTransfer.getData('Text');
if (isNaN(data)) {
// //item is an json app from iplant
var obj = eval("(" + data + ")");
var app = @org.iplant.pipeline.client.dnd.DragCreator::createApp(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
@org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = app;
}
[email protected]::drop(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
function handleDragEnd(e) {
[email protected]::dragEnd(Lorg/iplant/pipeline/client/json/IPCType;)(rec);
}
element.addEventListener('dragstart', handleDragStart, false);
element.addEventListener('dragenter', handleDragEnter, false);
element.addEventListener('dragover', handleDragOver, false);
element.addEventListener('dragleave', handleDragLeave, false);
element.addEventListener('drop', handleDrop, false);
element.addEventListener('dragend', handleDragEnd, false);
}-*/;
|
diff --git a/src/de/hotmail/gurkilein/bankcraft/MinecraftCommandListener.java b/src/de/hotmail/gurkilein/bankcraft/MinecraftCommandListener.java
index d3d1aa0..c1521a3 100644
--- a/src/de/hotmail/gurkilein/bankcraft/MinecraftCommandListener.java
+++ b/src/de/hotmail/gurkilein/bankcraft/MinecraftCommandListener.java
@@ -1,395 +1,395 @@
package de.hotmail.gurkilein.bankcraft;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import de.hotmail.gurkilein.bankcraft.banking.ExperienceBankingHandler;
import de.hotmail.gurkilein.bankcraft.banking.MoneyBankingHandler;
import de.hotmail.gurkilein.bankcraft.database.AccountDatabaseInterface;
import de.hotmail.gurkilein.bankcraft.database.DatabaseManagerInterface;
import de.hotmail.gurkilein.bankcraft.database.SignDatabaseInterface;
import de.hotmail.gurkilein.bankcraft.database.flatfile.DatabaseManagerFlatFile;
import de.hotmail.gurkilein.bankcraft.database.flatfile.ExperienceFlatFileInterface;
import de.hotmail.gurkilein.bankcraft.database.flatfile.MoneyFlatFileInterface;
import de.hotmail.gurkilein.bankcraft.database.flatfile.SignFlatFileInterface;
import de.hotmail.gurkilein.bankcraft.database.mysql.DatabaseManagerMysql;
import de.hotmail.gurkilein.bankcraft.database.mysql.ExperienceMysqlInterface;
import de.hotmail.gurkilein.bankcraft.database.mysql.MoneyMysqlInterface;
import de.hotmail.gurkilein.bankcraft.database.mysql.SignMysqlInterface;
public class MinecraftCommandListener implements CommandExecutor{
private Bankcraft bankcraft;
private ConfigurationHandler coHa;
public MinecraftCommandListener(Bankcraft bankcraft) {
this.bankcraft = bankcraft;
this.coHa = bankcraft.getConfigurationHandler();
}
@SuppressWarnings("unused")
private Bankcraft plugin;
public Double betrag;
public void sendHelp(Player p) {
p.sendMessage("---Bankcraft-Help---");
p.sendMessage("/bank "+coHa.getString("signAndCommand.help")+" Shows the help page.");
if (Bankcraft.perms.has(p, "bankcraft.command.balance") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.balance")+" PLAYER Shows your banked money.");
if (Bankcraft.perms.has(p, "bankcraft.command.balancexp") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.balancexp")+" PLAYER Shows your banked XP.");
if (Bankcraft.perms.has(p, "bankcraft.command.deposit") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.deposit")+" AMOUNT Deposits money to your Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.withdraw") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.withdraw")+" AMOUNT Withdraws money from your Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.depositxp") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.depositxp")+" AMOUNT Deposits XP to your Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.withdrawxp") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.withdrawxp")+" AMOUNT Withdraws XP from your Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.transfer") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.transfer")+" PLAYER AMOUNT Transfers money to another Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.transferxp") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.transferxp")+" PLAYER AMOUNT Transfers XP to another Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.interesttimer") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.interesttimer")+" Shows the remaining time until the next wave of interests.");
if (Bankcraft.perms.has(p, "bankcraft.command.exchange") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.exchange")+" AMOUNT Exchanges money to XP.");
if (Bankcraft.perms.has(p, "bankcraft.command.exchangexp") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.exchangexp")+" AMOUNT Exchanges XP to money.");
}
public void sendAdminHelp(Player p) {
p.sendMessage("---Bankcraft-AdminHelp---");
p.sendMessage("/bankadmin help Shows the help page.");
if (Bankcraft.perms.has(p, "bankcraft.command.set") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.set")+" PLAYER AMOUNT Sets a players money.");
if (Bankcraft.perms.has(p, "bankcraft.command.setxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.setxp")+" PLAYER AMOUNT Sets a players XP.");
if (Bankcraft.perms.has(p, "bankcraft.command.grant") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.grant")+" PLAYER AMOUNT Grants a Player money.");
if (Bankcraft.perms.has(p, "bankcraft.command.grantxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.grantxp")+" PLAYER AMOUNT Grants a player XP.");
if (Bankcraft.perms.has(p, "bankcraft.command.clear") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.clear")+" PLAYER Clears money from a players Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.clearxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.clearxp")+" PLAYER Clears XP from a players Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.databaseimport") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.databaseimport")+" OLDDATA NEWDATA Moves data from one database type to another");
}
@Override
public boolean onCommand(CommandSender sender, Command command, String cmdlabel, String[] vars) {
Player p;
if (sender instanceof Player) {
p = (Player) sender;
if (cmdlabel.equalsIgnoreCase("bank") || cmdlabel.equalsIgnoreCase("bc")) {
if (vars.length == 0) {
sendHelp(p);
return true;
}
if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.help"))) {
sendHelp(p);
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.interesttimer")) && (Bankcraft.perms.has(p, "bankcraft.command.interesttimer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
}
if (vars.length == 2) {
if (Util.isPositive(vars[1]) || vars[1].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase("add") && (Bankcraft.perms.has(p, "bankcraft.admin"))) {
Block signblock = p.getTargetBlock(null, 50);
if (signblock.getType() == Material.WALL_SIGN) {
Sign sign = (Sign) signblock.getState();
if (sign.getLine(0).contains("[Bank]")) {
Integer typsign = -1;
try {
typsign = bankcraft.getSignDatabaseInterface().getType(signblock.getX(), signblock.getY(), signblock.getZ(), signblock.getWorld());
} catch (Exception e) {
e.printStackTrace();
}
- if (typsign == 1 | typsign == 2 | typsign == 3 | typsign == 6 | typsign == 7 | typsign == 12 | typsign == 13) {
+ if (typsign == 1 || typsign == 2 || typsign == 3 || typsign == 4 || typsign == 6 || typsign == 7 || typsign == 8 || typsign == 9 || typsign == 12 || typsign == 13 || typsign == 14 || typsign == 15) {
Integer x = signblock.getX();
Integer y = signblock.getY();
Integer z = signblock.getZ();
World w = signblock.getWorld();
Integer newType;
Integer currentType = bankcraft.getSignDatabaseInterface().getType(x, y, z, w);
if (currentType == 1 || currentType == 2 || currentType == 6 || currentType == 7|| currentType == 12|| currentType == 13) {
newType = currentType +2;
bankcraft.getSignDatabaseInterface().changeType(x, y, z, newType, w);
}
bankcraft.getSignDatabaseInterface().addAmount(x, y, z, w, vars[1]);
coHa.printMessage(p, "message.amountAddedSuccessfullyToSign", vars[1], p.getName());
bankcraft.getSignHandler().updateSign(signblock,0);
return true;
}
}
}
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.deposit")) && (Bankcraft.perms.has(p, "bankcraft.command.deposit") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdraw")) && (Bankcraft.perms.has(p, "bankcraft.command.withdraw") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.depositxp")) && (Bankcraft.perms.has(p, "bankcraft.command.depositxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdrawxp")) && (Bankcraft.perms.has(p, "bankcraft.command.withdrawxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchange")) && (Bankcraft.perms.has(p, "bankcraft.command.exchange") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchangexp")) && (Bankcraft.perms.has(p, "bankcraft.command.exchangexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
}
}
if (vars.length == 3) {
if (Util.isPositive(vars[2]) || vars[2].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transfer")) && (Bankcraft.perms.has(p, "bankcraft.command.transfer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
double amount;
if (vars[1].equalsIgnoreCase("all")) {
amount = bankcraft.getMoneyDatabaseInterface().getBalance(p.getName());
} else {
amount = Double.parseDouble(vars[1]);
}
((MoneyBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
coHa.printMessage(p, "message.transferedSuccessfully", amount+"", vars[1]);
return true;
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transferxp")) && (Bankcraft.perms.has(p, "bankcraft.command.transferxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
int amount;
if (vars[1].equalsIgnoreCase("all")) {
amount = bankcraft.getExperienceDatabaseInterface().getBalance(p.getName());
} else {
amount = Integer.parseInt(vars[1]);
}
((ExperienceBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
coHa.printMessage(p, "message.transferedSuccessfullyXp", amount+"", vars[1]);
return true;
}
}
} else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
return true;
}
} else {
if (cmdlabel.equalsIgnoreCase("bankadmin") || cmdlabel.equalsIgnoreCase("bcadmin")) {
if (vars.length == 0) {
sendAdminHelp(p);
return true;
}
else if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.help"))) {
sendAdminHelp(p);
return true;
}
}
else if (vars.length == 2) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clear")) && (Bankcraft.perms.has(p, "bankcraft.command.clear") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], 0D);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account cleared!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clearxp")) && (Bankcraft.perms.has(p, "bankcraft.command.clearxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], 0);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account cleared!");
return true;
}
}
else if (vars.length == 3) {
if (Util.isDouble(vars[2])) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.set")) && (Bankcraft.perms.has(p, "bankcraft.command.set") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.setxp")) && (Bankcraft.perms.has(p, "bankcraft.command.setxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grant")) && (Bankcraft.perms.has(p, "bankcraft.command.grant") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().addToAccount(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Money to "+vars[1]+"!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grantxp")) && (Bankcraft.perms.has(p, "bankcraft.command.grantxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().addToAccount(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Experience to "+vars[1]+"!");
return true;
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.databaseimport")) && (Bankcraft.perms.has(p, "bankcraft.command.databaseimport") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing...");
DatabaseManagerInterface loadDataMan = null;
AccountDatabaseInterface <Double> loadDataMoney = null;
AccountDatabaseInterface <Integer> loadDataXp = null;
SignDatabaseInterface loadDataSign = null;
DatabaseManagerInterface saveDataMan = null;
AccountDatabaseInterface <Double> saveDataMoney = null;
AccountDatabaseInterface <Integer> saveDataXp = null;
SignDatabaseInterface saveDataSign = null;
if (vars[1].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from flatfile...");
loadDataMan = new DatabaseManagerFlatFile(bankcraft);
loadDataMoney = new MoneyFlatFileInterface(bankcraft);
loadDataXp = new ExperienceFlatFileInterface(bankcraft);
loadDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[1].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from mysql...");
loadDataMan = new DatabaseManagerMysql(bankcraft);
loadDataMoney = new MoneyMysqlInterface(bankcraft);
loadDataXp = new ExperienceMysqlInterface(bankcraft);
loadDataSign = new SignMysqlInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to flatfile...");
saveDataMan = new DatabaseManagerFlatFile(bankcraft);
saveDataMoney = new MoneyFlatFileInterface(bankcraft);
saveDataXp = new ExperienceFlatFileInterface(bankcraft);
saveDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to mysql...");
saveDataMan = new DatabaseManagerMysql(bankcraft);
saveDataMoney = new MoneyMysqlInterface(bankcraft);
saveDataXp = new ExperienceMysqlInterface(bankcraft);
saveDataSign = new SignMysqlInterface(bankcraft);
}
//get them ready
loadDataMan.setupDatabase();
saveDataMan.setupDatabase();
//move money data
for (String accountName: loadDataMoney.getAccounts()) {
saveDataMoney.setBalance(accountName, loadDataMoney.getBalance(accountName));
}
//move xp data
for (String accountName: loadDataXp.getAccounts()) {
saveDataXp.setBalance(accountName, loadDataXp.getBalance(accountName));
}
//move sign data
String amounts;
String[] amountsArray;
int type;
for (Location location: loadDataSign.getLocations(-1, null)) {
//Get amounts
amountsArray = loadDataSign.getAmounts((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
amounts = amountsArray[0];
for (int i = 1; i< amountsArray.length; i++) {
amounts+=":"+amountsArray[i];
}
//Get type
type = loadDataSign.getType((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
//Create new sign in save database
saveDataSign.createNewSign((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld(), type, amounts);
}
//close databases
loadDataMan.closeDatabase();
saveDataMan.closeDatabase();
//Send success message
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Moved all data from "+vars[1]+" to "+vars[2]+"!");
return true;
}
}
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
return true;
}
}
} else {
Bankcraft.log.info("[Bankcraft] Please use this ingame!");
}
return false;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String cmdlabel, String[] vars) {
Player p;
if (sender instanceof Player) {
p = (Player) sender;
if (cmdlabel.equalsIgnoreCase("bank") || cmdlabel.equalsIgnoreCase("bc")) {
if (vars.length == 0) {
sendHelp(p);
return true;
}
if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.help"))) {
sendHelp(p);
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.interesttimer")) && (Bankcraft.perms.has(p, "bankcraft.command.interesttimer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
}
if (vars.length == 2) {
if (Util.isPositive(vars[1]) || vars[1].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase("add") && (Bankcraft.perms.has(p, "bankcraft.admin"))) {
Block signblock = p.getTargetBlock(null, 50);
if (signblock.getType() == Material.WALL_SIGN) {
Sign sign = (Sign) signblock.getState();
if (sign.getLine(0).contains("[Bank]")) {
Integer typsign = -1;
try {
typsign = bankcraft.getSignDatabaseInterface().getType(signblock.getX(), signblock.getY(), signblock.getZ(), signblock.getWorld());
} catch (Exception e) {
e.printStackTrace();
}
if (typsign == 1 | typsign == 2 | typsign == 3 | typsign == 6 | typsign == 7 | typsign == 12 | typsign == 13) {
Integer x = signblock.getX();
Integer y = signblock.getY();
Integer z = signblock.getZ();
World w = signblock.getWorld();
Integer newType;
Integer currentType = bankcraft.getSignDatabaseInterface().getType(x, y, z, w);
if (currentType == 1 || currentType == 2 || currentType == 6 || currentType == 7|| currentType == 12|| currentType == 13) {
newType = currentType +2;
bankcraft.getSignDatabaseInterface().changeType(x, y, z, newType, w);
}
bankcraft.getSignDatabaseInterface().addAmount(x, y, z, w, vars[1]);
coHa.printMessage(p, "message.amountAddedSuccessfullyToSign", vars[1], p.getName());
bankcraft.getSignHandler().updateSign(signblock,0);
return true;
}
}
}
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.deposit")) && (Bankcraft.perms.has(p, "bankcraft.command.deposit") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdraw")) && (Bankcraft.perms.has(p, "bankcraft.command.withdraw") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.depositxp")) && (Bankcraft.perms.has(p, "bankcraft.command.depositxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdrawxp")) && (Bankcraft.perms.has(p, "bankcraft.command.withdrawxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchange")) && (Bankcraft.perms.has(p, "bankcraft.command.exchange") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchangexp")) && (Bankcraft.perms.has(p, "bankcraft.command.exchangexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
}
}
if (vars.length == 3) {
if (Util.isPositive(vars[2]) || vars[2].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transfer")) && (Bankcraft.perms.has(p, "bankcraft.command.transfer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
double amount;
if (vars[1].equalsIgnoreCase("all")) {
amount = bankcraft.getMoneyDatabaseInterface().getBalance(p.getName());
} else {
amount = Double.parseDouble(vars[1]);
}
((MoneyBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
coHa.printMessage(p, "message.transferedSuccessfully", amount+"", vars[1]);
return true;
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transferxp")) && (Bankcraft.perms.has(p, "bankcraft.command.transferxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
int amount;
if (vars[1].equalsIgnoreCase("all")) {
amount = bankcraft.getExperienceDatabaseInterface().getBalance(p.getName());
} else {
amount = Integer.parseInt(vars[1]);
}
((ExperienceBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
coHa.printMessage(p, "message.transferedSuccessfullyXp", amount+"", vars[1]);
return true;
}
}
} else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
return true;
}
} else {
if (cmdlabel.equalsIgnoreCase("bankadmin") || cmdlabel.equalsIgnoreCase("bcadmin")) {
if (vars.length == 0) {
sendAdminHelp(p);
return true;
}
else if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.help"))) {
sendAdminHelp(p);
return true;
}
}
else if (vars.length == 2) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clear")) && (Bankcraft.perms.has(p, "bankcraft.command.clear") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], 0D);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account cleared!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clearxp")) && (Bankcraft.perms.has(p, "bankcraft.command.clearxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], 0);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account cleared!");
return true;
}
}
else if (vars.length == 3) {
if (Util.isDouble(vars[2])) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.set")) && (Bankcraft.perms.has(p, "bankcraft.command.set") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.setxp")) && (Bankcraft.perms.has(p, "bankcraft.command.setxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grant")) && (Bankcraft.perms.has(p, "bankcraft.command.grant") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().addToAccount(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Money to "+vars[1]+"!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grantxp")) && (Bankcraft.perms.has(p, "bankcraft.command.grantxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().addToAccount(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Experience to "+vars[1]+"!");
return true;
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.databaseimport")) && (Bankcraft.perms.has(p, "bankcraft.command.databaseimport") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing...");
DatabaseManagerInterface loadDataMan = null;
AccountDatabaseInterface <Double> loadDataMoney = null;
AccountDatabaseInterface <Integer> loadDataXp = null;
SignDatabaseInterface loadDataSign = null;
DatabaseManagerInterface saveDataMan = null;
AccountDatabaseInterface <Double> saveDataMoney = null;
AccountDatabaseInterface <Integer> saveDataXp = null;
SignDatabaseInterface saveDataSign = null;
if (vars[1].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from flatfile...");
loadDataMan = new DatabaseManagerFlatFile(bankcraft);
loadDataMoney = new MoneyFlatFileInterface(bankcraft);
loadDataXp = new ExperienceFlatFileInterface(bankcraft);
loadDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[1].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from mysql...");
loadDataMan = new DatabaseManagerMysql(bankcraft);
loadDataMoney = new MoneyMysqlInterface(bankcraft);
loadDataXp = new ExperienceMysqlInterface(bankcraft);
loadDataSign = new SignMysqlInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to flatfile...");
saveDataMan = new DatabaseManagerFlatFile(bankcraft);
saveDataMoney = new MoneyFlatFileInterface(bankcraft);
saveDataXp = new ExperienceFlatFileInterface(bankcraft);
saveDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to mysql...");
saveDataMan = new DatabaseManagerMysql(bankcraft);
saveDataMoney = new MoneyMysqlInterface(bankcraft);
saveDataXp = new ExperienceMysqlInterface(bankcraft);
saveDataSign = new SignMysqlInterface(bankcraft);
}
//get them ready
loadDataMan.setupDatabase();
saveDataMan.setupDatabase();
//move money data
for (String accountName: loadDataMoney.getAccounts()) {
saveDataMoney.setBalance(accountName, loadDataMoney.getBalance(accountName));
}
//move xp data
for (String accountName: loadDataXp.getAccounts()) {
saveDataXp.setBalance(accountName, loadDataXp.getBalance(accountName));
}
//move sign data
String amounts;
String[] amountsArray;
int type;
for (Location location: loadDataSign.getLocations(-1, null)) {
//Get amounts
amountsArray = loadDataSign.getAmounts((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
amounts = amountsArray[0];
for (int i = 1; i< amountsArray.length; i++) {
amounts+=":"+amountsArray[i];
}
//Get type
type = loadDataSign.getType((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
//Create new sign in save database
saveDataSign.createNewSign((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld(), type, amounts);
}
//close databases
loadDataMan.closeDatabase();
saveDataMan.closeDatabase();
//Send success message
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Moved all data from "+vars[1]+" to "+vars[2]+"!");
return true;
}
}
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
return true;
}
}
} else {
Bankcraft.log.info("[Bankcraft] Please use this ingame!");
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String cmdlabel, String[] vars) {
Player p;
if (sender instanceof Player) {
p = (Player) sender;
if (cmdlabel.equalsIgnoreCase("bank") || cmdlabel.equalsIgnoreCase("bc")) {
if (vars.length == 0) {
sendHelp(p);
return true;
}
if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.help"))) {
sendHelp(p);
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.interesttimer")) && (Bankcraft.perms.has(p, "bankcraft.command.interesttimer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
}
if (vars.length == 2) {
if (Util.isPositive(vars[1]) || vars[1].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase("add") && (Bankcraft.perms.has(p, "bankcraft.admin"))) {
Block signblock = p.getTargetBlock(null, 50);
if (signblock.getType() == Material.WALL_SIGN) {
Sign sign = (Sign) signblock.getState();
if (sign.getLine(0).contains("[Bank]")) {
Integer typsign = -1;
try {
typsign = bankcraft.getSignDatabaseInterface().getType(signblock.getX(), signblock.getY(), signblock.getZ(), signblock.getWorld());
} catch (Exception e) {
e.printStackTrace();
}
if (typsign == 1 || typsign == 2 || typsign == 3 || typsign == 4 || typsign == 6 || typsign == 7 || typsign == 8 || typsign == 9 || typsign == 12 || typsign == 13 || typsign == 14 || typsign == 15) {
Integer x = signblock.getX();
Integer y = signblock.getY();
Integer z = signblock.getZ();
World w = signblock.getWorld();
Integer newType;
Integer currentType = bankcraft.getSignDatabaseInterface().getType(x, y, z, w);
if (currentType == 1 || currentType == 2 || currentType == 6 || currentType == 7|| currentType == 12|| currentType == 13) {
newType = currentType +2;
bankcraft.getSignDatabaseInterface().changeType(x, y, z, newType, w);
}
bankcraft.getSignDatabaseInterface().addAmount(x, y, z, w, vars[1]);
coHa.printMessage(p, "message.amountAddedSuccessfullyToSign", vars[1], p.getName());
bankcraft.getSignHandler().updateSign(signblock,0);
return true;
}
}
}
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.deposit")) && (Bankcraft.perms.has(p, "bankcraft.command.deposit") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdraw")) && (Bankcraft.perms.has(p, "bankcraft.command.withdraw") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.depositxp")) && (Bankcraft.perms.has(p, "bankcraft.command.depositxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdrawxp")) && (Bankcraft.perms.has(p, "bankcraft.command.withdrawxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchange")) && (Bankcraft.perms.has(p, "bankcraft.command.exchange") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchangexp")) && (Bankcraft.perms.has(p, "bankcraft.command.exchangexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
}
}
if (vars.length == 3) {
if (Util.isPositive(vars[2]) || vars[2].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transfer")) && (Bankcraft.perms.has(p, "bankcraft.command.transfer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
double amount;
if (vars[1].equalsIgnoreCase("all")) {
amount = bankcraft.getMoneyDatabaseInterface().getBalance(p.getName());
} else {
amount = Double.parseDouble(vars[1]);
}
((MoneyBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
coHa.printMessage(p, "message.transferedSuccessfully", amount+"", vars[1]);
return true;
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transferxp")) && (Bankcraft.perms.has(p, "bankcraft.command.transferxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
int amount;
if (vars[1].equalsIgnoreCase("all")) {
amount = bankcraft.getExperienceDatabaseInterface().getBalance(p.getName());
} else {
amount = Integer.parseInt(vars[1]);
}
((ExperienceBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
coHa.printMessage(p, "message.transferedSuccessfullyXp", amount+"", vars[1]);
return true;
}
}
} else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
return true;
}
} else {
if (cmdlabel.equalsIgnoreCase("bankadmin") || cmdlabel.equalsIgnoreCase("bcadmin")) {
if (vars.length == 0) {
sendAdminHelp(p);
return true;
}
else if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.help"))) {
sendAdminHelp(p);
return true;
}
}
else if (vars.length == 2) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clear")) && (Bankcraft.perms.has(p, "bankcraft.command.clear") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], 0D);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account cleared!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clearxp")) && (Bankcraft.perms.has(p, "bankcraft.command.clearxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], 0);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account cleared!");
return true;
}
}
else if (vars.length == 3) {
if (Util.isDouble(vars[2])) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.set")) && (Bankcraft.perms.has(p, "bankcraft.command.set") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.setxp")) && (Bankcraft.perms.has(p, "bankcraft.command.setxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grant")) && (Bankcraft.perms.has(p, "bankcraft.command.grant") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().addToAccount(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Money to "+vars[1]+"!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grantxp")) && (Bankcraft.perms.has(p, "bankcraft.command.grantxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().addToAccount(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Experience to "+vars[1]+"!");
return true;
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.databaseimport")) && (Bankcraft.perms.has(p, "bankcraft.command.databaseimport") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing...");
DatabaseManagerInterface loadDataMan = null;
AccountDatabaseInterface <Double> loadDataMoney = null;
AccountDatabaseInterface <Integer> loadDataXp = null;
SignDatabaseInterface loadDataSign = null;
DatabaseManagerInterface saveDataMan = null;
AccountDatabaseInterface <Double> saveDataMoney = null;
AccountDatabaseInterface <Integer> saveDataXp = null;
SignDatabaseInterface saveDataSign = null;
if (vars[1].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from flatfile...");
loadDataMan = new DatabaseManagerFlatFile(bankcraft);
loadDataMoney = new MoneyFlatFileInterface(bankcraft);
loadDataXp = new ExperienceFlatFileInterface(bankcraft);
loadDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[1].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from mysql...");
loadDataMan = new DatabaseManagerMysql(bankcraft);
loadDataMoney = new MoneyMysqlInterface(bankcraft);
loadDataXp = new ExperienceMysqlInterface(bankcraft);
loadDataSign = new SignMysqlInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to flatfile...");
saveDataMan = new DatabaseManagerFlatFile(bankcraft);
saveDataMoney = new MoneyFlatFileInterface(bankcraft);
saveDataXp = new ExperienceFlatFileInterface(bankcraft);
saveDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to mysql...");
saveDataMan = new DatabaseManagerMysql(bankcraft);
saveDataMoney = new MoneyMysqlInterface(bankcraft);
saveDataXp = new ExperienceMysqlInterface(bankcraft);
saveDataSign = new SignMysqlInterface(bankcraft);
}
//get them ready
loadDataMan.setupDatabase();
saveDataMan.setupDatabase();
//move money data
for (String accountName: loadDataMoney.getAccounts()) {
saveDataMoney.setBalance(accountName, loadDataMoney.getBalance(accountName));
}
//move xp data
for (String accountName: loadDataXp.getAccounts()) {
saveDataXp.setBalance(accountName, loadDataXp.getBalance(accountName));
}
//move sign data
String amounts;
String[] amountsArray;
int type;
for (Location location: loadDataSign.getLocations(-1, null)) {
//Get amounts
amountsArray = loadDataSign.getAmounts((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
amounts = amountsArray[0];
for (int i = 1; i< amountsArray.length; i++) {
amounts+=":"+amountsArray[i];
}
//Get type
type = loadDataSign.getType((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
//Create new sign in save database
saveDataSign.createNewSign((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld(), type, amounts);
}
//close databases
loadDataMan.closeDatabase();
saveDataMan.closeDatabase();
//Send success message
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Moved all data from "+vars[1]+" to "+vars[2]+"!");
return true;
}
}
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
return true;
}
}
} else {
Bankcraft.log.info("[Bankcraft] Please use this ingame!");
}
return false;
}
|
diff --git a/AccessProvider/src/org/nchelp/meteor/provider/access/IndexProviderService.java b/AccessProvider/src/org/nchelp/meteor/provider/access/IndexProviderService.java
index 9672113b..2046281b 100755
--- a/AccessProvider/src/org/nchelp/meteor/provider/access/IndexProviderService.java
+++ b/AccessProvider/src/org/nchelp/meteor/provider/access/IndexProviderService.java
@@ -1,382 +1,382 @@
/**
*
* Copyright 2002 - 2007 NCHELP
*
* Author: Tim Bornholtz, The Bornholtz Group
* Priority Technologies, Inc.
*
*
* This code is part of the Meteor system as defined and specified
* by the National Council of Higher Education Loan Programs, Inc.
* (NCHELP) and the Meteor Sponsors, and developed by Priority
* Technologies, Inc. (PTI).
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
********************************************************************************/
package org.nchelp.meteor.provider.access;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nchelp.meteor.message.MeteorIndexResponse;
import org.nchelp.meteor.provider.DataProvider;
import org.nchelp.meteor.provider.DataProviderList;
import org.nchelp.meteor.provider.DistributedRegistry;
import org.nchelp.meteor.provider.IndexProvider;
import org.nchelp.meteor.provider.MeteorParameters;
import org.nchelp.meteor.registry.Directory;
import org.nchelp.meteor.registry.DirectoryFactory;
import org.nchelp.meteor.security.SecurityToken;
import org.nchelp.meteor.util.Cache;
import org.nchelp.meteor.util.Messages;
import org.nchelp.meteor.util.exception.AssertionException;
import org.nchelp.meteor.util.exception.DirectoryException;
import org.nchelp.meteor.util.exception.IndexException;
import org.nchelp.meteor.util.exception.ParsingException;
/**
* IndexProviderService.java This is the only class in the entire Access
* Provider software that knows anything about the entire notion of Index
* Providers
*
* @since May 13, 2003
*/
public class IndexProviderService
{
private static final Log log = LogFactory.getLog(IndexProviderService.class);
private static Cache iProviderCache = new Cache();
public DataProviderList getDataProviders (DistributedRegistry registry, ResponseData response, MeteorParameters params)
{
List iProviders = null;
DataProviderList dProviders = new DataProviderList();
iProviders = this.getIndexProviderList(registry);
if (iProviders == null)
{
iProviders = new ArrayList();
}
if (iProviders.isEmpty())
{
// There's really no point in going on here
dProviders.addMessage(Messages.getMessage("registry.noindex"));
return dProviders;
}
// now request a list of data providers from each index provider.
Iterator iterator = iProviders.iterator();
IndexProvider iProvider = null;
while (iterator.hasNext())
{
iProvider = (IndexProvider)iterator.next();
MeteorIndexResponse ipResp = null;
try
{
if (iProvider == null)
{
log.error("The IndexProvider object is null");
continue;
}
ipResp = iProvider.getDataProviders(params);
}
catch (IndexException ex)
{
// Is this really something we want to show to the user?!?!
// I think not.
log.error(ex);
dProviders.addMessage(Messages.getMessage("index.noresponse"));
}
catch (AssertionException ex)
{
log.error(ex);
dProviders.addMessage(Messages.getMessage("security.tokenexpired"));
}
if (ipResp != null)
{
dProviders = this.aggregateList(response, ipResp.getIndexProvider(), dProviders,
ipResp.getDataProviderList(), params);
String message = ipResp.getErrorMessage();
if (message != null && message.length() > 0)
{
dProviders.addMessage(message);
}
}
}
return dProviders;
}
/**
* Get the list of Index Providers. Cache them in this method if necessary
*
* @param registry
* @return List
*/
private List getIndexProviderList (DistributedRegistry registry)
{
List iProviders = (List)iProviderCache.cached("");
if (iProviders == null || iProviders.isEmpty())
{
iProviders = registry.getIndexProviders();
if (iProviders != null)
{
iProviderCache.add("", iProviders);
}
}
return iProviders;
}
/**
* As each of the calls to AccessProvider.getDataProviders() returns call this
* method to eliminate any of the duplicate Data Providers
*
* @param dataProviders
* @return List
*/
private DataProviderList aggregateList (ResponseData responseData, IndexProvider currentIndexProvider,
DataProviderList dataProviders, List newDataProviders, MeteorParameters params)
{
// easiest way to do this is to cast this to a Set and add them then turn it
// back into a List
boolean unknownDPSent = false;
boolean error = false;
DataProviderList removedList = new DataProviderList();
if (newDataProviders == null)
{
return dataProviders;
}
if (dataProviders == null)
{
dataProviders = new DataProviderList();
}
// Loop through the newDataProviders and make sure they are real data
// providers
Iterator iter = newDataProviders.iterator();
Map dpMap = new HashMap();
while (iter.hasNext())
{
//make sure error flag is false for next data provider in list
error = false;
DataProvider dp = (DataProvider)iter.next();
Directory dir;
try
{
dir = DirectoryFactory.getInstance().getDirectory();
}
catch (DirectoryException ex)
{
log.error("Error connecting to the registry: " + ex.getMessage());
continue;
}
String status = null;
try
{
status = dir.getStatus(dp.getId(), Directory.TYPE_DATA_PROVIDER);
}
catch (DirectoryException ex)
{
// TODO: many conditions can put us here, but since the exception handling in the Directory implementations
// TODO: are so bad, we are stuck with bad handling here until it is fixed
//
// this exception will most often be caused by a data provider not being found in the registry, which is
// something expected
log.info("DirectoryException while validating the status of the Data Provider: " + dp.getId() +
". This Data Provider is being removed from the list of providers. Message: " + ex.getMessage());
removedList.add(dp);
iter.remove();
error = true;
}
if (!error) // TODO: this error status handling stinks, but I'm not allowed to fix it right now
{
if (!"AC".equals(status))
{
log.info("Data Provider: " + dp.getId() + " does not have a status of 'AC' (Active). It has a status of " + status +
". It is being removed from the list of Data Providers returned by the Index Provider");
removedList.add(dp);
iter.remove();
error = true;
}
else
{
URL url = null;
try
{
url = dir.getProviderURL(dp.getId(), Directory.TYPE_DATA_PROVIDER);
}
catch (DirectoryException ex)
{
log.error("DirectoryException while retrieving the URL of the Data Provider: " + dp.getId() +
". This Data Provider is being removed from the list of providers. Message: " + ex.getMessage());
removedList.add(dp);
iter.remove();
error = true;
url = null;
}
if (!error)
{
if (url != null)
{
dp.setURL(url);
String urlString = url.toString();
Object object = dpMap.get(urlString);
if (object == null)
{
// Load new dp into hashmap since not already present
dpMap.put(urlString, dp.getId());
log.debug("data provider " + dp.getId() + " added with URL: " + urlString);
}
else
{
// Remove dp if url already present in map
iter.remove();
log.debug("duplicate URL from data provider " + dp.getId() + " with URL: " + urlString);
}
}
else
{
removedList.add(dp);
iter.remove();
log.warn("URL missing in the registry for Data Provider: " + dp.getId() + " - removing data provider from list");
error = true;
}
}
}
if (!error)
{
try
{
// I don't actually care what the value is here. This method will
// throw an exception when the value isn't found
// There is logic elsewhere to determine if this level is high enough
// or not. For now we just don't care.
dir.getAuthenticationLevel(dp.getId(), "1", Directory.TYPE_DATA_PROVIDER, params.getRole());
}
catch (DirectoryException ex)
{
// If the DirectoryException is thrown then the value we are looking
// for does not exist in the registry
log.info("Data Provider: " + dp.getId() + " does not support the role: " + params.getRole() +
" and is being removed from the list of available providers");
removedList.add(dp);
iter.remove();
error = true;
}
}
}
// If an error occurred but this Data Provider hasn't been added to the
// response yet then
// put this DataProvider into the master response document to be
// displayed to the user
if (error && (!unknownDPSent) &&
!SecurityToken.roleAPCSR.equals(params.getRole()) &&
!SecurityToken.roleLENDER.equals(params.getRole()))
{
String ipName = currentIndexProvider.getName();
String ipID = currentIndexProvider.getIdentifier();
URL ipURL = currentIndexProvider.getURL();
if (ipName != null && ipURL != null)
{
log.info("Adding Index Provider Name: " + ipName + " with the URL: " + ipURL.toString() + " to the response XML");
StringBuffer xml = new StringBuffer("<MeteorDataProviderInfo>");
Iterator remIter = removedList.iterator();
while(remIter.hasNext()){
- DataProvider remDP = (DataProvider)iter.next();
+ DataProvider remDP = (DataProvider)remIter.next();
xml.append("<MeteorDataProviderInfo><MeteorDataProviderDetailInfo>");
// At this point we don't know what type it really is
xml.append("<DataProviderType>G</DataProviderType>");
xml.append("<DataProviderData>");
xml.append("<EntityName>");
xml.append(remDP.getName());
xml.append("</EntityName>");
xml.append("<EntityID>");
xml.append(remDP.getId());
xml.append("</EntityID>");
xml.append("<EntityURL>");
xml.append(remDP.getWebURL());
xml.append("</EntityURL>");
xml.append("<Contacts/>");
xml.append("</DataProviderData>");
xml.append("</MeteorDataProviderDetailInfo></MeteorDataProviderInfo>");
}
xml.append("<MeteorIndexProviderData><EntityName>" + ipName + "</EntityName>");
if (ipID != null)
{
xml.append("<EntityID>" + ipID + "</EntityID>");
}
xml.append("<EntityURL>" + ipURL.toString() + "</EntityURL>" + "<Contacts/>" + "</MeteorIndexProviderData>" +
"</MeteorDataProviderInfo>");
try
{
responseData.addResponse(xml.toString());
unknownDPSent = true;
}
catch (ParsingException ex)
{
// Can this really happen?
log.error("Parsing Exception adding the IndexProviderData to the MeteorDataResponse: " + ex.getMessage());
}
}
else
{
log.info("Trying to add Index Provider information to the output XML but either the name or the ID was null. " +
" Index Provider Name: " + ipName + " Index Provider URL: " + ipURL);
}
}
}
dataProviders.addAll(newDataProviders);
return dataProviders;
}
}
| true | true | private DataProviderList aggregateList (ResponseData responseData, IndexProvider currentIndexProvider,
DataProviderList dataProviders, List newDataProviders, MeteorParameters params)
{
// easiest way to do this is to cast this to a Set and add them then turn it
// back into a List
boolean unknownDPSent = false;
boolean error = false;
DataProviderList removedList = new DataProviderList();
if (newDataProviders == null)
{
return dataProviders;
}
if (dataProviders == null)
{
dataProviders = new DataProviderList();
}
// Loop through the newDataProviders and make sure they are real data
// providers
Iterator iter = newDataProviders.iterator();
Map dpMap = new HashMap();
while (iter.hasNext())
{
//make sure error flag is false for next data provider in list
error = false;
DataProvider dp = (DataProvider)iter.next();
Directory dir;
try
{
dir = DirectoryFactory.getInstance().getDirectory();
}
catch (DirectoryException ex)
{
log.error("Error connecting to the registry: " + ex.getMessage());
continue;
}
String status = null;
try
{
status = dir.getStatus(dp.getId(), Directory.TYPE_DATA_PROVIDER);
}
catch (DirectoryException ex)
{
// TODO: many conditions can put us here, but since the exception handling in the Directory implementations
// TODO: are so bad, we are stuck with bad handling here until it is fixed
//
// this exception will most often be caused by a data provider not being found in the registry, which is
// something expected
log.info("DirectoryException while validating the status of the Data Provider: " + dp.getId() +
". This Data Provider is being removed from the list of providers. Message: " + ex.getMessage());
removedList.add(dp);
iter.remove();
error = true;
}
if (!error) // TODO: this error status handling stinks, but I'm not allowed to fix it right now
{
if (!"AC".equals(status))
{
log.info("Data Provider: " + dp.getId() + " does not have a status of 'AC' (Active). It has a status of " + status +
". It is being removed from the list of Data Providers returned by the Index Provider");
removedList.add(dp);
iter.remove();
error = true;
}
else
{
URL url = null;
try
{
url = dir.getProviderURL(dp.getId(), Directory.TYPE_DATA_PROVIDER);
}
catch (DirectoryException ex)
{
log.error("DirectoryException while retrieving the URL of the Data Provider: " + dp.getId() +
". This Data Provider is being removed from the list of providers. Message: " + ex.getMessage());
removedList.add(dp);
iter.remove();
error = true;
url = null;
}
if (!error)
{
if (url != null)
{
dp.setURL(url);
String urlString = url.toString();
Object object = dpMap.get(urlString);
if (object == null)
{
// Load new dp into hashmap since not already present
dpMap.put(urlString, dp.getId());
log.debug("data provider " + dp.getId() + " added with URL: " + urlString);
}
else
{
// Remove dp if url already present in map
iter.remove();
log.debug("duplicate URL from data provider " + dp.getId() + " with URL: " + urlString);
}
}
else
{
removedList.add(dp);
iter.remove();
log.warn("URL missing in the registry for Data Provider: " + dp.getId() + " - removing data provider from list");
error = true;
}
}
}
if (!error)
{
try
{
// I don't actually care what the value is here. This method will
// throw an exception when the value isn't found
// There is logic elsewhere to determine if this level is high enough
// or not. For now we just don't care.
dir.getAuthenticationLevel(dp.getId(), "1", Directory.TYPE_DATA_PROVIDER, params.getRole());
}
catch (DirectoryException ex)
{
// If the DirectoryException is thrown then the value we are looking
// for does not exist in the registry
log.info("Data Provider: " + dp.getId() + " does not support the role: " + params.getRole() +
" and is being removed from the list of available providers");
removedList.add(dp);
iter.remove();
error = true;
}
}
}
// If an error occurred but this Data Provider hasn't been added to the
// response yet then
// put this DataProvider into the master response document to be
// displayed to the user
if (error && (!unknownDPSent) &&
!SecurityToken.roleAPCSR.equals(params.getRole()) &&
!SecurityToken.roleLENDER.equals(params.getRole()))
{
String ipName = currentIndexProvider.getName();
String ipID = currentIndexProvider.getIdentifier();
URL ipURL = currentIndexProvider.getURL();
if (ipName != null && ipURL != null)
{
log.info("Adding Index Provider Name: " + ipName + " with the URL: " + ipURL.toString() + " to the response XML");
StringBuffer xml = new StringBuffer("<MeteorDataProviderInfo>");
Iterator remIter = removedList.iterator();
while(remIter.hasNext()){
DataProvider remDP = (DataProvider)iter.next();
xml.append("<MeteorDataProviderInfo><MeteorDataProviderDetailInfo>");
// At this point we don't know what type it really is
xml.append("<DataProviderType>G</DataProviderType>");
xml.append("<DataProviderData>");
xml.append("<EntityName>");
xml.append(remDP.getName());
xml.append("</EntityName>");
xml.append("<EntityID>");
xml.append(remDP.getId());
xml.append("</EntityID>");
xml.append("<EntityURL>");
xml.append(remDP.getWebURL());
xml.append("</EntityURL>");
xml.append("<Contacts/>");
xml.append("</DataProviderData>");
xml.append("</MeteorDataProviderDetailInfo></MeteorDataProviderInfo>");
}
xml.append("<MeteorIndexProviderData><EntityName>" + ipName + "</EntityName>");
if (ipID != null)
{
xml.append("<EntityID>" + ipID + "</EntityID>");
}
xml.append("<EntityURL>" + ipURL.toString() + "</EntityURL>" + "<Contacts/>" + "</MeteorIndexProviderData>" +
"</MeteorDataProviderInfo>");
try
{
responseData.addResponse(xml.toString());
unknownDPSent = true;
}
catch (ParsingException ex)
{
// Can this really happen?
log.error("Parsing Exception adding the IndexProviderData to the MeteorDataResponse: " + ex.getMessage());
}
}
else
{
log.info("Trying to add Index Provider information to the output XML but either the name or the ID was null. " +
" Index Provider Name: " + ipName + " Index Provider URL: " + ipURL);
}
}
}
dataProviders.addAll(newDataProviders);
return dataProviders;
}
| private DataProviderList aggregateList (ResponseData responseData, IndexProvider currentIndexProvider,
DataProviderList dataProviders, List newDataProviders, MeteorParameters params)
{
// easiest way to do this is to cast this to a Set and add them then turn it
// back into a List
boolean unknownDPSent = false;
boolean error = false;
DataProviderList removedList = new DataProviderList();
if (newDataProviders == null)
{
return dataProviders;
}
if (dataProviders == null)
{
dataProviders = new DataProviderList();
}
// Loop through the newDataProviders and make sure they are real data
// providers
Iterator iter = newDataProviders.iterator();
Map dpMap = new HashMap();
while (iter.hasNext())
{
//make sure error flag is false for next data provider in list
error = false;
DataProvider dp = (DataProvider)iter.next();
Directory dir;
try
{
dir = DirectoryFactory.getInstance().getDirectory();
}
catch (DirectoryException ex)
{
log.error("Error connecting to the registry: " + ex.getMessage());
continue;
}
String status = null;
try
{
status = dir.getStatus(dp.getId(), Directory.TYPE_DATA_PROVIDER);
}
catch (DirectoryException ex)
{
// TODO: many conditions can put us here, but since the exception handling in the Directory implementations
// TODO: are so bad, we are stuck with bad handling here until it is fixed
//
// this exception will most often be caused by a data provider not being found in the registry, which is
// something expected
log.info("DirectoryException while validating the status of the Data Provider: " + dp.getId() +
". This Data Provider is being removed from the list of providers. Message: " + ex.getMessage());
removedList.add(dp);
iter.remove();
error = true;
}
if (!error) // TODO: this error status handling stinks, but I'm not allowed to fix it right now
{
if (!"AC".equals(status))
{
log.info("Data Provider: " + dp.getId() + " does not have a status of 'AC' (Active). It has a status of " + status +
". It is being removed from the list of Data Providers returned by the Index Provider");
removedList.add(dp);
iter.remove();
error = true;
}
else
{
URL url = null;
try
{
url = dir.getProviderURL(dp.getId(), Directory.TYPE_DATA_PROVIDER);
}
catch (DirectoryException ex)
{
log.error("DirectoryException while retrieving the URL of the Data Provider: " + dp.getId() +
". This Data Provider is being removed from the list of providers. Message: " + ex.getMessage());
removedList.add(dp);
iter.remove();
error = true;
url = null;
}
if (!error)
{
if (url != null)
{
dp.setURL(url);
String urlString = url.toString();
Object object = dpMap.get(urlString);
if (object == null)
{
// Load new dp into hashmap since not already present
dpMap.put(urlString, dp.getId());
log.debug("data provider " + dp.getId() + " added with URL: " + urlString);
}
else
{
// Remove dp if url already present in map
iter.remove();
log.debug("duplicate URL from data provider " + dp.getId() + " with URL: " + urlString);
}
}
else
{
removedList.add(dp);
iter.remove();
log.warn("URL missing in the registry for Data Provider: " + dp.getId() + " - removing data provider from list");
error = true;
}
}
}
if (!error)
{
try
{
// I don't actually care what the value is here. This method will
// throw an exception when the value isn't found
// There is logic elsewhere to determine if this level is high enough
// or not. For now we just don't care.
dir.getAuthenticationLevel(dp.getId(), "1", Directory.TYPE_DATA_PROVIDER, params.getRole());
}
catch (DirectoryException ex)
{
// If the DirectoryException is thrown then the value we are looking
// for does not exist in the registry
log.info("Data Provider: " + dp.getId() + " does not support the role: " + params.getRole() +
" and is being removed from the list of available providers");
removedList.add(dp);
iter.remove();
error = true;
}
}
}
// If an error occurred but this Data Provider hasn't been added to the
// response yet then
// put this DataProvider into the master response document to be
// displayed to the user
if (error && (!unknownDPSent) &&
!SecurityToken.roleAPCSR.equals(params.getRole()) &&
!SecurityToken.roleLENDER.equals(params.getRole()))
{
String ipName = currentIndexProvider.getName();
String ipID = currentIndexProvider.getIdentifier();
URL ipURL = currentIndexProvider.getURL();
if (ipName != null && ipURL != null)
{
log.info("Adding Index Provider Name: " + ipName + " with the URL: " + ipURL.toString() + " to the response XML");
StringBuffer xml = new StringBuffer("<MeteorDataProviderInfo>");
Iterator remIter = removedList.iterator();
while(remIter.hasNext()){
DataProvider remDP = (DataProvider)remIter.next();
xml.append("<MeteorDataProviderInfo><MeteorDataProviderDetailInfo>");
// At this point we don't know what type it really is
xml.append("<DataProviderType>G</DataProviderType>");
xml.append("<DataProviderData>");
xml.append("<EntityName>");
xml.append(remDP.getName());
xml.append("</EntityName>");
xml.append("<EntityID>");
xml.append(remDP.getId());
xml.append("</EntityID>");
xml.append("<EntityURL>");
xml.append(remDP.getWebURL());
xml.append("</EntityURL>");
xml.append("<Contacts/>");
xml.append("</DataProviderData>");
xml.append("</MeteorDataProviderDetailInfo></MeteorDataProviderInfo>");
}
xml.append("<MeteorIndexProviderData><EntityName>" + ipName + "</EntityName>");
if (ipID != null)
{
xml.append("<EntityID>" + ipID + "</EntityID>");
}
xml.append("<EntityURL>" + ipURL.toString() + "</EntityURL>" + "<Contacts/>" + "</MeteorIndexProviderData>" +
"</MeteorDataProviderInfo>");
try
{
responseData.addResponse(xml.toString());
unknownDPSent = true;
}
catch (ParsingException ex)
{
// Can this really happen?
log.error("Parsing Exception adding the IndexProviderData to the MeteorDataResponse: " + ex.getMessage());
}
}
else
{
log.info("Trying to add Index Provider information to the output XML but either the name or the ID was null. " +
" Index Provider Name: " + ipName + " Index Provider URL: " + ipURL);
}
}
}
dataProviders.addAll(newDataProviders);
return dataProviders;
}
|
diff --git a/galaxyCar/src/org/psywerx/car/view/StevecView.java b/galaxyCar/src/org/psywerx/car/view/StevecView.java
index 59f4665..bab871b 100644
--- a/galaxyCar/src/org/psywerx/car/view/StevecView.java
+++ b/galaxyCar/src/org/psywerx/car/view/StevecView.java
@@ -1,73 +1,73 @@
package org.psywerx.car.view;
import java.text.DecimalFormat;
import org.psywerx.car.DataListener;
import org.psywerx.car.R;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
public class StevecView extends View implements DataListener{
private final int MIN_ROTATE = -30;
private final int MAX_ROTATE = 180;
private final DecimalFormat FORMATTER = new DecimalFormat("0000");
private Paint mTextPaint = null;
private float mRotate = 0;
private float mSpeed = 0;
private float mAlpha = 0.3f;
private double mDistance = 0;
private long mTimestamp = 0;
public boolean setSpeed(float speed) {
long ct = System.nanoTime();
- mDistance += speed*(mTimestamp-ct)/1e9;
+ mDistance += speed*(ct-mTimestamp)/1e10;
mTimestamp = ct;
mSpeed = (1.0f-mAlpha)*mSpeed + mAlpha * speed;
float temp = -30+2.3f*mSpeed;
if (temp < MIN_ROTATE || temp > MAX_ROTATE)
return false;
this.mRotate = temp;
this.postInvalidate();
return true;
}
public StevecView(Context context, AttributeSet attrs) {
super(context, attrs);
mTimestamp = System.nanoTime();
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setColor(Color.LTGRAY);
mTextPaint.setTextSize(29);
mTextPaint.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Digitaldream.ttf"));
setSpeed(0);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.speedgaugeclean), 0, 0, null);
canvas.drawText(FORMATTER.format(mDistance), 85, 187, mTextPaint);
canvas.save();
canvas.rotate(mRotate,130,129);
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.cagr), 45, 124, null);
canvas.restore();
}
public void updateData(float[] data) {
//D.dbgv("updating stevec view with speed: "+data[3]);
setSpeed(data[3]);
}
public void setAlpha(float alpha) {
this.mAlpha = alpha;
}
}
| true | true | public boolean setSpeed(float speed) {
long ct = System.nanoTime();
mDistance += speed*(mTimestamp-ct)/1e9;
mTimestamp = ct;
mSpeed = (1.0f-mAlpha)*mSpeed + mAlpha * speed;
float temp = -30+2.3f*mSpeed;
if (temp < MIN_ROTATE || temp > MAX_ROTATE)
return false;
this.mRotate = temp;
this.postInvalidate();
return true;
}
| public boolean setSpeed(float speed) {
long ct = System.nanoTime();
mDistance += speed*(ct-mTimestamp)/1e10;
mTimestamp = ct;
mSpeed = (1.0f-mAlpha)*mSpeed + mAlpha * speed;
float temp = -30+2.3f*mSpeed;
if (temp < MIN_ROTATE || temp > MAX_ROTATE)
return false;
this.mRotate = temp;
this.postInvalidate();
return true;
}
|
diff --git a/src/haven/GLState.java b/src/haven/GLState.java
index ec157556..d6409ad6 100644
--- a/src/haven/GLState.java
+++ b/src/haven/GLState.java
@@ -1,742 +1,742 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser 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 General Public License for more details.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import java.util.*;
import javax.media.opengl.*;
import haven.glsl.ShaderMacro;
import static haven.GOut.checkerr;
public abstract class GLState {
public abstract void apply(GOut g);
public abstract void unapply(GOut g);
public abstract void prep(Buffer buf);
public void applyfrom(GOut g, GLState from) {
throw(new RuntimeException("Called applyfrom on non-conformant GLState (" + from + " -> " + this + ")"));
}
public void applyto(GOut g, GLState to) {
}
public void reapply(GOut g) {
}
public ShaderMacro[] shaders() {
return(null);
}
public boolean reqshaders() {
return(false);
}
public int capply() {
return(10);
}
public int cunapply() {
return(1);
}
public int capplyfrom(GLState from) {
return(-1);
}
public int capplyto(GLState to) {
return(0);
}
private static int slotnum = 0;
private static Slot<?>[] deplist = new Slot<?>[0];
private static Slot<?>[] idlist = new Slot<?>[0];
public static class Slot<T extends GLState> {
private static boolean dirty = false;
private static Collection<Slot<?>> all = new LinkedList<Slot<?>>();
public final Type type;
public final int id;
public final Class<T> scl;
private int depid = -1;
private final Slot<?>[] dep, rdep;
private Slot[] grdep;
public static enum Type {
SYS, GEOM, DRAW
}
public Slot(Type type, Class<T> scl, Slot<?>[] dep, Slot<?>[] rdep) {
this.type = type;
this.scl = scl;
synchronized(Slot.class) {
this.id = slotnum++;
dirty = true;
Slot<?>[] nlist = new Slot<?>[slotnum];
System.arraycopy(idlist, 0, nlist, 0, idlist.length);
nlist[this.id] = this;
idlist = nlist;
all.add(this);
}
if(dep == null)
this.dep = new Slot<?>[0];
else
this.dep = dep;
if(rdep == null)
this.rdep = new Slot<?>[0];
else
this.rdep = rdep;
for(Slot<?> ds : this.dep) {
if(ds == null)
throw(new NullPointerException());
}
for(Slot<?> ds : this.rdep) {
if(ds == null)
throw(new NullPointerException());
}
}
public Slot(Type type, Class<T> scl, Slot... dep) {
this(type, scl, dep, null);
}
private static void makedeps(Collection<Slot<?>> slots) {
Map<Slot<?>, Set<Slot<?>>> lrdep = new HashMap<Slot<?>, Set<Slot<?>>>();
for(Slot<?> s : slots)
lrdep.put(s, new HashSet<Slot<?>>());
for(Slot<?> s : slots) {
lrdep.get(s).addAll(Arrays.asList(s.rdep));
for(Slot<?> ds : s.dep)
lrdep.get(ds).add(s);
}
Set<Slot<?>> left = new HashSet<Slot<?>>(slots);
final Map<Slot<?>, Integer> order = new HashMap<Slot<?>, Integer>();
int id = left.size() - 1;
Slot<?>[] cp = new Slot<?>[0];
while(!left.isEmpty()) {
boolean err = true;
fin:
for(Iterator<Slot<?>> i = left.iterator(); i.hasNext();) {
Slot<?> s = i.next();
for(Slot<?> ds : lrdep.get(s)) {
if(left.contains(ds))
continue fin;
}
err = false;
order.put(s, s.depid = id--);
Set<Slot<?>> grdep = new HashSet<Slot<?>>();
for(Slot<?> ds : lrdep.get(s)) {
grdep.add(ds);
for(Slot<?> ds2 : ds.grdep)
grdep.add(ds2);
}
s.grdep = grdep.toArray(cp);
i.remove();
}
if(err)
throw(new RuntimeException("Cycle encountered while compiling state slot dependencies"));
}
Comparator<Slot> cmp = new Comparator<Slot>() {
public int compare(Slot a, Slot b) {
return(order.get(a) - order.get(b));
}
};
for(Slot<?> s : slots)
Arrays.sort(s.grdep, cmp);
}
public static void update() {
synchronized(Slot.class) {
if(!dirty)
return;
makedeps(all);
deplist = new Slot<?>[all.size()];
for(Slot s : all)
deplist[s.depid] = s;
dirty = false;
}
}
public String toString() {
return("Slot<" + scl.getName() + ">");
}
}
public static class Buffer {
private GLState[] states = new GLState[slotnum];
public final GLConfig cfg;
public Buffer(GLConfig cfg) {
this.cfg = cfg;
}
public Buffer copy() {
Buffer ret = new Buffer(cfg);
System.arraycopy(states, 0, ret.states, 0, states.length);
return(ret);
}
public void copy(Buffer dest) {
dest.adjust();
System.arraycopy(states, 0, dest.states, 0, states.length);
for(int i = states.length; i < dest.states.length; i++)
dest.states[i] = null;
}
public void copy(Buffer dest, Slot.Type type) {
dest.adjust();
adjust();
for(int i = 0; i < states.length; i++) {
if(idlist[i].type == type)
dest.states[i] = states[i];
}
}
private void adjust() {
if(states.length < slotnum) {
GLState[] n = new GLState[slotnum];
System.arraycopy(states, 0, n, 0, states.length);
this.states = n;
}
}
public <T extends GLState> void put(Slot<? super T> slot, T state) {
if(states.length <= slot.id)
adjust();
states[slot.id] = state;
}
@SuppressWarnings("unchecked")
public <T extends GLState> T get(Slot<T> slot) {
if(states.length <= slot.id)
return(null);
return((T)states[slot.id]);
}
public boolean equals(Object o) {
if(!(o instanceof Buffer))
return(false);
Buffer b = (Buffer)o;
adjust();
b.adjust();
for(int i = 0; i < states.length; i++) {
if(!states[i].equals(b.states[i]))
return(false);
}
return(true);
}
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append('[');
for(int i = 0; i < states.length; i++) {
if(i > 0)
buf.append(", ");
if(states[i] == null)
buf.append("null");
else
buf.append(states[i].toString());
}
buf.append(']');
return(buf.toString());
}
/* Should be used very, very sparingly. */
GLState[] states() {
return(states);
}
}
public static int bufdiff(Buffer f, Buffer t, boolean[] trans, boolean[] repl) {
Slot.update();
int cost = 0;
f.adjust(); t.adjust();
if(trans != null) {
for(int i = 0; i < trans.length; i++) {
trans[i] = false;
repl[i] = false;
}
}
for(int i = 0; i < f.states.length; i++) {
if(((f.states[i] == null) != (t.states[i] == null)) ||
((f.states[i] != null) && (t.states[i] != null) && !f.states[i].equals(t.states[i]))) {
if(!repl[i]) {
int cat = -1, caf = -1;
if((t.states[i] != null) && (f.states[i] != null)) {
cat = f.states[i].capplyto(t.states[i]);
caf = t.states[i].capplyfrom(f.states[i]);
}
if((cat >= 0) && (caf >= 0)) {
cost += cat + caf;
if(trans != null)
trans[i] = true;
} else {
if(f.states[i] != null)
cost += f.states[i].cunapply();
if(t.states[i] != null)
cost += t.states[i].capply();
if(trans != null)
repl[i] = true;
}
}
for(Slot ds : idlist[i].grdep) {
int id = ds.id;
if(repl[id])
continue;
if(trans != null)
repl[id] = true;
if(t.states[id] != null)
cost += t.states[id].cunapply();
if(f.states[id] != null)
cost += f.states[id].capply();
}
}
}
return(cost);
}
public static class TexUnit {
private final Applier st;
public final int id;
private TexUnit(Applier st, int id) {
this.st = st;
this.id = id;
}
public void act() {
st.texunit(id);
}
public void free() {
if(st.textab[id] != null)
throw(new RuntimeException("Texunit " + id + " freed twice"));
st.textab[id] = this;
}
}
public static class Applier {
public static boolean debug = false;
private Buffer old, cur, next;
public final GL2 gl;
public final GLConfig cfg;
private boolean[] trans = new boolean[0], repl = new boolean[0], adirty = new boolean[0];
private ShaderMacro[][] shaders = new ShaderMacro[0][];
private int proghash = 0;
public ShaderMacro.Program prog;
public boolean usedprog;
public boolean pdirty = false;
public long time = 0;
/* It seems ugly to treat these so specially, but right now I
* cannot see any good alternative. */
public Matrix4f cam = Matrix4f.id, wxf = Matrix4f.id, mv = Matrix4f.identity();
private Matrix4f ccam = null, cwxf = null;
public Applier(GL2 gl, GLConfig cfg) {
this.gl = gl;
this.cfg = cfg;
this.old = new Buffer(cfg);
this.cur = new Buffer(cfg);
this.next = new Buffer(cfg);
}
public <T extends GLState> void put(Slot<? super T> slot, T state) {
next.put(slot, state);
}
public <T extends GLState> T get(Slot<T> slot) {
return(next.get(slot));
}
public <T extends GLState> T cur(Slot<T> slot) {
return(cur.get(slot));
}
public <T extends GLState> T old(Slot<T> slot) {
return(old.get(slot));
}
public void prep(GLState st) {
st.prep(next);
}
public void set(Buffer to) {
to.copy(next);
}
public void copy(Buffer dest) {
next.copy(dest);
}
public Buffer copy() {
return(next.copy());
}
public void apply(GOut g) {
long st = 0;
if(Config.profile) st = System.nanoTime();
- Slot<?>[] deplist = GLState.deplist;
if(trans.length < slotnum) {
synchronized(Slot.class) {
trans = new boolean[slotnum];
repl = new boolean[slotnum];
shaders = Utils.extend(shaders, slotnum);
}
}
bufdiff(cur, next, trans, repl);
+ Slot<?>[] deplist = GLState.deplist;
boolean dirty = false;
for(int i = trans.length - 1; i >= 0; i--) {
if(repl[i] || trans[i]) {
GLState nst = next.states[i];
ShaderMacro[] ns = (nst == null)?null:nst.shaders();
if(ns != shaders[i]) {
proghash ^= System.identityHashCode(shaders[i]) ^ System.identityHashCode(ns);
shaders[i] = ns;
dirty = true;
}
}
}
usedprog = prog != null;
if(dirty) {
ShaderMacro.Program np;
boolean shreq = false;
for(int i = 0; i < trans.length; i++) {
if((shaders[i] != null) && next.states[i].reqshaders()) {
shreq = true;
break;
}
}
if(shreq && g.gc.pref.shuse.val) {
np = findprog(proghash, shaders);
} else {
np = null;
}
if(np != prog) {
if(np != null)
np.apply(g);
else
g.gl.glUseProgramObjectARB(0);
prog = np;
if(debug)
checkerr(g.gl);
pdirty = true;
}
}
if((prog != null) != usedprog) {
for(int i = 0; i < trans.length; i++) {
if(trans[i])
repl[i] = true;
}
}
cur.copy(old);
for(int i = deplist.length - 1; i >= 0; i--) {
int id = deplist[i].id;
if(repl[id]) {
if(cur.states[id] != null) {
cur.states[id].unapply(g);
if(debug)
stcheckerr(g, "unapply", cur.states[id]);
}
cur.states[id] = null;
}
}
/* Note on invariants: States may exit non-locally
* from apply, applyto/applyfrom or reapply (e.g. by
* throwing Loading exceptions) in a defined way
* provided they do so before they have changed any GL
* state. If they exit non-locally after GL state has
* been altered, future results are undefined. */
for(int i = 0; i < deplist.length; i++) {
int id = deplist[i].id;
if(repl[id]) {
if(next.states[id] != null) {
next.states[id].apply(g);
cur.states[id] = next.states[id];
if(debug)
stcheckerr(g, "apply", cur.states[id]);
}
if(!pdirty && (prog != null))
prog.adirty(deplist[i]);
} else if(trans[id]) {
cur.states[id].applyto(g, next.states[id]);
if(debug)
stcheckerr(g, "applyto", cur.states[id]);
next.states[id].applyfrom(g, cur.states[id]);
cur.states[id] = next.states[id];
if(debug)
stcheckerr(g, "applyfrom", cur.states[id]);
if(!pdirty && (prog != null))
prog.adirty(deplist[i]);
} else if((prog != null) && pdirty && (shaders[id] != null)) {
cur.states[id].reapply(g);
if(debug)
stcheckerr(g, "reapply", cur.states[id]);
}
}
if((ccam != cam) || (cwxf != wxf)) {
/* See comment above */
mv.load(ccam = cam).mul1(cwxf = wxf);
matmode(GL2.GL_MODELVIEW);
gl.glLoadMatrixf(mv.m, 0);
}
if(prog != null)
prog.autoapply(g, pdirty);
pdirty = false;
checkerr(gl);
if(Config.profile)
time += System.nanoTime() - st;
}
public static class ApplyException extends RuntimeException {
public final transient GLState st;
public final String func;
public ApplyException(String func, GLState st, Throwable cause) {
super("Error in " + func + " of " + st, cause);
this.st = st;
this.func = func;
}
}
private void stcheckerr(GOut g, String func, GLState st) {
try {
checkerr(g.gl);
} catch(RuntimeException e) {
throw(new ApplyException(func, st, e));
}
}
/* "Meta-states" */
private int matmode = GL2.GL_MODELVIEW;
private int texunit = 0;
public void matmode(int mode) {
if(mode != matmode) {
gl.glMatrixMode(mode);
matmode = mode;
}
}
public void texunit(int unit) {
if(unit != texunit) {
gl.glActiveTexture(GL.GL_TEXTURE0 + unit);
texunit = unit;
}
}
private TexUnit[] textab = new TexUnit[0];
public TexUnit texalloc() {
int i;
for(i = 0; i < textab.length; i++) {
if(textab[i] != null) {
TexUnit ret = textab[i];
textab[i] = null;
return(ret);
}
}
textab = new TexUnit[i + 1];
return(new TexUnit(this, i));
}
/* Program internation */
public static class SavedProg {
public final int hash;
public final ShaderMacro.Program prog;
public final ShaderMacro[][] shaders;
public SavedProg next;
boolean used = true;
public SavedProg(int hash, ShaderMacro.Program prog, ShaderMacro[][] shaders) {
this.hash = hash;
this.prog = prog;
this.shaders = Utils.splice(shaders, 0);
}
}
private SavedProg[] ptab = new SavedProg[32];
private int nprog = 0;
private long lastclean = System.currentTimeMillis();
private ShaderMacro.Program findprog(int hash, ShaderMacro[][] shaders) {
int idx = hash & (ptab.length - 1);
outer: for(SavedProg s = ptab[idx]; s != null; s = s.next) {
if(s.hash != hash)
continue;
int i;
for(i = 0; i < s.shaders.length; i++) {
if(shaders[i] != s.shaders[i])
continue outer;
}
for(; i < shaders.length; i++) {
if(shaders[i] != null)
continue outer;
}
s.used = true;
return(s.prog);
}
Collection<ShaderMacro> mods = new LinkedList<ShaderMacro>();
for(int i = 0; i < shaders.length; i++) {
if(shaders[i] == null)
continue;
for(int o = 0; o < shaders[i].length; o++)
mods.add(shaders[i][o]);
}
ShaderMacro.Program prog = ShaderMacro.Program.build(mods);
SavedProg s = new SavedProg(hash, prog, shaders);
s.next = ptab[idx];
ptab[idx] = s;
nprog++;
if(nprog > ptab.length)
rehash(ptab.length * 2);
return(prog);
}
private void rehash(int nlen) {
SavedProg[] ntab = new SavedProg[nlen];
for(int i = 0; i < ptab.length; i++) {
while(ptab[i] != null) {
SavedProg s = ptab[i];
ptab[i] = s.next;
int ni = s.hash & (ntab.length - 1);
s.next = ntab[ni];
ntab[ni] = s;
}
}
ptab = ntab;
}
public void clean() {
long now = System.currentTimeMillis();
if(now - lastclean > 60000) {
for(int i = 0; i < ptab.length; i++) {
SavedProg c, p;
for(c = ptab[i], p = null; c != null; p = c, c = c.next) {
if(!c.used) {
if(p != null)
p.next = c.next;
else
ptab[i] = c.next;
c.prog.dispose();
nprog--;
} else {
c.used = false;
}
}
}
/* XXX: Rehash into smaller table? It's probably not a
* problem, but it might be nice just for
* completeness. */
lastclean = now;
}
}
public int numprogs() {
return(nprog);
}
}
private class Wrapping implements Rendered {
private final Rendered r;
private Wrapping(Rendered r) {
if(r == null)
throw(new NullPointerException("Wrapping null in " + GLState.this));
this.r = r;
}
public void draw(GOut g) {}
public boolean setup(RenderList rl) {
rl.add(r, GLState.this);
return(false);
}
}
public Rendered apply(Rendered r) {
return(new Wrapping(r));
}
public static abstract class Abstract extends GLState {
public void apply(GOut g) {}
public void unapply(GOut g) {}
}
public static GLState compose(final GLState... states) {
return(new Abstract() {
public void prep(Buffer buf) {
for(GLState st : states) {
if(st == null)
throw(new RuntimeException("null state in list of " + Arrays.asList(states)));
st.prep(buf);
}
}
});
}
public static class Delegate extends Abstract {
public GLState del;
public Delegate(GLState del) {
this.del = del;
}
public void prep(Buffer buf) {
del.prep(buf);
}
}
public interface GlobalState {
public Global global(RenderList r, Buffer ctx);
}
public interface Global {
public void postsetup(RenderList rl);
public void prerender(RenderList rl, GOut g);
public void postrender(RenderList rl, GOut g);
}
public static abstract class StandAlone extends GLState {
public final Slot<StandAlone> slot;
public StandAlone(Slot.Type type, Slot<?>... dep) {
slot = new Slot<StandAlone>(type, StandAlone.class, dep);
}
public void prep(Buffer buf) {
buf.put(slot, this);
}
}
public static final GLState nullstate = new GLState() {
public void apply(GOut g) {}
public void unapply(GOut g) {}
public void prep(Buffer buf) {}
};
static {
Console.setscmd("applydb", new Console.Command() {
public void run(Console cons, String[] args) {
Applier.debug = Utils.parsebool(args[1], false);
}
});
}
}
| false | true | public void apply(GOut g) {
long st = 0;
if(Config.profile) st = System.nanoTime();
Slot<?>[] deplist = GLState.deplist;
if(trans.length < slotnum) {
synchronized(Slot.class) {
trans = new boolean[slotnum];
repl = new boolean[slotnum];
shaders = Utils.extend(shaders, slotnum);
}
}
bufdiff(cur, next, trans, repl);
boolean dirty = false;
for(int i = trans.length - 1; i >= 0; i--) {
if(repl[i] || trans[i]) {
GLState nst = next.states[i];
ShaderMacro[] ns = (nst == null)?null:nst.shaders();
if(ns != shaders[i]) {
proghash ^= System.identityHashCode(shaders[i]) ^ System.identityHashCode(ns);
shaders[i] = ns;
dirty = true;
}
}
}
usedprog = prog != null;
if(dirty) {
ShaderMacro.Program np;
boolean shreq = false;
for(int i = 0; i < trans.length; i++) {
if((shaders[i] != null) && next.states[i].reqshaders()) {
shreq = true;
break;
}
}
if(shreq && g.gc.pref.shuse.val) {
np = findprog(proghash, shaders);
} else {
np = null;
}
if(np != prog) {
if(np != null)
np.apply(g);
else
g.gl.glUseProgramObjectARB(0);
prog = np;
if(debug)
checkerr(g.gl);
pdirty = true;
}
}
if((prog != null) != usedprog) {
for(int i = 0; i < trans.length; i++) {
if(trans[i])
repl[i] = true;
}
}
cur.copy(old);
for(int i = deplist.length - 1; i >= 0; i--) {
int id = deplist[i].id;
if(repl[id]) {
if(cur.states[id] != null) {
cur.states[id].unapply(g);
if(debug)
stcheckerr(g, "unapply", cur.states[id]);
}
cur.states[id] = null;
}
}
/* Note on invariants: States may exit non-locally
* from apply, applyto/applyfrom or reapply (e.g. by
* throwing Loading exceptions) in a defined way
* provided they do so before they have changed any GL
* state. If they exit non-locally after GL state has
* been altered, future results are undefined. */
for(int i = 0; i < deplist.length; i++) {
int id = deplist[i].id;
if(repl[id]) {
if(next.states[id] != null) {
next.states[id].apply(g);
cur.states[id] = next.states[id];
if(debug)
stcheckerr(g, "apply", cur.states[id]);
}
if(!pdirty && (prog != null))
prog.adirty(deplist[i]);
} else if(trans[id]) {
cur.states[id].applyto(g, next.states[id]);
if(debug)
stcheckerr(g, "applyto", cur.states[id]);
next.states[id].applyfrom(g, cur.states[id]);
cur.states[id] = next.states[id];
if(debug)
stcheckerr(g, "applyfrom", cur.states[id]);
if(!pdirty && (prog != null))
prog.adirty(deplist[i]);
} else if((prog != null) && pdirty && (shaders[id] != null)) {
cur.states[id].reapply(g);
if(debug)
stcheckerr(g, "reapply", cur.states[id]);
}
}
if((ccam != cam) || (cwxf != wxf)) {
/* See comment above */
mv.load(ccam = cam).mul1(cwxf = wxf);
matmode(GL2.GL_MODELVIEW);
gl.glLoadMatrixf(mv.m, 0);
}
if(prog != null)
prog.autoapply(g, pdirty);
pdirty = false;
checkerr(gl);
if(Config.profile)
time += System.nanoTime() - st;
}
| public void apply(GOut g) {
long st = 0;
if(Config.profile) st = System.nanoTime();
if(trans.length < slotnum) {
synchronized(Slot.class) {
trans = new boolean[slotnum];
repl = new boolean[slotnum];
shaders = Utils.extend(shaders, slotnum);
}
}
bufdiff(cur, next, trans, repl);
Slot<?>[] deplist = GLState.deplist;
boolean dirty = false;
for(int i = trans.length - 1; i >= 0; i--) {
if(repl[i] || trans[i]) {
GLState nst = next.states[i];
ShaderMacro[] ns = (nst == null)?null:nst.shaders();
if(ns != shaders[i]) {
proghash ^= System.identityHashCode(shaders[i]) ^ System.identityHashCode(ns);
shaders[i] = ns;
dirty = true;
}
}
}
usedprog = prog != null;
if(dirty) {
ShaderMacro.Program np;
boolean shreq = false;
for(int i = 0; i < trans.length; i++) {
if((shaders[i] != null) && next.states[i].reqshaders()) {
shreq = true;
break;
}
}
if(shreq && g.gc.pref.shuse.val) {
np = findprog(proghash, shaders);
} else {
np = null;
}
if(np != prog) {
if(np != null)
np.apply(g);
else
g.gl.glUseProgramObjectARB(0);
prog = np;
if(debug)
checkerr(g.gl);
pdirty = true;
}
}
if((prog != null) != usedprog) {
for(int i = 0; i < trans.length; i++) {
if(trans[i])
repl[i] = true;
}
}
cur.copy(old);
for(int i = deplist.length - 1; i >= 0; i--) {
int id = deplist[i].id;
if(repl[id]) {
if(cur.states[id] != null) {
cur.states[id].unapply(g);
if(debug)
stcheckerr(g, "unapply", cur.states[id]);
}
cur.states[id] = null;
}
}
/* Note on invariants: States may exit non-locally
* from apply, applyto/applyfrom or reapply (e.g. by
* throwing Loading exceptions) in a defined way
* provided they do so before they have changed any GL
* state. If they exit non-locally after GL state has
* been altered, future results are undefined. */
for(int i = 0; i < deplist.length; i++) {
int id = deplist[i].id;
if(repl[id]) {
if(next.states[id] != null) {
next.states[id].apply(g);
cur.states[id] = next.states[id];
if(debug)
stcheckerr(g, "apply", cur.states[id]);
}
if(!pdirty && (prog != null))
prog.adirty(deplist[i]);
} else if(trans[id]) {
cur.states[id].applyto(g, next.states[id]);
if(debug)
stcheckerr(g, "applyto", cur.states[id]);
next.states[id].applyfrom(g, cur.states[id]);
cur.states[id] = next.states[id];
if(debug)
stcheckerr(g, "applyfrom", cur.states[id]);
if(!pdirty && (prog != null))
prog.adirty(deplist[i]);
} else if((prog != null) && pdirty && (shaders[id] != null)) {
cur.states[id].reapply(g);
if(debug)
stcheckerr(g, "reapply", cur.states[id]);
}
}
if((ccam != cam) || (cwxf != wxf)) {
/* See comment above */
mv.load(ccam = cam).mul1(cwxf = wxf);
matmode(GL2.GL_MODELVIEW);
gl.glLoadMatrixf(mv.m, 0);
}
if(prog != null)
prog.autoapply(g, pdirty);
pdirty = false;
checkerr(gl);
if(Config.profile)
time += System.nanoTime() - st;
}
|
diff --git a/src/org/thoughtcrime/securesms/mms/AudioSlide.java b/src/org/thoughtcrime/securesms/mms/AudioSlide.java
index ee27e9e95..f0df498fa 100644
--- a/src/org/thoughtcrime/securesms/mms/AudioSlide.java
+++ b/src/org/thoughtcrime/securesms/mms/AudioSlide.java
@@ -1,84 +1,85 @@
/**
* Copyright (C) 2011 Whisper Systems
*
* 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.thoughtcrime.securesms.mms;
import java.io.IOException;
import org.thoughtcrime.securesms.R;
import ws.com.google.android.mms.pdu.PduPart;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore.Audio;
import android.widget.ImageView;
public class AudioSlide extends Slide {
public AudioSlide(Context context, PduPart part) {
super(context, part);
}
public AudioSlide(Context context, Uri uri) throws IOException, MediaTooLargeException {
super(context, constructPartFromUri(context, uri));
}
@Override
public boolean hasImage() {
return true;
}
@Override
public boolean hasAudio() {
return true;
}
@Override
public Drawable getThumbnail(int maxWidth, int maxHeight) {
return context.getResources().getDrawable(R.drawable.ic_menu_add_sound);
}
public static PduPart constructPartFromUri(Context context, Uri uri) throws IOException, MediaTooLargeException {
PduPart part = new PduPart();
if (getMediaSize(context, uri) > MAX_MESSAGE_SIZE)
throw new MediaTooLargeException("Audio track larger than size maximum.");
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[]{Audio.Media.MIME_TYPE}, null, null, null);
if (cursor != null && cursor.moveToFirst())
- part.setContentType(cursor.getString(0).getBytes());
+ part.setContentType(cursor.getString(0).getBytes());
else
- throw new IOException("Unable to query content type.");
+ throw new IOException("Unable to query content type.");
} finally {
- cursor.close();
+ if (cursor != null)
+ cursor.close();
}
part.setDataUri(uri);
part.setContentId((System.currentTimeMillis()+"").getBytes());
part.setName(("Audio" + System.currentTimeMillis()).getBytes());
return part;
}
}
| false | true | public static PduPart constructPartFromUri(Context context, Uri uri) throws IOException, MediaTooLargeException {
PduPart part = new PduPart();
if (getMediaSize(context, uri) > MAX_MESSAGE_SIZE)
throw new MediaTooLargeException("Audio track larger than size maximum.");
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[]{Audio.Media.MIME_TYPE}, null, null, null);
if (cursor != null && cursor.moveToFirst())
part.setContentType(cursor.getString(0).getBytes());
else
throw new IOException("Unable to query content type.");
} finally {
cursor.close();
}
part.setDataUri(uri);
part.setContentId((System.currentTimeMillis()+"").getBytes());
part.setName(("Audio" + System.currentTimeMillis()).getBytes());
return part;
}
| public static PduPart constructPartFromUri(Context context, Uri uri) throws IOException, MediaTooLargeException {
PduPart part = new PduPart();
if (getMediaSize(context, uri) > MAX_MESSAGE_SIZE)
throw new MediaTooLargeException("Audio track larger than size maximum.");
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[]{Audio.Media.MIME_TYPE}, null, null, null);
if (cursor != null && cursor.moveToFirst())
part.setContentType(cursor.getString(0).getBytes());
else
throw new IOException("Unable to query content type.");
} finally {
if (cursor != null)
cursor.close();
}
part.setDataUri(uri);
part.setContentId((System.currentTimeMillis()+"").getBytes());
part.setName(("Audio" + System.currentTimeMillis()).getBytes());
return part;
}
|
diff --git a/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ANTLRGrammarGenerator.java b/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ANTLRGrammarGenerator.java
index 52f33f43d..340258d54 100644
--- a/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ANTLRGrammarGenerator.java
+++ b/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ANTLRGrammarGenerator.java
@@ -1,874 +1,874 @@
/*******************************************************************************
* Copyright (c) 2006-2009
* Software Technology Group, Dresden University of Technology
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version. This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the GNU Lesser General Public License for more details. You should have
* received a copy of the GNU Lesser General Public License along with this
* program; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*
* Contributors:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.codegen.generators;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.RecognitionException;
import org.eclipse.emf.codegen.ecore.genmodel.GenClass;
import org.eclipse.emf.codegen.ecore.genmodel.GenFeature;
import org.eclipse.emf.codegen.ecore.genmodel.GenPackage;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.EcoreUtil.Copier;
import org.emftext.runtime.IOptions;
import org.emftext.runtime.resource.ITokenResolveResult;
import org.emftext.runtime.resource.ITokenResolver;
import org.emftext.runtime.resource.ITokenResolverFactory;
import org.emftext.runtime.resource.impl.AbstractEMFTextParser;
import org.emftext.runtime.resource.impl.ContextDependentURIFragmentFactory;
import org.emftext.runtime.resource.impl.TokenResolveResult;
import org.emftext.runtime.resource.impl.UnexpectedContentTypeException;
import org.emftext.sdk.codegen.GenerationContext;
import org.emftext.sdk.codegen.GenerationProblem;
import org.emftext.sdk.codegen.OptionManager;
import org.emftext.sdk.codegen.GenerationProblem.Severity;
import org.emftext.sdk.codegen.composites.ANTLRGrammarComposite;
import org.emftext.sdk.codegen.composites.StringComposite;
import org.emftext.sdk.codegen.util.GeneratorUtil;
import org.emftext.sdk.concretesyntax.Cardinality;
import org.emftext.sdk.concretesyntax.CardinalityDefinition;
import org.emftext.sdk.concretesyntax.Choice;
import org.emftext.sdk.concretesyntax.CompoundDefinition;
import org.emftext.sdk.concretesyntax.ConcreteSyntax;
import org.emftext.sdk.concretesyntax.ConcretesyntaxPackage;
import org.emftext.sdk.concretesyntax.Containment;
import org.emftext.sdk.concretesyntax.CsString;
import org.emftext.sdk.concretesyntax.Definition;
import org.emftext.sdk.concretesyntax.LineBreak;
import org.emftext.sdk.concretesyntax.OptionTypes;
import org.emftext.sdk.concretesyntax.PLUS;
import org.emftext.sdk.concretesyntax.Placeholder;
import org.emftext.sdk.concretesyntax.QUESTIONMARK;
import org.emftext.sdk.concretesyntax.Rule;
import org.emftext.sdk.concretesyntax.Sequence;
import org.emftext.sdk.concretesyntax.Terminal;
import org.emftext.sdk.concretesyntax.TokenDefinition;
import org.emftext.sdk.concretesyntax.WhiteSpaces;
import org.emftext.sdk.finders.GenClassFinder;
import org.emftext.sdk.syntax_analysis.LeftRecursionDetector;
/**
* The text parser generator maps from one or more concrete syntaxes (*.cs) and
* one or more Ecore generator models to an ANTLR parser specification.
* If the derived specification does not contain syntactical conflicts which
* could break the ANTLR generation algorithm or the ANTLR parsing algorithm
* (e.g. ambiguities in the configuration or in token definitions which are
* not checked by this generator) it can be used to generate a text parser
* which allows to create metamodel instances from plain text files.
*
* @author Sven Karol ([email protected])
*/
public class ANTLRGrammarGenerator extends BaseGenerator {
/**
* The name of the EOF token which can be printed to force end of file after a parse from the root.
*/
public static final String EOF_TOKEN_NAME = "EOF";
private ConcreteSyntax conrceteSyntax;
private String tokenResolverFactoryName;
private String qualifiedReferenceResolverSwitchName;
/**
* A map to collect all (non-containment) references that will contain proxy
* objects after parsing.
*/
//private Collection<GenFeature> nonContainmentReferences;
/**
* A map that projects the fully qualified name of generator classes to
* the set of fully qualified names of all their super classes.
*/
private Map<String, Collection<String>> genClassNames2superClassNames;
private Collection<GenClass> allGenClasses;
private boolean forceEOFToken;
private GenClassFinder genClassFinder = new GenClassFinder();
private GenerationContext context;
public ANTLRGrammarGenerator(GenerationContext context) {
super(context.getPackageName(), context.getCapitalizedConcreteSyntaxName());
this.context = context;
qualifiedReferenceResolverSwitchName = context.getQualifiedReferenceResolverSwitchClassName();
conrceteSyntax = context.getConcreteSyntax();
tokenResolverFactoryName = context.getTokenResolverFactoryClassName();
}
private void initOptions() {
forceEOFToken = OptionManager.INSTANCE.getBooleanOptionValue(conrceteSyntax, OptionTypes.FORCE_EOF);
}
private void initCaches(){
allGenClasses = genClassFinder.findAllGenClasses(conrceteSyntax, true, true);
genClassNames2superClassNames = genClassFinder.findAllSuperclasses(allGenClasses);
}
public boolean generate(PrintWriter pw){
initOptions();
initCaches();
String csName = getResourceClassName();
String lexerName = getLexerName(csName);
boolean backtracking = OptionManager.INSTANCE.getBooleanOptionValue(conrceteSyntax, OptionTypes.ANTLR_BACKTRACKING);
boolean memoize = OptionManager.INSTANCE.getBooleanOptionValue(conrceteSyntax, OptionTypes.ANTLR_MEMOIZE);
StringComposite sc = new ANTLRGrammarComposite();
sc.add("grammar " + csName + ";");
sc.addLineBreak();
sc.add("options {");
sc.add("superClass = " + AbstractEMFTextParser.class.getSimpleName() + ";");
sc.add("backtrack = " + backtracking + ";");
sc.add("memoize = " + memoize + ";");
sc.add("}");
sc.addLineBreak();
- //the lexer: package def. and error handling
+ //the lexer: package definition and error handling
sc.add("@lexer::header {");
sc.add("package " + super.getResourcePackageName() + ";");
sc.add("}");
sc.addLineBreak();
sc.add("@lexer::members {");
sc.add("public " + java.util.List.class.getName() + "<" + RecognitionException.class.getName() + "> lexerExceptions = new " + java.util.ArrayList.class.getName() + "<" + RecognitionException.class.getName() + ">();");
sc.add("public " + java.util.List.class.getName() + "<" + Integer.class.getName() + "> lexerExceptionsPosition = new " + java.util.ArrayList.class.getName() + "<" + Integer.class.getName() + ">();");
sc.addLineBreak();
sc.add("public void reportError(" + RecognitionException.class.getName() + " e) {");
sc.add("lexerExceptions.add(e);");
sc.add("lexerExceptionsPosition.add(((" + ANTLRStringStream.class.getName() + ")input).index());");
sc.add("}");
sc.add("}");
- //the parser: package def. and entry (doParse) method
+ //the parser: package definition and entry (doParse) method
sc.add("@header{");
sc.add("package " + super.getResourcePackageName() + ";");
sc.addLineBreak();
printDefaultImports(sc);
sc.add("}");
sc.addLineBreak();
sc.add("@members{");
sc.add("private " + ITokenResolverFactory.class.getName() + " tokenResolverFactory = new " + tokenResolverFactoryName +"();");
sc.add("private int lastPosition;");
sc.add("private " + TokenResolveResult.class.getName() + " tokenResolveResult = new " + TokenResolveResult.class.getName() + "();");
sc.add("private " + qualifiedReferenceResolverSwitchName + " referenceResolverSwitch;");
sc.addLineBreak();
sc.add("protected EObject doParse() throws RecognitionException {");
sc.add("lastPosition = 0;");
sc.add("((" + lexerName + ")getTokenStream().getTokenSource()).lexerExceptions = lexerExceptions;"); //required because the lexer class can not be subclassed
sc.add("((" + lexerName + ")getTokenStream().getTokenSource()).lexerExceptionsPosition = lexerExceptionsPosition;"); //required because the lexer class can not be subclassed
sc.add("Object typeObject = null;");
sc.add("Map<?,?> options = getOptions();");
sc.add("if (options != null) {");
sc.add("typeObject = options.get(IOptions.RESOURCE_CONTENT_TYPE);");
sc.add("}");
sc.add("if (typeObject == null) {");
sc.add("return start();");
sc.add("} else if (typeObject instanceof EClass) {");
sc.add("EClass type = (EClass)typeObject;");
for(Rule rule:conrceteSyntax.getAllRules()){
String qualifiedClassName = rule.getMetaclass().getQualifiedInterfaceName();
String ruleName = getLowerCase(rule.getMetaclass().getName());
sc.add("if (type.getInstanceClass() == " + qualifiedClassName +".class) {");
sc.add("return " + ruleName + "();");
sc.add("}");
}
sc.add("}");
sc.add("throw new " + UnexpectedContentTypeException.class.getName() + "(typeObject);");
sc.add("}");
sc.addLineBreak();
sc.add("@SuppressWarnings(\"unchecked\")");
sc.add("private boolean addObjectToList(" + EObject.class.getName() + " element, int featureID, " + Object.class.getName() + " proxy) {");
sc.add("return ((" + List.class.getName() + "<" + Object.class.getName() + ">) element.eGet(element.eClass().getEStructuralFeature(featureID))).add(proxy);");
sc.add("}");
sc.addLineBreak();
sc.add("private " + TokenResolveResult.class.getName() + " getFreshTokenResolveResult() {");
sc.add("tokenResolveResult.clear();");
sc.add("return tokenResolveResult;");
sc.add("}");
sc.addLineBreak();
List<TokenDefinition> collectTokenDefinitions = collectCollectTokenDefinitions(conrceteSyntax.getTokens());
sc.add("protected void collectHiddenTokens(" + EObject.class.getName() + " element) {");
if (!collectTokenDefinitions.isEmpty()) {
//sc.add("System.out.println(\"collectHiddenTokens(\" + element.getClass().getSimpleName() + \", \" + o + \") \");");
sc.add("int currentPos = getTokenStream().index();");
sc.add("if (currentPos == 0) {");
sc.add("return;");
sc.add("}");
sc.add("int endPos = currentPos - 1;");
sc.add("for (; endPos >= lastPosition; endPos--) {");
sc.add(org.antlr.runtime.Token.class.getName() + " token = getTokenStream().get(endPos);");
sc.add("int _channel = token.getChannel();");
sc.add("if (_channel != 99) {");
sc.add("break;");
sc.add("}");
sc.add("}");
sc.add("for (int pos = lastPosition; pos < endPos; pos++) {");
sc.add(org.antlr.runtime.Token.class.getName() + " token = getTokenStream().get(pos);");
sc.add("int _channel = token.getChannel();");
sc.add("if (_channel == 99) {");
//sc.add("System.out.println(\"\t\" + token);");
for (TokenDefinition tokenDefinition : collectTokenDefinitions) {
String attributeName = tokenDefinition.getAttributeName();
// figure out which feature the token belongs to
sc.add("if (token.getType() == " + lexerName + "." + tokenDefinition.getName() + ") {");
// Unfortunately, we must use the feature name instead of the constant here,
// because collect-in tokens can be stored in arbitrary classes. Therefore,
// we do not know the EClass of the element at generation time.
sc.add(EStructuralFeature.class.getName() + " feature = element.eClass().getEStructuralFeature(\"" + attributeName + "\");");
sc.add("if (feature != null) {");
sc.add("// call token resolver");
String identifierPrefix = "resolved";
String resolverIdentifier = identifierPrefix + "Resolver";
String resolvedObjectIdentifier = identifierPrefix + "Object";
String resolveResultIdentifier = identifierPrefix + "Result";
sc.add(ITokenResolver.class.getName() + " " + resolverIdentifier +" = tokenResolverFactory.createCollectInTokenResolver(\"" + attributeName + "\");");
sc.add(resolverIdentifier +".setOptions(getOptions());");
sc.add(ITokenResolveResult.class.getName() + " " + resolveResultIdentifier + " = getFreshTokenResolveResult();");
sc.add(resolverIdentifier + ".resolve(token.getText(), feature, " + resolveResultIdentifier + ");");
sc.add("java.lang.Object " + resolvedObjectIdentifier + " = " + resolveResultIdentifier + ".getResolvedToken();");
sc.add("if (" + resolvedObjectIdentifier + " == null) {");
sc.add("getResource().addError(" + resolveResultIdentifier + ".getErrorMessage(), ((CommonToken) token).getLine(), ((CommonToken) token).getCharPositionInLine(), ((CommonToken) token).getStartIndex(), ((CommonToken) token).getStopIndex());\n");
sc.add("}");
sc.add("if (java.lang.String.class.isInstance(" + resolvedObjectIdentifier + ")) {");
sc.add("((java.util.List) element.eGet(feature)).add((String) " + resolvedObjectIdentifier + ");");
sc.add("} else {");
sc.add("System.out.println(\"WARNING: Attribute " + attributeName + " for token \" + token + \" has wrong type in element \" + element + \" (expected java.lang.String).\");");
sc.add("}");
sc.add("} else {");
sc.add("System.out.println(\"WARNING: Attribute " + attributeName + " for token \" + token + \" was not found in element \" + element + \".\");");
sc.add("}");
sc.add("}");
}
sc.add("}");
sc.add("}");
sc.add("lastPosition = (endPos < 0 ? 0 : endPos);");
}
sc.add("}");
sc.add("public void setReferenceResolverSwitch(" + context.getQualifiedReferenceResolverSwitchClassName() + " referenceResolverSwitch) {");
sc.add("this.referenceResolverSwitch = referenceResolverSwitch;");
sc.add("}");
sc.add("}");
sc.addLineBreak();
printStartRule(sc);
EList<GenClass> eClassesWithSyntax = new BasicEList<GenClass>();
Map<GenClass, Collection<Terminal>> eClassesReferenced = new LinkedHashMap<GenClass, Collection<Terminal>>();
printGrammarRules(sc, eClassesWithSyntax, eClassesReferenced);
printImplicitChoiceRules(sc, eClassesWithSyntax, eClassesReferenced);
printTokenDefinitions(sc);
pw.print(sc.toString());
return getCollectedErrors().size() == 0;
}
private List<TokenDefinition> collectCollectTokenDefinitions(List<TokenDefinition> tokenDefinitions){
List<TokenDefinition> collectList = new LinkedList<TokenDefinition>();
for(TokenDefinition tokenDefinition:tokenDefinitions){
String attributeName = tokenDefinition.getAttributeName();
if (attributeName != null) {
collectList.add(tokenDefinition);
}
}
return collectList;
}
private String getLexerName(String csName) {
return csName + "Lexer";
}
private void printStartRule(StringComposite sc){
//do the start symbol rule
sc.add("start ");
sc.add("returns [ EObject element = null]");
sc.add(":");
sc.add("(");
int count = 0;
for (Iterator<GenClass> i = conrceteSyntax.getActiveStartSymbols().iterator(); i.hasNext(); ) {
GenClass aStart = i.next();
sc.add("c" + count + " = " + getLowerCase(aStart.getName()) + "{ element = c" + count + "; }");
if (i.hasNext()) {
sc.add("| ");
}
count++;
}
sc.add(")");
if (forceEOFToken) {
sc.add(EOF_TOKEN_NAME);
}
sc.addLineBreak();
sc.add(";");
sc.addLineBreak();
}
private void printRightRecursion(StringComposite sc, Rule rule, EList<GenClass> eClassesWithSyntax, Map<GenClass, Collection<Terminal>> classesReferenced) {
String ruleName = rule.getMetaclass().getName();
GenClass recursiveType = rule.getMetaclass();
{
Copier copier = new Copier(true, true);
Rule ruleCopy = (Rule) copier.copy(rule);
copier.copyReferences();
sc.add(getLowerCase(ruleName));
sc.add(" returns [" + ruleName + " element = null]");
sc.add("@init{");
sc.add("element = " + getCreateObjectCall(recursiveType) + ";");
sc.add("collectHiddenTokens(element);");
sc.add("List<EObject> dummyEObjects = new ArrayList<EObject>();");
sc.add("}");
sc.add(":");
Choice choice = ConcretesyntaxPackage.eINSTANCE.getConcretesyntaxFactory().createChoice();
Sequence newSequence = ConcretesyntaxPackage.eINSTANCE.getConcretesyntaxFactory().createSequence();
Choice reducedChoice = ConcretesyntaxPackage.eINSTANCE.getConcretesyntaxFactory().createChoice();
CompoundDefinition compound = ConcretesyntaxPackage.eINSTANCE.getConcretesyntaxFactory().createCompoundDefinition();
compound.setDefinitions(reducedChoice);
newSequence.getParts().add(compound);
choice.getOptions().add(newSequence);
List<Sequence> recursionFreeSequences = new ArrayList<Sequence>();
LeftRecursionDetector lrd = new LeftRecursionDetector(genClassNames2superClassNames, conrceteSyntax);
for (Sequence sequence : ruleCopy.getDefinition().getOptions()) {
Rule leftProducingRule = lrd.findLeftProducingRule(rule.getMetaclass(), sequence, rule);
if (leftProducingRule == null) {
recursionFreeSequences.add(sequence);
}
}
reducedChoice.getOptions().addAll(recursionFreeSequences);
ruleCopy.setDefinition(choice);
printChoice(ruleCopy.getDefinition(), ruleCopy, sc, 0, classesReferenced);
sc.add(" ( dummyEObject = "+ getLowerCase(ruleName) + "_tail { dummyEObjects.add(dummyEObject);} )*");
sc.add("{");
sc.add("element = (" + ruleName+ ") apply(element, dummyEObjects);");
sc.add("}");
sc.add(";");
sc.addLineBreak();
}
{
Rule tailCopy = rule;
EList<Sequence> options = tailCopy.getDefinition().getOptions();
String recurseName = "";
List<Sequence> sequencesToRemove = new ArrayList<Sequence>();
for (Sequence sequence : options) {
int indexRecurse = 0;
EList<Definition> parts = sequence.getParts();
for (Definition definition : parts) {
if (definition instanceof Containment) {
Containment c = (Containment) definition;
GenClass featureType = c.getFeature().getTypeGenClass();
if (recursiveType.equals(featureType) ||
genClassNames2superClassNames.get(featureType.getQualifiedInterfaceName()).contains(recursiveType.getQualifiedInterfaceName()) ||
genClassNames2superClassNames.get(recursiveType.getQualifiedInterfaceName()).contains(featureType.getQualifiedInterfaceName())) {
indexRecurse = parts.indexOf(definition);
recurseName = c.getFeature().getName();
break;
}
}
}
if (parts.size()-1 == indexRecurse ) {
sequencesToRemove.add(sequence);
} else {
for (int i = 0; i <= indexRecurse; i++) {
parts.remove(i);
}
}
}
for (Sequence sequence : sequencesToRemove) {
tailCopy.getDefinition().getOptions().remove(sequence);
}
sc.add(getLowerCase(ruleName) + "_tail");
sc.add(" returns [DummyEObject element = null]");
sc.add("@init{");
sc.add("element = new DummyEObject(" + getCreateObjectCall(rule.getMetaclass()) + "()" +", \""+recurseName+"\");");
sc.add("collectHiddenTokens(element);");
sc.add("}");
sc.add(":");
printChoice(tailCopy.getDefinition(), tailCopy, sc, 0, classesReferenced);
sc.add(";");
sc.addLineBreak();
}
eClassesWithSyntax.add(rule.getMetaclass());
}
private String getCreateObjectCall(GenClass genClass) {
GenPackage genPackage = genClass.getGenPackage();
if (Map.Entry.class.getName().equals(genClass.getEcoreClass().getInstanceClassName())) {
return "new DummyEObject("+ genPackage.getQualifiedPackageClassName() + ".eINSTANCE.get" + genClass.getName()
+ "(),\"" + genClass.getName() + "\")";
} else {
return genPackage.getQualifiedFactoryInterfaceName() + ".eINSTANCE.create" + genClass.getName() + "()";
}
}
private void printGrammarRules(StringComposite sc, EList<GenClass> eClassesWithSyntax, Map<GenClass,Collection<Terminal>> eClassesReferenced) {
for(Rule rule : conrceteSyntax.getAllRules()) {
LeftRecursionDetector lrd = new LeftRecursionDetector(genClassNames2superClassNames, conrceteSyntax);
Rule recursionRule = lrd.findLeftRecursion(rule);
if (recursionRule != null) {
boolean autofix = OptionManager.INSTANCE.getBooleanOptionValue(conrceteSyntax, OptionTypes.AUTOFIX_SIMPLE_LEFTRECURSION);
if(lrd.isDirectLeftRecursive(rule)) {// direct left recursion
if (autofix) {
printRightRecursion(sc, rule, eClassesWithSyntax, eClassesReferenced);
Collection<GenClass> subClasses = GeneratorUtil.getSubClassesWithSyntax(rule.getMetaclass(), conrceteSyntax);
if(!subClasses.isEmpty()){
sc.add("|//derived choice rules for sub-classes: ");
printSubClassChoices(sc,subClasses);
sc.addLineBreak();
}
String message = "Applied experimental autofix: Rule \"" + rule.getMetaclass().getName() + "\" is direct left recursive by rule \"" + recursionRule.getMetaclass().getName() +
"\".";
GenerationProblem generationWarning = new GenerationProblem(message, rule, Severity.WARNING);
addProblem(generationWarning);
continue;
}
else {
String message = "Warning: Rule \"" + rule.getMetaclass().getName() + "\" is direct left recursive by rule \"" + recursionRule.getMetaclass().getName() + "\".";
GenerationProblem generationWarning = new GenerationProblem(message, rule, Severity.WARNING);
addProblem(generationWarning);
printGrammarRule(rule, sc, eClassesWithSyntax, eClassesReferenced);
}
}
else {
String message = "Rule \"" + rule.getMetaclass().getName() + "\" is mutual left recursive by rule \"" + recursionRule.getMetaclass().getName()+"\"! Please restructure the grammar.";
GenerationProblem generationWarning = new GenerationProblem(message, rule, Severity.WARNING);
addProblem(generationWarning);
printGrammarRule(rule, sc, eClassesWithSyntax, eClassesReferenced);
}
}
else {
printGrammarRule(rule, sc, eClassesWithSyntax, eClassesReferenced);
}
}
}
private void printGrammarRule(Rule rule, StringComposite sc, EList<GenClass> eClassesWithSyntax, Map<GenClass,Collection<Terminal>> eClassesReferenced) {
GenClass genClass = rule.getMetaclass();
String ruleName = genClass.getName();
String qualifiedClassName = genClass.getQualifiedInterfaceName();
sc.add(getLowerCase(ruleName));
if (Map.Entry.class.getName().equals(genClass.getEcoreClass().getInstanceClassName())) {
sc.add(" returns [DummyEObject element = null]");
} else {
sc.add(" returns [" + qualifiedClassName + " element = null]");
}
sc.add("@init{");
sc.add("}");
sc.add(":");
printChoice(rule.getDefinition(), rule, sc, 0, eClassesReferenced);
Collection<GenClass> subClasses = GeneratorUtil.getSubClassesWithSyntax(genClass, conrceteSyntax);
if(!subClasses.isEmpty()){
sc.add("|//derived choice rules for sub-classes: ");
sc.addLineBreak();
printSubClassChoices(sc,subClasses);
sc.addLineBreak();
}
sc.add(";");
sc.addLineBreak();
eClassesWithSyntax.add(genClass);
}
private int printChoice(Choice choice, Rule rule, StringComposite sc, int count,Map<GenClass,Collection<Terminal>> eClassesReferenced) {
Iterator<Sequence> it = choice.getOptions().iterator();
while(it.hasNext()){
Sequence seq = it.next();
count = printSequence(seq, rule, sc, count, eClassesReferenced);
if(it.hasNext()){
sc.addLineBreak();
sc.add("|");
}
}
return count;
}
private int printSequence(Sequence sequence, Rule rule, StringComposite sc, int count,Map<GenClass,Collection<Terminal>> eClassesReferenced) {
Iterator<Definition> it = sequence.getParts().iterator();
while(it.hasNext()){
Definition def = it.next();
if(def instanceof LineBreak || def instanceof WhiteSpaces)
continue;
String cardinality = computeCardinalityString(def);
if(cardinality!=null){
sc.add("(");
}
if(def instanceof CompoundDefinition){
CompoundDefinition compoundDef = (CompoundDefinition) def;
sc.add("(");
count = printChoice(compoundDef.getDefinitions(), rule,sc, count, eClassesReferenced);
sc.add(")");
}
else if(def instanceof CsString){
count = printCsString((CsString) def, rule, sc, count, eClassesReferenced);
}
else{
assert def instanceof Terminal;
count = printTerminal((Terminal) def, rule, sc, count, eClassesReferenced);
}
if(cardinality!=null){
sc.addLineBreak();
sc.add(")" + cardinality);
}
sc.addLineBreak();
}
return count;
}
private int printCsString(CsString csString, Rule rule, StringComposite sc, int count, Map<GenClass,Collection<Terminal>> eClassesReferenced){
final String identifier = "a" + count;
sc.add(identifier + " = '" + csString.getValue().replaceAll("'", "\\\\'") + "' {");
sc.add("if (element == null) {");
sc.add("element = " + getCreateObjectCall(rule.getMetaclass()) + ";");
sc.add("}");
sc.add("collectHiddenTokens(element);");
sc.add("copyLocalizationInfos((CommonToken)" + identifier + ", element);");
sc.add("}");
return ++count;
}
private int printTerminal(Terminal terminal, Rule rule, StringComposite sc, int count,Map<GenClass,Collection<Terminal>> eClassesReferenced){
final GenClass genClass = rule.getMetaclass();
final GenFeature genFeature = terminal.getFeature();
final EStructuralFeature eFeature = genFeature.getEcoreFeature();
final String ident = "a" + count;
final String proxyIdent = "proxy";
StringComposite resolvements = new ANTLRGrammarComposite();
sc.add("(");
if(terminal instanceof Containment){
assert ((EReference)eFeature).isContainment();
Containment containment = (Containment) terminal;
EList<GenClass> types;
//is there an explicit type defined?
if (!containment.getTypes().isEmpty()) {
types = containment.getTypes();
}
else {
types = new BasicEList<GenClass>();
types.add(genFeature.getTypeGenClass());
}
int internalCount = 0;
for(GenClass type : types) {
if (internalCount != 0) {
sc.add("|");
}
String internalIdent = ident + "_" + internalCount;
sc.add(internalIdent + " = " + getLowerCase(type.getName()));
if(!(genFeature.getEcoreFeature() instanceof EAttribute)){
//remember which classes are referenced to add choice rules for these classes later
if (!eClassesReferenced.keySet().contains(type)) {
eClassesReferenced.put(type, new HashSet<Terminal>());
}
eClassesReferenced.get(type).add(terminal);
}
printTerminalAction(terminal, rule, sc, genClass, genFeature,
eFeature, internalIdent, proxyIdent, internalIdent, resolvements);
internalCount++;
}
} else {
assert terminal instanceof Placeholder;
Placeholder placeholder = (Placeholder) terminal;
TokenDefinition token = placeholder.getToken();
String tokenName = token.getName();
sc.add(ident + " = " + tokenName);
sc.addLineBreak();
String targetTypeName = null;
String resolvedIdent = "resolved";
String preResolved = resolvedIdent + "Object";
String resolverIdent = "tokenResolver";
resolvements.add(ITokenResolver.class.getName() + " " +resolverIdent +" = tokenResolverFactory.createTokenResolver(\"" + tokenName + "\");");
resolvements.add(resolverIdent +".setOptions(getOptions());");
resolvements.add(ITokenResolveResult.class.getName() + " result = getFreshTokenResolveResult();");
resolvements.add(resolverIdent + ".resolve(" +ident+ ".getText(), element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + "), result);");
resolvements.add("Object " + preResolved + " = result.getResolvedToken();");
resolvements.add("if (" + preResolved + " == null) {");
resolvements.add("getResource().addError(result.getErrorMessage(), ((CommonToken) " + ident + ").getLine(), ((CommonToken) " + ident + ").getCharPositionInLine(), ((CommonToken) " + ident + ").getStartIndex(), ((CommonToken) " + ident + ").getStopIndex());");
resolvements.add("}");
String expressionToBeSet = null;
if (eFeature instanceof EReference) {
targetTypeName = "String";
expressionToBeSet = proxyIdent;
//a sub type that can be instantiated as a proxy
GenClass instanceType = genFeature.getTypeGenClass();
GenClass proxyType = null;
if (instanceType.isAbstract() || instanceType.isInterface()) {
for(GenClass instanceCand : allGenClasses) {
Collection<String> supertypes = genClassNames2superClassNames.get(instanceCand.getQualifiedInterfaceName());
if (!instanceCand.isAbstract() &&
!instanceCand.isInterface() &&
supertypes.contains(instanceType.getQualifiedInterfaceName())) {
proxyType = instanceCand;
break;
}
}
} else {
proxyType = instanceType;
}
resolvements.add(targetTypeName + " " + resolvedIdent + " = (" + targetTypeName + ") "+preResolved+";");
resolvements.add(proxyType.getQualifiedInterfaceName() + " " + expressionToBeSet + " = " + getCreateObjectCall(proxyType) + ";");
resolvements.add("collectHiddenTokens(element);");
resolvements.add("getResource().registerContextDependentProxy(new "+ ContextDependentURIFragmentFactory.class.getName() + "<" + genFeature.getGenClass().getQualifiedInterfaceName() + ", " + genFeature.getTypeGenClass().getQualifiedInterfaceName() + ">(" + context.getReferenceResolverAccessor("referenceResolverSwitch",genFeature) + "), element, (org.eclipse.emf.ecore.EReference) element.eClass().getEStructuralFeature(" + GeneratorUtil.getFeatureConstant(genClass, genFeature) + "), " + resolvedIdent + ", "+ proxyIdent + ");");
// remember that we must resolve proxy objects for this feature
context.addNonContainmentReference(genFeature);
}
else{
// the feature is an EAttribute
targetTypeName = genFeature.getQualifiedListItemType(null);
resolvements.add(targetTypeName + " " + resolvedIdent + " = (" + getObjectTypeName(targetTypeName) + ")" + preResolved + ";");
expressionToBeSet = "resolved";
}
printTerminalAction(terminal, rule, sc, genClass, genFeature,
eFeature, ident, proxyIdent, expressionToBeSet, resolvements);
}
sc.add(")");
return ++count;
}
private void printTerminalAction(Terminal terminal, Rule rule,
StringComposite sc, final GenClass genClass,
final GenFeature genFeature, final EStructuralFeature eFeature,
final String ident, final String proxyIdent,
String expressionToBeSet, StringComposite resolvements) {
sc.add("{");
sc.add("if (element == null) {");
sc.add("element = " + getCreateObjectCall(rule.getMetaclass()) + ";");
sc.add("}");
sc.add(resolvements);
sc.add("if (" + expressionToBeSet + " != null) {");
if (eFeature.getUpperBound() == 1) {
if (Map.Entry.class.getName().equals(eFeature.getEType().getInstanceClassName())) {
sc.add("addMapEntry(element, element.eClass().getEStructuralFeature("
+ GeneratorUtil.getFeatureConstant(genClass,
genFeature)
+ "), "
+ expressionToBeSet
+ ");");
} else {
sc.add("element.eSet(element.eClass().getEStructuralFeature("
+ GeneratorUtil.getFeatureConstant(genClass, genFeature)
+ "), " + expressionToBeSet + ");");
}
} else {
if (Map.Entry.class.getName().equals(eFeature.getEType().getInstanceClassName())) {
sc.add("addMapEntry(element, element.eClass().getEStructuralFeature("
+ GeneratorUtil.getFeatureConstant(genClass,
genFeature)
+ "), "
+ expressionToBeSet
+ ");");
} else {
sc.add("addObjectToList(element, "
+ GeneratorUtil.getFeatureConstant(genClass, genFeature)
+ ", " + expressionToBeSet + ");");
}
}
sc.add("}");
sc.add("collectHiddenTokens(element);");
if (terminal instanceof Containment) {
sc.add("copyLocalizationInfos(" + ident + ", element); ");
} else {
sc.add("copyLocalizationInfos((CommonToken) " + ident + ", element);");
if (eFeature instanceof EReference) {
//additionally set position information for the proxy instance
sc.add("copyLocalizationInfos((CommonToken) " + ident + ", " + proxyIdent + ");");
}
}
sc.add("}");
}
private void printImplicitChoiceRules(StringComposite sc, EList<GenClass> eClassesWithSyntax, Map<GenClass,Collection<Terminal>> eClassesReferenced){
for(GenClass referencedClass : eClassesReferenced.keySet()) {
if(!containsEqualByName(eClassesWithSyntax,referencedClass)) {
//rule not explicitly defined in CS: most likely a choice rule in the AS
Collection<GenClass> subClasses = GeneratorUtil.getSubClassesWithSyntax(referencedClass, conrceteSyntax);
if (!subClasses.isEmpty()) {
sc.add(getLowerCase(referencedClass.getName()));
sc.add(" returns [" + referencedClass.getQualifiedInterfaceName() + " element = null]");
sc.add(":");
printSubClassChoices(sc, subClasses);
sc.addLineBreak();
sc.add(";");
sc.addLineBreak();
eClassesWithSyntax.add(referencedClass);
}
}
}
}
private void printSubClassChoices(StringComposite sc, Collection<GenClass> subClasses){
int count = 0;
for(Iterator<GenClass> i = subClasses.iterator(); i.hasNext(); ) {
GenClass subRef = i.next();
sc.add("c" + count + " = " + getLowerCase(subRef.getName()) + "{ element = c" + count + "; }");
if (i.hasNext()) {
sc.add("|");
}
count++;
}
}
private boolean containsEqualByName(EList<GenClass> list, GenClass o){
for(GenClass entry:list){
EClass entryClass = entry.getEcoreClass();
EClass oClass = o.getEcoreClass();
if(entryClass.getName().equals(oClass.getName())&&entryClass.getEPackage().getNsURI().equals(oClass.getEPackage().getNsURI())){
return true;
}
}
return false;
}
private void printTokenDefinitions(StringComposite sc) {
for (TokenDefinition tokenDefinition : conrceteSyntax.getAllTokens()) {
printToken(tokenDefinition, sc);
}
}
private void printToken(TokenDefinition definition, StringComposite sc){
sc.add(definition.getName());
sc.add(":");
sc.add(definition.getRegex());
if (definition.isHidden()) {
sc.add("{ _channel = 99; }");
}
sc.add(";");
}
private void printDefaultImports(StringComposite sc){
sc.add("import " + org.eclipse.emf.ecore.EObject.class.getName() + ";");
sc.add("import " + org.eclipse.emf.ecore.InternalEObject.class.getName() + ";");
sc.add("import " + org.eclipse.emf.common.util.URI.class.getName() + ";");
sc.add("import " + AbstractEMFTextParser.class.getName() + ";");
sc.add("import " + IOptions.class.getName() + ";");
sc.add("import " + UnexpectedContentTypeException.class.getName() + ";");
sc.add("import " + EClass.class.getName() + ";");
}
private String computeCardinalityString(Definition definition){
Cardinality cardinality = null;
if (definition instanceof CardinalityDefinition) {
cardinality = ((CardinalityDefinition) definition).getCardinality();
}
if(cardinality==null)
return null;
else if(cardinality instanceof PLUS)
return "+";
else if(cardinality instanceof QUESTIONMARK)
return "?";
else
return "*";
}
}
| false | true | public boolean generate(PrintWriter pw){
initOptions();
initCaches();
String csName = getResourceClassName();
String lexerName = getLexerName(csName);
boolean backtracking = OptionManager.INSTANCE.getBooleanOptionValue(conrceteSyntax, OptionTypes.ANTLR_BACKTRACKING);
boolean memoize = OptionManager.INSTANCE.getBooleanOptionValue(conrceteSyntax, OptionTypes.ANTLR_MEMOIZE);
StringComposite sc = new ANTLRGrammarComposite();
sc.add("grammar " + csName + ";");
sc.addLineBreak();
sc.add("options {");
sc.add("superClass = " + AbstractEMFTextParser.class.getSimpleName() + ";");
sc.add("backtrack = " + backtracking + ";");
sc.add("memoize = " + memoize + ";");
sc.add("}");
sc.addLineBreak();
//the lexer: package def. and error handling
sc.add("@lexer::header {");
sc.add("package " + super.getResourcePackageName() + ";");
sc.add("}");
sc.addLineBreak();
sc.add("@lexer::members {");
sc.add("public " + java.util.List.class.getName() + "<" + RecognitionException.class.getName() + "> lexerExceptions = new " + java.util.ArrayList.class.getName() + "<" + RecognitionException.class.getName() + ">();");
sc.add("public " + java.util.List.class.getName() + "<" + Integer.class.getName() + "> lexerExceptionsPosition = new " + java.util.ArrayList.class.getName() + "<" + Integer.class.getName() + ">();");
sc.addLineBreak();
sc.add("public void reportError(" + RecognitionException.class.getName() + " e) {");
sc.add("lexerExceptions.add(e);");
sc.add("lexerExceptionsPosition.add(((" + ANTLRStringStream.class.getName() + ")input).index());");
sc.add("}");
sc.add("}");
//the parser: package def. and entry (doParse) method
sc.add("@header{");
sc.add("package " + super.getResourcePackageName() + ";");
sc.addLineBreak();
printDefaultImports(sc);
sc.add("}");
sc.addLineBreak();
sc.add("@members{");
sc.add("private " + ITokenResolverFactory.class.getName() + " tokenResolverFactory = new " + tokenResolverFactoryName +"();");
sc.add("private int lastPosition;");
sc.add("private " + TokenResolveResult.class.getName() + " tokenResolveResult = new " + TokenResolveResult.class.getName() + "();");
sc.add("private " + qualifiedReferenceResolverSwitchName + " referenceResolverSwitch;");
sc.addLineBreak();
sc.add("protected EObject doParse() throws RecognitionException {");
sc.add("lastPosition = 0;");
sc.add("((" + lexerName + ")getTokenStream().getTokenSource()).lexerExceptions = lexerExceptions;"); //required because the lexer class can not be subclassed
sc.add("((" + lexerName + ")getTokenStream().getTokenSource()).lexerExceptionsPosition = lexerExceptionsPosition;"); //required because the lexer class can not be subclassed
sc.add("Object typeObject = null;");
sc.add("Map<?,?> options = getOptions();");
sc.add("if (options != null) {");
sc.add("typeObject = options.get(IOptions.RESOURCE_CONTENT_TYPE);");
sc.add("}");
sc.add("if (typeObject == null) {");
sc.add("return start();");
sc.add("} else if (typeObject instanceof EClass) {");
sc.add("EClass type = (EClass)typeObject;");
for(Rule rule:conrceteSyntax.getAllRules()){
String qualifiedClassName = rule.getMetaclass().getQualifiedInterfaceName();
String ruleName = getLowerCase(rule.getMetaclass().getName());
sc.add("if (type.getInstanceClass() == " + qualifiedClassName +".class) {");
sc.add("return " + ruleName + "();");
sc.add("}");
}
sc.add("}");
sc.add("throw new " + UnexpectedContentTypeException.class.getName() + "(typeObject);");
sc.add("}");
sc.addLineBreak();
sc.add("@SuppressWarnings(\"unchecked\")");
sc.add("private boolean addObjectToList(" + EObject.class.getName() + " element, int featureID, " + Object.class.getName() + " proxy) {");
sc.add("return ((" + List.class.getName() + "<" + Object.class.getName() + ">) element.eGet(element.eClass().getEStructuralFeature(featureID))).add(proxy);");
sc.add("}");
sc.addLineBreak();
sc.add("private " + TokenResolveResult.class.getName() + " getFreshTokenResolveResult() {");
sc.add("tokenResolveResult.clear();");
sc.add("return tokenResolveResult;");
sc.add("}");
sc.addLineBreak();
List<TokenDefinition> collectTokenDefinitions = collectCollectTokenDefinitions(conrceteSyntax.getTokens());
sc.add("protected void collectHiddenTokens(" + EObject.class.getName() + " element) {");
if (!collectTokenDefinitions.isEmpty()) {
//sc.add("System.out.println(\"collectHiddenTokens(\" + element.getClass().getSimpleName() + \", \" + o + \") \");");
sc.add("int currentPos = getTokenStream().index();");
sc.add("if (currentPos == 0) {");
sc.add("return;");
sc.add("}");
sc.add("int endPos = currentPos - 1;");
sc.add("for (; endPos >= lastPosition; endPos--) {");
sc.add(org.antlr.runtime.Token.class.getName() + " token = getTokenStream().get(endPos);");
sc.add("int _channel = token.getChannel();");
sc.add("if (_channel != 99) {");
sc.add("break;");
sc.add("}");
sc.add("}");
sc.add("for (int pos = lastPosition; pos < endPos; pos++) {");
sc.add(org.antlr.runtime.Token.class.getName() + " token = getTokenStream().get(pos);");
sc.add("int _channel = token.getChannel();");
sc.add("if (_channel == 99) {");
//sc.add("System.out.println(\"\t\" + token);");
for (TokenDefinition tokenDefinition : collectTokenDefinitions) {
String attributeName = tokenDefinition.getAttributeName();
// figure out which feature the token belongs to
sc.add("if (token.getType() == " + lexerName + "." + tokenDefinition.getName() + ") {");
// Unfortunately, we must use the feature name instead of the constant here,
// because collect-in tokens can be stored in arbitrary classes. Therefore,
// we do not know the EClass of the element at generation time.
sc.add(EStructuralFeature.class.getName() + " feature = element.eClass().getEStructuralFeature(\"" + attributeName + "\");");
sc.add("if (feature != null) {");
sc.add("// call token resolver");
String identifierPrefix = "resolved";
String resolverIdentifier = identifierPrefix + "Resolver";
String resolvedObjectIdentifier = identifierPrefix + "Object";
String resolveResultIdentifier = identifierPrefix + "Result";
sc.add(ITokenResolver.class.getName() + " " + resolverIdentifier +" = tokenResolverFactory.createCollectInTokenResolver(\"" + attributeName + "\");");
sc.add(resolverIdentifier +".setOptions(getOptions());");
sc.add(ITokenResolveResult.class.getName() + " " + resolveResultIdentifier + " = getFreshTokenResolveResult();");
sc.add(resolverIdentifier + ".resolve(token.getText(), feature, " + resolveResultIdentifier + ");");
sc.add("java.lang.Object " + resolvedObjectIdentifier + " = " + resolveResultIdentifier + ".getResolvedToken();");
sc.add("if (" + resolvedObjectIdentifier + " == null) {");
sc.add("getResource().addError(" + resolveResultIdentifier + ".getErrorMessage(), ((CommonToken) token).getLine(), ((CommonToken) token).getCharPositionInLine(), ((CommonToken) token).getStartIndex(), ((CommonToken) token).getStopIndex());\n");
sc.add("}");
sc.add("if (java.lang.String.class.isInstance(" + resolvedObjectIdentifier + ")) {");
sc.add("((java.util.List) element.eGet(feature)).add((String) " + resolvedObjectIdentifier + ");");
sc.add("} else {");
sc.add("System.out.println(\"WARNING: Attribute " + attributeName + " for token \" + token + \" has wrong type in element \" + element + \" (expected java.lang.String).\");");
sc.add("}");
sc.add("} else {");
sc.add("System.out.println(\"WARNING: Attribute " + attributeName + " for token \" + token + \" was not found in element \" + element + \".\");");
sc.add("}");
sc.add("}");
}
sc.add("}");
sc.add("}");
sc.add("lastPosition = (endPos < 0 ? 0 : endPos);");
}
sc.add("}");
sc.add("public void setReferenceResolverSwitch(" + context.getQualifiedReferenceResolverSwitchClassName() + " referenceResolverSwitch) {");
sc.add("this.referenceResolverSwitch = referenceResolverSwitch;");
sc.add("}");
sc.add("}");
sc.addLineBreak();
printStartRule(sc);
EList<GenClass> eClassesWithSyntax = new BasicEList<GenClass>();
Map<GenClass, Collection<Terminal>> eClassesReferenced = new LinkedHashMap<GenClass, Collection<Terminal>>();
printGrammarRules(sc, eClassesWithSyntax, eClassesReferenced);
printImplicitChoiceRules(sc, eClassesWithSyntax, eClassesReferenced);
printTokenDefinitions(sc);
pw.print(sc.toString());
return getCollectedErrors().size() == 0;
}
| public boolean generate(PrintWriter pw){
initOptions();
initCaches();
String csName = getResourceClassName();
String lexerName = getLexerName(csName);
boolean backtracking = OptionManager.INSTANCE.getBooleanOptionValue(conrceteSyntax, OptionTypes.ANTLR_BACKTRACKING);
boolean memoize = OptionManager.INSTANCE.getBooleanOptionValue(conrceteSyntax, OptionTypes.ANTLR_MEMOIZE);
StringComposite sc = new ANTLRGrammarComposite();
sc.add("grammar " + csName + ";");
sc.addLineBreak();
sc.add("options {");
sc.add("superClass = " + AbstractEMFTextParser.class.getSimpleName() + ";");
sc.add("backtrack = " + backtracking + ";");
sc.add("memoize = " + memoize + ";");
sc.add("}");
sc.addLineBreak();
//the lexer: package definition and error handling
sc.add("@lexer::header {");
sc.add("package " + super.getResourcePackageName() + ";");
sc.add("}");
sc.addLineBreak();
sc.add("@lexer::members {");
sc.add("public " + java.util.List.class.getName() + "<" + RecognitionException.class.getName() + "> lexerExceptions = new " + java.util.ArrayList.class.getName() + "<" + RecognitionException.class.getName() + ">();");
sc.add("public " + java.util.List.class.getName() + "<" + Integer.class.getName() + "> lexerExceptionsPosition = new " + java.util.ArrayList.class.getName() + "<" + Integer.class.getName() + ">();");
sc.addLineBreak();
sc.add("public void reportError(" + RecognitionException.class.getName() + " e) {");
sc.add("lexerExceptions.add(e);");
sc.add("lexerExceptionsPosition.add(((" + ANTLRStringStream.class.getName() + ")input).index());");
sc.add("}");
sc.add("}");
//the parser: package definition and entry (doParse) method
sc.add("@header{");
sc.add("package " + super.getResourcePackageName() + ";");
sc.addLineBreak();
printDefaultImports(sc);
sc.add("}");
sc.addLineBreak();
sc.add("@members{");
sc.add("private " + ITokenResolverFactory.class.getName() + " tokenResolverFactory = new " + tokenResolverFactoryName +"();");
sc.add("private int lastPosition;");
sc.add("private " + TokenResolveResult.class.getName() + " tokenResolveResult = new " + TokenResolveResult.class.getName() + "();");
sc.add("private " + qualifiedReferenceResolverSwitchName + " referenceResolverSwitch;");
sc.addLineBreak();
sc.add("protected EObject doParse() throws RecognitionException {");
sc.add("lastPosition = 0;");
sc.add("((" + lexerName + ")getTokenStream().getTokenSource()).lexerExceptions = lexerExceptions;"); //required because the lexer class can not be subclassed
sc.add("((" + lexerName + ")getTokenStream().getTokenSource()).lexerExceptionsPosition = lexerExceptionsPosition;"); //required because the lexer class can not be subclassed
sc.add("Object typeObject = null;");
sc.add("Map<?,?> options = getOptions();");
sc.add("if (options != null) {");
sc.add("typeObject = options.get(IOptions.RESOURCE_CONTENT_TYPE);");
sc.add("}");
sc.add("if (typeObject == null) {");
sc.add("return start();");
sc.add("} else if (typeObject instanceof EClass) {");
sc.add("EClass type = (EClass)typeObject;");
for(Rule rule:conrceteSyntax.getAllRules()){
String qualifiedClassName = rule.getMetaclass().getQualifiedInterfaceName();
String ruleName = getLowerCase(rule.getMetaclass().getName());
sc.add("if (type.getInstanceClass() == " + qualifiedClassName +".class) {");
sc.add("return " + ruleName + "();");
sc.add("}");
}
sc.add("}");
sc.add("throw new " + UnexpectedContentTypeException.class.getName() + "(typeObject);");
sc.add("}");
sc.addLineBreak();
sc.add("@SuppressWarnings(\"unchecked\")");
sc.add("private boolean addObjectToList(" + EObject.class.getName() + " element, int featureID, " + Object.class.getName() + " proxy) {");
sc.add("return ((" + List.class.getName() + "<" + Object.class.getName() + ">) element.eGet(element.eClass().getEStructuralFeature(featureID))).add(proxy);");
sc.add("}");
sc.addLineBreak();
sc.add("private " + TokenResolveResult.class.getName() + " getFreshTokenResolveResult() {");
sc.add("tokenResolveResult.clear();");
sc.add("return tokenResolveResult;");
sc.add("}");
sc.addLineBreak();
List<TokenDefinition> collectTokenDefinitions = collectCollectTokenDefinitions(conrceteSyntax.getTokens());
sc.add("protected void collectHiddenTokens(" + EObject.class.getName() + " element) {");
if (!collectTokenDefinitions.isEmpty()) {
//sc.add("System.out.println(\"collectHiddenTokens(\" + element.getClass().getSimpleName() + \", \" + o + \") \");");
sc.add("int currentPos = getTokenStream().index();");
sc.add("if (currentPos == 0) {");
sc.add("return;");
sc.add("}");
sc.add("int endPos = currentPos - 1;");
sc.add("for (; endPos >= lastPosition; endPos--) {");
sc.add(org.antlr.runtime.Token.class.getName() + " token = getTokenStream().get(endPos);");
sc.add("int _channel = token.getChannel();");
sc.add("if (_channel != 99) {");
sc.add("break;");
sc.add("}");
sc.add("}");
sc.add("for (int pos = lastPosition; pos < endPos; pos++) {");
sc.add(org.antlr.runtime.Token.class.getName() + " token = getTokenStream().get(pos);");
sc.add("int _channel = token.getChannel();");
sc.add("if (_channel == 99) {");
//sc.add("System.out.println(\"\t\" + token);");
for (TokenDefinition tokenDefinition : collectTokenDefinitions) {
String attributeName = tokenDefinition.getAttributeName();
// figure out which feature the token belongs to
sc.add("if (token.getType() == " + lexerName + "." + tokenDefinition.getName() + ") {");
// Unfortunately, we must use the feature name instead of the constant here,
// because collect-in tokens can be stored in arbitrary classes. Therefore,
// we do not know the EClass of the element at generation time.
sc.add(EStructuralFeature.class.getName() + " feature = element.eClass().getEStructuralFeature(\"" + attributeName + "\");");
sc.add("if (feature != null) {");
sc.add("// call token resolver");
String identifierPrefix = "resolved";
String resolverIdentifier = identifierPrefix + "Resolver";
String resolvedObjectIdentifier = identifierPrefix + "Object";
String resolveResultIdentifier = identifierPrefix + "Result";
sc.add(ITokenResolver.class.getName() + " " + resolverIdentifier +" = tokenResolverFactory.createCollectInTokenResolver(\"" + attributeName + "\");");
sc.add(resolverIdentifier +".setOptions(getOptions());");
sc.add(ITokenResolveResult.class.getName() + " " + resolveResultIdentifier + " = getFreshTokenResolveResult();");
sc.add(resolverIdentifier + ".resolve(token.getText(), feature, " + resolveResultIdentifier + ");");
sc.add("java.lang.Object " + resolvedObjectIdentifier + " = " + resolveResultIdentifier + ".getResolvedToken();");
sc.add("if (" + resolvedObjectIdentifier + " == null) {");
sc.add("getResource().addError(" + resolveResultIdentifier + ".getErrorMessage(), ((CommonToken) token).getLine(), ((CommonToken) token).getCharPositionInLine(), ((CommonToken) token).getStartIndex(), ((CommonToken) token).getStopIndex());\n");
sc.add("}");
sc.add("if (java.lang.String.class.isInstance(" + resolvedObjectIdentifier + ")) {");
sc.add("((java.util.List) element.eGet(feature)).add((String) " + resolvedObjectIdentifier + ");");
sc.add("} else {");
sc.add("System.out.println(\"WARNING: Attribute " + attributeName + " for token \" + token + \" has wrong type in element \" + element + \" (expected java.lang.String).\");");
sc.add("}");
sc.add("} else {");
sc.add("System.out.println(\"WARNING: Attribute " + attributeName + " for token \" + token + \" was not found in element \" + element + \".\");");
sc.add("}");
sc.add("}");
}
sc.add("}");
sc.add("}");
sc.add("lastPosition = (endPos < 0 ? 0 : endPos);");
}
sc.add("}");
sc.add("public void setReferenceResolverSwitch(" + context.getQualifiedReferenceResolverSwitchClassName() + " referenceResolverSwitch) {");
sc.add("this.referenceResolverSwitch = referenceResolverSwitch;");
sc.add("}");
sc.add("}");
sc.addLineBreak();
printStartRule(sc);
EList<GenClass> eClassesWithSyntax = new BasicEList<GenClass>();
Map<GenClass, Collection<Terminal>> eClassesReferenced = new LinkedHashMap<GenClass, Collection<Terminal>>();
printGrammarRules(sc, eClassesWithSyntax, eClassesReferenced);
printImplicitChoiceRules(sc, eClassesWithSyntax, eClassesReferenced);
printTokenDefinitions(sc);
pw.print(sc.toString());
return getCollectedErrors().size() == 0;
}
|
diff --git a/src/main/java/com/voxbone/kelpie/CallSession.java b/src/main/java/com/voxbone/kelpie/CallSession.java
index 2c8b3c3..9610352 100755
--- a/src/main/java/com/voxbone/kelpie/CallSession.java
+++ b/src/main/java/com/voxbone/kelpie/CallSession.java
@@ -1,589 +1,589 @@
/**
* Copyright 2012 Voxbone SA/NV
*
* 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.voxbone.kelpie;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.Vector;
import javax.sdp.Attribute;
import javax.sdp.MediaDescription;
import javax.sdp.SdpException;
import javax.sdp.SdpFactory;
import javax.sdp.SdpParseException;
import javax.sdp.SessionDescription;
import javax.sdp.Time;
import javax.sip.ClientTransaction;
import javax.sip.Dialog;
import javax.sip.ServerTransaction;
import javax.sip.message.Message;
import org.apache.log4j.Logger;
import org.jabberstudio.jso.JID;
import org.jabberstudio.jso.NSI;
import org.jabberstudio.jso.Packet;
import org.jabberstudio.jso.StreamElement;
/**
*
* Represents a call, contains the information for the Jingle as well as the sip side of the call
*
*/
public class CallSession
{
private static LinkedList<Payload> supported = new LinkedList<Payload>();
public static Payload PAYLOAD_SPEEX = new Payload(99, "speex", 16000, 22000);
public static Payload PAYLOAD_SPEEX2 = new Payload(98, "speex", 8000, 11000);
public static Payload PAYLOAD_PCMU = new Payload(0, "PCMU", 8000, 64000);
public static Payload PAYLOAD_PCMA = new Payload(8, "PCMA", 8000, 64000);
public static Payload PAYLOAD_G723 = new Payload(4, "G723", 8000, 6300);
public static VPayload PAYLOAD_H263 = new VPayload(34, "H263", 90000, 512000, 320, 200, 15);
public static VPayload PAYLOAD_H264 = new VPayload(97, "H264", 90000, 512000, 640, 480, 15);
public static VPayload PAYLOAD_H264SVC = new VPayload(96, "H264-SVC", 90000, 512000, 640, 480, 15);
static
{
supported.add(PAYLOAD_SPEEX);
supported.add(PAYLOAD_SPEEX2);
supported.add(PAYLOAD_PCMU);
supported.add(PAYLOAD_PCMA);
supported.add(PAYLOAD_G723);
supported.add(PAYLOAD_H264);
supported.add(PAYLOAD_H263);
supported.add(PAYLOAD_H264SVC);
}
public static class Payload
{
int id;
String name;
int clockRate;
int bitRate;
public Payload(int id, String name, int clockRate, int bitRate)
{
this.id = id;
this.name = name;
this.clockRate = clockRate;
this.bitRate = bitRate;
}
}
public static class VPayload extends Payload
{
int width;
int height;
int framerate;
public VPayload(int id, String name, int clockRate, int bitRate, int width, int height, int framerate)
{
super(id, name, clockRate, bitRate);
this.width = width;
this.height = height;
this.framerate = framerate;
}
}
String jabberSessionId;
JID jabberRemote;
JID jabberLocal;
String jabberInitiator;
String candidateUser;
String candidateVUser;
boolean sentTransport = false;
boolean sentVTransport = false;
boolean callAccepted = false;
Dialog sipDialog;
ServerTransaction inviteTransaction;
ClientTransaction inviteOutTransaction;
public RtpRelay relay;
public RtpRelay vRelay;
LinkedList<Payload> offerPayloads = new LinkedList<Payload>();
LinkedList<Payload> answerPayloads = new LinkedList<Payload>();
LinkedList<VPayload> offerVPayloads = new LinkedList<VPayload>();
LinkedList<VPayload> answerVPayloads = new LinkedList<VPayload>();
Logger logger = Logger.getLogger(this.getClass());
private static int nextInternalCallId = 0;
public String internalCallId;
public CallSession()
{
internalCallId = "CS" + String.format("%08x", nextInternalCallId++);
try
{
relay = new RtpRelay(this, false);
}
catch (IOException e)
{
logger.error("Can't setup rtp relay", e);
}
}
private boolean isSupportedPayload(Payload payload)
{
for (Payload p : supported)
{
if (p.name.equalsIgnoreCase(payload.name) && payload.clockRate == p.clockRate)
{
return true;
}
}
return false;
}
public Payload getByName(String name, int clockRate)
{
for (Payload p : supported)
{
if (p.name.equalsIgnoreCase(name) && p.clockRate == clockRate)
{
return p;
}
}
return null;
}
public Payload getByName(String name)
{
for (Payload p : supported)
{
if (p instanceof VPayload)
{
VPayload vp = (VPayload) p;
if (p.name.equalsIgnoreCase(name))
{
return vp;
}
}
}
return null;
}
public Payload getById(int id)
{
for (Payload p : supported)
{
if (p.id == id)
{
return p;
}
}
return null;
}
public void parseInitiate(Packet p)
{
StreamElement session = p.getFirstElement(new NSI("session", "http://www.google.com/session"));
jabberSessionId = session.getID();
jabberRemote = p.getFrom();
jabberLocal = p.getTo();
jabberInitiator = session.getAttributeValue("initiator");
parseSession(session, true);
}
public void parseAccept(Packet p)
{
StreamElement session = p.getFirstElement();
parseSession(session, false);
}
private void parseSession(StreamElement session, boolean offer)
{
StreamElement description = session.getFirstElement("description");
if (description.getNamespaceURI().equals("http://www.google.com/session/video"))
{
logger.info("[[" + internalCallId + "]] Video call detected, enabling video rtp stream");
if (vRelay == null)
{
try
{
vRelay = new RtpRelay(this, true);
}
catch (IOException e)
{
logger.error("Can't setup video rtp relay", e);
}
}
}
for (Object opt : description.listElements())
{
StreamElement pt = (StreamElement) opt;
if (pt.getNamespaceURI().equals("http://www.google.com/session/video") && pt.getLocalName().equals("payload-type"))
{
try
{
int id = Integer.parseInt(pt.getAttributeValue("id"));
String name = pt.getAttributeValue("name");
// int width = Integer.parseInt(pt.getAttributeValue("width"));
// int height = Integer.parseInt(pt.getAttributeValue("height"));
//int framerate = Integer.parseInt(pt.getAttributeValue("framerate"));
Payload p = getByName(name);
if (p != null && p instanceof VPayload)
{
VPayload tmp = (VPayload) p;
// save the rtp map id, but load in our offical config....
VPayload vp = new VPayload(id, tmp.name, tmp.clockRate, tmp.bitRate, tmp.width, tmp.height, tmp.framerate);
if (offer)
{
offerVPayloads.add(vp);
}
else
{
answerVPayloads.add(vp);
}
}
}
catch (NumberFormatException e)
{
// ignore tags we don't understand (but write full log, in case we need to investigate)
logger.warn("[[" + internalCallId + "]] failed to parse tag in session : ", e);
logger.debug("[[" + internalCallId + "]] NumberFormatException -> session contents : " + session.toString());
logger.debug("[[" + internalCallId + "]] NumberFormatException -> description item contents : " + pt.toString());
}
}
else if(pt.getNamespaceURI().equals("http://www.google.com/session/phone") && pt.getLocalName().equals("payload-type"))
{
try
{
int id = Integer.parseInt(pt.getAttributeValue("id"));
String name = pt.getAttributeValue("name");
int clockrate = 0;
if (pt.getAttributeValue("clockrate") != null) {
clockrate = Integer.parseInt(pt.getAttributeValue("clockrate"));
}
int bitrate = 0;
if (pt.getAttributeValue("bitrate") != null)
{
bitrate = Integer.parseInt(pt.getAttributeValue("bitrate"));
}
Payload payload = new Payload(id, name, clockrate, bitrate);
if (isSupportedPayload(payload))
{
if (offer)
{
offerPayloads.add(payload);
}
else
{
answerPayloads.add(payload);
}
}
}
catch (NumberFormatException e)
{
// ignore tags we don't understand (but write full log, in case we need to investigate)
logger.warn("[[" + internalCallId + "]] failed to parse tag in session : ", e);
logger.debug("[[" + internalCallId + "]] NumberFormatException -> session contents : " + session.toString());
logger.debug("[[" + internalCallId + "]] NumberFormatException -> description item contents : " + pt.toString());
}
}
}
}
public SessionDescription buildSDP(boolean offer)
{
SdpFactory sdpFactory = SdpFactory.getInstance();
try
{
SessionDescription sd = sdpFactory.createSessionDescription();
sd.setVersion(sdpFactory.createVersion(0));
long ntpts = SdpFactory.getNtpTime(new Date());
sd.setOrigin(sdpFactory.createOrigin("JabberGW", ntpts, ntpts, "IN", "IP4", SipService.getLocalIP()));
sd.setSessionName(sdpFactory.createSessionName("Jabber Call"));
Vector<Time> times = new Vector<Time>();
times.add(sdpFactory.createTime());
sd.setTimeDescriptions(times);
sd.setConnection(sdpFactory.createConnection(SipService.getLocalIP()));
int [] formats;
Vector<Attribute> attributes = new Vector<Attribute>();
if (offer)
{
formats = new int[offerPayloads.size() + 1];
int i = 0;
for (Payload p : offerPayloads)
{
formats[i++] = p.id;
attributes.add(sdpFactory.createAttribute("rtpmap", Integer.toString(p.id) + " " + p.name + "/" + p.clockRate));
}
}
else
{
formats = new int[answerPayloads.size() + 1];
int i = 0;
for (Payload p : answerPayloads)
{
formats[i++] = p.id;
attributes.add(sdpFactory.createAttribute("rtpmap", Integer.toString(p.id) + " " + p.name + "/" + p.clockRate));
}
}
formats[formats.length - 1] = 101;
attributes.add(sdpFactory.createAttribute("rtpmap", "101 telephone-event/8000"));
attributes.add(sdpFactory.createAttribute("fmtp", "101 0-15"));
MediaDescription md = sdpFactory.createMediaDescription("audio", this.relay.getSipPort(), 1, "RTP/AVP", formats);
md.setAttributes(attributes);
Vector<MediaDescription> mds = new Vector<MediaDescription>();
mds.add(md);
if (vRelay != null)
{
// video call, add video m-line
attributes = new Vector<Attribute>();
if (offer)
{
formats = new int[offerVPayloads.size()];
int i = 0;
for (Payload p : offerVPayloads)
{
formats[i++] = p.id;
attributes.add(sdpFactory.createAttribute("rtpmap", Integer.toString(p.id) + " " + p.name + "/" + p.clockRate));
attributes.add(sdpFactory.createAttribute("fmtp", Integer.toString(p.id) + " packetization-rate=1"));
}
}
else
{
formats = new int[answerVPayloads.size()];
int i = 0;
for (Payload p : answerVPayloads)
{
formats[i++] = p.id;
attributes.add(sdpFactory.createAttribute("rtpmap", Integer.toString(p.id) + " " + p.name + "/" + p.clockRate));
attributes.add(sdpFactory.createAttribute("fmtp", Integer.toString(p.id) + " packetization-rate=1"));
}
}
attributes.add(sdpFactory.createAttribute("framerate", "30"));
attributes.add(sdpFactory.createAttribute("rtcp", Integer.toString(this.vRelay.getSipRtcpPort())));
md.setBandwidth("AS", 960);
md = sdpFactory.createMediaDescription("video", this.vRelay.getSipPort(), 1, "RTP/AVP", formats);
md.setAttributes(attributes);
mds.add(md);
}
sd.setMediaDescriptions(mds);
return sd;
}
catch (SdpException e)
{
logger.error("Error building SDP", e);
}
return null;
}
public void parseSDP(String sdp, boolean offer)
{
SdpFactory sdpFactory = SdpFactory.getInstance();
try
{
SessionDescription sd = sdpFactory.createSessionDescription(sdp);
@SuppressWarnings("unchecked")
Vector<MediaDescription> mdesc = (Vector<MediaDescription>) sd.getMediaDescriptions(false);
for (MediaDescription md : mdesc)
{
javax.sdp.Media media = md.getMedia();
- if (media.getMediaType().equals("video"))
+ if (media.getMediaType().equals("video") && media.getMediaPort() != 0 )
{
logger.info("[[" + internalCallId + "]] Video sdp detected! starting video rtp stream...");
if (vRelay == null)
{
try
{
vRelay = new RtpRelay(this, true);
}
catch (IOException e)
{
logger.error("unable to create video relay!", e);
}
}
int remotePort = media.getMediaPort();
String remoteParty = null;
if (md.getConnection() != null)
{
remoteParty = md.getConnection().getAddress();
}
else
{
remoteParty = sd.getConnection().getAddress();
}
vRelay.setSipDest(remoteParty, remotePort);
@SuppressWarnings("unchecked")
Vector<Attribute> attributes = (Vector<Attribute>) md.getAttributes(false);
for (Attribute attrib : attributes)
{
if (attrib.getName().equals("rtpmap"))
{
logger.debug("[[" + internalCallId + "]] Got attribute value " + attrib.getValue());
String fields[] = attrib.getValue().split(" ", 2);
int codec = Integer.parseInt(fields[0]);
String name = fields[1].split("/")[0];
int clockRate = Integer.parseInt(fields[1].split("/")[1]);
logger.debug("[[" + internalCallId + "]] Payload " + codec + " rate " + clockRate + " is mapped to " + name);
if (codec >= 96)
{
Payload bitRatePayload = getByName(name, clockRate);
if (bitRatePayload != null && bitRatePayload instanceof VPayload)
{
VPayload tmp = (VPayload) bitRatePayload;
VPayload p = new VPayload(codec, tmp.name, clockRate, tmp.bitRate, tmp.width, tmp.height, tmp.framerate);
if (offer)
{
offerVPayloads.add(p);
}
else
{
answerVPayloads.add(p);
}
}
}
}
}
}
else
{
int remotePort = media.getMediaPort();
String remoteParty = null;
if (md.getConnection() != null)
{
remoteParty = md.getConnection().getAddress();
}
else
{
remoteParty = sd.getConnection().getAddress();
}
relay.setSipDest(remoteParty, remotePort);
@SuppressWarnings("unchecked")
Vector<String> codecs = (Vector<String>) media.getMediaFormats(false);
for (String codec : codecs)
{
int id = Integer.parseInt(codec);
logger.debug("[[" + internalCallId + "]] Got a codec " + id);
if (id < 97)
{
Payload p = getById(id);
if (p != null)
{
if (offer)
{
offerPayloads.add(p);
}
else
{
answerPayloads.add(p);
}
}
}
}
@SuppressWarnings("unchecked")
Vector<Attribute> attributes = (Vector<Attribute>) md.getAttributes(false);
for (Attribute attrib : attributes)
{
if (attrib.getName().equals("rtpmap"))
{
logger.debug("[[" + internalCallId + "]] Got attribute value " + attrib.getValue());
String fields[] = attrib.getValue().split(" ", 2);
int codec = Integer.parseInt(fields[0]);
String name = fields[1].split("/")[0];
int clockRate = Integer.parseInt(fields[1].split("/")[1]);
logger.debug("[[" + internalCallId + "]] Payload " + codec + " rate " + clockRate + " is mapped to " + name);
if (codec >= 96)
{
Payload bitRatePayload = getByName(name, clockRate);
if (bitRatePayload != null)
{
Payload p = new Payload(codec, name, clockRate, bitRatePayload.bitRate);
if (offer)
{
offerPayloads.add(p);
}
else
{
answerPayloads.add(p);
}
}
}
}
}
}
}
}
catch (SdpParseException e)
{
logger.error("Unable to parse SDP!", e);
}
catch (SdpException e)
{
logger.error("Unable to parse SDP!", e);
}
}
public void parseInvite(Message message, Dialog d, ServerTransaction trans)
{
sipDialog = d;
inviteTransaction = trans;
parseSDP(new String(message.getRawContent()), true);
}
}
| true | true | public void parseSDP(String sdp, boolean offer)
{
SdpFactory sdpFactory = SdpFactory.getInstance();
try
{
SessionDescription sd = sdpFactory.createSessionDescription(sdp);
@SuppressWarnings("unchecked")
Vector<MediaDescription> mdesc = (Vector<MediaDescription>) sd.getMediaDescriptions(false);
for (MediaDescription md : mdesc)
{
javax.sdp.Media media = md.getMedia();
if (media.getMediaType().equals("video"))
{
logger.info("[[" + internalCallId + "]] Video sdp detected! starting video rtp stream...");
if (vRelay == null)
{
try
{
vRelay = new RtpRelay(this, true);
}
catch (IOException e)
{
logger.error("unable to create video relay!", e);
}
}
int remotePort = media.getMediaPort();
String remoteParty = null;
if (md.getConnection() != null)
{
remoteParty = md.getConnection().getAddress();
}
else
{
remoteParty = sd.getConnection().getAddress();
}
vRelay.setSipDest(remoteParty, remotePort);
@SuppressWarnings("unchecked")
Vector<Attribute> attributes = (Vector<Attribute>) md.getAttributes(false);
for (Attribute attrib : attributes)
{
if (attrib.getName().equals("rtpmap"))
{
logger.debug("[[" + internalCallId + "]] Got attribute value " + attrib.getValue());
String fields[] = attrib.getValue().split(" ", 2);
int codec = Integer.parseInt(fields[0]);
String name = fields[1].split("/")[0];
int clockRate = Integer.parseInt(fields[1].split("/")[1]);
logger.debug("[[" + internalCallId + "]] Payload " + codec + " rate " + clockRate + " is mapped to " + name);
if (codec >= 96)
{
Payload bitRatePayload = getByName(name, clockRate);
if (bitRatePayload != null && bitRatePayload instanceof VPayload)
{
VPayload tmp = (VPayload) bitRatePayload;
VPayload p = new VPayload(codec, tmp.name, clockRate, tmp.bitRate, tmp.width, tmp.height, tmp.framerate);
if (offer)
{
offerVPayloads.add(p);
}
else
{
answerVPayloads.add(p);
}
}
}
}
}
}
else
{
int remotePort = media.getMediaPort();
String remoteParty = null;
if (md.getConnection() != null)
{
remoteParty = md.getConnection().getAddress();
}
else
{
remoteParty = sd.getConnection().getAddress();
}
relay.setSipDest(remoteParty, remotePort);
@SuppressWarnings("unchecked")
Vector<String> codecs = (Vector<String>) media.getMediaFormats(false);
for (String codec : codecs)
{
int id = Integer.parseInt(codec);
logger.debug("[[" + internalCallId + "]] Got a codec " + id);
if (id < 97)
{
Payload p = getById(id);
if (p != null)
{
if (offer)
{
offerPayloads.add(p);
}
else
{
answerPayloads.add(p);
}
}
}
}
@SuppressWarnings("unchecked")
Vector<Attribute> attributes = (Vector<Attribute>) md.getAttributes(false);
for (Attribute attrib : attributes)
{
if (attrib.getName().equals("rtpmap"))
{
logger.debug("[[" + internalCallId + "]] Got attribute value " + attrib.getValue());
String fields[] = attrib.getValue().split(" ", 2);
int codec = Integer.parseInt(fields[0]);
String name = fields[1].split("/")[0];
int clockRate = Integer.parseInt(fields[1].split("/")[1]);
logger.debug("[[" + internalCallId + "]] Payload " + codec + " rate " + clockRate + " is mapped to " + name);
if (codec >= 96)
{
Payload bitRatePayload = getByName(name, clockRate);
if (bitRatePayload != null)
{
Payload p = new Payload(codec, name, clockRate, bitRatePayload.bitRate);
if (offer)
{
offerPayloads.add(p);
}
else
{
answerPayloads.add(p);
}
}
}
}
}
}
}
}
catch (SdpParseException e)
{
logger.error("Unable to parse SDP!", e);
}
catch (SdpException e)
{
logger.error("Unable to parse SDP!", e);
}
}
| public void parseSDP(String sdp, boolean offer)
{
SdpFactory sdpFactory = SdpFactory.getInstance();
try
{
SessionDescription sd = sdpFactory.createSessionDescription(sdp);
@SuppressWarnings("unchecked")
Vector<MediaDescription> mdesc = (Vector<MediaDescription>) sd.getMediaDescriptions(false);
for (MediaDescription md : mdesc)
{
javax.sdp.Media media = md.getMedia();
if (media.getMediaType().equals("video") && media.getMediaPort() != 0 )
{
logger.info("[[" + internalCallId + "]] Video sdp detected! starting video rtp stream...");
if (vRelay == null)
{
try
{
vRelay = new RtpRelay(this, true);
}
catch (IOException e)
{
logger.error("unable to create video relay!", e);
}
}
int remotePort = media.getMediaPort();
String remoteParty = null;
if (md.getConnection() != null)
{
remoteParty = md.getConnection().getAddress();
}
else
{
remoteParty = sd.getConnection().getAddress();
}
vRelay.setSipDest(remoteParty, remotePort);
@SuppressWarnings("unchecked")
Vector<Attribute> attributes = (Vector<Attribute>) md.getAttributes(false);
for (Attribute attrib : attributes)
{
if (attrib.getName().equals("rtpmap"))
{
logger.debug("[[" + internalCallId + "]] Got attribute value " + attrib.getValue());
String fields[] = attrib.getValue().split(" ", 2);
int codec = Integer.parseInt(fields[0]);
String name = fields[1].split("/")[0];
int clockRate = Integer.parseInt(fields[1].split("/")[1]);
logger.debug("[[" + internalCallId + "]] Payload " + codec + " rate " + clockRate + " is mapped to " + name);
if (codec >= 96)
{
Payload bitRatePayload = getByName(name, clockRate);
if (bitRatePayload != null && bitRatePayload instanceof VPayload)
{
VPayload tmp = (VPayload) bitRatePayload;
VPayload p = new VPayload(codec, tmp.name, clockRate, tmp.bitRate, tmp.width, tmp.height, tmp.framerate);
if (offer)
{
offerVPayloads.add(p);
}
else
{
answerVPayloads.add(p);
}
}
}
}
}
}
else
{
int remotePort = media.getMediaPort();
String remoteParty = null;
if (md.getConnection() != null)
{
remoteParty = md.getConnection().getAddress();
}
else
{
remoteParty = sd.getConnection().getAddress();
}
relay.setSipDest(remoteParty, remotePort);
@SuppressWarnings("unchecked")
Vector<String> codecs = (Vector<String>) media.getMediaFormats(false);
for (String codec : codecs)
{
int id = Integer.parseInt(codec);
logger.debug("[[" + internalCallId + "]] Got a codec " + id);
if (id < 97)
{
Payload p = getById(id);
if (p != null)
{
if (offer)
{
offerPayloads.add(p);
}
else
{
answerPayloads.add(p);
}
}
}
}
@SuppressWarnings("unchecked")
Vector<Attribute> attributes = (Vector<Attribute>) md.getAttributes(false);
for (Attribute attrib : attributes)
{
if (attrib.getName().equals("rtpmap"))
{
logger.debug("[[" + internalCallId + "]] Got attribute value " + attrib.getValue());
String fields[] = attrib.getValue().split(" ", 2);
int codec = Integer.parseInt(fields[0]);
String name = fields[1].split("/")[0];
int clockRate = Integer.parseInt(fields[1].split("/")[1]);
logger.debug("[[" + internalCallId + "]] Payload " + codec + " rate " + clockRate + " is mapped to " + name);
if (codec >= 96)
{
Payload bitRatePayload = getByName(name, clockRate);
if (bitRatePayload != null)
{
Payload p = new Payload(codec, name, clockRate, bitRatePayload.bitRate);
if (offer)
{
offerPayloads.add(p);
}
else
{
answerPayloads.add(p);
}
}
}
}
}
}
}
}
catch (SdpParseException e)
{
logger.error("Unable to parse SDP!", e);
}
catch (SdpException e)
{
logger.error("Unable to parse SDP!", e);
}
}
|
diff --git a/src/com/scholastic/sbam/server/database/util/SqlExecution.java b/src/com/scholastic/sbam/server/database/util/SqlExecution.java
index b78a408..0610405 100644
--- a/src/com/scholastic/sbam/server/database/util/SqlExecution.java
+++ b/src/com/scholastic/sbam/server/database/util/SqlExecution.java
@@ -1,101 +1,101 @@
package com.scholastic.sbam.server.database.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlExecution {
protected Connection conn;
protected Statement sqlStmt;
protected ResultSet results;
public SqlExecution() {
}
public SqlExecution(String sql) throws SQLException {
executeStatement(sql); // Do nothing with the result... let the programmer get it later with the getter.
}
/**
* Execute a statement.
*
* @param sql
* The statement to execute.
* @return
* The result set.
* @throws SQLException
*/
public ResultSet executeStatement(String sql) throws SQLException {
// Close any previous result set and statement
closeResult();
// Create the connection, if not already present
if (conn == null)
conn = HibernateUtil.getConnection();
// Create the new statement
- Statement sqlStmt = conn.createStatement();
+ sqlStmt = conn.createStatement();
// Execute the query
try {
results = sqlStmt.executeQuery(sql);
} catch (SQLException sqlExc) {
System.out.println(sql);
System.out.println(sqlExc.getMessage());
sqlExc.printStackTrace();
throw sqlExc;
}
return results;
}
/**
* Close any open result set and statement
* @throws SQLException
*/
public void closeResult() throws SQLException {
if (results != null)
results.close();
if (sqlStmt != null)
sqlStmt.close();
}
/**
* Close everything.
*
* @throws SQLException
*/
public void close() throws SQLException {
closeResult();
if (conn != null)
HibernateUtil.freeConnection(conn); // conn.close();
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public Statement getSqlStmt() {
return sqlStmt;
}
public void setSqlStmt(Statement sqlStmt) {
this.sqlStmt = sqlStmt;
}
public ResultSet getResults() {
return results;
}
public void setResults(ResultSet results) {
this.results = results;
}
}
| true | true | public ResultSet executeStatement(String sql) throws SQLException {
// Close any previous result set and statement
closeResult();
// Create the connection, if not already present
if (conn == null)
conn = HibernateUtil.getConnection();
// Create the new statement
Statement sqlStmt = conn.createStatement();
// Execute the query
try {
results = sqlStmt.executeQuery(sql);
} catch (SQLException sqlExc) {
System.out.println(sql);
System.out.println(sqlExc.getMessage());
sqlExc.printStackTrace();
throw sqlExc;
}
return results;
}
| public ResultSet executeStatement(String sql) throws SQLException {
// Close any previous result set and statement
closeResult();
// Create the connection, if not already present
if (conn == null)
conn = HibernateUtil.getConnection();
// Create the new statement
sqlStmt = conn.createStatement();
// Execute the query
try {
results = sqlStmt.executeQuery(sql);
} catch (SQLException sqlExc) {
System.out.println(sql);
System.out.println(sqlExc.getMessage());
sqlExc.printStackTrace();
throw sqlExc;
}
return results;
}
|
diff --git a/illadownload/src/illarion/download/util/Lang.java b/illadownload/src/illarion/download/util/Lang.java
index 6b5e1ef9..ec0305ed 100644
--- a/illadownload/src/illarion/download/util/Lang.java
+++ b/illadownload/src/illarion/download/util/Lang.java
@@ -1,153 +1,153 @@
/*
* This file is part of the Illarion Download Utility.
*
* Copyright © 2012 - Illarion e.V.
*
* The Illarion Download Utility 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.
*
* The Illarion Download Utility 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 the Illarion Download Utility. If not, see <http://www.gnu.org/licenses/>.
*/
package illarion.download.util;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import illarion.common.util.MessageSource;
/**
* This class is used to manage the language settings of this application.
*
* @author Martin Karing
* @version 1.00
* @since 1.00
*/
public final class Lang
implements MessageSource {
/**
* The singleton instance of this class.
*/
private static final Lang INSTANCE = new Lang();
/**
* The logger instance that handles the log output of this class.
*/
private static final Logger LOGGER = Logger.getLogger(Lang.class.getName());
/**
* The file name of the message bundles the client loads for the language.
*/
private static final String MESSAGE_BUNDLE = "messages"; //$NON-NLS-1$
/**
* The current local settings.
*/
private Locale locale;
/**
* The storage of the localized messages. Holds the key for the string and the localized full message.
*/
private final ResourceBundle messages;
/**
* Constructor of the game. Triggers the messages to load.
*/
private Lang() {
locale = Locale.getDefault();
- if (locale.getLanguage() == Locale.GERMAN.getLanguage()) {
+ if (locale.getLanguage().equals(Locale.GERMAN.getLanguage())) {
locale = Locale.GERMAN;
} else {
locale = Locale.ENGLISH;
}
messages = ResourceBundle.getBundle(MESSAGE_BUNDLE, locale, Lang.class.getClassLoader());
}
/**
* Get the singleton instance of this class.
*
* @return the instance of the class
*/
public static Lang getInstance() {
return INSTANCE;
}
/**
* Get a localized message from a key.
*
* @param key The key of the localized message
* @return the localized message or the key with surrounding < > in case the key was not found in the storage
*/
public static String getMsg(final String key) {
return INSTANCE.getMessage(key);
}
/**
* Get the current local settings.
*
* @return the local object of the chosen local settings
*/
public Locale getLocale() {
return locale;
}
/**
* Get a localized message from a key.
*
* @param key The key of the localized message
* @return the localized message or the key with surrounding < > in case the key was not found in the storage
*/
@SuppressWarnings("nls")
@Override
public String getMessage(final String key) {
try {
return messages.getString(key).replace("\\n", "\n");
} catch (final MissingResourceException e) {
LOGGER.warning("Failed searching translated version of: " + key);
return "<" + key + ">";
}
}
/**
* Check if a key contains a message.
*
* @param key the key that shall be checked
* @return true in case a message was found
*/
public boolean hasMsg(final String key) {
try {
messages.getString(key);
} catch (final MissingResourceException e) {
return false;
}
return true;
}
/**
* Check if the client is currently running with the English language.
*
* @return true if the language is set to English
*/
public boolean isEnglish() {
return locale == Locale.ENGLISH;
}
/**
* Check if the client is currently running with the German language.
*
* @return true if the language is set to German
*/
public boolean isGerman() {
return locale == Locale.GERMAN;
}
}
| true | true | private Lang() {
locale = Locale.getDefault();
if (locale.getLanguage() == Locale.GERMAN.getLanguage()) {
locale = Locale.GERMAN;
} else {
locale = Locale.ENGLISH;
}
messages = ResourceBundle.getBundle(MESSAGE_BUNDLE, locale, Lang.class.getClassLoader());
}
| private Lang() {
locale = Locale.getDefault();
if (locale.getLanguage().equals(Locale.GERMAN.getLanguage())) {
locale = Locale.GERMAN;
} else {
locale = Locale.ENGLISH;
}
messages = ResourceBundle.getBundle(MESSAGE_BUNDLE, locale, Lang.class.getClassLoader());
}
|
diff --git a/sample_bots/DispersionBot/src/MyBot.java b/sample_bots/DispersionBot/src/MyBot.java
index c9a9b8b..396b060 100644
--- a/sample_bots/DispersionBot/src/MyBot.java
+++ b/sample_bots/DispersionBot/src/MyBot.java
@@ -1,79 +1,80 @@
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class MyBot extends Bot {
/**
* Main method executed by the game engine for starting the bot.
*
* @param args
* command line arguments
*
* @throws IOException
* if an I/O error occurs
*/
public static void main(String[] args) throws IOException {
new MyBot().readSystemInput();
}
/**
* The DoTurn function is where your code goes.<br/>
* The Game object contains the state of the game, including information
* about all planets and fleets that currently exist.<br/>
* Inside this function, you issue orders using the {@link Game#issueOrder}
* functions.<br/>
* For example, to send 10 ships from planet 3 to planet 8, you would say
* <code>game.issueOrder(3, 8, 10).</code>
*
* <p>
* There is already a basic strategy in place here.<br/>
* You can use it as a starting point, or you can throw it out entirely and
* replace it with your own.
* </p>
*
* @param game
* the Game instance
*/
@Override
public void doTurn() {
Game game = getGame();
// Count my production
int production = 0;
for (EconomicPlanet p : game.getMyEconomicPlanets()) {
production += p.revenue;
}
/* Sort targets by weakness */
List<Planet> targets = game.getNotMyPlanets();
Collections.sort(targets, new Comparator<Planet>() {
@Override
public int compare(Planet p1, Planet p2) {
return p1.numShips - p2.numShips;
}
});
/* Sort sources by strength */
List<MilitaryPlanet> sources = game.getMyMilitaryPlanets();
Collections.sort(sources, new Comparator<Planet>() {
@Override
public int compare(Planet p1, Planet p2) {
return p2.numShips - p1.numShips;
}
});
/* Send one */
Iterator<Planet> itTargets = targets.iterator();
while (itTargets.hasNext() && production > 0) {
for (Planet src : sources) {
if (src.numShips > 0) {
game.issueOrder(src.id, itTargets.next().id, 1);
+ production--;
break;
}
}
}
}
}
| true | true | public void doTurn() {
Game game = getGame();
// Count my production
int production = 0;
for (EconomicPlanet p : game.getMyEconomicPlanets()) {
production += p.revenue;
}
/* Sort targets by weakness */
List<Planet> targets = game.getNotMyPlanets();
Collections.sort(targets, new Comparator<Planet>() {
@Override
public int compare(Planet p1, Planet p2) {
return p1.numShips - p2.numShips;
}
});
/* Sort sources by strength */
List<MilitaryPlanet> sources = game.getMyMilitaryPlanets();
Collections.sort(sources, new Comparator<Planet>() {
@Override
public int compare(Planet p1, Planet p2) {
return p2.numShips - p1.numShips;
}
});
/* Send one */
Iterator<Planet> itTargets = targets.iterator();
while (itTargets.hasNext() && production > 0) {
for (Planet src : sources) {
if (src.numShips > 0) {
game.issueOrder(src.id, itTargets.next().id, 1);
break;
}
}
}
}
| public void doTurn() {
Game game = getGame();
// Count my production
int production = 0;
for (EconomicPlanet p : game.getMyEconomicPlanets()) {
production += p.revenue;
}
/* Sort targets by weakness */
List<Planet> targets = game.getNotMyPlanets();
Collections.sort(targets, new Comparator<Planet>() {
@Override
public int compare(Planet p1, Planet p2) {
return p1.numShips - p2.numShips;
}
});
/* Sort sources by strength */
List<MilitaryPlanet> sources = game.getMyMilitaryPlanets();
Collections.sort(sources, new Comparator<Planet>() {
@Override
public int compare(Planet p1, Planet p2) {
return p2.numShips - p1.numShips;
}
});
/* Send one */
Iterator<Planet> itTargets = targets.iterator();
while (itTargets.hasNext() && production > 0) {
for (Planet src : sources) {
if (src.numShips > 0) {
game.issueOrder(src.id, itTargets.next().id, 1);
production--;
break;
}
}
}
}
|
diff --git a/src/org/pixmob/hcl/HttpRequestBuilder.java b/src/org/pixmob/hcl/HttpRequestBuilder.java
index eb8317c..1507cc7 100644
--- a/src/org/pixmob/hcl/HttpRequestBuilder.java
+++ b/src/org/pixmob/hcl/HttpRequestBuilder.java
@@ -1,485 +1,485 @@
/*
* Copyright (C) 2012 Pixmob (http://github.com/pixmob)
*
* 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.pixmob.hcl;
import static org.pixmob.hcl.Constants.HTTP_GET;
import static org.pixmob.hcl.Constants.HTTP_POST;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
import android.content.Context;
import android.os.Build;
/**
* This class is used to prepare and execute an Http request.
* @author Pixmob
*/
public final class HttpRequestBuilder {
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final String CONTENT_CHARSET = "UTF-8";
private static final Map<String, List<String>> NO_HEADERS = new HashMap<String, List<String>>(
0);
private static TrustManager[] trustManagers;
private final byte[] buffer = new byte[1024];
private final HttpClient hc;
private String uri;
private String method;
private Set<Integer> expectedStatusCodes = new HashSet<Integer>(2);
private Map<String, String> cookies;
private Map<String, List<String>> headers;
private Map<String, String> parameters;
private byte[] payload;
private HttpResponseHandler handler;
HttpRequestBuilder(final HttpClient hc, final String uri,
final String method) {
this.hc = hc;
this.uri = uri;
this.method = method;
}
public HttpRequestBuilder expectStatusCode(int... statusCodes) {
if (statusCodes != null) {
for (final int statusCode : statusCodes) {
if (statusCode < 1) {
throw new IllegalArgumentException("Invalid status code: "
+ statusCode);
}
expectedStatusCodes.add(statusCode);
}
}
return this;
}
public HttpRequestBuilder setCookies(Map<String, String> cookies) {
this.cookies = cookies;
return this;
}
public HttpRequestBuilder setHeaders(Map<String, List<String>> headers) {
this.headers = headers;
return this;
}
public HttpRequestBuilder addHeader(String name, String value) {
if (name == null) {
throw new IllegalArgumentException("Header name cannot be null");
}
if (value == null) {
throw new IllegalArgumentException("Header value cannot be null");
}
if (headers == null) {
headers = new HashMap<String, List<String>>(2);
}
List<String> values = headers.get(name);
if (values == null) {
values = new ArrayList<String>(1);
headers.put(name, values);
}
values.add(value);
return this;
}
public HttpRequestBuilder setParameters(Map<String, String> parameters) {
this.parameters = parameters;
return this;
}
public HttpRequestBuilder setParameter(String name, String value) {
if (name == null) {
throw new IllegalArgumentException("Parameter name cannot be null");
}
if (value == null) {
throw new IllegalArgumentException("Parameter value cannot be null");
}
if (parameters == null) {
parameters = new HashMap<String, String>(4);
}
parameters.put(name, value);
return this;
}
public HttpRequestBuilder setCookie(String name, String value) {
if (name == null) {
throw new IllegalArgumentException("Cookie name cannot be null");
}
if (value == null) {
throw new IllegalArgumentException("Cookie value cannot be null");
}
if (cookies == null) {
cookies = new HashMap<String, String>(2);
}
cookies.put(name, value);
return this;
}
public HttpRequestBuilder setHandler(HttpResponseHandler handler) {
this.handler = handler;
return this;
}
public void execute() throws HttpClientException {
HttpURLConnection conn = null;
UncloseableInputStream payloadStream = null;
try {
if (parameters != null && !parameters.isEmpty()) {
final StringBuilder buf = new StringBuilder(256);
if (!HTTP_POST.equals(method)) {
buf.append('?');
}
for (final Map.Entry<String, String> e : parameters.entrySet()) {
if (buf.length() != 0) {
buf.append("&");
}
final String name = e.getKey();
final String value = e.getValue();
buf.append(URLEncoder.encode(name, CONTENT_CHARSET))
.append(URLEncoder.encode(value, CONTENT_CHARSET));
}
if (HTTP_POST.equals(method)) {
try {
payload = buf.toString().getBytes(CONTENT_CHARSET);
} catch (UnsupportedEncodingException e) {
// Unlikely to happen.
throw new HttpClientException("Encoding error", e);
}
} else {
uri += buf;
}
}
conn = (HttpURLConnection) new URL(uri).openConnection();
conn.setConnectTimeout(hc.getConnectTimeout());
conn.setReadTimeout(hc.getReadTimeout());
conn.setAllowUserInteraction(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod(method);
if (HTTP_GET.equals(method)) {
conn.setDoInput(true);
}
if (HTTP_POST.equals(method)) {
conn.setDoOutput(true);
conn.setUseCaches(false);
}
if (headers != null && !headers.isEmpty()) {
for (final Map.Entry<String, List<String>> e : headers
.entrySet()) {
final List<String> values = e.getValue();
if (values != null) {
final String name = e.getKey();
for (final String value : values) {
conn.addRequestProperty(name, value);
}
}
}
}
final StringBuilder cookieHeaderValue = new StringBuilder(256);
prepareCookieHeader(cookies, cookieHeaderValue);
prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
final String userAgent = hc.getUserAgent();
if (userAgent != null) {
conn.setRequestProperty("User-Agent", userAgent);
}
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("Location", uri);
conn.setRequestProperty("Referrer", uri);
conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);
if (HTTP_POST.equals(method)) {
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset="
+ CONTENT_CHARSET);
if (payload != null) {
conn.setFixedLengthStreamingMode(payload.length);
}
}
if (conn instanceof HttpsURLConnection) {
setupSecureConnection(hc.getContext(),
(HttpsURLConnection) conn);
}
conn.connect();
final int statusCode = conn.getResponseCode();
if (statusCode == -1) {
throw new HttpClientException("Invalid response from " + uri);
}
if (!expectedStatusCodes.isEmpty()
&& !expectedStatusCodes.contains(statusCode)) {
throw new HttpClientException("Expected status code "
+ expectedStatusCodes + ", got " + statusCode);
} else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
throw new HttpClientException("Expected status code 2xx, got "
+ statusCode);
}
final Map<String, List<String>> headerFields = conn
.getHeaderFields();
final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
if (headerFields != null) {
final List<String> newCookies = headerFields.get("Set-Cookie");
if (newCookies != null) {
for (final String newCookie : newCookies) {
final String rawCookie = newCookie.split(";", 2)[0];
final int i = rawCookie.indexOf('=');
final String name = rawCookie.substring(0, i);
final String value = rawCookie.substring(i + 1);
inMemoryCookies.put(name, value);
}
}
}
payloadStream = new UncloseableInputStream(getInputStream(conn));
if (handler != null) {
final HttpResponse resp = new HttpResponse(statusCode,
payloadStream, headerFields == null ? NO_HEADERS
: headerFields, inMemoryCookies);
try {
handler.onResponse(resp);
} catch (Exception e) {
throw new HttpClientException("Error in response handler",
e);
}
}
} catch (SocketTimeoutException e) {
if (handler != null) {
try {
handler.onTimeout();
} catch (Exception e2) {
throw new HttpClientException("Error in response handler",
e2);
}
}
} catch (IOException e) {
throw new HttpClientException("Connection failed to " + uri, e);
} finally {
if (conn != null) {
if (payloadStream != null) {
// Fully read Http response:
// http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
try {
while (payloadStream.read(buffer) != -1)
;
} catch (IOException ignore) {
}
+ payloadStream.forceClose();
}
- payloadStream.forceClose();
conn.disconnect();
}
}
}
private static void prepareCookieHeader(Map<String, String> cookies,
StringBuilder headerValue) {
if (cookies != null) {
for (final Map.Entry<String, String> e : cookies.entrySet()) {
if (headerValue.length() != 0) {
headerValue.append("; ");
}
headerValue.append(e.getKey()).append("=").append(e.getValue());
}
}
}
/**
* Open the {@link InputStream} of an Http response. This method supports
* GZIP and DEFLATE responses.
*/
private static InputStream getInputStream(HttpURLConnection conn)
throws IOException {
final List<String> contentEncodingValues = conn.getHeaderFields().get(
"Content-Encoding");
if (contentEncodingValues != null) {
for (final String contentEncoding : contentEncodingValues) {
if (contentEncoding != null) {
if (contentEncoding.contains("gzip")) {
return new GZIPInputStream(conn.getInputStream());
}
if (contentEncoding.contains("deflate")) {
return new InflaterInputStream(conn.getInputStream(),
new Inflater(true));
}
}
}
}
return conn.getInputStream();
}
private static KeyStore loadCertificates(Context context)
throws IOException {
try {
final KeyStore localTrustStore = KeyStore.getInstance("BKS");
final InputStream in = context.getResources().openRawResource(
R.raw.hcl_keystore);
try {
localTrustStore.load(in, null);
} finally {
in.close();
}
return localTrustStore;
} catch (Exception e) {
final IOException ioe = new IOException(
"Failed to load SSL certificates");
ioe.initCause(e);
throw ioe;
}
}
/**
* Setup SSL connection.
*/
private static void setupSecureConnection(Context context,
HttpsURLConnection conn) throws IOException {
final SSLContext sslContext;
try {
// SSL certificates are provided by the Guardian Project:
// https://github.com/guardianproject/cacert
if (trustManagers == null) {
// Load SSL certificates:
// http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
// Earlier Android versions do not have updated root CA
// certificates, resulting in connection errors.
final KeyStore keyStore = loadCertificates(context);
final CustomTrustManager customTrustManager = new CustomTrustManager(
keyStore);
trustManagers = new TrustManager[] { customTrustManager };
}
// Init SSL connection with custom certificates.
// The same SecureRandom instance is used for every connection to
// speed up initialization.
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, SECURE_RANDOM);
} catch (GeneralSecurityException e) {
final IOException ioe = new IOException(
"Failed to initialize SSL engine");
ioe.initCause(e);
throw ioe;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// Fix slow read:
// http://code.google.com/p/android/issues/detail?id=13117
// Prior to ICS, the host name is still resolved even if we already
// know its IP address, for each connection.
final SSLSocketFactory delegate = sslContext.getSocketFactory();
final SSLSocketFactory socketFactory = new SSLSocketFactory() {
@Override
public Socket createSocket(String host, int port)
throws IOException, UnknownHostException {
InetAddress addr = InetAddress.getByName(host);
injectHostname(addr, host);
return delegate.createSocket(addr, port);
}
@Override
public Socket createSocket(InetAddress host, int port)
throws IOException {
return delegate.createSocket(host, port);
}
@Override
public Socket createSocket(String host, int port,
InetAddress localHost, int localPort)
throws IOException, UnknownHostException {
return delegate.createSocket(host, port, localHost,
localPort);
}
@Override
public Socket createSocket(InetAddress address, int port,
InetAddress localAddress, int localPort)
throws IOException {
return delegate.createSocket(address, port, localAddress,
localPort);
}
private void injectHostname(InetAddress address, String host) {
try {
Field field = InetAddress.class
.getDeclaredField("hostName");
field.setAccessible(true);
field.set(address, host);
} catch (Exception ignored) {
}
}
@Override
public Socket createSocket(Socket s, String host, int port,
boolean autoClose) throws IOException {
injectHostname(s.getInetAddress(), host);
return delegate.createSocket(s, host, port, autoClose);
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
};
conn.setSSLSocketFactory(socketFactory);
} else {
conn.setSSLSocketFactory(sslContext.getSocketFactory());
}
conn.setHostnameVerifier(new BrowserCompatHostnameVerifier());
}
}
| false | true | public void execute() throws HttpClientException {
HttpURLConnection conn = null;
UncloseableInputStream payloadStream = null;
try {
if (parameters != null && !parameters.isEmpty()) {
final StringBuilder buf = new StringBuilder(256);
if (!HTTP_POST.equals(method)) {
buf.append('?');
}
for (final Map.Entry<String, String> e : parameters.entrySet()) {
if (buf.length() != 0) {
buf.append("&");
}
final String name = e.getKey();
final String value = e.getValue();
buf.append(URLEncoder.encode(name, CONTENT_CHARSET))
.append(URLEncoder.encode(value, CONTENT_CHARSET));
}
if (HTTP_POST.equals(method)) {
try {
payload = buf.toString().getBytes(CONTENT_CHARSET);
} catch (UnsupportedEncodingException e) {
// Unlikely to happen.
throw new HttpClientException("Encoding error", e);
}
} else {
uri += buf;
}
}
conn = (HttpURLConnection) new URL(uri).openConnection();
conn.setConnectTimeout(hc.getConnectTimeout());
conn.setReadTimeout(hc.getReadTimeout());
conn.setAllowUserInteraction(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod(method);
if (HTTP_GET.equals(method)) {
conn.setDoInput(true);
}
if (HTTP_POST.equals(method)) {
conn.setDoOutput(true);
conn.setUseCaches(false);
}
if (headers != null && !headers.isEmpty()) {
for (final Map.Entry<String, List<String>> e : headers
.entrySet()) {
final List<String> values = e.getValue();
if (values != null) {
final String name = e.getKey();
for (final String value : values) {
conn.addRequestProperty(name, value);
}
}
}
}
final StringBuilder cookieHeaderValue = new StringBuilder(256);
prepareCookieHeader(cookies, cookieHeaderValue);
prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
final String userAgent = hc.getUserAgent();
if (userAgent != null) {
conn.setRequestProperty("User-Agent", userAgent);
}
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("Location", uri);
conn.setRequestProperty("Referrer", uri);
conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);
if (HTTP_POST.equals(method)) {
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset="
+ CONTENT_CHARSET);
if (payload != null) {
conn.setFixedLengthStreamingMode(payload.length);
}
}
if (conn instanceof HttpsURLConnection) {
setupSecureConnection(hc.getContext(),
(HttpsURLConnection) conn);
}
conn.connect();
final int statusCode = conn.getResponseCode();
if (statusCode == -1) {
throw new HttpClientException("Invalid response from " + uri);
}
if (!expectedStatusCodes.isEmpty()
&& !expectedStatusCodes.contains(statusCode)) {
throw new HttpClientException("Expected status code "
+ expectedStatusCodes + ", got " + statusCode);
} else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
throw new HttpClientException("Expected status code 2xx, got "
+ statusCode);
}
final Map<String, List<String>> headerFields = conn
.getHeaderFields();
final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
if (headerFields != null) {
final List<String> newCookies = headerFields.get("Set-Cookie");
if (newCookies != null) {
for (final String newCookie : newCookies) {
final String rawCookie = newCookie.split(";", 2)[0];
final int i = rawCookie.indexOf('=');
final String name = rawCookie.substring(0, i);
final String value = rawCookie.substring(i + 1);
inMemoryCookies.put(name, value);
}
}
}
payloadStream = new UncloseableInputStream(getInputStream(conn));
if (handler != null) {
final HttpResponse resp = new HttpResponse(statusCode,
payloadStream, headerFields == null ? NO_HEADERS
: headerFields, inMemoryCookies);
try {
handler.onResponse(resp);
} catch (Exception e) {
throw new HttpClientException("Error in response handler",
e);
}
}
} catch (SocketTimeoutException e) {
if (handler != null) {
try {
handler.onTimeout();
} catch (Exception e2) {
throw new HttpClientException("Error in response handler",
e2);
}
}
} catch (IOException e) {
throw new HttpClientException("Connection failed to " + uri, e);
} finally {
if (conn != null) {
if (payloadStream != null) {
// Fully read Http response:
// http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
try {
while (payloadStream.read(buffer) != -1)
;
} catch (IOException ignore) {
}
}
payloadStream.forceClose();
conn.disconnect();
}
}
}
| public void execute() throws HttpClientException {
HttpURLConnection conn = null;
UncloseableInputStream payloadStream = null;
try {
if (parameters != null && !parameters.isEmpty()) {
final StringBuilder buf = new StringBuilder(256);
if (!HTTP_POST.equals(method)) {
buf.append('?');
}
for (final Map.Entry<String, String> e : parameters.entrySet()) {
if (buf.length() != 0) {
buf.append("&");
}
final String name = e.getKey();
final String value = e.getValue();
buf.append(URLEncoder.encode(name, CONTENT_CHARSET))
.append(URLEncoder.encode(value, CONTENT_CHARSET));
}
if (HTTP_POST.equals(method)) {
try {
payload = buf.toString().getBytes(CONTENT_CHARSET);
} catch (UnsupportedEncodingException e) {
// Unlikely to happen.
throw new HttpClientException("Encoding error", e);
}
} else {
uri += buf;
}
}
conn = (HttpURLConnection) new URL(uri).openConnection();
conn.setConnectTimeout(hc.getConnectTimeout());
conn.setReadTimeout(hc.getReadTimeout());
conn.setAllowUserInteraction(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod(method);
if (HTTP_GET.equals(method)) {
conn.setDoInput(true);
}
if (HTTP_POST.equals(method)) {
conn.setDoOutput(true);
conn.setUseCaches(false);
}
if (headers != null && !headers.isEmpty()) {
for (final Map.Entry<String, List<String>> e : headers
.entrySet()) {
final List<String> values = e.getValue();
if (values != null) {
final String name = e.getKey();
for (final String value : values) {
conn.addRequestProperty(name, value);
}
}
}
}
final StringBuilder cookieHeaderValue = new StringBuilder(256);
prepareCookieHeader(cookies, cookieHeaderValue);
prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
final String userAgent = hc.getUserAgent();
if (userAgent != null) {
conn.setRequestProperty("User-Agent", userAgent);
}
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("Location", uri);
conn.setRequestProperty("Referrer", uri);
conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);
if (HTTP_POST.equals(method)) {
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset="
+ CONTENT_CHARSET);
if (payload != null) {
conn.setFixedLengthStreamingMode(payload.length);
}
}
if (conn instanceof HttpsURLConnection) {
setupSecureConnection(hc.getContext(),
(HttpsURLConnection) conn);
}
conn.connect();
final int statusCode = conn.getResponseCode();
if (statusCode == -1) {
throw new HttpClientException("Invalid response from " + uri);
}
if (!expectedStatusCodes.isEmpty()
&& !expectedStatusCodes.contains(statusCode)) {
throw new HttpClientException("Expected status code "
+ expectedStatusCodes + ", got " + statusCode);
} else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
throw new HttpClientException("Expected status code 2xx, got "
+ statusCode);
}
final Map<String, List<String>> headerFields = conn
.getHeaderFields();
final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
if (headerFields != null) {
final List<String> newCookies = headerFields.get("Set-Cookie");
if (newCookies != null) {
for (final String newCookie : newCookies) {
final String rawCookie = newCookie.split(";", 2)[0];
final int i = rawCookie.indexOf('=');
final String name = rawCookie.substring(0, i);
final String value = rawCookie.substring(i + 1);
inMemoryCookies.put(name, value);
}
}
}
payloadStream = new UncloseableInputStream(getInputStream(conn));
if (handler != null) {
final HttpResponse resp = new HttpResponse(statusCode,
payloadStream, headerFields == null ? NO_HEADERS
: headerFields, inMemoryCookies);
try {
handler.onResponse(resp);
} catch (Exception e) {
throw new HttpClientException("Error in response handler",
e);
}
}
} catch (SocketTimeoutException e) {
if (handler != null) {
try {
handler.onTimeout();
} catch (Exception e2) {
throw new HttpClientException("Error in response handler",
e2);
}
}
} catch (IOException e) {
throw new HttpClientException("Connection failed to " + uri, e);
} finally {
if (conn != null) {
if (payloadStream != null) {
// Fully read Http response:
// http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
try {
while (payloadStream.read(buffer) != -1)
;
} catch (IOException ignore) {
}
payloadStream.forceClose();
}
conn.disconnect();
}
}
}
|
diff --git a/sikuli-script/src/main/java/org/sikuli/script/TextRecognizer.java b/sikuli-script/src/main/java/org/sikuli/script/TextRecognizer.java
index 74980b29..edc35a4b 100644
--- a/sikuli-script/src/main/java/org/sikuli/script/TextRecognizer.java
+++ b/sikuli-script/src/main/java/org/sikuli/script/TextRecognizer.java
@@ -1,73 +1,73 @@
package org.sikuli.script;
import java.awt.image.*;
import java.io.*;
import java.net.URL;
import java.util.Enumeration;
import org.sikuli.script.natives.Mat;
import org.sikuli.script.natives.Vision;
import com.wapmx.nativeutils.jniloader.NativeLoader;
// Singleton
public class TextRecognizer {
protected static TextRecognizer _instance = null;
static {
try{
NativeLoader.loadLibrary("VisionProxy");
TextRecognizer tr = TextRecognizer.getInstance();
}
catch(IOException e){
e.printStackTrace();
}
}
protected TextRecognizer(){
init();
}
boolean _init_succeeded = false;
public void init(){
- Debug.info("Text Recgonizer inited.");
+ Debug.info("Text Recognizer inited.");
try{
String path = ResourceExtractor.extract("tessdata");
// TESSDATA_PREFIX doesn't contain tessdata/
if(path.endsWith("tessdata/"))
path = path.substring(0,path.length()-9);
Settings.OcrDataPath = path;
Debug.log(3, "OCR data path: " + path);
Vision.initOCR(Settings.OcrDataPath);
_init_succeeded = true;
}
catch(IOException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
public static TextRecognizer getInstance(){
if(_instance==null)
_instance = new TextRecognizer();
return _instance;
}
public String recognize(ScreenImage simg){
BufferedImage img = simg.getImage();
return recognize(img);
}
public String recognize(BufferedImage img){
if (_init_succeeded){
Mat mat = OpenCV.convertBufferedImageToMat(img);
return Vision.recognize(mat);
}else{
return "";
}
}
}
| true | true | public void init(){
Debug.info("Text Recgonizer inited.");
try{
String path = ResourceExtractor.extract("tessdata");
// TESSDATA_PREFIX doesn't contain tessdata/
if(path.endsWith("tessdata/"))
path = path.substring(0,path.length()-9);
Settings.OcrDataPath = path;
Debug.log(3, "OCR data path: " + path);
Vision.initOCR(Settings.OcrDataPath);
_init_succeeded = true;
}
catch(IOException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
| public void init(){
Debug.info("Text Recognizer inited.");
try{
String path = ResourceExtractor.extract("tessdata");
// TESSDATA_PREFIX doesn't contain tessdata/
if(path.endsWith("tessdata/"))
path = path.substring(0,path.length()-9);
Settings.OcrDataPath = path;
Debug.log(3, "OCR data path: " + path);
Vision.initOCR(Settings.OcrDataPath);
_init_succeeded = true;
}
catch(IOException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
|
diff --git a/src/app/server/udpservlet/ElectionReceiveServlet.java b/src/app/server/udpservlet/ElectionReceiveServlet.java
index 6fed76f..631705f 100644
--- a/src/app/server/udpservlet/ElectionReceiveServlet.java
+++ b/src/app/server/udpservlet/ElectionReceiveServlet.java
@@ -1,72 +1,75 @@
package app.server.udpservlet;
import java.net.SocketTimeoutException;
import packet.AnswerPacket;
import packet.CoordinatorPacket;
import packet.ElectionPacket;
import udp.FIFOObjectUDPServlet;
import utils.LiteLogger;
import app.server.Config;
import app.server.RetailStoreServerImpl;
public class ElectionReceiveServlet extends FIFOObjectUDPServlet<RetailStoreServerImpl> {
private static final long serialVersionUID = 6453595686631867382L;
public static int electionId = 0;
public ElectionReceiveServlet(int port, RetailStoreServerImpl owner) {
super(port, owner);
}
@Override
public void run() {
while (true) {
int timeout = 10000;
Object packet;
try {
// getOwner().setElectionState(ElectionState.WAIT_FOR_REPLY); //TODO: to remove, for testing only
packet = receiveWithTimeout(timeout);
LiteLogger.log("ELECTION PACKET RECEIVED!! PACKET = ", packet);
if (packet instanceof ElectionPacket) {
ElectionPacket electionPacket = (ElectionPacket)packet;
LiteLogger.log("Election packet type = Election");
if (getOwner().getElectionState() == ElectionState.IDLE) {
AnswerPacket answerPacket = new AnswerPacket();
answerPacket.setElectionId(electionPacket.getId());
}
}
else if (packet instanceof AnswerPacket) {
LiteLogger.log("Election packet type = Answer");
getOwner().setElectionState(ElectionState.WAIT_FOR_LEADER);
}
else if (packet instanceof CoordinatorPacket) {
LiteLogger.log("Election packet type = Coordinator");
getOwner().setElectionState(ElectionState.IDLE);
getOwner().setLeaderId( CoordinatorPacket.class.cast(packet).getLeaderId());
}
+ else {
+ LiteLogger.log("SOMETHING WENT WRONG, INVALID TYPE RECEIVED");
+ }
} catch (SocketTimeoutException e) {
System.out.println(e.getMessage() + "\n" + e.getStackTrace());
if (getOwner().getElectionState() == ElectionState.WAIT_FOR_REPLY) {
LiteLogger.log("Election state = ", getOwner().getElectionState());
CoordinatorPacket coordinator = new CoordinatorPacket();
coordinator.setLeaderId(getOwner().getId());
LiteLogger.log("New coordinator object created. Setting leader to ", getOwner().getId());
getOwner().broadcastAll(coordinator, Config.ELECTION_RECEIVE_LISTEN_PORT);
getOwner().setLeaderId(getOwner().getId());
getOwner().setElectionState(ElectionState.IDLE);
}
else if (getOwner().getElectionState() == ElectionState.WAIT_FOR_LEADER) {
//(new Thread(new ElectionServlet(Config.ELECTION_LISTEN_PORT, getOwner()))).start();
}
}
}
}
}
| true | true | public void run() {
while (true) {
int timeout = 10000;
Object packet;
try {
// getOwner().setElectionState(ElectionState.WAIT_FOR_REPLY); //TODO: to remove, for testing only
packet = receiveWithTimeout(timeout);
LiteLogger.log("ELECTION PACKET RECEIVED!! PACKET = ", packet);
if (packet instanceof ElectionPacket) {
ElectionPacket electionPacket = (ElectionPacket)packet;
LiteLogger.log("Election packet type = Election");
if (getOwner().getElectionState() == ElectionState.IDLE) {
AnswerPacket answerPacket = new AnswerPacket();
answerPacket.setElectionId(electionPacket.getId());
}
}
else if (packet instanceof AnswerPacket) {
LiteLogger.log("Election packet type = Answer");
getOwner().setElectionState(ElectionState.WAIT_FOR_LEADER);
}
else if (packet instanceof CoordinatorPacket) {
LiteLogger.log("Election packet type = Coordinator");
getOwner().setElectionState(ElectionState.IDLE);
getOwner().setLeaderId( CoordinatorPacket.class.cast(packet).getLeaderId());
}
} catch (SocketTimeoutException e) {
System.out.println(e.getMessage() + "\n" + e.getStackTrace());
if (getOwner().getElectionState() == ElectionState.WAIT_FOR_REPLY) {
LiteLogger.log("Election state = ", getOwner().getElectionState());
CoordinatorPacket coordinator = new CoordinatorPacket();
coordinator.setLeaderId(getOwner().getId());
LiteLogger.log("New coordinator object created. Setting leader to ", getOwner().getId());
getOwner().broadcastAll(coordinator, Config.ELECTION_RECEIVE_LISTEN_PORT);
getOwner().setLeaderId(getOwner().getId());
getOwner().setElectionState(ElectionState.IDLE);
}
else if (getOwner().getElectionState() == ElectionState.WAIT_FOR_LEADER) {
//(new Thread(new ElectionServlet(Config.ELECTION_LISTEN_PORT, getOwner()))).start();
}
}
}
}
| public void run() {
while (true) {
int timeout = 10000;
Object packet;
try {
// getOwner().setElectionState(ElectionState.WAIT_FOR_REPLY); //TODO: to remove, for testing only
packet = receiveWithTimeout(timeout);
LiteLogger.log("ELECTION PACKET RECEIVED!! PACKET = ", packet);
if (packet instanceof ElectionPacket) {
ElectionPacket electionPacket = (ElectionPacket)packet;
LiteLogger.log("Election packet type = Election");
if (getOwner().getElectionState() == ElectionState.IDLE) {
AnswerPacket answerPacket = new AnswerPacket();
answerPacket.setElectionId(electionPacket.getId());
}
}
else if (packet instanceof AnswerPacket) {
LiteLogger.log("Election packet type = Answer");
getOwner().setElectionState(ElectionState.WAIT_FOR_LEADER);
}
else if (packet instanceof CoordinatorPacket) {
LiteLogger.log("Election packet type = Coordinator");
getOwner().setElectionState(ElectionState.IDLE);
getOwner().setLeaderId( CoordinatorPacket.class.cast(packet).getLeaderId());
}
else {
LiteLogger.log("SOMETHING WENT WRONG, INVALID TYPE RECEIVED");
}
} catch (SocketTimeoutException e) {
System.out.println(e.getMessage() + "\n" + e.getStackTrace());
if (getOwner().getElectionState() == ElectionState.WAIT_FOR_REPLY) {
LiteLogger.log("Election state = ", getOwner().getElectionState());
CoordinatorPacket coordinator = new CoordinatorPacket();
coordinator.setLeaderId(getOwner().getId());
LiteLogger.log("New coordinator object created. Setting leader to ", getOwner().getId());
getOwner().broadcastAll(coordinator, Config.ELECTION_RECEIVE_LISTEN_PORT);
getOwner().setLeaderId(getOwner().getId());
getOwner().setElectionState(ElectionState.IDLE);
}
else if (getOwner().getElectionState() == ElectionState.WAIT_FOR_LEADER) {
//(new Thread(new ElectionServlet(Config.ELECTION_LISTEN_PORT, getOwner()))).start();
}
}
}
}
|
diff --git a/src/main/java/org/apache/commons/digester3/xmlrules/XmlRulesModule.java b/src/main/java/org/apache/commons/digester3/xmlrules/XmlRulesModule.java
index 386bf853..8dbe0fc3 100644
--- a/src/main/java/org/apache/commons/digester3/xmlrules/XmlRulesModule.java
+++ b/src/main/java/org/apache/commons/digester3/xmlrules/XmlRulesModule.java
@@ -1,127 +1,125 @@
package org.apache.commons.digester3.xmlrules;
/*
* 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.util.Set;
import org.apache.commons.digester3.binder.LinkedRuleBuilder;
import org.apache.commons.digester3.binder.RulesBinder;
import org.apache.commons.digester3.binder.RulesModule;
/**
*
*/
final class XmlRulesModule
implements RulesModule
{
private final RulesBinder targetRulesBinder;
private final Set<String> rootSystemIds;
private final String rootPath;
private WithMemoryRulesBinder memoryRulesBinder;
public XmlRulesModule( final RulesBinder targetRulesBinder, Set<String> rootSystemIds,
/* @Nullable */String rootPath )
{
this.targetRulesBinder = targetRulesBinder;
this.rootSystemIds = rootSystemIds;
this.rootPath = rootPath;
}
/**
* {@inheritDoc}
*/
public void configure( RulesBinder rulesBinder )
{
if ( rulesBinder instanceof WithMemoryRulesBinder )
{
memoryRulesBinder = (WithMemoryRulesBinder) rulesBinder;
}
else
{
memoryRulesBinder = new WithMemoryRulesBinder( rulesBinder );
if ( !rootSystemIds.isEmpty() )
{
memoryRulesBinder.getIncludedFiles().addAll( rootSystemIds );
}
}
PatternStack patternStack = memoryRulesBinder.getPatternStack();
if ( rootPath != null )
{
patternStack.push( rootPath );
}
try
{
forPattern( "*/pattern" ).addRule( new PatternRule( patternStack ) );
forPattern( "*/include" ).addRule( new IncludeRule( memoryRulesBinder, targetRulesBinder ) );
forPattern( "*/bean-property-setter-rule" ).addRule( new BeanPropertySetterRule( targetRulesBinder,
patternStack ) );
forPattern( "*/call-method-rule" ).addRule( new CallMethodRule( targetRulesBinder, patternStack ) );
forPattern( "*/call-param-rule" ).addRule( new CallParamRule( targetRulesBinder, patternStack ) );
forPattern( "*/object-param-rule" ).addRule( new ObjectParamRule( targetRulesBinder, patternStack ) );
forPattern( "*/factory-create-rule" ).addRule( new FactoryCreateRule( targetRulesBinder, patternStack ) );
forPattern( "*/object-create-rule" ).addRule( new ObjectCreateRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-properties-rule" ).addRule( new SetPropertiesRule( targetRulesBinder, patternStack ) );
- forPattern( "*/set-properties-rule/alias" ).addRule( new SetPropertiesAliasRule( targetRulesBinder,
- patternStack ) );
- forPattern( "*/set-properties-rule/ignore" ).addRule( new SetPropertiesIgnoreRule( targetRulesBinder,
- patternStack ) );
+ forPattern( "*/set-properties-rule/alias" )
+ .addRule( new SetPropertiesAliasRule( targetRulesBinder, patternStack ) );
+ forPattern( "*/set-properties-rule/ignore" )
+ .addRule( new SetPropertiesIgnoreRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-property-rule" ).addRule( new SetPropertyRule( targetRulesBinder, patternStack ) );
- forPattern( "*/set-nested-properties-rule" ).addRule( new SetNestedPropertiesRule( targetRulesBinder,
- patternStack ) );
- forPattern( "*/set-nested-properties-rule/alias" ).addRule( new SetNestedPropertiesAliasRule(
- targetRulesBinder,
- patternStack ) );
- forPattern( "*/set-nested-properties-rule/ignore" ).addRule( new SetPropertiesIgnoreRule(
- targetRulesBinder,
- patternStack ) );
+ forPattern( "*/set-nested-properties-rule" )
+ .addRule( new SetNestedPropertiesRule( targetRulesBinder, patternStack ) );
+ forPattern( "*/set-nested-properties-rule/alias" )
+ .addRule( new SetNestedPropertiesAliasRule( targetRulesBinder, patternStack ) );
+ forPattern( "*/set-nested-properties-rule/ignore" )
+ .addRule( new SetPropertiesIgnoreRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-top-rule" ).addRule( new SetTopRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-next-rule" ).addRule( new SetNextRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-root-rule" ).addRule( new SetRootRule( targetRulesBinder, patternStack ) );
}
finally
{
memoryRulesBinder = null;
}
}
/**
* @param pattern
* @return
*/
protected LinkedRuleBuilder forPattern( String pattern )
{
return memoryRulesBinder.forPattern( pattern );
}
}
| false | true | public void configure( RulesBinder rulesBinder )
{
if ( rulesBinder instanceof WithMemoryRulesBinder )
{
memoryRulesBinder = (WithMemoryRulesBinder) rulesBinder;
}
else
{
memoryRulesBinder = new WithMemoryRulesBinder( rulesBinder );
if ( !rootSystemIds.isEmpty() )
{
memoryRulesBinder.getIncludedFiles().addAll( rootSystemIds );
}
}
PatternStack patternStack = memoryRulesBinder.getPatternStack();
if ( rootPath != null )
{
patternStack.push( rootPath );
}
try
{
forPattern( "*/pattern" ).addRule( new PatternRule( patternStack ) );
forPattern( "*/include" ).addRule( new IncludeRule( memoryRulesBinder, targetRulesBinder ) );
forPattern( "*/bean-property-setter-rule" ).addRule( new BeanPropertySetterRule( targetRulesBinder,
patternStack ) );
forPattern( "*/call-method-rule" ).addRule( new CallMethodRule( targetRulesBinder, patternStack ) );
forPattern( "*/call-param-rule" ).addRule( new CallParamRule( targetRulesBinder, patternStack ) );
forPattern( "*/object-param-rule" ).addRule( new ObjectParamRule( targetRulesBinder, patternStack ) );
forPattern( "*/factory-create-rule" ).addRule( new FactoryCreateRule( targetRulesBinder, patternStack ) );
forPattern( "*/object-create-rule" ).addRule( new ObjectCreateRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-properties-rule" ).addRule( new SetPropertiesRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-properties-rule/alias" ).addRule( new SetPropertiesAliasRule( targetRulesBinder,
patternStack ) );
forPattern( "*/set-properties-rule/ignore" ).addRule( new SetPropertiesIgnoreRule( targetRulesBinder,
patternStack ) );
forPattern( "*/set-property-rule" ).addRule( new SetPropertyRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-nested-properties-rule" ).addRule( new SetNestedPropertiesRule( targetRulesBinder,
patternStack ) );
forPattern( "*/set-nested-properties-rule/alias" ).addRule( new SetNestedPropertiesAliasRule(
targetRulesBinder,
patternStack ) );
forPattern( "*/set-nested-properties-rule/ignore" ).addRule( new SetPropertiesIgnoreRule(
targetRulesBinder,
patternStack ) );
forPattern( "*/set-top-rule" ).addRule( new SetTopRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-next-rule" ).addRule( new SetNextRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-root-rule" ).addRule( new SetRootRule( targetRulesBinder, patternStack ) );
}
finally
{
memoryRulesBinder = null;
}
}
| public void configure( RulesBinder rulesBinder )
{
if ( rulesBinder instanceof WithMemoryRulesBinder )
{
memoryRulesBinder = (WithMemoryRulesBinder) rulesBinder;
}
else
{
memoryRulesBinder = new WithMemoryRulesBinder( rulesBinder );
if ( !rootSystemIds.isEmpty() )
{
memoryRulesBinder.getIncludedFiles().addAll( rootSystemIds );
}
}
PatternStack patternStack = memoryRulesBinder.getPatternStack();
if ( rootPath != null )
{
patternStack.push( rootPath );
}
try
{
forPattern( "*/pattern" ).addRule( new PatternRule( patternStack ) );
forPattern( "*/include" ).addRule( new IncludeRule( memoryRulesBinder, targetRulesBinder ) );
forPattern( "*/bean-property-setter-rule" ).addRule( new BeanPropertySetterRule( targetRulesBinder,
patternStack ) );
forPattern( "*/call-method-rule" ).addRule( new CallMethodRule( targetRulesBinder, patternStack ) );
forPattern( "*/call-param-rule" ).addRule( new CallParamRule( targetRulesBinder, patternStack ) );
forPattern( "*/object-param-rule" ).addRule( new ObjectParamRule( targetRulesBinder, patternStack ) );
forPattern( "*/factory-create-rule" ).addRule( new FactoryCreateRule( targetRulesBinder, patternStack ) );
forPattern( "*/object-create-rule" ).addRule( new ObjectCreateRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-properties-rule" ).addRule( new SetPropertiesRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-properties-rule/alias" )
.addRule( new SetPropertiesAliasRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-properties-rule/ignore" )
.addRule( new SetPropertiesIgnoreRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-property-rule" ).addRule( new SetPropertyRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-nested-properties-rule" )
.addRule( new SetNestedPropertiesRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-nested-properties-rule/alias" )
.addRule( new SetNestedPropertiesAliasRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-nested-properties-rule/ignore" )
.addRule( new SetPropertiesIgnoreRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-top-rule" ).addRule( new SetTopRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-next-rule" ).addRule( new SetNextRule( targetRulesBinder, patternStack ) );
forPattern( "*/set-root-rule" ).addRule( new SetRootRule( targetRulesBinder, patternStack ) );
}
finally
{
memoryRulesBinder = null;
}
}
|
diff --git a/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java b/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java
index 4d07328c7d..30d5bacfbc 100644
--- a/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java
@@ -1,244 +1,244 @@
package org.apache.lucene.search.payloads;
/*
* 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 org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.DocsAndPositionsEnum;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.ComplexExplanation;
import org.apache.lucene.search.similarities.DefaultSimilarity;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.search.similarities.Similarity.SloppySimScorer;
import org.apache.lucene.search.spans.TermSpans;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.search.spans.SpanWeight;
import org.apache.lucene.search.spans.SpanScorer;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import java.io.IOException;
/**
* This class is very similar to
* {@link org.apache.lucene.search.spans.SpanTermQuery} except that it factors
* in the value of the payload located at each of the positions where the
* {@link org.apache.lucene.index.Term} occurs.
* <p/>
* NOTE: In order to take advantage of this with the default scoring implementation
* ({@link DefaultSimilarity}), you must override {@link DefaultSimilarity#scorePayload(int, int, int, BytesRef)},
* which returns 1 by default.
* <p/>
* Payload scores are aggregated using a pluggable {@link PayloadFunction}.
* @see org.apache.lucene.search.similarities.Similarity.SloppySimScorer#computePayloadFactor(int, int, int, BytesRef)
**/
public class PayloadTermQuery extends SpanTermQuery {
protected PayloadFunction function;
private boolean includeSpanScore;
public PayloadTermQuery(Term term, PayloadFunction function) {
this(term, function, true);
}
public PayloadTermQuery(Term term, PayloadFunction function,
boolean includeSpanScore) {
super(term);
this.function = function;
this.includeSpanScore = includeSpanScore;
}
@Override
public Weight createWeight(IndexSearcher searcher) throws IOException {
return new PayloadTermWeight(this, searcher);
}
protected class PayloadTermWeight extends SpanWeight {
public PayloadTermWeight(PayloadTermQuery query, IndexSearcher searcher)
throws IOException {
super(query, searcher);
}
@Override
public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder,
boolean topScorer, Bits acceptDocs) throws IOException {
return new PayloadTermSpanScorer((TermSpans) query.getSpans(context, acceptDocs, termContexts),
this, similarity.sloppySimScorer(stats, context));
}
protected class PayloadTermSpanScorer extends SpanScorer {
protected BytesRef payload;
protected float payloadScore;
protected int payloadsSeen;
private final TermSpans termSpans;
public PayloadTermSpanScorer(TermSpans spans, Weight weight, Similarity.SloppySimScorer docScorer) throws IOException {
super(spans, weight, docScorer);
termSpans = spans;
}
@Override
protected boolean setFreqCurrentDoc() throws IOException {
if (!more) {
return false;
}
doc = spans.doc();
freq = 0.0f;
payloadScore = 0;
payloadsSeen = 0;
while (more && doc == spans.doc()) {
int matchLength = spans.end() - spans.start();
freq += docScorer.computeSlopFactor(matchLength);
processPayload(similarity);
more = spans.next();// this moves positions to the next match in this
// document
}
return more || (freq != 0);
}
protected void processPayload(Similarity similarity) throws IOException {
final DocsAndPositionsEnum postings = termSpans.getPostings();
if (postings.hasPayload()) {
payload = postings.getPayload();
if (payload != null) {
payloadScore = function.currentScore(doc, term.field(),
spans.start(), spans.end(), payloadsSeen, payloadScore,
docScorer.computePayloadFactor(doc, spans.start(), spans.end(), payload));
} else {
payloadScore = function.currentScore(doc, term.field(),
spans.start(), spans.end(), payloadsSeen, payloadScore, 1F);
}
payloadsSeen++;
} else {
// zero out the payload?
}
}
/**
*
* @return {@link #getSpanScore()} * {@link #getPayloadScore()}
* @throws IOException
*/
@Override
public float score() throws IOException {
return includeSpanScore ? getSpanScore() * getPayloadScore()
: getPayloadScore();
}
/**
* Returns the SpanScorer score only.
* <p/>
* Should not be overridden without good cause!
*
* @return the score for just the Span part w/o the payload
* @throws IOException
*
* @see #score()
*/
protected float getSpanScore() throws IOException {
return super.score();
}
/**
* The score for the payload
*
* @return The score, as calculated by
* {@link PayloadFunction#docScore(int, String, int, float)}
*/
protected float getPayloadScore() {
return function.docScore(doc, term.field(), payloadsSeen, payloadScore);
}
}
@Override
public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
PayloadTermSpanScorer scorer = (PayloadTermSpanScorer) scorer(context, true, false, context.reader().getLiveDocs());
if (scorer != null) {
int newDoc = scorer.advance(doc);
if (newDoc == doc) {
float freq = scorer.freq();
SloppySimScorer docScorer = similarity.sloppySimScorer(stats, context);
Explanation expl = new Explanation();
expl.setDescription("weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:");
Explanation scoreExplanation = docScorer.explain(doc, new Explanation(freq, "phraseFreq=" + freq));
expl.addDetail(scoreExplanation);
expl.setValue(scoreExplanation.getValue());
// now the payloads part
// QUESTION: Is there a way to avoid this skipTo call? We need to know
// whether to load the payload or not
// GSI: I suppose we could toString the payload, but I don't think that
// would be a good idea
- Explanation payloadExpl = new Explanation(scorer.getPayloadScore(), "scorePayload(...)");
+ Explanation payloadExpl = function.explain(doc, scorer.payloadsSeen, scorer.payloadScore);
payloadExpl.setValue(scorer.getPayloadScore());
// combined
ComplexExplanation result = new ComplexExplanation();
if (includeSpanScore) {
result.addDetail(expl);
result.addDetail(payloadExpl);
result.setValue(expl.getValue() * payloadExpl.getValue());
result.setDescription("btq, product of:");
} else {
result.addDetail(payloadExpl);
result.setValue(payloadExpl.getValue());
result.setDescription("btq(includeSpanScore=false), result of:");
}
result.setMatch(true); // LUCENE-1303
return result;
}
}
return new ComplexExplanation(false, 0.0f, "no matching term");
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((function == null) ? 0 : function.hashCode());
result = prime * result + (includeSpanScore ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
PayloadTermQuery other = (PayloadTermQuery) obj;
if (function == null) {
if (other.function != null)
return false;
} else if (!function.equals(other.function))
return false;
if (includeSpanScore != other.includeSpanScore)
return false;
return true;
}
}
| true | true | public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
PayloadTermSpanScorer scorer = (PayloadTermSpanScorer) scorer(context, true, false, context.reader().getLiveDocs());
if (scorer != null) {
int newDoc = scorer.advance(doc);
if (newDoc == doc) {
float freq = scorer.freq();
SloppySimScorer docScorer = similarity.sloppySimScorer(stats, context);
Explanation expl = new Explanation();
expl.setDescription("weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:");
Explanation scoreExplanation = docScorer.explain(doc, new Explanation(freq, "phraseFreq=" + freq));
expl.addDetail(scoreExplanation);
expl.setValue(scoreExplanation.getValue());
// now the payloads part
// QUESTION: Is there a way to avoid this skipTo call? We need to know
// whether to load the payload or not
// GSI: I suppose we could toString the payload, but I don't think that
// would be a good idea
Explanation payloadExpl = new Explanation(scorer.getPayloadScore(), "scorePayload(...)");
payloadExpl.setValue(scorer.getPayloadScore());
// combined
ComplexExplanation result = new ComplexExplanation();
if (includeSpanScore) {
result.addDetail(expl);
result.addDetail(payloadExpl);
result.setValue(expl.getValue() * payloadExpl.getValue());
result.setDescription("btq, product of:");
} else {
result.addDetail(payloadExpl);
result.setValue(payloadExpl.getValue());
result.setDescription("btq(includeSpanScore=false), result of:");
}
result.setMatch(true); // LUCENE-1303
return result;
}
}
return new ComplexExplanation(false, 0.0f, "no matching term");
}
| public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
PayloadTermSpanScorer scorer = (PayloadTermSpanScorer) scorer(context, true, false, context.reader().getLiveDocs());
if (scorer != null) {
int newDoc = scorer.advance(doc);
if (newDoc == doc) {
float freq = scorer.freq();
SloppySimScorer docScorer = similarity.sloppySimScorer(stats, context);
Explanation expl = new Explanation();
expl.setDescription("weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:");
Explanation scoreExplanation = docScorer.explain(doc, new Explanation(freq, "phraseFreq=" + freq));
expl.addDetail(scoreExplanation);
expl.setValue(scoreExplanation.getValue());
// now the payloads part
// QUESTION: Is there a way to avoid this skipTo call? We need to know
// whether to load the payload or not
// GSI: I suppose we could toString the payload, but I don't think that
// would be a good idea
Explanation payloadExpl = function.explain(doc, scorer.payloadsSeen, scorer.payloadScore);
payloadExpl.setValue(scorer.getPayloadScore());
// combined
ComplexExplanation result = new ComplexExplanation();
if (includeSpanScore) {
result.addDetail(expl);
result.addDetail(payloadExpl);
result.setValue(expl.getValue() * payloadExpl.getValue());
result.setDescription("btq, product of:");
} else {
result.addDetail(payloadExpl);
result.setValue(payloadExpl.getValue());
result.setDescription("btq(includeSpanScore=false), result of:");
}
result.setMatch(true); // LUCENE-1303
return result;
}
}
return new ComplexExplanation(false, 0.0f, "no matching term");
}
|
diff --git a/src/callgraphanalyzer/Comparator.java b/src/callgraphanalyzer/Comparator.java
index 5cfb422..de35f2d 100644
--- a/src/callgraphanalyzer/Comparator.java
+++ b/src/callgraphanalyzer/Comparator.java
@@ -1,386 +1,386 @@
package callgraphanalyzer;
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 models.CallGraph;
import models.Commit;
import models.CallGraph.MethodPercentage;
import models.CommitFamily;
import models.DiffEntry;
import models.DiffEntry.diff_types;
import models.Pair;
import parser.Parser;
import parser.Resolver;
import db.CallGraphDb;
import differ.diff_match_patch;
import differ.diff_match_patch.Diff;
import differ.diffObjectResult;
public class Comparator
{
public class ModifiedMethod
{
public ModifiedMethod(Set<MethodPercentage> oldM, Set<MethodPercentage> newM)
{
this.oldMethods = oldM;
this.newMethods = newM;
}
public Set<MethodPercentage> oldMethods = new HashSet<MethodPercentage>();
public Set<MethodPercentage> newMethods = new HashSet<MethodPercentage>();
}
public class CompareResult
{
public CompareResult()
{
}
public void clear()
{
addedFiles.clear();
deletedFiles.clear();
modifiedFileMethodMap.clear();
modifiedBinaryFiles.clear();
}
public void print()
{
for (String file : addedFiles)
System.out.println("+\t" + file);
for (String file : deletedFiles)
System.out.println("-\t" + file);
for (String file : modifiedBinaryFiles.keySet())
{
String commitID = modifiedBinaryFiles.get(file);
System.out.println("+-[BIN]\t" + file + " in " + commitID);
}
for (String file : modifiedFileMethodMap.keySet())
{
ModifiedMethod methods = modifiedFileMethodMap.get(file);
System.out.println("+-\t" + file);
for (MethodPercentage mo : methods.oldMethods)
System.out
.println("\tModified old method: " + mo.getMethod().getName() +" "+ mo.getPercentage()+ "%");
for (MethodPercentage mn : methods.newMethods)
System.out
.println("\tModified new method: " + mn.getMethod().getName()+" "+ mn.getPercentage()+ "%");
}
}
public Set<String> addedFiles = new HashSet<String>();
public Set<String> deletedFiles = new HashSet<String>();
public Map<String, ModifiedMethod> modifiedFileMethodMap = new HashMap<String, ModifiedMethod>();
public Map<String, String> modifiedBinaryFiles = new HashMap<String, String>();
}
public CallGraphDb db;
public CallGraph newCallGraph;
public CallGraph oldCallGraph;
public Map<String, String> FileMap;
private CompareResult compareResult = new CompareResult();
public Commit newCommit;
public Commit oldCommit;
public String CurrentBranch;
public String CurrentBranchID;
/**
* Constructs a new Comparator class. This class connects the FileDiffer
* {@link #differ} and CallGraph {@link #newCallGraph}
*
* @param db
* Name of the Database.
* @param CommitIDOne
* SHA-1 Hash of the commit in question.
* @param CommitIDTwo
* SHA-1 Hash of the second commit.
*/
public Comparator(CallGraphDb db, String CommitIDOne, String CommitIDTwo)
{
this.db = db;
this.newCallGraph = generateCallGraphAtCommit(CommitIDTwo);
this.newCallGraph.setCommitID(CommitIDTwo);
this.oldCallGraph = generateCallGraphAtCommit(CommitIDOne);
this.oldCallGraph.setCommitID(CommitIDOne);
}
public void updateCGVariables(String oldCommit, String newCommit) {
this.oldCommit = db.getCommit(oldCommit);
this.newCommit = db.getCommit(newCommit);
}
public CallGraph generateCallGraphAtCommit(String commitID) {
CallGraph callGraph = new CallGraph();
Parser parser = new Parser(callGraph);
List<CommitFamily> commits = db.getCommitPathToRoot(commitID);
List<CommitFamily> path = reversePath(commits);
List<String> files = new LinkedList<String>();
if(path.isEmpty()) {
// It's the initial commit
files.addAll(db.getFilesAdded(commitID));
files.removeAll(db.getFilesDeleted(commitID));
}
for(CommitFamily commitF: path) {
files.addAll(db.getFilesAdded(commitF.getChildId()));
files.removeAll(db.getFilesDeleted(commitF.getChildId()));
}
for(String file: files) {
if(!file.endsWith(".java"))
continue;
parser.parseFileFromString(file, db.getRawFileFromDiffTree(file, commitID));
}
// Get the Java util library
CallGraphDb libraryDB = new CallGraphDb();
libraryDB.connect("JavaLibraries");
libraryDB.setBranchName("master");
commits = libraryDB.getCommitPathToRoot("e436a78a73f967d47aebd02ac58677255bbec125");
path = reversePath(commits);
files = new LinkedList<String>();
if(path.isEmpty()) {
// It's the initial commit
files.addAll(libraryDB.getFilesAdded(commitID));
files.removeAll(libraryDB.getFilesDeleted(commitID));
}
for(CommitFamily commitF: path) {
files.addAll(libraryDB.getFilesAdded(commitF.getChildId()));
files.removeAll(libraryDB.getFilesDeleted(commitF.getChildId()));
}
for(String file: files) {
if(!file.endsWith(".java"))
continue;
parser.parseFileFromString(file, libraryDB.getRawFileFromDiffTree(file, commitID));
}
Resolver resolver = new Resolver(callGraph);
resolver.resolveAll();
return callGraph;
}
private List<CommitFamily> reversePath(List<CommitFamily> path) {
List<CommitFamily> returnPath = new ArrayList<CommitFamily>();
for(CommitFamily CF: path)
returnPath.add(0, CF);
return returnPath;
}
public boolean CompareCommits(String oldCommitID, String newCommitID)
{
this.compareResult.clear();
// these two commit are consecutive, just got the diff and generated method
List<String> fileChanged = db.getFilesChanged(oldCommitID, newCommitID);
for(String fileName : fileChanged)
{
List<DiffEntry> diffEntries = db.getDiffsFromTwoConsecutiveCommits(fileName, oldCommitID, newCommitID);
if(!diffEntries.isEmpty())
{
// return the change sets from the two files
List<diffObjectResult> deleteObjects = new ArrayList<diffObjectResult>();
List<diffObjectResult> insertObjects = new ArrayList<diffObjectResult>();
for(DiffEntry entry : diffEntries)
{
if(entry.getDiff_type() == diff_types.DIFF_MODIFYDELETE)
{
diffObjectResult result = new diffObjectResult();
result.start = entry.getChar_start();
result.end = entry.getChar_end();
result.diffObject = new Diff(diff_match_patch.Operation.DELETE, entry.getDiff_text());
deleteObjects.add(result);
}
else if(entry.getDiff_type() == diff_types.DIFF_MODIFYINSERT)
{
diffObjectResult result = new diffObjectResult();
result.start = entry.getChar_start();
result.end = entry.getChar_end();
result.diffObject = new Diff(diff_match_patch.Operation.INSERT, entry.getDiff_text());
insertObjects.add(result);
}
else if(entry.getDiff_type() == diff_types.DIFF_ADD)
{
this.compareResult.addedFiles.add(fileName);
}
else if(entry.getDiff_type() == diff_types.DIFF_DELETE)
{
this.compareResult.deletedFiles.add(fileName);
}
else if(entry.getDiff_type() == diff_types.DIFF_UNKNOWN)
{
System.out.println("ERROR! Unknown operation on File: " + fileName);
}
}
// figure out which function has changed
getModifiedMethodsForFile(fileName, deleteObjects, insertObjects);
}
}
return true;
}
/**
* get all methods in a file that might be changed from new commit to other
*
* @param fileName
* file path
* @param callgraph
* @param diffs
* list of diff objects
* @return
*/
public void getModifiedMethodsForFile(String fileName,
List<diffObjectResult> deleteDiffs,
List<diffObjectResult> insertDiffs)
{
Set<MethodPercentage> newMethods = new HashSet<MethodPercentage>();
Set<MethodPercentage> oldMethods = new HashSet<MethodPercentage>();
// methods from old file version+
for (diffObjectResult diff : deleteDiffs)
{
List<MethodPercentage> changedMethod = this.oldCallGraph
.getPercentageOfMethodUsingCharacters(fileName, diff.start, diff.end, this.oldCommit.getCommit_id());
for (MethodPercentage m : changedMethod)
{
// find if the method exists
boolean methodExist = false;
for(MethodPercentage oldm : oldMethods)
{
if(oldm.getMethod().equals(m))
{
methodExist = true;
oldm.addPercentage(m.getPercentage());
break;
}
}
// add to oldMethodList
if(!methodExist)
oldMethods.add(m);
}
}
// methods from new file version
for (diffObjectResult diff : insertDiffs)
{
List<MethodPercentage> changedMethod = this.newCallGraph
.getPercentageOfMethodUsingCharacters(fileName, diff.start, diff.end, this.newCommit.getCommit_id());
for (MethodPercentage m : changedMethod)
{
// find if the method exists
boolean methodExist = false;
for(MethodPercentage newm : newMethods)
{
if(newm.getMethod().equals(m))
{
methodExist = true;
newm.addPercentage(m.getPercentage());
break;
}
}
// add to oldMethodList
if(!methodExist)
newMethods.add(m);
}
}
// Insert to modifiedMethod map
- if (!this.compareResult.modifiedFileMethodMap.containsKey(fileName))
+ if (!this.compareResult.modifiedFileMethodMap.containsKey(fileName) && (!oldMethods.isEmpty()||!newMethods.isEmpty()))
{
ModifiedMethod mm = new ModifiedMethod(oldMethods, newMethods);
this.compareResult.modifiedFileMethodMap.put(fileName, mm);
}
}
public void print()
{
//this.compareResult.print();
}
public CompareResult getCompareResult()
{
return compareResult;
}
public CallGraph forwardUpdateCallGraph(CallGraph cg, String newCommit) {
if(cg.getCommitID().equals(newCommit))
return cg;
if(hasChild(cg.getCommitID(), newCommit)) {
List<String> files = db.getFilesChanged(cg.getCommitID(), newCommit);
List<Pair<String,String>> changedFiles = new ArrayList<Pair<String,String>>();
for(String file: files) {
if(file.endsWith(".java")) {
String rawFile = db.getRawFileFromDiffTree(file, newCommit);
//cg.updateCallGraphByFile(file, rawFile);
changedFiles.add(new Pair<String,String>(file, rawFile));
}
}
cg.updateCallGraphByFiles(changedFiles);
}
else {
cg = buildCallGraph(cg, newCommit);
}
cg.setCommitID(newCommit);
return cg;
}
public CallGraph reverseUpdateCallGraph(CallGraph cg, String newCommit) {
if(cg.getCommitID().equals(newCommit))
return cg;
if(hasChild(newCommit, cg.getCommitID())) {
List<String> files = db.getFilesChanged(newCommit, cg.getCommitID());
List<Pair<String,String>> changedFiles = new ArrayList<Pair<String,String>>();
for(String file: files) {
String rawFile = db.getRawFileFromDiffTree(file, newCommit);
//cg.updateCallGraphByFile(file, rawFile);
changedFiles.add(new Pair<String,String>(file, rawFile));
}
cg.updateCallGraphByFiles(changedFiles);
}
else {
cg = buildCallGraph(cg, newCommit);
}
cg.setCommitID(newCommit);
return cg;
}
private boolean hasChild(String parentID, String childID) {
return db.parentHasChild(parentID, childID);
}
private CallGraph buildCallGraph(CallGraph cg, String CommitID) {
cg = generateCallGraphAtCommit(CommitID);
cg.setCommitID(CommitID);
return cg;
}
}
| true | true | public void getModifiedMethodsForFile(String fileName,
List<diffObjectResult> deleteDiffs,
List<diffObjectResult> insertDiffs)
{
Set<MethodPercentage> newMethods = new HashSet<MethodPercentage>();
Set<MethodPercentage> oldMethods = new HashSet<MethodPercentage>();
// methods from old file version+
for (diffObjectResult diff : deleteDiffs)
{
List<MethodPercentage> changedMethod = this.oldCallGraph
.getPercentageOfMethodUsingCharacters(fileName, diff.start, diff.end, this.oldCommit.getCommit_id());
for (MethodPercentage m : changedMethod)
{
// find if the method exists
boolean methodExist = false;
for(MethodPercentage oldm : oldMethods)
{
if(oldm.getMethod().equals(m))
{
methodExist = true;
oldm.addPercentage(m.getPercentage());
break;
}
}
// add to oldMethodList
if(!methodExist)
oldMethods.add(m);
}
}
// methods from new file version
for (diffObjectResult diff : insertDiffs)
{
List<MethodPercentage> changedMethod = this.newCallGraph
.getPercentageOfMethodUsingCharacters(fileName, diff.start, diff.end, this.newCommit.getCommit_id());
for (MethodPercentage m : changedMethod)
{
// find if the method exists
boolean methodExist = false;
for(MethodPercentage newm : newMethods)
{
if(newm.getMethod().equals(m))
{
methodExist = true;
newm.addPercentage(m.getPercentage());
break;
}
}
// add to oldMethodList
if(!methodExist)
newMethods.add(m);
}
}
// Insert to modifiedMethod map
if (!this.compareResult.modifiedFileMethodMap.containsKey(fileName))
{
ModifiedMethod mm = new ModifiedMethod(oldMethods, newMethods);
this.compareResult.modifiedFileMethodMap.put(fileName, mm);
}
}
| public void getModifiedMethodsForFile(String fileName,
List<diffObjectResult> deleteDiffs,
List<diffObjectResult> insertDiffs)
{
Set<MethodPercentage> newMethods = new HashSet<MethodPercentage>();
Set<MethodPercentage> oldMethods = new HashSet<MethodPercentage>();
// methods from old file version+
for (diffObjectResult diff : deleteDiffs)
{
List<MethodPercentage> changedMethod = this.oldCallGraph
.getPercentageOfMethodUsingCharacters(fileName, diff.start, diff.end, this.oldCommit.getCommit_id());
for (MethodPercentage m : changedMethod)
{
// find if the method exists
boolean methodExist = false;
for(MethodPercentage oldm : oldMethods)
{
if(oldm.getMethod().equals(m))
{
methodExist = true;
oldm.addPercentage(m.getPercentage());
break;
}
}
// add to oldMethodList
if(!methodExist)
oldMethods.add(m);
}
}
// methods from new file version
for (diffObjectResult diff : insertDiffs)
{
List<MethodPercentage> changedMethod = this.newCallGraph
.getPercentageOfMethodUsingCharacters(fileName, diff.start, diff.end, this.newCommit.getCommit_id());
for (MethodPercentage m : changedMethod)
{
// find if the method exists
boolean methodExist = false;
for(MethodPercentage newm : newMethods)
{
if(newm.getMethod().equals(m))
{
methodExist = true;
newm.addPercentage(m.getPercentage());
break;
}
}
// add to oldMethodList
if(!methodExist)
newMethods.add(m);
}
}
// Insert to modifiedMethod map
if (!this.compareResult.modifiedFileMethodMap.containsKey(fileName) && (!oldMethods.isEmpty()||!newMethods.isEmpty()))
{
ModifiedMethod mm = new ModifiedMethod(oldMethods, newMethods);
this.compareResult.modifiedFileMethodMap.put(fileName, mm);
}
}
|
diff --git a/fog/src/de/tuilmenau/ics/fog/transfer/manager/ProcessList.java b/fog/src/de/tuilmenau/ics/fog/transfer/manager/ProcessList.java
index fd8d90c2..e295121b 100644
--- a/fog/src/de/tuilmenau/ics/fog/transfer/manager/ProcessList.java
+++ b/fog/src/de/tuilmenau/ics/fog/transfer/manager/ProcessList.java
@@ -1,94 +1,96 @@
/*******************************************************************************
* 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.transfer.manager;
import java.util.Iterator;
import java.util.LinkedList;
import de.tuilmenau.ics.fog.facade.Identity;
/**
* List of processes belonging to one transfer plane element.
*/
public class ProcessList implements Iterable<Process>
{
public ProcessList()
{
}
public void registerProcess(Process process)
{
Process existingProcess = getProcess(process.getOwner(), process.getID());
// is there already a process registered for the ID?
if(existingProcess == null) {
mProcesses.addFirst(process);
} else {
// maybe it is the same process?
if(existingProcess != process) {
throw new RuntimeException(this +" - Process ID " +process.getID() +" already in use for " +existingProcess +". Can not use it for " +process +".");
}
}
}
/**
* Returns a process if it is changeable by the entity and has the given process number.
*/
public Process getProcess(Identity owner, int processID)
{
- for(Process process : mProcesses) {
- if(process.getID() == processID) {
- // do we filter for owners?
- if(owner != null) {
- // check if the entities are the same
- if(process.isChangableBy(owner)) {
+ if(mProcesses != null){
+ for(Process process : mProcesses) {
+ if(process.getID() == processID) {
+ // do we filter for owners?
+ if(owner != null) {
+ // check if the entities are the same
+ if(process.isChangableBy(owner)) {
+ return process;
+ }
+ } else {
return process;
}
- } else {
- return process;
}
}
}
return null;
}
public boolean unregisterProcess(Process process)
{
return mProcesses.remove(process);
}
public int size()
{
return mProcesses.size();
}
@Override
public Iterator<Process> iterator()
{
if(mProcesses.size() > 0) {
return mProcesses.iterator();
} else {
return null;
}
}
public String toString()
{
return this.getClass().getSimpleName() + ":" + mProcesses.toString();
}
private LinkedList<Process> mProcesses = new LinkedList<Process>();
}
| false | true | public Process getProcess(Identity owner, int processID)
{
for(Process process : mProcesses) {
if(process.getID() == processID) {
// do we filter for owners?
if(owner != null) {
// check if the entities are the same
if(process.isChangableBy(owner)) {
return process;
}
} else {
return process;
}
}
}
return null;
}
| public Process getProcess(Identity owner, int processID)
{
if(mProcesses != null){
for(Process process : mProcesses) {
if(process.getID() == processID) {
// do we filter for owners?
if(owner != null) {
// check if the entities are the same
if(process.isChangableBy(owner)) {
return process;
}
} else {
return process;
}
}
}
}
return null;
}
|
diff --git a/main/src/cgeo/geocaching/VisitCacheActivity.java b/main/src/cgeo/geocaching/VisitCacheActivity.java
index c93eb1fa5..43caa58c4 100644
--- a/main/src/cgeo/geocaching/VisitCacheActivity.java
+++ b/main/src/cgeo/geocaching/VisitCacheActivity.java
@@ -1,752 +1,752 @@
package cgeo.geocaching;
import cgeo.geocaching.LogTemplateProvider.LogTemplate;
import cgeo.geocaching.enumerations.LogTypeTrackable;
import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.gcvote.GCVote;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class VisitCacheActivity extends cgLogForm {
static final String EXTRAS_FOUND = "found";
static final String EXTRAS_TEXT = "text";
static final String EXTRAS_GEOCODE = "geocode";
static final String EXTRAS_ID = "id";
private static final int MENU_SIGNATURE = 1;
private static final int SUBMENU_VOTE = 2;
private LayoutInflater inflater = null;
private cgCache cache = null;
private List<Integer> types = new ArrayList<Integer>();
private ProgressDialog waitDialog = null;
private String cacheid = null;
private String geocode = null;
private String text = null;
private boolean alreadyFound = false;
private String[] viewstates = null;
private boolean gettingViewstate = true;
private List<cgTrackableLog> trackables = null;
private Calendar date = Calendar.getInstance();
private int typeSelected = 1;
private int attempts = 0;
private Button postButton = null;
private Button saveButton = null;
private Button clearButton = null;
private CheckBox tweetCheck = null;
private LinearLayout tweetBox = null;
private double rating = 0.0;
private boolean tbChanged = false;
// handlers
private final Handler loadDataHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (!types.contains(typeSelected)) {
typeSelected = types.get(0);
setType(typeSelected);
showToast(res.getString(R.string.info_log_type_changed));
}
if (cgBase.isEmpty(viewstates) && attempts < 2) {
showToast(res.getString(R.string.err_log_load_data_again));
final LoadDataThread thread;
thread = new LoadDataThread();
thread.start();
return;
} else if (cgBase.isEmpty(viewstates) && attempts >= 2) {
showToast(res.getString(R.string.err_log_load_data));
showProgress(false);
return;
}
gettingViewstate = false; // we're done, user can post log
enablePostButton(true);
// add trackables
if (CollectionUtils.isNotEmpty(trackables)) {
if (inflater == null) {
inflater = getLayoutInflater();
}
final LinearLayout inventoryView = (LinearLayout) findViewById(R.id.inventory);
inventoryView.removeAllViews();
for (cgTrackableLog tb : trackables) {
LinearLayout inventoryItem = (LinearLayout) inflater.inflate(R.layout.visit_trackable, null);
((TextView) inventoryItem.findViewById(R.id.trackcode)).setText(tb.trackCode);
((TextView) inventoryItem.findViewById(R.id.name)).setText(tb.name);
((TextView) inventoryItem.findViewById(R.id.action)).setText(res.getString(Settings.isTrackableAutoVisit() ? LogTypeTrackable.VISITED.resourceId : LogTypeTrackable.DO_NOTHING.resourceId));
inventoryItem.setId(tb.id);
final String tbCode = tb.trackCode;
inventoryItem.setClickable(true);
registerForContextMenu(inventoryItem);
inventoryItem.findViewById(R.id.info).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final Intent trackablesIntent = new Intent(VisitCacheActivity.this, cgeotrackable.class);
trackablesIntent.putExtra(EXTRAS_GEOCODE, tbCode);
startActivity(trackablesIntent);
}
});
inventoryItem.findViewById(R.id.action).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openContextMenu(view);
}
});
inventoryView.addView(inventoryItem);
if (Settings.isTrackableAutoVisit())
{
tb.action = LogTypeTrackable.VISITED;
tbChanged = true;
}
}
if (inventoryView.getChildCount() > 0) {
((LinearLayout) findViewById(R.id.inventory_box)).setVisibility(View.VISIBLE);
}
if (inventoryView.getChildCount() > 1) {
final LinearLayout inventoryChangeAllView = (LinearLayout) findViewById(R.id.inventory_changeall);
final Button changeButton = (Button) inventoryChangeAllView.findViewById(R.id.changebutton);
registerForContextMenu(changeButton);
changeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openContextMenu(view);
}
});
- ((LinearLayout) findViewById(R.id.inventory_changeall)).setVisibility(View.VISIBLE);
+ inventoryChangeAllView.setVisibility(View.VISIBLE);
}
}
showProgress(false);
}
};
private void enablePostButton(boolean enabled) {
postButton.setEnabled(enabled);
if (enabled) {
postButton.setOnClickListener(new PostListener());
}
else {
postButton.setOnTouchListener(null);
postButton.setOnClickListener(null);
}
updatePostButtonText();
}
private void updatePostButtonText() {
if (postButton.isEnabled()) {
if (typeSelected == cgBase.LOG_FOUND_IT && Settings.isGCvoteLogin()) {
if (rating == 0) {
postButton.setText(res.getString(R.string.log_post_no_rate));
} else {
postButton.setText(res.getString(R.string.log_post_rate) + " " + ratingTextValue(rating) + "*");
}
} else {
postButton.setText(res.getString(R.string.log_post));
}
}
else {
postButton.setText(res.getString(R.string.log_post_not_possible));
}
}
private final Handler postLogHandler = new Handler() {
@Override
public void handleMessage(final Message msg) {
if (waitDialog != null) {
waitDialog.dismiss();
}
final StatusCode error = (StatusCode) msg.obj;
if (error == StatusCode.NO_ERROR) {
showToast(res.getString(R.string.info_log_posted));
// No need to save the log when quitting if it has been posted.
text = currentLogText();
finish();
} else if (error == StatusCode.LOG_SAVED) {
showToast(res.getString(R.string.info_log_saved));
if (waitDialog != null) {
waitDialog.dismiss();
}
finish();
} else {
showToast(error.getErrorString(res));
}
}
};
public VisitCacheActivity() {
super("c:geo-log");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme();
setContentView(R.layout.visit);
setTitle(res.getString(R.string.log_new_log));
// get parameters
final Bundle extras = getIntent().getExtras();
if (extras != null) {
cacheid = extras.getString(EXTRAS_ID);
geocode = extras.getString(EXTRAS_GEOCODE);
text = extras.getString(EXTRAS_TEXT);
alreadyFound = extras.getBoolean(EXTRAS_FOUND);
}
if ((StringUtils.isBlank(cacheid)) && StringUtils.isNotBlank(geocode)) {
cacheid = app.getCacheid(geocode);
}
if (StringUtils.isBlank(geocode) && StringUtils.isNotBlank(cacheid)) {
geocode = app.getGeocode(cacheid);
}
cache = app.getCacheByGeocode(geocode);
if (StringUtils.isNotBlank(cache.getName())) {
setTitle(res.getString(R.string.log_new_log) + " " + cache.getName());
} else {
setTitle(res.getString(R.string.log_new_log) + " " + cache.getGeocode().toUpperCase());
}
app.setAction(geocode);
init();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onStop() {
super.onStop();
saveLog(false);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
init();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu menuLog = null;
menuLog = menu.addSubMenu(0, 0, 0, res.getString(R.string.log_add)).setIcon(android.R.drawable.ic_menu_add);
for (LogTemplate template : LogTemplateProvider.getTemplates()) {
menuLog.add(0, template.getItemId(), 0, template.getResourceId());
}
menuLog.add(0, MENU_SIGNATURE, 0, res.getString(R.string.init_signature));
final SubMenu menuStars = menu.addSubMenu(0, SUBMENU_VOTE, 0, res.getString(R.string.log_rating)).setIcon(android.R.drawable.ic_menu_sort_by_size);
menuStars.add(0, 10, 0, res.getString(R.string.log_no_rating));
menuStars.add(0, 19, 0, res.getString(R.string.log_stars_5) + " (" + res.getString(R.string.log_stars_5_description) + ")");
menuStars.add(0, 18, 0, res.getString(R.string.log_stars_45) + " (" + res.getString(R.string.log_stars_45_description) + ")");
menuStars.add(0, 17, 0, res.getString(R.string.log_stars_4) + " (" + res.getString(R.string.log_stars_4_description) + ")");
menuStars.add(0, 16, 0, res.getString(R.string.log_stars_35) + " (" + res.getString(R.string.log_stars_35_description) + ")");
menuStars.add(0, 15, 0, res.getString(R.string.log_stars_3) + " (" + res.getString(R.string.log_stars_3_description) + ")");
menuStars.add(0, 14, 0, res.getString(R.string.log_stars_25) + " (" + res.getString(R.string.log_stars_25_description) + ")");
menuStars.add(0, 13, 0, res.getString(R.string.log_stars_2) + " (" + res.getString(R.string.log_stars_2_description) + ")");
menuStars.add(0, 12, 0, res.getString(R.string.log_stars_15) + " (" + res.getString(R.string.log_stars_15_description) + ")");
menuStars.add(0, 11, 0, res.getString(R.string.log_stars_1) + " (" + res.getString(R.string.log_stars_1_description) + ")");
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
final boolean signatureAvailable = Settings.getSignature() != null;
menu.findItem(MENU_SIGNATURE).setVisible(signatureAvailable);
final boolean voteAvailable = Settings.isGCvoteLogin() && typeSelected == cgBase.LOG_FOUND_IT && StringUtils.isNotBlank(cache.getGuid());
menu.findItem(SUBMENU_VOTE).setVisible(voteAvailable);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int id = item.getItemId();
if (id == MENU_SIGNATURE) {
insertIntoLog(LogTemplateProvider.applyTemplates(Settings.getSignature(), base, false), true);
return true;
} else if (id >= 10 && id <= 19) {
rating = (id - 9) / 2.0;
if (rating < 1) {
rating = 0;
}
updatePostButtonText();
return true;
}
final LogTemplate template = LogTemplateProvider.getTemplate(id);
if (template != null) {
final String newText = template.getValue(base, false);
insertIntoLog(newText, true);
return true;
}
return false;
}
private void insertIntoLog(String newText, final boolean moveCursor) {
final EditText log = (EditText) findViewById(R.id.log);
cgBase.insertAtPosition(log, newText, moveCursor);
}
private static String ratingTextValue(final double rating) {
return String.format("%.1f", rating);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo info) {
super.onCreateContextMenu(menu, view, info);
final int viewId = view.getId();
if (viewId == R.id.type) {
for (final int typeOne : types) {
menu.add(viewId, typeOne, 0, cgBase.logTypes2.get(typeOne));
Log.w(Settings.tag, "Adding " + typeOne + " " + cgBase.logTypes2.get(typeOne));
}
} else if (viewId == R.id.changebutton) {
final int textId = ((TextView) findViewById(viewId)).getId();
menu.setHeaderTitle(res.getString(R.string.log_tb_changeall));
for (LogTypeTrackable logType : LogTypeTrackable.values()) {
menu.add(textId, logType.id, 0, res.getString(logType.resourceId));
}
} else {
final int realViewId = ((LinearLayout) findViewById(viewId)).getId();
for (final cgTrackableLog tb : trackables) {
if (tb.id == realViewId) {
menu.setHeaderTitle(tb.name);
}
}
for (LogTypeTrackable logType : LogTypeTrackable.values()) {
menu.add(realViewId, logType.id, 0, res.getString(logType.resourceId));
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final int group = item.getGroupId();
final int id = item.getItemId();
if (group == R.id.type) {
setType(id);
return true;
} else if (group == R.id.changebutton) {
try {
final LogTypeTrackable logType = LogTypeTrackable.findById(id);
if (logType != null) {
final LinearLayout inventView = (LinearLayout) findViewById(R.id.inventory);
for (int count = 0; count < inventView.getChildCount(); count++) {
final LinearLayout tbView = (LinearLayout) inventView.getChildAt(count);
if (tbView == null) {
return false;
}
final TextView tbText = (TextView) tbView.findViewById(R.id.action);
if (tbText == null) {
return false;
}
tbText.setText(res.getString(logType.resourceId));
}
for (cgTrackableLog tb : trackables) {
tb.action = logType;
}
tbChanged = true;
return true;
}
} catch (Exception e) {
Log.e(Settings.tag, "cgeovisit.onContextItemSelected: " + e.toString());
}
} else {
try {
final LogTypeTrackable logType = LogTypeTrackable.findById(id);
if (logType != null) {
final LinearLayout tbView = (LinearLayout) findViewById(group);
if (tbView == null) {
return false;
}
final TextView tbText = (TextView) tbView.findViewById(R.id.action);
if (tbText == null) {
return false;
}
for (cgTrackableLog tb : trackables) {
if (tb.id == group) {
tbChanged = true;
tb.action = logType;
tbText.setText(res.getString(logType.resourceId));
Log.i(Settings.tag, "Trackable " + tb.trackCode + " (" + tb.name + ") has new action: #" + id);
}
}
return true;
}
} catch (Exception e) {
Log.e(Settings.tag, "cgeovisit.onContextItemSelected: " + e.toString());
}
}
return false;
}
public void init() {
if (geocode != null) {
app.setAction(geocode);
}
postButton = (Button) findViewById(R.id.post);
tweetBox = (LinearLayout) findViewById(R.id.tweet_box);
tweetCheck = (CheckBox) findViewById(R.id.tweet);
clearButton = (Button) findViewById(R.id.clear);
saveButton = (Button) findViewById(R.id.save);
types = cache.getPossibleLogTypes();
final cgLog log = app.loadLogOffline(geocode);
if (log != null) {
typeSelected = log.type;
date.setTime(new Date(log.date));
text = log.log;
updatePostButtonText();
} else if (StringUtils.isNotBlank(Settings.getSignature())
&& Settings.isAutoInsertSignature()
&& StringUtils.isBlank(((EditText) findViewById(R.id.log)).getText())) {
insertIntoLog(LogTemplateProvider.applyTemplates(Settings.getSignature(), base, false), false);
}
if (!types.contains(typeSelected)) {
if (alreadyFound) {
typeSelected = cgBase.LOG_NOTE;
} else {
typeSelected = types.get(0);
}
setType(typeSelected);
}
final Button typeButton = (Button) findViewById(R.id.type);
registerForContextMenu(typeButton);
typeButton.setText(cgBase.logTypes2.get(typeSelected));
typeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openContextMenu(view);
}
});
final Button dateButton = (Button) findViewById(R.id.date);
dateButton.setText(base.formatShortDate(date.getTime().getTime()));
dateButton.setOnClickListener(new DateListener());
final EditText logView = (EditText) findViewById(R.id.log);
if (StringUtils.isBlank(logView.getText()) && StringUtils.isNotBlank(text)) {
logView.setText(text);
}
tweetCheck.setChecked(true);
if (cgBase.isEmpty(viewstates)) {
enablePostButton(false);
new LoadDataThread().start();
} else {
enablePostButton(false);
}
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveLog(true);
}
});
clearButton.setOnClickListener(new ClearListener());
}
@Override
public void setDate(Calendar dateIn) {
date = dateIn;
final Button dateButton = (Button) findViewById(R.id.date);
dateButton.setText(base.formatShortDate(date.getTime().getTime()));
}
public void setType(int type) {
final Button typeButton = (Button) findViewById(R.id.type);
if (cgBase.logTypes2.get(type) != null) {
typeSelected = type;
}
if (cgBase.logTypes2.get(typeSelected) == null) {
typeSelected = 1;
}
typeButton.setText(cgBase.logTypes2.get(typeSelected));
if (type == 2 && !tbChanged) {
// TODO: change action
} else if (type != 2 && !tbChanged) {
// TODO: change action
}
if (type == cgBase.LOG_FOUND_IT && Settings.isUseTwitter()) {
tweetBox.setVisibility(View.VISIBLE);
} else {
tweetBox.setVisibility(View.GONE);
}
updatePostButtonText();
}
private class DateListener implements View.OnClickListener {
public void onClick(View arg0) {
final Dialog dateDialog = new cgeodate(VisitCacheActivity.this, VisitCacheActivity.this, date);
dateDialog.setCancelable(true);
dateDialog.show();
}
}
private class PostListener implements View.OnClickListener {
public void onClick(View arg0) {
if (!gettingViewstate) {
waitDialog = ProgressDialog.show(VisitCacheActivity.this, null, res.getString(R.string.log_saving), true);
waitDialog.setCancelable(true);
final String log = ((EditText) findViewById(R.id.log)).getText().toString();
final Thread thread = new PostLogThread(postLogHandler, log);
thread.start();
} else {
showToast(res.getString(R.string.err_log_load_data_still));
}
}
}
private class ClearListener implements View.OnClickListener {
public void onClick(View arg0) {
app.clearLogOffline(geocode);
if (alreadyFound) {
typeSelected = cgBase.LOG_NOTE;
} else {
typeSelected = types.get(0);
}
date.setTime(new Date());
text = null;
setType(typeSelected);
final Button dateButton = (Button) findViewById(R.id.date);
dateButton.setText(base.formatShortDate(date.getTime().getTime()));
dateButton.setOnClickListener(new DateListener());
final EditText logView = (EditText) findViewById(R.id.log);
logView.setText("");
clearButton.setOnClickListener(new ClearListener());
showToast(res.getString(R.string.info_log_cleared));
}
}
private class LoadDataThread extends Thread {
public LoadDataThread() {
super("Load data for logging");
if (cacheid == null) {
showToast(res.getString(R.string.err_detail_cache_forgot_visit));
finish();
return;
}
if (!Settings.isLogin()) { // allow offline logging
showToast(res.getString(R.string.err_login));
return;
}
}
@Override
public void run() {
if (!Settings.isLogin()) {
// enable only offline logging, don't get the current state of the cache
return;
}
final Parameters params = new Parameters();
gettingViewstate = true;
attempts++;
try {
if (StringUtils.isNotBlank(cacheid)) {
params.put("ID", cacheid);
} else {
loadDataHandler.sendEmptyMessage(0);
return;
}
final String page = cgBase.getResponseData(cgBase.request("http://www.geocaching.com/seek/log.aspx", params, false, false, false));
viewstates = cgBase.getViewstates(page);
trackables = cgBase.parseTrackableLog(page);
final List<Integer> typesPre = cgBase.parseTypes(page);
if (CollectionUtils.isNotEmpty(typesPre)) {
types.clear();
types.addAll(typesPre);
types.remove(Integer.valueOf(cgBase.LOG_UPDATE_COORDINATES));
}
} catch (Exception e) {
Log.e(Settings.tag, "cgeovisit.loadData.run: " + e.toString());
}
loadDataHandler.sendEmptyMessage(0);
}
}
private class PostLogThread extends Thread {
private final Handler handler;
private final String log;
public PostLogThread(Handler handlerIn, String logIn) {
super("Post log");
handler = handlerIn;
log = logIn;
}
@Override
public void run() {
final StatusCode status = postLogFn(log);
handler.sendMessage(handler.obtainMessage(0, status));
}
}
public StatusCode postLogFn(String log) {
try {
final StatusCode status = cgBase.postLog(app, geocode, cacheid, viewstates, typeSelected,
date.get(Calendar.YEAR), (date.get(Calendar.MONTH) + 1), date.get(Calendar.DATE),
log, trackables);
if (status == StatusCode.NO_ERROR) {
final cgLog logNow = new cgLog();
logNow.author = Settings.getUsername();
logNow.date = date.getTimeInMillis();
logNow.type = typeSelected;
logNow.log = log;
if (cache != null && null != cache.getLogs()) {
cache.getLogs().add(0, logNow);
}
app.addLog(geocode, logNow);
if (typeSelected == cgBase.LOG_FOUND_IT) {
app.markFound(geocode);
if (cache != null) {
cache.setFound(true);
}
}
if (cache != null) {
app.putCacheInCache(cache);
} else {
app.removeCacheFromCache(geocode);
}
}
if (status == StatusCode.NO_ERROR) {
app.clearLogOffline(geocode);
}
if (status == StatusCode.NO_ERROR && typeSelected == cgBase.LOG_FOUND_IT && Settings.isUseTwitter()
&& Settings.isTwitterLoginValid()
&& tweetCheck.isChecked() && tweetBox.getVisibility() == View.VISIBLE) {
cgBase.postTweetCache(app, geocode);
}
if (status == StatusCode.NO_ERROR && typeSelected == cgBase.LOG_FOUND_IT && Settings.isGCvoteLogin()) {
GCVote.setRating(cache, rating);
}
return status;
} catch (Exception e) {
Log.e(Settings.tag, "cgeovisit.postLogFn: " + e.toString());
}
return StatusCode.LOG_POST_ERROR;
}
private void saveLog(final boolean force) {
final String log = currentLogText();
// Do not erase the saved log if the user has removed all the characters
// without using "Clear". This may be a manipulation mistake, and erasing
// again will be easy using "Clear" while retyping the text may not be.
if (force || (log.length() > 0 && !StringUtils.equals(log, text))) {
cache.logOffline(this, log, date, typeSelected);
}
text = log;
}
private String currentLogText() {
return ((EditText) findViewById(R.id.log)).getText().toString();
}
}
| true | true | public void handleMessage(Message msg) {
if (!types.contains(typeSelected)) {
typeSelected = types.get(0);
setType(typeSelected);
showToast(res.getString(R.string.info_log_type_changed));
}
if (cgBase.isEmpty(viewstates) && attempts < 2) {
showToast(res.getString(R.string.err_log_load_data_again));
final LoadDataThread thread;
thread = new LoadDataThread();
thread.start();
return;
} else if (cgBase.isEmpty(viewstates) && attempts >= 2) {
showToast(res.getString(R.string.err_log_load_data));
showProgress(false);
return;
}
gettingViewstate = false; // we're done, user can post log
enablePostButton(true);
// add trackables
if (CollectionUtils.isNotEmpty(trackables)) {
if (inflater == null) {
inflater = getLayoutInflater();
}
final LinearLayout inventoryView = (LinearLayout) findViewById(R.id.inventory);
inventoryView.removeAllViews();
for (cgTrackableLog tb : trackables) {
LinearLayout inventoryItem = (LinearLayout) inflater.inflate(R.layout.visit_trackable, null);
((TextView) inventoryItem.findViewById(R.id.trackcode)).setText(tb.trackCode);
((TextView) inventoryItem.findViewById(R.id.name)).setText(tb.name);
((TextView) inventoryItem.findViewById(R.id.action)).setText(res.getString(Settings.isTrackableAutoVisit() ? LogTypeTrackable.VISITED.resourceId : LogTypeTrackable.DO_NOTHING.resourceId));
inventoryItem.setId(tb.id);
final String tbCode = tb.trackCode;
inventoryItem.setClickable(true);
registerForContextMenu(inventoryItem);
inventoryItem.findViewById(R.id.info).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final Intent trackablesIntent = new Intent(VisitCacheActivity.this, cgeotrackable.class);
trackablesIntent.putExtra(EXTRAS_GEOCODE, tbCode);
startActivity(trackablesIntent);
}
});
inventoryItem.findViewById(R.id.action).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openContextMenu(view);
}
});
inventoryView.addView(inventoryItem);
if (Settings.isTrackableAutoVisit())
{
tb.action = LogTypeTrackable.VISITED;
tbChanged = true;
}
}
if (inventoryView.getChildCount() > 0) {
((LinearLayout) findViewById(R.id.inventory_box)).setVisibility(View.VISIBLE);
}
if (inventoryView.getChildCount() > 1) {
final LinearLayout inventoryChangeAllView = (LinearLayout) findViewById(R.id.inventory_changeall);
final Button changeButton = (Button) inventoryChangeAllView.findViewById(R.id.changebutton);
registerForContextMenu(changeButton);
changeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openContextMenu(view);
}
});
((LinearLayout) findViewById(R.id.inventory_changeall)).setVisibility(View.VISIBLE);
}
}
showProgress(false);
}
| public void handleMessage(Message msg) {
if (!types.contains(typeSelected)) {
typeSelected = types.get(0);
setType(typeSelected);
showToast(res.getString(R.string.info_log_type_changed));
}
if (cgBase.isEmpty(viewstates) && attempts < 2) {
showToast(res.getString(R.string.err_log_load_data_again));
final LoadDataThread thread;
thread = new LoadDataThread();
thread.start();
return;
} else if (cgBase.isEmpty(viewstates) && attempts >= 2) {
showToast(res.getString(R.string.err_log_load_data));
showProgress(false);
return;
}
gettingViewstate = false; // we're done, user can post log
enablePostButton(true);
// add trackables
if (CollectionUtils.isNotEmpty(trackables)) {
if (inflater == null) {
inflater = getLayoutInflater();
}
final LinearLayout inventoryView = (LinearLayout) findViewById(R.id.inventory);
inventoryView.removeAllViews();
for (cgTrackableLog tb : trackables) {
LinearLayout inventoryItem = (LinearLayout) inflater.inflate(R.layout.visit_trackable, null);
((TextView) inventoryItem.findViewById(R.id.trackcode)).setText(tb.trackCode);
((TextView) inventoryItem.findViewById(R.id.name)).setText(tb.name);
((TextView) inventoryItem.findViewById(R.id.action)).setText(res.getString(Settings.isTrackableAutoVisit() ? LogTypeTrackable.VISITED.resourceId : LogTypeTrackable.DO_NOTHING.resourceId));
inventoryItem.setId(tb.id);
final String tbCode = tb.trackCode;
inventoryItem.setClickable(true);
registerForContextMenu(inventoryItem);
inventoryItem.findViewById(R.id.info).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final Intent trackablesIntent = new Intent(VisitCacheActivity.this, cgeotrackable.class);
trackablesIntent.putExtra(EXTRAS_GEOCODE, tbCode);
startActivity(trackablesIntent);
}
});
inventoryItem.findViewById(R.id.action).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openContextMenu(view);
}
});
inventoryView.addView(inventoryItem);
if (Settings.isTrackableAutoVisit())
{
tb.action = LogTypeTrackable.VISITED;
tbChanged = true;
}
}
if (inventoryView.getChildCount() > 0) {
((LinearLayout) findViewById(R.id.inventory_box)).setVisibility(View.VISIBLE);
}
if (inventoryView.getChildCount() > 1) {
final LinearLayout inventoryChangeAllView = (LinearLayout) findViewById(R.id.inventory_changeall);
final Button changeButton = (Button) inventoryChangeAllView.findViewById(R.id.changebutton);
registerForContextMenu(changeButton);
changeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openContextMenu(view);
}
});
inventoryChangeAllView.setVisibility(View.VISIBLE);
}
}
showProgress(false);
}
|
diff --git a/src/org/mcteam/factions/commands/FCommandTag.java b/src/org/mcteam/factions/commands/FCommandTag.java
index 3cc3938f..2c1b69df 100644
--- a/src/org/mcteam/factions/commands/FCommandTag.java
+++ b/src/org/mcteam/factions/commands/FCommandTag.java
@@ -1,65 +1,65 @@
package org.mcteam.factions.commands;
import java.util.ArrayList;
import org.mcteam.factions.Conf;
import org.mcteam.factions.Faction;
import org.mcteam.factions.struct.Role;
import org.mcteam.factions.util.TextUtil;
public class FCommandTag extends FBaseCommand {
public FCommandTag() {
aliases.add("tag");
requiredParameters.add("faction tag");
helpDescription = "Change the faction tag";
}
public void perform() {
if ( ! assertHasFaction()) {
return;
}
if( isLocked() ) {
sendLockMessage();
return;
}
if ( ! assertMinRole(Role.MODERATOR)) {
return;
}
String tag = parameters.get(0);
// TODO does not first test cover selfcase?
if (Faction.isTagTaken(tag) && ! TextUtil.getComparisonString(tag).equals(me.getFaction().getComparisonTag())) {
sendMessage("That tag is already taken");
return;
}
ArrayList<String> errors = new ArrayList<String>();
errors.addAll(Faction.validateTag(tag));
if (errors.size() > 0) {
sendMessage(errors);
return;
}
Faction myFaction = me.getFaction();
String oldtag = myFaction.getTag();
myFaction.setTag(tag);
// Inform
myFaction.sendMessage(me.getNameAndRelevant(myFaction)+Conf.colorSystem+" changed your faction tag to "+Conf.colorMember+myFaction.getTag());
for (Faction faction : Faction.getAll()) {
if (faction == me.getFaction()) {
continue;
}
- faction.sendMessage(Conf.colorSystem+"The faction "+me.getRelationColor(faction)+oldtag+Conf.colorSystem+" chainged their name to "+myFaction.getTag(faction));
+ faction.sendMessage(Conf.colorSystem+"The faction "+me.getRelationColor(faction)+oldtag+Conf.colorSystem+" changed their name to "+myFaction.getTag(faction));
}
}
}
| true | true | public void perform() {
if ( ! assertHasFaction()) {
return;
}
if( isLocked() ) {
sendLockMessage();
return;
}
if ( ! assertMinRole(Role.MODERATOR)) {
return;
}
String tag = parameters.get(0);
// TODO does not first test cover selfcase?
if (Faction.isTagTaken(tag) && ! TextUtil.getComparisonString(tag).equals(me.getFaction().getComparisonTag())) {
sendMessage("That tag is already taken");
return;
}
ArrayList<String> errors = new ArrayList<String>();
errors.addAll(Faction.validateTag(tag));
if (errors.size() > 0) {
sendMessage(errors);
return;
}
Faction myFaction = me.getFaction();
String oldtag = myFaction.getTag();
myFaction.setTag(tag);
// Inform
myFaction.sendMessage(me.getNameAndRelevant(myFaction)+Conf.colorSystem+" changed your faction tag to "+Conf.colorMember+myFaction.getTag());
for (Faction faction : Faction.getAll()) {
if (faction == me.getFaction()) {
continue;
}
faction.sendMessage(Conf.colorSystem+"The faction "+me.getRelationColor(faction)+oldtag+Conf.colorSystem+" chainged their name to "+myFaction.getTag(faction));
}
}
| public void perform() {
if ( ! assertHasFaction()) {
return;
}
if( isLocked() ) {
sendLockMessage();
return;
}
if ( ! assertMinRole(Role.MODERATOR)) {
return;
}
String tag = parameters.get(0);
// TODO does not first test cover selfcase?
if (Faction.isTagTaken(tag) && ! TextUtil.getComparisonString(tag).equals(me.getFaction().getComparisonTag())) {
sendMessage("That tag is already taken");
return;
}
ArrayList<String> errors = new ArrayList<String>();
errors.addAll(Faction.validateTag(tag));
if (errors.size() > 0) {
sendMessage(errors);
return;
}
Faction myFaction = me.getFaction();
String oldtag = myFaction.getTag();
myFaction.setTag(tag);
// Inform
myFaction.sendMessage(me.getNameAndRelevant(myFaction)+Conf.colorSystem+" changed your faction tag to "+Conf.colorMember+myFaction.getTag());
for (Faction faction : Faction.getAll()) {
if (faction == me.getFaction()) {
continue;
}
faction.sendMessage(Conf.colorSystem+"The faction "+me.getRelationColor(faction)+oldtag+Conf.colorSystem+" changed their name to "+myFaction.getTag(faction));
}
}
|
diff --git a/org.eclipse.help.base/src/org/eclipse/help/internal/base/HelpDisplay.java b/org.eclipse.help.base/src/org/eclipse/help/internal/base/HelpDisplay.java
index fb9cccf19..355b33032 100644
--- a/org.eclipse.help.base/src/org/eclipse/help/internal/base/HelpDisplay.java
+++ b/org.eclipse.help.base/src/org/eclipse/help/internal/base/HelpDisplay.java
@@ -1,265 +1,266 @@
/*******************************************************************************
* 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 Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.help.internal.base;
import java.io.*;
import java.net.*;
import org.eclipse.core.runtime.*;
import org.eclipse.help.*;
import org.eclipse.help.internal.*;
import org.eclipse.help.internal.appserver.*;
import org.eclipse.help.internal.context.*;
/**
* This class provides methods to display help. It is independent of platform
* UI.
*/
public class HelpDisplay {
/**
* Constructor.
*/
public HelpDisplay() {
super();
}
/**
* Displays help.
*/
public void displayHelp(boolean forceExternal) {
// Do not start help view if documentaton is not available, display
// error
if (HelpSystem.getTocs().length == 0) {
HelpBasePlugin.logError(
"Failed launching help. Documentation is not installed.", //$NON-NLS-1$
null);
// There is no documentation
BaseHelpSystem.getDefaultErrorUtil()
.displayError(
HelpBaseResources
.getString("HelpDisplay.docsNotInstalled")); //$NON-NLS-1$
//Documentation is not installed.
return;
}
displayHelpURL(null, forceExternal);
}
/**
* Displays a help resource specified as a url.
* <ul>
* <li>a URL in a format that can be returned by
* {@link org.eclipse.help.IHelpResource#getHref() IHelpResource.getHref()}
* <li>a URL query in the format format
* <em>key=value&key=value ...</em> The valid keys are: "tab", "toc",
* "topic", "contextId". For example,
* <em>toc="/myplugin/mytoc.xml"&topic="/myplugin/references/myclass.html"</em>
* is valid.
* </ul>
*/
public void displayHelpResource(String href, boolean forceExternal) {
// check if this is a toc
IToc toc = HelpPlugin.getTocManager().getToc(href, Platform.getNL());
if (toc != null)
try {
displayHelpURL(
"toc=" + URLEncoder.encode(toc.getHref(), "UTF-8"), forceExternal); //$NON-NLS-1$ //$NON-NLS-2$
} catch (UnsupportedEncodingException uee) {
}
else if (href != null && (href.startsWith("tab=") //$NON-NLS-1$
|| href.startsWith("toc=") //$NON-NLS-1$
|| href.startsWith("topic=") //$NON-NLS-1$
|| href.startsWith("contextId="))) { //$NON-NLS-1$ // assume it is a query string
displayHelpURL(href, forceExternal);
} else { // assume this is a topic
if (getNoframesURL(href) == null) {
try {
displayHelpURL(
"topic=" + URLEncoder.encode(href, "UTF-8"), forceExternal); //$NON-NLS-1$ //$NON-NLS-2$
} catch (UnsupportedEncodingException uee) {
}
} else if (href.startsWith("jar:file:")) { //$NON-NLS-1$
// topic from a jar to display without frames
displayHelpURL(
getBaseURL() + "nftopic/" + getNoframesURL(href), true); //$NON-NLS-1$
} else {
displayHelpURL(getNoframesURL(href), true);
}
}
}
/**
* Display help for the a given topic and related topics.
*
* @param context
* context for which related topics will be displayed
* @param topic
* related topic to be selected
*/
public void displayHelp(IContext context, IHelpResource topic,
boolean forceExternal) {
if (context == null || topic == null || topic.getHref() == null)
return;
String topicURL = getTopicURL(topic.getHref());
if (getNoframesURL(topicURL) == null) {
try {
String url = "tab=links" //$NON-NLS-1$
+ "&contextId=" //$NON-NLS-1$
+ URLEncoder.encode(getContextID(context), "UTF-8") //$NON-NLS-1$
+ "&topic=" //$NON-NLS-1$
+ URLEncoder.encode(topicURL, "UTF-8"); //$NON-NLS-1$
displayHelpURL(url, forceExternal);
} catch (UnsupportedEncodingException uee) {
}
} else if (topicURL.startsWith("jar:file:")) { //$NON-NLS-1$
// topic from a jar to display without frames
displayHelpURL(
getBaseURL() + "nftopic/" + getNoframesURL(topicURL), true); //$NON-NLS-1$
} else {
displayHelpURL(getNoframesURL(topicURL), true);
}
}
/**
* Display help to search view for given query and selected topic.
*
* @param searchQuery
* search query in URL format key=value&key=value
* @param topic
* selected from the search results
*/
public void displaySearch(String searchQuery, String topic,
boolean forceExternal) {
if (searchQuery == null || topic == null)
return;
if (getNoframesURL(topic) == null) {
try {
String url = "tab=search&" //$NON-NLS-1$
+ searchQuery + "&topic=" //$NON-NLS-1$
+ URLEncoder.encode(getTopicURL(topic), "UTF-8"); //$NON-NLS-1$
displayHelpURL(url, forceExternal);
} catch (UnsupportedEncodingException uee) {
}
} else {
displayHelpURL(getNoframesURL(topic), true);
}
}
/**
* Displays the specified url. The url can contain query parameters to
* identify how help displays the document
*/
private void displayHelpURL(String helpURL, boolean forceExternal) {
if (!BaseHelpSystem.ensureWebappRunning()) {
return;
}
if (BaseHelpSystem.getMode() == BaseHelpSystem.MODE_STANDALONE) {
// wait for Display to be created
DisplayUtils.waitForDisplay();
}
try {
/*
if (helpURL == null || helpURL.length() == 0) {
BaseHelpSystem.getHelpBrowser(forceExternal).displayURL(
getFramesetURL());
} else if (helpURL.startsWith("tab=") //$NON-NLS-1$
|| helpURL.startsWith("toc=") //$NON-NLS-1$
|| helpURL.startsWith("topic=") //$NON-NLS-1$
|| helpURL.startsWith("contextId=")) { //$NON-NLS-1$
BaseHelpSystem.getHelpBrowser(forceExternal).displayURL(
getFramesetURL() + "?" + helpURL); //$NON-NLS-1$
} else {
BaseHelpSystem.getHelpBrowser(forceExternal)
.displayURL(helpURL);
}
*/
if (helpURL == null || helpURL.length() == 0) {
helpURL = getFramesetURL();
} else if (helpURL.startsWith("tab=") //$NON-NLS-1$
|| helpURL.startsWith("toc=") //$NON-NLS-1$
|| helpURL.startsWith("topic=") //$NON-NLS-1$
|| helpURL.startsWith("contextId=")) { //$NON-NLS-1$
helpURL = getFramesetURL() + "?" + helpURL; //$NON-NLS-1$
}
BaseHelpSystem.getHelpBrowser(forceExternal)
.displayURL(helpURL);
} catch (Exception e) {
- HelpBasePlugin.logError(
- "An exception occurred while launching help.", e); //$NON-NLS-1$
+ HelpBasePlugin
+ .logError(
+ "An exception occurred while launching help. Check the log at " + Platform.getLogFileLocation().toOSString(), e); //$NON-NLS-1$
BaseHelpSystem.getDefaultErrorUtil()
.displayError(
HelpBaseResources
- .getString("HelpDisplay.exceptionMessage")); //$NON-NLS-1$
+ .getString("HelpDisplay.exceptionMessage", Platform.getLogFileLocation().toOSString())); //$NON-NLS-1$
}
}
private String getContextID(IContext context) {
if (context instanceof Context)
return ((Context) context).getID();
return HelpPlugin.getContextManager().addContext(context);
}
private String getBaseURL() {
return "http://" //$NON-NLS-1$
+ WebappManager.getHost() + ":" //$NON-NLS-1$
+ WebappManager.getPort() + "/help/"; //$NON-NLS-1$
}
private String getFramesetURL() {
return getBaseURL() + "index.jsp"; //$NON-NLS-1$
}
private String getTopicURL(String topic) {
if (topic == null)
return null;
if (topic.startsWith("../")) //$NON-NLS-1$
topic = topic.substring(2);
/*
* if (topic.startsWith("/")) { String base = "http://" +
* AppServer.getHost() + ":" + AppServer.getPort(); base +=
* "/help/content/help:"; topic = base + topic; }
*/
return topic;
}
/**
* If href contains URL parameter noframes=true return href with that
* paramter removed, otherwise returns null
*
* @param href
* @return String or null
*/
private String getNoframesURL(String href) {
if (href == null) {
return null;
}
int ix = href.indexOf("?noframes=true&"); //$NON-NLS-1$
if (ix >= 0) {
//remove noframes=true&
return href.substring(0, ix + 1)
+ href.substring(ix + "?noframes=true&".length()); //$NON-NLS-1$
}
ix = href.indexOf("noframes=true"); //$NON-NLS-1$
if (ix > 0) {
//remove &noframes=true
return href.substring(0, ix - 1)
+ href.substring(ix + "noframes=true".length()); //$NON-NLS-1$
}
// can be displayed in frames
return null;
}
}
| false | true | private void displayHelpURL(String helpURL, boolean forceExternal) {
if (!BaseHelpSystem.ensureWebappRunning()) {
return;
}
if (BaseHelpSystem.getMode() == BaseHelpSystem.MODE_STANDALONE) {
// wait for Display to be created
DisplayUtils.waitForDisplay();
}
try {
/*
if (helpURL == null || helpURL.length() == 0) {
BaseHelpSystem.getHelpBrowser(forceExternal).displayURL(
getFramesetURL());
} else if (helpURL.startsWith("tab=") //$NON-NLS-1$
|| helpURL.startsWith("toc=") //$NON-NLS-1$
|| helpURL.startsWith("topic=") //$NON-NLS-1$
|| helpURL.startsWith("contextId=")) { //$NON-NLS-1$
BaseHelpSystem.getHelpBrowser(forceExternal).displayURL(
getFramesetURL() + "?" + helpURL); //$NON-NLS-1$
} else {
BaseHelpSystem.getHelpBrowser(forceExternal)
.displayURL(helpURL);
}
*/
if (helpURL == null || helpURL.length() == 0) {
helpURL = getFramesetURL();
} else if (helpURL.startsWith("tab=") //$NON-NLS-1$
|| helpURL.startsWith("toc=") //$NON-NLS-1$
|| helpURL.startsWith("topic=") //$NON-NLS-1$
|| helpURL.startsWith("contextId=")) { //$NON-NLS-1$
helpURL = getFramesetURL() + "?" + helpURL; //$NON-NLS-1$
}
BaseHelpSystem.getHelpBrowser(forceExternal)
.displayURL(helpURL);
} catch (Exception e) {
HelpBasePlugin.logError(
"An exception occurred while launching help.", e); //$NON-NLS-1$
BaseHelpSystem.getDefaultErrorUtil()
.displayError(
HelpBaseResources
.getString("HelpDisplay.exceptionMessage")); //$NON-NLS-1$
}
}
| private void displayHelpURL(String helpURL, boolean forceExternal) {
if (!BaseHelpSystem.ensureWebappRunning()) {
return;
}
if (BaseHelpSystem.getMode() == BaseHelpSystem.MODE_STANDALONE) {
// wait for Display to be created
DisplayUtils.waitForDisplay();
}
try {
/*
if (helpURL == null || helpURL.length() == 0) {
BaseHelpSystem.getHelpBrowser(forceExternal).displayURL(
getFramesetURL());
} else if (helpURL.startsWith("tab=") //$NON-NLS-1$
|| helpURL.startsWith("toc=") //$NON-NLS-1$
|| helpURL.startsWith("topic=") //$NON-NLS-1$
|| helpURL.startsWith("contextId=")) { //$NON-NLS-1$
BaseHelpSystem.getHelpBrowser(forceExternal).displayURL(
getFramesetURL() + "?" + helpURL); //$NON-NLS-1$
} else {
BaseHelpSystem.getHelpBrowser(forceExternal)
.displayURL(helpURL);
}
*/
if (helpURL == null || helpURL.length() == 0) {
helpURL = getFramesetURL();
} else if (helpURL.startsWith("tab=") //$NON-NLS-1$
|| helpURL.startsWith("toc=") //$NON-NLS-1$
|| helpURL.startsWith("topic=") //$NON-NLS-1$
|| helpURL.startsWith("contextId=")) { //$NON-NLS-1$
helpURL = getFramesetURL() + "?" + helpURL; //$NON-NLS-1$
}
BaseHelpSystem.getHelpBrowser(forceExternal)
.displayURL(helpURL);
} catch (Exception e) {
HelpBasePlugin
.logError(
"An exception occurred while launching help. Check the log at " + Platform.getLogFileLocation().toOSString(), e); //$NON-NLS-1$
BaseHelpSystem.getDefaultErrorUtil()
.displayError(
HelpBaseResources
.getString("HelpDisplay.exceptionMessage", Platform.getLogFileLocation().toOSString())); //$NON-NLS-1$
}
}
|
diff --git a/grails/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java b/grails/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java
index e6e5fdcb2..8c8f6b945 100644
--- a/grails/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java
+++ b/grails/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java
@@ -1,656 +1,656 @@
/*
* 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.commons.spring;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.commons.GrailsDataSource;
import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.commons.GrailsPageFlowClass;
import org.codehaus.groovy.grails.commons.GrailsServiceClass;
import org.codehaus.groovy.grails.commons.GrailsTagLibClass;
import org.codehaus.groovy.grails.commons.GrailsTaskClass;
import org.codehaus.groovy.grails.commons.GrailsTaskClassProperty;
import org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean;
import org.codehaus.groovy.grails.orm.hibernate.support.HibernateDialectDetectorFactoryBean;
import org.codehaus.groovy.grails.orm.hibernate.validation.GrailsDomainClassValidator;
import org.codehaus.groovy.grails.scaffolding.DefaultGrailsResponseHandlerFactory;
import org.codehaus.groovy.grails.scaffolding.DefaultGrailsScaffoldViewResolver;
import org.codehaus.groovy.grails.scaffolding.DefaultGrailsScaffolder;
import org.codehaus.groovy.grails.scaffolding.DefaultScaffoldRequestHandler;
import org.codehaus.groovy.grails.scaffolding.GrailsScaffoldDomain;
import org.codehaus.groovy.grails.scaffolding.ViewDelegatingScaffoldResponseHandler;
import org.codehaus.groovy.grails.support.ClassEditor;
import org.codehaus.groovy.grails.web.errors.GrailsExceptionResolver;
import org.codehaus.groovy.grails.web.pageflow.GrailsFlowBuilder;
import org.codehaus.groovy.grails.web.pageflow.execution.servlet.GrailsServletFlowExecutionManager;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsUrlHandlerMapping;
import org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController;
import org.codehaus.groovy.grails.web.servlet.view.GrailsViewResolver;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.aop.target.HotSwappableTargetSource;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateAccessor;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor;
import org.springframework.scheduling.quartz.CronTriggerBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerBean;
import org.springframework.transaction.interceptor.TransactionProxyFactoryBean;
import org.springframework.util.Assert;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.webflow.config.FlowFactoryBean;
import org.springframework.webflow.mvc.FlowController;
import org.springmodules.beans.factory.config.MapToPropertiesFactoryBean;
import org.springmodules.beans.factory.drivers.Bean;
import org.springmodules.db.hsqldb.ServerBean;
/**
* <p>Creates beans and bean references for a Grails application.
*
* @author Steven Devijver
* @since Jul 2, 2005
*/
public class SpringConfig {
private GrailsApplication application = null;
private static final Log LOG = LogFactory.getLog(SpringConfig.class);
public SpringConfig(GrailsApplication application) {
super();
this.application = application;
}
public Collection getBeanReferences() {
Collection beanReferences = new ArrayList();
Map urlMappings = new HashMap();
/**
* Regarding conversion to plugins:
*
* N/A: not applicable, does not need to be converted
* OK: already converted to plugin (please mention plugin name
*/
Assert.notNull(application);
// configure general references
// N/A
Bean classLoader = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
classLoader.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
classLoader.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getClassLoader"));
// Register custom class editor
// OK: org.codehaus.groovy.grails.plugins.support.classeditor.ClassEditorPlugin
Bean classEditor = SpringConfigUtils.createSingletonBean(ClassEditor.class);
classEditor.setProperty("classLoader", classLoader);
Bean propertyEditors = SpringConfigUtils.createSingletonBean(CustomEditorConfigurer.class);
Map customEditors = new HashMap();
customEditors.put(SpringConfigUtils.createLiteralValue("java.lang.Class"), classEditor);
propertyEditors.setProperty("customEditors", SpringConfigUtils.createMap(customEditors));
beanReferences.add(SpringConfigUtils.createBeanReference("customEditors", propertyEditors));
// configure exception handler
// OK: org.codehaus.groovy.grails.web.plugins.support.exceptionResolver.GrailsExceptionResolverPlugin
Bean exceptionHandler = SpringConfigUtils.createSingletonBean(GrailsExceptionResolver.class);
exceptionHandler.setProperty("exceptionMappings", SpringConfigUtils.createLiteralValue("java.lang.Exception=error"));
beanReferences.add(SpringConfigUtils.createBeanReference("exceptionHandler", exceptionHandler));
// configure multipart support
// OK: org.codehaus.groovy.grails.web.plugins.support.multipartresolver.CommonsMultipartResolverPlugin
Bean multipartResolver = SpringConfigUtils.createSingletonBean(CommonsMultipartResolver.class);
beanReferences.add(SpringConfigUtils.createBeanReference("multipartResolver", multipartResolver));
// configure data source & hibernate
LOG.info("[SpringConfig] Configuring i18n support");
populateI18nSupport(beanReferences);
// configure data source & hibernate
LOG.info("[SpringConfig] Configuring Grails data source");
populateDataSourceReferences(beanReferences);
// configure domain classes
LOG.info("[SpringConfig] Configuring Grails domain");
populateDomainClassReferences(beanReferences, classLoader);
// configure services
LOG.info("[SpringConfig] Configuring Grails services");
populateServiceClassReferences(beanReferences);
// configure grails page flows
LOG.info("[SpringConfig] Configuring GrabuildSessionFactoryils page flows");
populatePageFlowReferences(beanReferences, urlMappings);
// configure grails controllers
LOG.info("[SpringConfig] Configuring Grails controllers");
populateControllerReferences(beanReferences, urlMappings);
// configure scaffolding
LOG.info("[SpringConfig] Configuring Grails scaffolding");
populateScaffoldingReferences(beanReferences);
// configure tasks
LOG.info("[SpringConfig] Configuring Grails tasks");
populateTasksReferences(beanReferences);
return beanReferences;
}
// configures tasks
private void populateTasksReferences(Collection beanReferences) {
GrailsTaskClass[] grailsTaskClasses = application.getGrailsTasksClasses();
Collection schedulerReferences = new ArrayList();
// todo jdbc job loading
for (int i = 0; i < grailsTaskClasses.length; i++) {
GrailsTaskClass grailsTaskClass = grailsTaskClasses[i];
Bean taskClassBean = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
taskClassBean.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
taskClassBean.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsTaskClass"));
taskClassBean.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsTaskClass.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName() + "Class", taskClassBean));
/* additional indirrection so that autowireing would be possible */
Bean taskInstance = SpringConfigUtils.createSingletonBean();
taskInstance.setFactoryBean(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName() + "Class"));
taskInstance.setFactoryMethod("newInstance");
taskInstance.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference( grailsTaskClass.getFullName(), taskInstance));
Bean jobDetailFactoryBean = SpringConfigUtils.createSingletonBean( MethodInvokingJobDetailFactoryBean.class );
jobDetailFactoryBean.setProperty("targetObject", SpringConfigUtils.createBeanReference( grailsTaskClass.getFullName() ));
jobDetailFactoryBean.setProperty("targetMethod", SpringConfigUtils.createLiteralValue(GrailsTaskClassProperty.EXECUTE));
jobDetailFactoryBean.setProperty("group", SpringConfigUtils.createLiteralValue(grailsTaskClass.getGroup()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"JobDetail", jobDetailFactoryBean));
if( !grailsTaskClass.isCronExpressionConfigured() ){ /* configuring Task using startDelay and timeOut */
Bean triggerBean = SpringConfigUtils.createSingletonBean(SimpleTriggerBean.class);
triggerBean.setProperty("jobDetail", SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"JobDetail"));
triggerBean.setProperty("startDelay", SpringConfigUtils.createLiteralValue( grailsTaskClass.getStartDelay() ));
triggerBean.setProperty("repeatInterval", SpringConfigUtils.createLiteralValue( grailsTaskClass.getTimeout() ));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"SimpleTrigger", triggerBean));
schedulerReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"SimpleTrigger"));
}else{ /* configuring Task using cronExpression */
Bean triggerBean = SpringConfigUtils.createSingletonBean(CronTriggerBean.class);
triggerBean.setProperty("jobDetail", SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"JobDetail"));
triggerBean.setProperty("cronExpression", SpringConfigUtils.createLiteralValue(grailsTaskClass.getCronExpression()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"CronTrigger", triggerBean));
schedulerReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"CronTrigger"));
}
}
Bean schedulerFactoryBean = SpringConfigUtils.createSingletonBean(SchedulerFactoryBean.class);
schedulerFactoryBean.setProperty("triggers", SpringConfigUtils.createList(schedulerReferences));
beanReferences.add(SpringConfigUtils.createBeanReference("GrailsSchedulerBean",schedulerFactoryBean));
}
private void populateI18nSupport(Collection beanReferences) {
// setup message source
// OK: org.codehaus.groovy.grails.web.plugins.support.i18n.ReloadableResourceBundleMessageSourcePlugin
Bean messageSource = SpringConfigUtils.createSingletonBean( ReloadableResourceBundleMessageSource.class );
messageSource.setProperty( "basename", SpringConfigUtils.createLiteralValue("WEB-INF/classes/grails-app/i18n/messages"));
beanReferences.add(SpringConfigUtils.createBeanReference("messageSource", messageSource));
// setup locale change interceptor
// OK: org.codehaus.groovy.grails.web.plugins.support.i18n.LocaleChangeInterceptorPlugin
Bean localeChangeInterceptor = SpringConfigUtils.createSingletonBean(LocaleChangeInterceptor.class);
localeChangeInterceptor.setProperty("paramName", SpringConfigUtils.createLiteralValue("lang"));
beanReferences.add(SpringConfigUtils.createBeanReference("localeChangeInterceptor", localeChangeInterceptor));
// setup locale resolver
// OK: org.codehaus.groovy.grails.web.plugins.support.i18n.CookieLocaleResolverPlugin
Bean localeResolver = SpringConfigUtils.createSingletonBean(CookieLocaleResolver.class);
beanReferences.add(SpringConfigUtils.createBeanReference("localeResolver", localeResolver));
}
// configures scaffolding
private void populateScaffoldingReferences(Collection beanReferences) {
// go through all the controllers
GrailsControllerClass[] simpleControllers = application.getControllers();
for (int i = 0; i < simpleControllers.length; i++) {
// retrieve appropriate domain class
Class scaffoldedClass = simpleControllers[i].getScaffoldedClass();
GrailsDomainClass domainClass;
if(scaffoldedClass == null) {
domainClass = application.getGrailsDomainClass(simpleControllers[i].getName());
if(domainClass != null) {
scaffoldedClass = domainClass.getClazz();
}
}
if(scaffoldedClass == null) {
LOG.info("[Spring] Scaffolding disabled for controller ["+simpleControllers[i].getFullName()+"], no equivalent domain class named ["+simpleControllers[i].getName()+"]");
}
else {
Bean scaffolder = SpringConfigUtils.createSingletonBean(DefaultGrailsScaffolder.class);
// create scaffold domain
Collection constructorArguments = new ArrayList();
constructorArguments.add(SpringConfigUtils.createLiteralValue(scaffoldedClass.getName()));
constructorArguments.add(SpringConfigUtils.createBeanReference("sessionFactory"));
Bean domain = SpringConfigUtils.createSingletonBean(GrailsScaffoldDomain.class, constructorArguments);
// domain.setProperty("validator", SpringConfigUtils.createBeanReference( domainClass.getFullName() + "Validator"));
beanReferences.add( SpringConfigUtils.createBeanReference( scaffoldedClass.getName() + "ScaffoldDomain",domain ) );
// create and configure request handler
Bean requestHandler = SpringConfigUtils.createSingletonBean(DefaultScaffoldRequestHandler.class);
requestHandler.setProperty("scaffoldDomain", SpringConfigUtils.createBeanReference(scaffoldedClass.getName() + "ScaffoldDomain"));
// create response factory
constructorArguments = new ArrayList();
constructorArguments.add(SpringConfigUtils.createBeanReference("grailsApplication"));
// configure default response handler
Bean defaultResponseHandler = SpringConfigUtils.createSingletonBean(ViewDelegatingScaffoldResponseHandler.class);
// configure a simple view delegating resolver
Bean defaultViewResolver = SpringConfigUtils.createSingletonBean(DefaultGrailsScaffoldViewResolver.class,constructorArguments);
defaultResponseHandler.setProperty("scaffoldViewResolver", defaultViewResolver);
// create constructor arguments response handler factory
constructorArguments = new ArrayList();
constructorArguments.add(SpringConfigUtils.createBeanReference("grailsApplication"));
constructorArguments.add(defaultResponseHandler);
Bean responseHandlerFactory = SpringConfigUtils.createSingletonBean( DefaultGrailsResponseHandlerFactory.class,constructorArguments );
scaffolder.setProperty( "scaffoldResponseHandlerFactory", responseHandlerFactory );
scaffolder.setProperty("scaffoldRequestHandler", requestHandler);
beanReferences.add( SpringConfigUtils.createBeanReference( simpleControllers[i].getFullName() + "Scaffolder",scaffolder ) );
}
}
}
private void populateControllerReferences(Collection beanReferences, Map urlMappings) {
Bean simpleGrailsController = SpringConfigUtils.createSingletonBean(SimpleGrailsController.class);
simpleGrailsController.setAutowire("byType");
beanReferences.add(SpringConfigUtils.createBeanReference(SimpleGrailsController.APPLICATION_CONTEXT_ID, simpleGrailsController));
Bean grailsViewResolver = SpringConfigUtils.createSingletonBean(GrailsViewResolver.class);
grailsViewResolver.setProperty("viewClass",SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.view.JstlView"));
- grailsViewResolver.setProperty("prefix", SpringConfigUtils.createLiteralValue(GrailsApplicationAttributes.PATH_TO_VIEWS));
+ grailsViewResolver.setProperty("prefix", SpringConfigUtils.createLiteralValue(GrailsApplicationAttributes.PATH_TO_VIEWS + '/'));
grailsViewResolver.setProperty("suffix", SpringConfigUtils.createLiteralValue(".jsp"));
beanReferences.add(SpringConfigUtils.createBeanReference("jspViewResolver", grailsViewResolver));
Bean simpleUrlHandlerMapping = null;
if (application.getControllers().length > 0 || application.getPageFlows().length > 0) {
simpleUrlHandlerMapping = SpringConfigUtils.createSingletonBean(GrailsUrlHandlerMapping.class);
//beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID + "Target", simpleUrlHandlerMapping));
Collection args = new ArrayList();
args.add(simpleUrlHandlerMapping);
Bean simpleUrlHandlerMappingTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE,simpleUrlHandlerMappingTargetSource));
// configure handler interceptors
Bean openSessionInViewInterceptor = SpringConfigUtils.createSingletonBean(OpenSessionInViewInterceptor.class);
openSessionInViewInterceptor.setProperty("flushMode",SpringConfigUtils.createLiteralValue(String.valueOf(HibernateAccessor.FLUSH_AUTO)));
openSessionInViewInterceptor.setProperty("sessionFactory", SpringConfigUtils.createBeanReference("sessionFactory"));
beanReferences.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor",openSessionInViewInterceptor));
Collection interceptors = new ArrayList();
interceptors.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor"));
simpleUrlHandlerMapping.setProperty("interceptors", SpringConfigUtils.createList(interceptors));
Bean simpleUrlHandlerMappingProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
simpleUrlHandlerMappingProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE));
simpleUrlHandlerMappingProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.HandlerMapping"));
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID, simpleUrlHandlerMappingProxy));
}
GrailsControllerClass[] simpleControllers = application.getControllers();
for (int i = 0; i < simpleControllers.length; i++) {
GrailsControllerClass simpleController = simpleControllers[i];
if (!simpleController.getAvailable()) {
continue;
}
// setup controller class by retrieving it from the grails application
Bean controllerClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
controllerClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
controllerClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getController"));
controllerClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(simpleController.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class", controllerClass));
// configure controller class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class"));
Bean controllerTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource", controllerTargetSource));
// setup AOP proxy that uses hot swappable target source
Bean controllerClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
controllerClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource"));
controllerClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsControllerClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy", controllerClassProxy));
// create prototype bean that uses the controller AOP proxy controller class bean as a factory
Bean controller = SpringConfigUtils.createPrototypeBean();
controller.setFactoryBean(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy"));
controller.setFactoryMethod("newInstance");
controller.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName(), controller));
for (int x = 0; x < simpleController.getURIs().length; x++) {
if(!urlMappings.containsKey(simpleController.getURIs()[x]))
urlMappings.put(simpleController.getURIs()[x], SimpleGrailsController.APPLICATION_CONTEXT_ID);
}
}
if (simpleUrlHandlerMapping != null) {
simpleUrlHandlerMapping.setProperty("mappings", SpringConfigUtils.createProperties(urlMappings));
}
GrailsTagLibClass[] tagLibs = application.getGrailsTabLibClasses();
for (int i = 0; i < tagLibs.length; i++) {
GrailsTagLibClass grailsTagLib = tagLibs[i];
// setup taglib class by retrieving it from the grails application bean
Bean taglibClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
taglibClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
taglibClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsTagLibClass"));
taglibClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsTagLib.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class", taglibClass));
// configure taglib class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class"));
Bean taglibTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
// setup AOP proxy that uses hot swappable target source
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource", taglibTargetSource));
Bean taglibClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
taglibClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource"));
taglibClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsTagLibClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy", taglibClassProxy));
// create prototype bean that refers to the AOP proxied taglib class uses it as a factory
Bean taglib = SpringConfigUtils.createPrototypeBean();
taglib.setFactoryBean(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy"));
taglib.setFactoryMethod("newInstance");
taglib.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName(), taglib));
}
}
private void populateDataSourceReferences(Collection beanReferences) {
boolean dependsOnHsqldbServer = false;
GrailsDataSource grailsDataSource = application.getGrailsDataSource();
Bean localSessionFactoryBean = SpringConfigUtils.createSingletonBean(ConfigurableLocalSessionFactoryBean.class);
if (grailsDataSource != null) {
// OK: org.codehaus.groovy.grails.plugins.datasource.PooledDatasourcePlugin
// OK: org.codehaus.groovy.grails.plugins.datasource.NonPooledDataSourcePlugin
Bean dataSource;
if (grailsDataSource.isPooled()) {
dataSource = SpringConfigUtils.createSingletonBean(BasicDataSource.class);
dataSource.setDestroyMethod("close");
} else {
dataSource = SpringConfigUtils.createSingletonBean(DriverManagerDataSource.class);
}
dataSource.setProperty("driverClassName", SpringConfigUtils.createLiteralValue(grailsDataSource.getDriverClassName()));
dataSource.setProperty("url", SpringConfigUtils.createLiteralValue(grailsDataSource.getUrl()));
dataSource.setProperty("username", SpringConfigUtils.createLiteralValue(grailsDataSource.getUsername()));
dataSource.setProperty("password", SpringConfigUtils.createLiteralValue(grailsDataSource.getPassword()));
if(grailsDataSource.getConfigurationClass() != null) {
LOG.info("[SpringConfig] Using custom Hibernate configuration class ["+grailsDataSource.getConfigurationClass()+"]");
localSessionFactoryBean.setProperty("configClass", SpringConfigUtils.createLiteralValue(grailsDataSource.getConfigurationClass().getName()));
}
beanReferences.add(SpringConfigUtils.createBeanReference("dataSource", dataSource));
} else {
// N/A
Bean dataSource = SpringConfigUtils.createSingletonBean(BasicDataSource.class);
dataSource.setDestroyMethod("close");
dataSource.setProperty("driverClassName", SpringConfigUtils.createLiteralValue("org.hsqldb.jdbcDriver"));
dataSource.setProperty("url", SpringConfigUtils.createLiteralValue("jdbc:hsqldb:hsql://localhost:9101/"));
dataSource.setProperty("username", SpringConfigUtils.createLiteralValue("sa"));
dataSource.setProperty("password", SpringConfigUtils.createLiteralValue(""));
beanReferences.add(SpringConfigUtils.createBeanReference("dataSource", dataSource));
Bean hsqldbServer = SpringConfigUtils.createSingletonBean(ServerBean.class);
hsqldbServer.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
Map hsqldbProperties = new HashMap();
hsqldbProperties.put("server.port", "9101");
hsqldbProperties.put("server.database.0", "mem:temp");
hsqldbServer.setProperty("serverProperties", SpringConfigUtils.createProperties(hsqldbProperties));
beanReferences.add(SpringConfigUtils.createBeanReference("hsqldbServer", hsqldbServer));
dependsOnHsqldbServer = true;
}
// OK: org.codehaus.groovy.grails.plugins.hibernate.HibernateDialectDetectorPlugin
Map vendorNameDialectMappings = new HashMap();
URL hibernateDialects = this.application.getClassLoader().getResource("hibernate-dialects.properties");
if(hibernateDialects != null) {
Properties p = new Properties();
try {
p.load(hibernateDialects.openStream());
Iterator iter = p.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry e = (Map.Entry)iter.next();
// Note: the entry is reversed in the properties file since the database product
// name can contain spaces.
vendorNameDialectMappings.put(e.getValue(), "org.hibernate.dialect." + e.getKey());
}
} catch (IOException e) {
LOG.info("[SpringConfig] Error loading hibernate-dialects.properties file: " + e.getMessage());
}
}
Bean dialectDetector = SpringConfigUtils.createSingletonBean(HibernateDialectDetectorFactoryBean.class);
dialectDetector.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
dialectDetector.setProperty("vendorNameDialectMappings", SpringConfigUtils.createProperties(vendorNameDialectMappings));
if (dependsOnHsqldbServer) {
Collection dependsOn = new ArrayList();
dependsOn.add(SpringConfigUtils.createBeanReference("hsqldbServer"));
dialectDetector.setDependsOn(dependsOn);
}
Map hibernatePropertiesMap = new HashMap();
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.dialect"), dialectDetector);
if(grailsDataSource == null ) {
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.hbm2ddl.auto"), SpringConfigUtils.createLiteralValue("create-drop"));
}
else {
if(grailsDataSource.getDbCreate() != null) {
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.hbm2ddl.auto"), SpringConfigUtils.createLiteralValue(grailsDataSource.getDbCreate()));
}
}
Bean hibernateProperties = SpringConfigUtils.createSingletonBean(MapToPropertiesFactoryBean.class);
hibernateProperties.setProperty("map", SpringConfigUtils.createMap(hibernatePropertiesMap));
// N/A
Bean grailsClassLoader = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
grailsClassLoader.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
grailsClassLoader.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getClassLoader"));
localSessionFactoryBean.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
ClassLoader cl = this.application.getClassLoader();
URL hibernateConfig = cl.getResource("hibernate.cfg.xml");
if(hibernateConfig != null) {
localSessionFactoryBean.setProperty("configLocation", SpringConfigUtils.createLiteralValue("classpath:hibernate.cfg.xml"));
}
localSessionFactoryBean.setProperty("hibernateProperties", hibernateProperties);
localSessionFactoryBean.setProperty("grailsApplication", SpringConfigUtils.createBeanReference("grailsApplication"));
localSessionFactoryBean.setProperty("classLoader", grailsClassLoader);
beanReferences.add(SpringConfigUtils.createBeanReference("sessionFactory", localSessionFactoryBean));
// OK: org.codehaus.groovy.grails.plugins.hibernate.HibernateTransactionManagerPlugin
Bean transactionManager = SpringConfigUtils.createSingletonBean(HibernateTransactionManager.class);
transactionManager.setProperty("sessionFactory", SpringConfigUtils.createBeanReference("sessionFactory"));
beanReferences.add(SpringConfigUtils.createBeanReference("transactionManager", transactionManager));
}
private void populateDomainClassReferences(Collection beanReferences, Bean classLoader) {
GrailsDomainClass[] grailsDomainClasses = application.getGrailsDomainClasses();
for (int i = 0; i < grailsDomainClasses.length; i++) {
GrailsDomainClass grailsDomainClass = grailsDomainClasses[i];
Bean domainClassBean = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
domainClassBean.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
domainClassBean.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsDomainClass"));
domainClassBean.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsDomainClass.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsDomainClass.getFullName() + "DomainClass", domainClassBean));
// create persistent class bean references
Bean persistentClassBean = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
persistentClassBean.setProperty("targetObject", SpringConfigUtils.createBeanReference(grailsDomainClass.getFullName() + "DomainClass"));
persistentClassBean.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getClazz"));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsDomainClass.getFullName() + "PersistentClass", persistentClassBean));
/*Collection constructorArguments = new ArrayList();
// configure persistent methods
constructorArguments.add(SpringConfigUtils.createBeanReference("grailsApplication"));
constructorArguments.add(SpringConfigUtils.createLiteralValue(grailsDomainClass.getClazz().getName()));
constructorArguments.add(SpringConfigUtils.createBeanReference("sessionFactory"));
constructorArguments.add(classLoader);
Bean hibernatePersistentMethods = SpringConfigUtils.createSingletonBean(DomainClassMethods.class, constructorArguments);
beanReferences.add(SpringConfigUtils.createBeanReference(grailsDomainClass.getFullName() + "PersistentMethods", hibernatePersistentMethods));*/
// configure validator
Bean validatorBean = SpringConfigUtils.createSingletonBean( GrailsDomainClassValidator.class);
validatorBean.setProperty( "domainClass" ,SpringConfigUtils.createBeanReference(grailsDomainClass.getFullName() + "DomainClass") );
validatorBean.setProperty( "sessionFactory" ,SpringConfigUtils.createBeanReference("sessionFactory") );
validatorBean.setProperty( "messageSource" ,SpringConfigUtils.createBeanReference("messageSource") );
beanReferences.add( SpringConfigUtils.createBeanReference( grailsDomainClass.getFullName() + "Validator", validatorBean ) );
}
}
private void populateServiceClassReferences(Collection beanReferences) {
GrailsServiceClass[] serviceClasses = application.getGrailsServiceClasses();
for (int i = 0; i <serviceClasses.length; i++) {
GrailsServiceClass grailsServiceClass = serviceClasses[i];
Bean serviceClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
serviceClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
serviceClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsServiceClass"));
serviceClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsServiceClass.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsServiceClass.getFullName() + "Class", serviceClass));
Bean serviceInstance = SpringConfigUtils.createSingletonBean();
serviceInstance.setFactoryBean(SpringConfigUtils.createBeanReference(grailsServiceClass.getFullName() + "Class"));
serviceInstance.setFactoryMethod("newInstance");
if (grailsServiceClass.byName()) {
serviceInstance.setAutowire("byName");
} else if (grailsServiceClass.byType()) {
serviceInstance.setAutowire("byType");
}
// configure the service instance as a hotswappable target source
// if its transactional configure transactional proxy
if (grailsServiceClass.isTransactional()) {
Map transactionAttributes = new HashMap();
transactionAttributes.put("*", "PROPAGATION_REQUIRED");
Bean transactionalProxy = SpringConfigUtils.createSingletonBean(TransactionProxyFactoryBean.class);
transactionalProxy.setProperty("target", serviceInstance);
transactionalProxy.setProperty("proxyTargetClass", SpringConfigUtils.createLiteralValue("true"));
transactionalProxy.setProperty("transactionAttributes", SpringConfigUtils.createProperties(transactionAttributes));
transactionalProxy.setProperty("transactionManager", SpringConfigUtils.createBeanReference("transactionManager"));
beanReferences.add(SpringConfigUtils.createBeanReference(WordUtils.uncapitalize(grailsServiceClass.getName()) + "Service", transactionalProxy));
} else {
// otherwise configure a standard proxy
beanReferences.add(SpringConfigUtils.createBeanReference(WordUtils.uncapitalize(grailsServiceClass.getName()) + "Service", serviceInstance));
}
}
}
/**
* Configures Grails page flows
*/
private void populatePageFlowReferences(Collection beanReferences, Map urlMappings) {
GrailsPageFlowClass[] pageFlows = application.getPageFlows();
for (int i = 0; i < pageFlows.length; i++) {
GrailsPageFlowClass pageFlow = pageFlows[i];
if (!pageFlow.getAvailable()) {
continue;
}
Bean pageFlowClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
pageFlowClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
pageFlowClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getPageFlow"));
pageFlowClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(pageFlow.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class", pageFlowClass));
Bean pageFlowInstance = SpringConfigUtils.createSingletonBean();
pageFlowInstance.setFactoryBean(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class"));
pageFlowInstance.setFactoryMethod("newInstance");
if (pageFlow.byType()) {
pageFlowInstance.setAutowire("byType");
} else if (pageFlow.byName()) {
pageFlowInstance.setAutowire("byName");
}
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName(), pageFlowInstance));
Bean flowBuilder = SpringConfigUtils.createSingletonBean(GrailsFlowBuilder.class);
flowBuilder.setProperty("pageFlowClass", SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class"));
Bean flowFactoryBean = SpringConfigUtils.createSingletonBean(FlowFactoryBean.class);
flowFactoryBean.setProperty("flowBuilder", flowBuilder);
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFlowId(), flowFactoryBean));
if (pageFlow.getAccessible()) {
Bean flowExecutionManager = SpringConfigUtils.createSingletonBean(GrailsServletFlowExecutionManager.class);
flowExecutionManager.setProperty("flow", SpringConfigUtils.createBeanReference(pageFlow.getFlowId()));
Bean flowController = SpringConfigUtils.createSingletonBean(FlowController.class);
flowController.setProperty("flowExecutionManager", flowExecutionManager);
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Controller", flowController));
urlMappings.put(pageFlow.getUri(), pageFlow.getFullName() + "Controller");
}
}
}
}
| true | true | private void populateControllerReferences(Collection beanReferences, Map urlMappings) {
Bean simpleGrailsController = SpringConfigUtils.createSingletonBean(SimpleGrailsController.class);
simpleGrailsController.setAutowire("byType");
beanReferences.add(SpringConfigUtils.createBeanReference(SimpleGrailsController.APPLICATION_CONTEXT_ID, simpleGrailsController));
Bean grailsViewResolver = SpringConfigUtils.createSingletonBean(GrailsViewResolver.class);
grailsViewResolver.setProperty("viewClass",SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.view.JstlView"));
grailsViewResolver.setProperty("prefix", SpringConfigUtils.createLiteralValue(GrailsApplicationAttributes.PATH_TO_VIEWS));
grailsViewResolver.setProperty("suffix", SpringConfigUtils.createLiteralValue(".jsp"));
beanReferences.add(SpringConfigUtils.createBeanReference("jspViewResolver", grailsViewResolver));
Bean simpleUrlHandlerMapping = null;
if (application.getControllers().length > 0 || application.getPageFlows().length > 0) {
simpleUrlHandlerMapping = SpringConfigUtils.createSingletonBean(GrailsUrlHandlerMapping.class);
//beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID + "Target", simpleUrlHandlerMapping));
Collection args = new ArrayList();
args.add(simpleUrlHandlerMapping);
Bean simpleUrlHandlerMappingTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE,simpleUrlHandlerMappingTargetSource));
// configure handler interceptors
Bean openSessionInViewInterceptor = SpringConfigUtils.createSingletonBean(OpenSessionInViewInterceptor.class);
openSessionInViewInterceptor.setProperty("flushMode",SpringConfigUtils.createLiteralValue(String.valueOf(HibernateAccessor.FLUSH_AUTO)));
openSessionInViewInterceptor.setProperty("sessionFactory", SpringConfigUtils.createBeanReference("sessionFactory"));
beanReferences.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor",openSessionInViewInterceptor));
Collection interceptors = new ArrayList();
interceptors.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor"));
simpleUrlHandlerMapping.setProperty("interceptors", SpringConfigUtils.createList(interceptors));
Bean simpleUrlHandlerMappingProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
simpleUrlHandlerMappingProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE));
simpleUrlHandlerMappingProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.HandlerMapping"));
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID, simpleUrlHandlerMappingProxy));
}
GrailsControllerClass[] simpleControllers = application.getControllers();
for (int i = 0; i < simpleControllers.length; i++) {
GrailsControllerClass simpleController = simpleControllers[i];
if (!simpleController.getAvailable()) {
continue;
}
// setup controller class by retrieving it from the grails application
Bean controllerClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
controllerClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
controllerClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getController"));
controllerClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(simpleController.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class", controllerClass));
// configure controller class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class"));
Bean controllerTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource", controllerTargetSource));
// setup AOP proxy that uses hot swappable target source
Bean controllerClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
controllerClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource"));
controllerClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsControllerClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy", controllerClassProxy));
// create prototype bean that uses the controller AOP proxy controller class bean as a factory
Bean controller = SpringConfigUtils.createPrototypeBean();
controller.setFactoryBean(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy"));
controller.setFactoryMethod("newInstance");
controller.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName(), controller));
for (int x = 0; x < simpleController.getURIs().length; x++) {
if(!urlMappings.containsKey(simpleController.getURIs()[x]))
urlMappings.put(simpleController.getURIs()[x], SimpleGrailsController.APPLICATION_CONTEXT_ID);
}
}
if (simpleUrlHandlerMapping != null) {
simpleUrlHandlerMapping.setProperty("mappings", SpringConfigUtils.createProperties(urlMappings));
}
GrailsTagLibClass[] tagLibs = application.getGrailsTabLibClasses();
for (int i = 0; i < tagLibs.length; i++) {
GrailsTagLibClass grailsTagLib = tagLibs[i];
// setup taglib class by retrieving it from the grails application bean
Bean taglibClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
taglibClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
taglibClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsTagLibClass"));
taglibClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsTagLib.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class", taglibClass));
// configure taglib class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class"));
Bean taglibTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
// setup AOP proxy that uses hot swappable target source
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource", taglibTargetSource));
Bean taglibClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
taglibClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource"));
taglibClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsTagLibClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy", taglibClassProxy));
// create prototype bean that refers to the AOP proxied taglib class uses it as a factory
Bean taglib = SpringConfigUtils.createPrototypeBean();
taglib.setFactoryBean(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy"));
taglib.setFactoryMethod("newInstance");
taglib.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName(), taglib));
}
}
| private void populateControllerReferences(Collection beanReferences, Map urlMappings) {
Bean simpleGrailsController = SpringConfigUtils.createSingletonBean(SimpleGrailsController.class);
simpleGrailsController.setAutowire("byType");
beanReferences.add(SpringConfigUtils.createBeanReference(SimpleGrailsController.APPLICATION_CONTEXT_ID, simpleGrailsController));
Bean grailsViewResolver = SpringConfigUtils.createSingletonBean(GrailsViewResolver.class);
grailsViewResolver.setProperty("viewClass",SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.view.JstlView"));
grailsViewResolver.setProperty("prefix", SpringConfigUtils.createLiteralValue(GrailsApplicationAttributes.PATH_TO_VIEWS + '/'));
grailsViewResolver.setProperty("suffix", SpringConfigUtils.createLiteralValue(".jsp"));
beanReferences.add(SpringConfigUtils.createBeanReference("jspViewResolver", grailsViewResolver));
Bean simpleUrlHandlerMapping = null;
if (application.getControllers().length > 0 || application.getPageFlows().length > 0) {
simpleUrlHandlerMapping = SpringConfigUtils.createSingletonBean(GrailsUrlHandlerMapping.class);
//beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID + "Target", simpleUrlHandlerMapping));
Collection args = new ArrayList();
args.add(simpleUrlHandlerMapping);
Bean simpleUrlHandlerMappingTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE,simpleUrlHandlerMappingTargetSource));
// configure handler interceptors
Bean openSessionInViewInterceptor = SpringConfigUtils.createSingletonBean(OpenSessionInViewInterceptor.class);
openSessionInViewInterceptor.setProperty("flushMode",SpringConfigUtils.createLiteralValue(String.valueOf(HibernateAccessor.FLUSH_AUTO)));
openSessionInViewInterceptor.setProperty("sessionFactory", SpringConfigUtils.createBeanReference("sessionFactory"));
beanReferences.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor",openSessionInViewInterceptor));
Collection interceptors = new ArrayList();
interceptors.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor"));
simpleUrlHandlerMapping.setProperty("interceptors", SpringConfigUtils.createList(interceptors));
Bean simpleUrlHandlerMappingProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
simpleUrlHandlerMappingProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE));
simpleUrlHandlerMappingProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.HandlerMapping"));
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID, simpleUrlHandlerMappingProxy));
}
GrailsControllerClass[] simpleControllers = application.getControllers();
for (int i = 0; i < simpleControllers.length; i++) {
GrailsControllerClass simpleController = simpleControllers[i];
if (!simpleController.getAvailable()) {
continue;
}
// setup controller class by retrieving it from the grails application
Bean controllerClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
controllerClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
controllerClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getController"));
controllerClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(simpleController.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class", controllerClass));
// configure controller class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class"));
Bean controllerTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource", controllerTargetSource));
// setup AOP proxy that uses hot swappable target source
Bean controllerClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
controllerClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource"));
controllerClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsControllerClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy", controllerClassProxy));
// create prototype bean that uses the controller AOP proxy controller class bean as a factory
Bean controller = SpringConfigUtils.createPrototypeBean();
controller.setFactoryBean(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy"));
controller.setFactoryMethod("newInstance");
controller.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName(), controller));
for (int x = 0; x < simpleController.getURIs().length; x++) {
if(!urlMappings.containsKey(simpleController.getURIs()[x]))
urlMappings.put(simpleController.getURIs()[x], SimpleGrailsController.APPLICATION_CONTEXT_ID);
}
}
if (simpleUrlHandlerMapping != null) {
simpleUrlHandlerMapping.setProperty("mappings", SpringConfigUtils.createProperties(urlMappings));
}
GrailsTagLibClass[] tagLibs = application.getGrailsTabLibClasses();
for (int i = 0; i < tagLibs.length; i++) {
GrailsTagLibClass grailsTagLib = tagLibs[i];
// setup taglib class by retrieving it from the grails application bean
Bean taglibClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
taglibClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
taglibClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsTagLibClass"));
taglibClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsTagLib.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class", taglibClass));
// configure taglib class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class"));
Bean taglibTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
// setup AOP proxy that uses hot swappable target source
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource", taglibTargetSource));
Bean taglibClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
taglibClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource"));
taglibClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsTagLibClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy", taglibClassProxy));
// create prototype bean that refers to the AOP proxied taglib class uses it as a factory
Bean taglib = SpringConfigUtils.createPrototypeBean();
taglib.setFactoryBean(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy"));
taglib.setFactoryMethod("newInstance");
taglib.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName(), taglib));
}
}
|
diff --git a/src/com/android/deskclock/DeskClock.java b/src/com/android/deskclock/DeskClock.java
index f8b7129..e7060b5 100644
--- a/src/com/android/deskclock/DeskClock.java
+++ b/src/com/android/deskclock/DeskClock.java
@@ -1,733 +1,739 @@
/*
* 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.deskclock;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
import static android.os.BatteryManager.BATTERY_STATUS_FULL;
import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
/**
* DeskClock clock view for desk docks.
*/
public class DeskClock extends Activity {
private static final boolean DEBUG = false;
private static final String LOG_TAG = "DeskClock";
// Package ID of the music player.
private static final String MUSIC_PACKAGE_ID = "com.android.music";
// Alarm action for midnight (so we can update the date display).
private static final String ACTION_MIDNIGHT = "com.android.deskclock.MIDNIGHT";
// Interval between polls of the weather widget. Its refresh period is
// likely to be much longer (~3h), but we want to pick up any changes
// within 5 minutes.
private final long FETCH_WEATHER_DELAY = 5 * 60 * 1000; // 5 min
// Delay before engaging the burn-in protection mode (green-on-black).
private final long SCREEN_SAVER_TIMEOUT = 10 * 60 * 1000; // 10 min
// Repositioning delay in screen saver.
private final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min
// Color to use for text & graphics in screen saver mode.
private final int SCREEN_SAVER_COLOR = 0xFF308030;
private final int SCREEN_SAVER_COLOR_DIM = 0xFF183018;
// Internal message IDs.
private final int FETCH_WEATHER_DATA_MSG = 0x1000;
private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000;
private final int SCREEN_SAVER_MOVE_MSG = 0x2001;
// Weather widget query information.
private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
private static final String WEATHER_CONTENT_PATH = "/weather/current";
private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
"location",
"timestamp",
"temperature",
"highTemperature",
"lowTemperature",
"iconUrl",
"iconResId",
"description",
};
// State variables follow.
private DigitalClock mTime;
private TextView mDate;
private TextView mNextAlarm = null;
private TextView mBatteryDisplay;
private TextView mWeatherCurrentTemperature;
private TextView mWeatherHighTemperature;
private TextView mWeatherLowTemperature;
private TextView mWeatherLocation;
private ImageView mWeatherIcon;
private String mWeatherCurrentTemperatureString;
private String mWeatherHighTemperatureString;
private String mWeatherLowTemperatureString;
private String mWeatherLocationString;
private Drawable mWeatherIconDrawable;
private Resources mGenieResources = null;
private boolean mDimmed = false;
private boolean mScreenSaverMode = false;
private DateFormat mDateFormat;
private int mBatteryLevel = -1;
private boolean mPluggedIn = false;
private boolean mInDock = false;
private int mIdleTimeoutEpoch = 0;
private boolean mWeatherFetchScheduled = false;
private Random mRNG;
private PendingIntent mMidnightIntent;
private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_DATE_CHANGED.equals(action)) {
refreshDate();
} else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
handleBatteryUpdate(
intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
intent.getIntExtra("level", 0));
}
}
};
private final Handler mHandy = new Handler() {
@Override
public void handleMessage(Message m) {
if (m.what == FETCH_WEATHER_DATA_MSG) {
if (!mWeatherFetchScheduled) return;
mWeatherFetchScheduled = false;
new Thread() { public void run() { fetchWeatherData(); } }.start();
scheduleWeatherFetchDelayed(FETCH_WEATHER_DELAY);
} else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
updateWeatherDisplay();
} else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
if (m.arg1 == mIdleTimeoutEpoch) {
saveScreen();
}
} else if (m.what == SCREEN_SAVER_MOVE_MSG) {
moveScreenSaver();
}
}
};
private void moveScreenSaver() {
moveScreenSaverTo(-1,-1);
}
private void moveScreenSaverTo(int x, int y) {
if (!mScreenSaverMode) return;
final View saver_view = findViewById(R.id.saver_view);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (x < 0 || y < 0) {
int myWidth = saver_view.getMeasuredWidth();
int myHeight = saver_view.getMeasuredHeight();
x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
}
if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)",
System.currentTimeMillis(), x, y));
saver_view.setLayoutParams(new AbsoluteLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
x,
y));
// Synchronize our jumping so that it happens exactly on the second.
mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG,
SCREEN_SAVER_MOVE_DELAY +
(1000 - (System.currentTimeMillis() % 1000)));
}
private void setWakeLock(boolean hold) {
if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
winParams.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
winParams.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
if (hold)
winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
else
winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
win.setAttributes(winParams);
}
private void restoreScreen() {
if (!mScreenSaverMode) return;
if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
mScreenSaverMode = false;
initViews();
doDim(false); // restores previous dim mode
refreshAll();
}
// Special screen-saver mode for OLED displays that burn in quickly
private void saveScreen() {
if (mScreenSaverMode) return;
if (DEBUG) Log.d(LOG_TAG, "saveScreen");
// quickly stash away the x/y of the current date
final View oldTimeDate = findViewById(R.id.time_date);
int oldLoc[] = new int[2];
oldTimeDate.getLocationOnScreen(oldLoc);
mScreenSaverMode = true;
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
win.setAttributes(winParams);
// give up any internal focus before we switch layouts
final View focused = getCurrentFocus();
if (focused != null) focused.clearFocus();
setContentView(R.layout.desk_clock_saver);
mTime = (DigitalClock) findViewById(R.id.time);
mDate = (TextView) findViewById(R.id.date);
mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
((TextView)findViewById(R.id.am_pm)).setTextColor(color);
mDate.setTextColor(color);
mNextAlarm.setTextColor(color);
mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
getResources().getDrawable(mDimmed
? R.drawable.ic_lock_idle_alarm_saver_dim
: R.drawable.ic_lock_idle_alarm_saver),
null, null, null);
mBatteryDisplay =
mWeatherCurrentTemperature =
mWeatherHighTemperature =
mWeatherLowTemperature =
mWeatherLocation = null;
mWeatherIcon = null;
refreshDate();
refreshAlarm();
moveScreenSaverTo(oldLoc[0], oldLoc[1]);
}
@Override
public void onUserInteraction() {
if (mScreenSaverMode)
restoreScreen();
}
private boolean supportsWeather() {
return (mGenieResources != null);
}
private void scheduleWeatherFetchDelayed(long delay) {
if (mWeatherFetchScheduled) return;
if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
mWeatherFetchScheduled = true;
mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay);
}
private void unscheduleWeatherFetch() {
mWeatherFetchScheduled = false;
}
private static final boolean sCelsius;
static {
String cc = Locale.getDefault().getCountry().toLowerCase();
sCelsius = !("us".equals(cc) || "bz".equals(cc) || "jm".equals(cc));
}
private static int celsiusToLocal(int tempC) {
return sCelsius ? tempC : (int) Math.round(tempC * 1.8f + 32);
}
private void fetchWeatherData() {
// if we couldn't load the weather widget's resources, we simply
// assume it's not present on the device.
if (mGenieResources == null) return;
Uri queryUri = new Uri.Builder()
.scheme(android.content.ContentResolver.SCHEME_CONTENT)
.authority(WEATHER_CONTENT_AUTHORITY)
.path(WEATHER_CONTENT_PATH)
.appendPath(new Long(System.currentTimeMillis()).toString())
.build();
if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
Cursor cur;
try {
cur = managedQuery(
queryUri,
WEATHER_CONTENT_COLUMNS,
null,
null,
null);
} catch (RuntimeException e) {
Log.e(LOG_TAG, "Weather query failed", e);
cur = null;
}
if (cur != null && cur.moveToFirst()) {
if (DEBUG) {
java.lang.StringBuilder sb =
new java.lang.StringBuilder("Weather query result: {");
for(int i=0; i<cur.getColumnCount(); i++) {
if (i>0) sb.append(", ");
sb.append(cur.getColumnName(i))
.append("=")
.append(cur.getString(i));
}
sb.append("}");
Log.d(LOG_TAG, sb.toString());
}
mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
cur.getColumnIndexOrThrow("iconResId")));
mWeatherCurrentTemperatureString = String.format("%d\u00b0",
celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("temperature"))));
mWeatherHighTemperatureString = String.format("%d\u00b0",
celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
mWeatherLowTemperatureString = String.format("%d\u00b0",
celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
mWeatherLocationString = cur.getString(
cur.getColumnIndexOrThrow("location"));
} else {
Log.w(LOG_TAG, "No weather information available (cur="
+ cur +")");
mWeatherIconDrawable = null;
mWeatherHighTemperatureString = "";
mWeatherLowTemperatureString = "";
mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize
}
mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
}
private void refreshWeather() {
if (supportsWeather())
scheduleWeatherFetchDelayed(0);
updateWeatherDisplay(); // in case we have it cached
}
private void updateWeatherDisplay() {
if (mWeatherCurrentTemperature == null) return;
mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString);
mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
mWeatherLocation.setText(mWeatherLocationString);
mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
}
// Adapted from KeyguardUpdateMonitor.java
private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
if (pluggedIn != mPluggedIn) {
setWakeLock(pluggedIn);
}
if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
mBatteryLevel = batteryLevel;
mPluggedIn = pluggedIn;
refreshBattery();
}
}
private void refreshBattery() {
if (mBatteryDisplay == null) return;
if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
0, 0, android.R.drawable.ic_lock_idle_charging, 0);
mBatteryDisplay.setText(
getString(R.string.battery_charging_level, mBatteryLevel));
mBatteryDisplay.setVisibility(View.VISIBLE);
} else {
mBatteryDisplay.setVisibility(View.INVISIBLE);
}
}
private void refreshDate() {
final Date now = new Date();
if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now);
mDate.setText(mDateFormat.format(now));
}
private void refreshAlarm() {
if (mNextAlarm == null) return;
String nextAlarm = Settings.System.getString(getContentResolver(),
Settings.System.NEXT_ALARM_FORMATTED);
if (!TextUtils.isEmpty(nextAlarm)) {
mNextAlarm.setText(nextAlarm);
//mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
// android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
mNextAlarm.setVisibility(View.VISIBLE);
} else {
mNextAlarm.setVisibility(View.INVISIBLE);
}
}
private void refreshAll() {
refreshDate();
refreshAlarm();
refreshBattery();
refreshWeather();
}
private void doDim(boolean fade) {
View tintView = findViewById(R.id.window_tint);
if (tintView == null) return;
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// dim the wallpaper somewhat (how much is determined below)
winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
if (mDimmed) {
winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
winParams.dimAmount = 0.67f; // pump up contrast in dim mode
// show the window tint
tintView.startAnimation(AnimationUtils.loadAnimation(this,
fade ? R.anim.dim
: R.anim.dim_instant));
} else {
winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
winParams.dimAmount = 0.5f; // lower contrast in normal mode
// hide the window tint
tintView.startAnimation(AnimationUtils.loadAnimation(this,
fade ? R.anim.undim
: R.anim.undim_instant));
}
win.setAttributes(winParams);
}
@Override
public void onResume() {
super.onResume();
if (DEBUG) Log.d(LOG_TAG, "onResume");
// reload the date format in case the user has changed settings
// recently
final SimpleDateFormat dateFormat = (SimpleDateFormat)
java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
// This is a little clumsy; we want to honor the locale's date format
// (rather than simply hardcoding "Weekday, Month Date") but
// DateFormat.FULL includes the year (at least, in enUS). So we lop
// that bit off if it's there; should have no effect on
// locale-specific date strings that look different.
mDateFormat = new SimpleDateFormat(dateFormat.toPattern()
.replace(", yyyy", "")); // no year
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_DATE_CHANGED);
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
filter.addAction(ACTION_MIDNIGHT);
Calendar today = Calendar.getInstance();
today.add(Calendar.DATE, 1);
mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC, today.getTimeInMillis(), AlarmManager.INTERVAL_DAY, mMidnightIntent);
registerReceiver(mIntentReceiver, filter);
doDim(false);
restoreScreen();
refreshAll(); // will schedule periodic weather fetch
setWakeLock(mPluggedIn);
mIdleTimeoutEpoch++;
mHandy.sendMessageDelayed(
Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG, mIdleTimeoutEpoch, 0),
SCREEN_SAVER_TIMEOUT);
final boolean launchedFromDock
= getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
if (supportsWeather() && launchedFromDock && !mInDock) {
if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
sendBroadcast(
new Intent("com.google.android.apps.genie.REFRESH")
.putExtra("requestWeather", true));
}
mInDock = launchedFromDock;
}
@Override
public void onPause() {
if (DEBUG) Log.d(LOG_TAG, "onPause");
// Turn off the screen saver. (But don't un-dim.)
restoreScreen();
// Other things we don't want to be doing in the background.
unregisterReceiver(mIntentReceiver);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.cancel(mMidnightIntent);
unscheduleWeatherFetch();
super.onPause();
}
@Override
public void onStop() {
if (DEBUG) Log.d(LOG_TAG, "onStop");
// Avoid situations where the user launches Alarm Clock and is
// surprised to find it in dim mode (because it was last used in dim
// mode, but that last use is long in the past).
mDimmed = false;
super.onStop();
}
private void initViews() {
// give up any internal focus before we switch layouts
final View focused = getCurrentFocus();
if (focused != null) focused.clearFocus();
setContentView(R.layout.desk_clock);
mTime = (DigitalClock) findViewById(R.id.time);
mDate = (TextView) findViewById(R.id.date);
mBatteryDisplay = (TextView) findViewById(R.id.battery);
mTime.getRootView().requestFocus();
mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
mWeatherLocation = (TextView) findViewById(R.id.weather_location);
mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
alarmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(DeskClock.this, AlarmClock.class));
}
});
final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
galleryButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
startActivity(new Intent(
Intent.ACTION_VIEW,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
- .putExtra("slideshow", true));
+ .putExtra("slideshow", true)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} catch (android.content.ActivityNotFoundException e) {
Log.e(LOG_TAG, "Couldn't launch image browser", e);
}
}
});
final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
musicButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
- Intent musicAppQuery = getPackageManager().getLaunchIntentForPackage(MUSIC_PACKAGE_ID);
+ Intent musicAppQuery = getPackageManager()
+ .getLaunchIntentForPackage(MUSIC_PACKAGE_ID)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (musicAppQuery != null) {
startActivity(musicAppQuery);
}
} catch (android.content.ActivityNotFoundException e) {
Log.e(LOG_TAG, "Couldn't launch music browser", e);
}
}
});
final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
homeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(
new Intent(Intent.ACTION_MAIN)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addCategory(Intent.CATEGORY_HOME));
}
});
final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
nightmodeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mDimmed = ! mDimmed;
doDim(true);
}
});
nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
saveScreen();
return true;
}
});
final View weatherView = findViewById(R.id.weather);
weatherView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!supportsWeather()) return;
- Intent genieAppQuery = getPackageManager().getLaunchIntentForPackage(GENIE_PACKAGE_ID);
+ Intent genieAppQuery = getPackageManager()
+ .getLaunchIntentForPackage(GENIE_PACKAGE_ID)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (genieAppQuery != null) {
startActivity(genieAppQuery);
}
}
});
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (!mScreenSaverMode) {
initViews();
doDim(false);
refreshAll();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_item_alarms) {
startActivity(new Intent(DeskClock.this, AlarmClock.class));
return true;
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.desk_clock_menu, menu);
return true;
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mRNG = new Random();
try {
mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
} catch (PackageManager.NameNotFoundException e) {
// no weather info available
Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");
}
initViews();
}
}
| false | true | private void initViews() {
// give up any internal focus before we switch layouts
final View focused = getCurrentFocus();
if (focused != null) focused.clearFocus();
setContentView(R.layout.desk_clock);
mTime = (DigitalClock) findViewById(R.id.time);
mDate = (TextView) findViewById(R.id.date);
mBatteryDisplay = (TextView) findViewById(R.id.battery);
mTime.getRootView().requestFocus();
mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
mWeatherLocation = (TextView) findViewById(R.id.weather_location);
mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
alarmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(DeskClock.this, AlarmClock.class));
}
});
final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
galleryButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
startActivity(new Intent(
Intent.ACTION_VIEW,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
.putExtra("slideshow", true));
} catch (android.content.ActivityNotFoundException e) {
Log.e(LOG_TAG, "Couldn't launch image browser", e);
}
}
});
final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
musicButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
Intent musicAppQuery = getPackageManager().getLaunchIntentForPackage(MUSIC_PACKAGE_ID);
if (musicAppQuery != null) {
startActivity(musicAppQuery);
}
} catch (android.content.ActivityNotFoundException e) {
Log.e(LOG_TAG, "Couldn't launch music browser", e);
}
}
});
final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
homeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(
new Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_HOME));
}
});
final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
nightmodeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mDimmed = ! mDimmed;
doDim(true);
}
});
nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
saveScreen();
return true;
}
});
final View weatherView = findViewById(R.id.weather);
weatherView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!supportsWeather()) return;
Intent genieAppQuery = getPackageManager().getLaunchIntentForPackage(GENIE_PACKAGE_ID);
if (genieAppQuery != null) {
startActivity(genieAppQuery);
}
}
});
}
| private void initViews() {
// give up any internal focus before we switch layouts
final View focused = getCurrentFocus();
if (focused != null) focused.clearFocus();
setContentView(R.layout.desk_clock);
mTime = (DigitalClock) findViewById(R.id.time);
mDate = (TextView) findViewById(R.id.date);
mBatteryDisplay = (TextView) findViewById(R.id.battery);
mTime.getRootView().requestFocus();
mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
mWeatherLocation = (TextView) findViewById(R.id.weather_location);
mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
alarmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(DeskClock.this, AlarmClock.class));
}
});
final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
galleryButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
startActivity(new Intent(
Intent.ACTION_VIEW,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
.putExtra("slideshow", true)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} catch (android.content.ActivityNotFoundException e) {
Log.e(LOG_TAG, "Couldn't launch image browser", e);
}
}
});
final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
musicButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
Intent musicAppQuery = getPackageManager()
.getLaunchIntentForPackage(MUSIC_PACKAGE_ID)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (musicAppQuery != null) {
startActivity(musicAppQuery);
}
} catch (android.content.ActivityNotFoundException e) {
Log.e(LOG_TAG, "Couldn't launch music browser", e);
}
}
});
final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
homeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(
new Intent(Intent.ACTION_MAIN)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addCategory(Intent.CATEGORY_HOME));
}
});
final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
nightmodeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mDimmed = ! mDimmed;
doDim(true);
}
});
nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
saveScreen();
return true;
}
});
final View weatherView = findViewById(R.id.weather);
weatherView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!supportsWeather()) return;
Intent genieAppQuery = getPackageManager()
.getLaunchIntentForPackage(GENIE_PACKAGE_ID)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (genieAppQuery != null) {
startActivity(genieAppQuery);
}
}
});
}
|
diff --git a/src/com/arcao/geocaching4locus/ImportFromGCActivity.java b/src/com/arcao/geocaching4locus/ImportFromGCActivity.java
index 0d6f5b47..0eef2a5b 100644
--- a/src/com/arcao/geocaching4locus/ImportFromGCActivity.java
+++ b/src/com/arcao/geocaching4locus/ImportFromGCActivity.java
@@ -1,154 +1,153 @@
package com.arcao.geocaching4locus;
import org.acra.ErrorReporter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.arcao.geocaching4locus.authentication.AuthenticatorActivity;
import com.arcao.geocaching4locus.constants.AppConstants;
import com.arcao.geocaching4locus.fragment.FullCacheDownloadConfirmDialogFragment;
import com.arcao.geocaching4locus.fragment.FullCacheDownloadConfirmDialogFragment.OnFullCacheDownloadConfirmDialogListener;
import com.arcao.geocaching4locus.fragment.GCNumberInputDialogFragment;
import com.arcao.geocaching4locus.fragment.GCNumberInputDialogFragment.OnInputFinishedListener;
import com.arcao.geocaching4locus.fragment.ImportDialogFragment;
import com.arcao.geocaching4locus.task.ImportTask.OnTaskFinishedListener;
import com.arcao.geocaching4locus.util.LocusTesting;
public class ImportFromGCActivity extends FragmentActivity implements OnTaskFinishedListener, OnInputFinishedListener, OnFullCacheDownloadConfirmDialogListener {
private static final String TAG = ImportFromGCActivity.class.getName();
private static final int REQUEST_LOGIN = 1;
private boolean authenticatorActivityVisible = false;
private boolean showGCNumberInputDialog = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!LocusTesting.isLocusInstalled(this)) {
LocusTesting.showLocusMissingError(this);
return;
}
// if import task is running, show the import task progress dialog
- ImportDialogFragment fragment = (ImportDialogFragment) getSupportFragmentManager().findFragmentByTag(ImportDialogFragment.TAG);
- if (fragment != null) {
- fragment.show(getSupportFragmentManager(), ImportDialogFragment.TAG);
+ if (getSupportFragmentManager().findFragmentByTag(ImportDialogFragment.TAG) != null) {
+ showGCNumberInputDialog = false;
return;
}
// test if user is logged in
if (!Geocaching4LocusApplication.getAuthenticatorHelper().hasAccount()) {
if (savedInstanceState != null)
authenticatorActivityVisible = savedInstanceState.getBoolean(AppConstants.STATE_AUTHENTICATOR_ACTIVITY_VISIBLE, false);
if (!authenticatorActivityVisible) {
startActivityForResult(AuthenticatorActivity.createIntent(this, true), REQUEST_LOGIN);
authenticatorActivityVisible = true;
}
return;
}
if (showBasicMemeberWarningDialog())
return;
showGCNumberInputDialog = true;
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
// play with fragments here
if (showGCNumberInputDialog) {
showGCNumberInputDialog();
showGCNumberInputDialog = false;
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(AppConstants.STATE_AUTHENTICATOR_ACTIVITY_VISIBLE, authenticatorActivityVisible);
}
protected void showGCNumberInputDialog() {
if (getSupportFragmentManager().findFragmentByTag(GCNumberInputDialogFragment.TAG) != null)
return;
GCNumberInputDialogFragment.newInstance().show(getSupportFragmentManager(), GCNumberInputDialogFragment.TAG);
}
protected boolean showBasicMemeberWarningDialog() {
if (!Geocaching4LocusApplication.getAuthenticatorHelper().getRestrictions().isFullGeocachesLimitWarningRequired())
return false;
// check next dialog fragment
if (getSupportFragmentManager().findFragmentByTag(GCNumberInputDialogFragment.TAG) != null)
return false;
if (getSupportFragmentManager().findFragmentByTag(FullCacheDownloadConfirmDialogFragment.TAG) != null)
return true;
FullCacheDownloadConfirmDialogFragment.newInstance().show(getSupportFragmentManager(), FullCacheDownloadConfirmDialogFragment.TAG);
return true;
}
protected void startImport(String cacheId) {
ErrorReporter.getInstance().putCustomData("source", "importFromGC;" + cacheId);
if (getSupportFragmentManager().findFragmentByTag(ImportDialogFragment.TAG) != null)
return;
ImportDialogFragment.newInstance(cacheId).show(getSupportFragmentManager(), ImportDialogFragment.TAG);
}
@Override
public void onInputFinished(String input) {
if (input != null) {
startImport(input);
} else {
onTaskFinished(false);
}
}
@Override
public void onTaskFinished(boolean success) {
Log.d(TAG, "onTaskFinished result: " + success);
setResult(success ? RESULT_OK : RESULT_CANCELED);
finish();
}
@Override
public void onFullCacheDownloadConfirmDialogFinished(boolean success) {
Log.d(TAG, "onFullCacheDownloadConfirmDialogFinished result: " + success);
if (success) {
showGCNumberInputDialog();
} else {
onTaskFinished(false);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// restart update process after log in
if (requestCode == REQUEST_LOGIN) {
authenticatorActivityVisible = false;
if (resultCode == RESULT_OK) {
// we can't show dialog here, we'll do it in onPostResume
showGCNumberInputDialog = true;
} else {
onTaskFinished(false);
}
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!LocusTesting.isLocusInstalled(this)) {
LocusTesting.showLocusMissingError(this);
return;
}
// if import task is running, show the import task progress dialog
ImportDialogFragment fragment = (ImportDialogFragment) getSupportFragmentManager().findFragmentByTag(ImportDialogFragment.TAG);
if (fragment != null) {
fragment.show(getSupportFragmentManager(), ImportDialogFragment.TAG);
return;
}
// test if user is logged in
if (!Geocaching4LocusApplication.getAuthenticatorHelper().hasAccount()) {
if (savedInstanceState != null)
authenticatorActivityVisible = savedInstanceState.getBoolean(AppConstants.STATE_AUTHENTICATOR_ACTIVITY_VISIBLE, false);
if (!authenticatorActivityVisible) {
startActivityForResult(AuthenticatorActivity.createIntent(this, true), REQUEST_LOGIN);
authenticatorActivityVisible = true;
}
return;
}
if (showBasicMemeberWarningDialog())
return;
showGCNumberInputDialog = true;
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!LocusTesting.isLocusInstalled(this)) {
LocusTesting.showLocusMissingError(this);
return;
}
// if import task is running, show the import task progress dialog
if (getSupportFragmentManager().findFragmentByTag(ImportDialogFragment.TAG) != null) {
showGCNumberInputDialog = false;
return;
}
// test if user is logged in
if (!Geocaching4LocusApplication.getAuthenticatorHelper().hasAccount()) {
if (savedInstanceState != null)
authenticatorActivityVisible = savedInstanceState.getBoolean(AppConstants.STATE_AUTHENTICATOR_ACTIVITY_VISIBLE, false);
if (!authenticatorActivityVisible) {
startActivityForResult(AuthenticatorActivity.createIntent(this, true), REQUEST_LOGIN);
authenticatorActivityVisible = true;
}
return;
}
if (showBasicMemeberWarningDialog())
return;
showGCNumberInputDialog = true;
}
|
diff --git a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
index 1c388b1..e438d60 100644
--- a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
+++ b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
@@ -1,439 +1,439 @@
/*
* Created on Jul 27, 2005
*/
package uk.org.ponder.rsf.renderer.html;
import java.io.InputStream;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import uk.org.ponder.rsf.components.UIAnchor;
import uk.org.ponder.rsf.components.UIBound;
import uk.org.ponder.rsf.components.UIBoundBoolean;
import uk.org.ponder.rsf.components.UIBoundList;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIComponent;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInput;
import uk.org.ponder.rsf.components.UILink;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UIOutputMultiline;
import uk.org.ponder.rsf.components.UIParameter;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UISelectChoice;
import uk.org.ponder.rsf.components.UISelectLabel;
import uk.org.ponder.rsf.components.UIVerbatim;
import uk.org.ponder.rsf.renderer.ComponentRenderer;
import uk.org.ponder.rsf.renderer.DecoratorManager;
import uk.org.ponder.rsf.renderer.RenderSystem;
import uk.org.ponder.rsf.renderer.RenderUtil;
import uk.org.ponder.rsf.renderer.StaticComponentRenderer;
import uk.org.ponder.rsf.renderer.StaticRendererCollection;
import uk.org.ponder.rsf.renderer.TagRenderContext;
import uk.org.ponder.rsf.request.FossilizedConverter;
import uk.org.ponder.rsf.request.SubmittedValueEntry;
import uk.org.ponder.rsf.template.XMLLump;
import uk.org.ponder.rsf.template.XMLLumpList;
import uk.org.ponder.rsf.uitype.UITypes;
import uk.org.ponder.rsf.view.View;
import uk.org.ponder.streamutil.StreamCopyUtil;
import uk.org.ponder.streamutil.write.PrintOutputStream;
import uk.org.ponder.stringutil.StringList;
import uk.org.ponder.stringutil.URLUtil;
import uk.org.ponder.util.Logger;
import uk.org.ponder.xml.XMLUtil;
import uk.org.ponder.xml.XMLWriter;
/**
* The implementation of the standard XHTML rendering System. This class is due
* for basic refactoring since it contains logic that belongs in a) a "base
* System-independent" lookup bean, and b) in a number of individual
* ComponentRenderer objects.
*
* @author Antranig Basman ([email protected])
*
*/
public class BasicHTMLRenderSystem implements RenderSystem {
private StaticRendererCollection scrc;
private DecoratorManager decoratormanager;
public void setStaticRenderers(StaticRendererCollection scrc) {
this.scrc = scrc;
}
public void setDecoratorManager(DecoratorManager decoratormanager) {
this.decoratormanager = decoratormanager;
}
// two methods for the RenderSystemDecoder interface
public void normalizeRequestMap(Map requestparams) {
String key = RenderUtil.findCommandParams(requestparams);
if (key != null) {
String params = key.substring(FossilizedConverter.COMMAND_LINK_PARAMETERS
.length());
RenderUtil.unpackCommandLink(params, requestparams);
requestparams.remove(key);
}
}
public void fixupUIType(SubmittedValueEntry sve) {
if (sve.oldvalue instanceof Boolean) {
if (sve.newvalue == null)
sve.newvalue = Boolean.FALSE;
}
else if (sve.oldvalue instanceof String[]) {
if (sve.newvalue == null)
sve.newvalue = new String[] {};
}
}
private void closeTag(PrintOutputStream pos, XMLLump uselump) {
pos.print("</");
pos.write(uselump.buffer, uselump.start + 1, uselump.length - 2);
pos.print(">");
}
private void dumpBoundFields(UIBound torender, XMLWriter xmlw) {
if (torender != null) {
if (torender.fossilizedbinding != null) {
RenderUtil.dumpHiddenField(torender.fossilizedbinding.name,
torender.fossilizedbinding.value, xmlw);
}
if (torender.fossilizedshaper != null) {
RenderUtil.dumpHiddenField(torender.fossilizedshaper.name,
torender.fossilizedshaper.value, xmlw);
}
}
}
// No, this method will not stay like this forever! We plan on an architecture
// with renderer-per-component "class" as before, plus interceptors.
// Although a lot of the parameterisation now lies in the allowable tag
// set at target.
public int renderComponent(UIComponent torendero, View view, XMLLump[] lumps,
int lumpindex, PrintOutputStream pos) {
XMLWriter xmlw = new XMLWriter(pos);
XMLLump lump = lumps[lumpindex];
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap
.headsForID(XMLLump.PAYLOAD_COMPONENT)
: null;
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr != null) {
int tagtype = scr.render(lumps, lumpindex, xmlw);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
}
if (lump.textEquals("<form ")) {
Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID
+ " and all children at " + lump.toDebugString()
+ " since no peer component");
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos);
lumpindex = payload.lumpindex;
}
String fullID = torendero.getFullID();
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
attrcopy.put("id", fullID);
attrcopy.remove(XMLLump.ID_ATTRIBUTE);
decoratormanager.decorate(torendero.decorators, uselump.getTag(), attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, lumps,
uselump, endopen, close, pos, xmlw);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
pos.write(uselump.buffer, uselump.start, uselump.length);
// TODO: Note that these are actually BOUND now. Create some kind of
// defaultBoundRenderer.
if (torendero instanceof UIBound) {
UIBound torender = (UIBound) torendero;
if (!torender.willinput) {
if (torendero.getClass() == UIOutput.class) {
String value = ((UIOutput) torendero).getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero.getClass() == UIOutputMultiline.class) {
StringList value = ((UIOutputMultiline) torendero).getValue();
if (value == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
for (int i = 0; i < value.size(); ++i) {
if (i != 0) {
pos.print("<br/>");
}
xmlw.write(value.stringAt(i));
}
closeTag(pos, uselump);
}
}
else if (torender.getClass() == UIAnchor.class) {
String value = ((UIAnchor) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
renderUnchanged(rendercontext);
}
else {
attrcopy.put("name", value);
replaceAttributes(rendercontext);
}
}
}
// factor out component-invariant processing of UIBound.
else { // Bound with willinput = true
attrcopy.put("name", fullID);
// attrcopy.put("id", fullID);
String value = "";
String body = null;
if (torendero instanceof UIInput) {
value = ((UIInput) torender).getValue();
if (uselump.textEquals("<textarea ")) {
body = value;
}
else {
attrcopy.put("value", value);
}
}
else if (torendero instanceof UIBoundBoolean) {
if (((UIBoundBoolean) torender).getValue()) {
attrcopy.put("checked", "yes");
}
else {
attrcopy.remove("checked");
}
attrcopy.put("value", "true");
}
rewriteLeaf(body, rendercontext);
// unify hidden field processing? ANY parameter children found must
// be dumped as hidden fields.
}
// dump any fossilized binding for this component.
dumpBoundFields(torender, xmlw);
} // end if UIBound
else if (torendero instanceof UISelect) {
UISelect select = (UISelect) torendero;
// The HTML submitted value from a <select> actually corresponds
// with the selection member, not the top-level component.
attrcopy.put("name", select.selection.submittingname);
attrcopy.put("id", select.selection.getFullID());
boolean ishtmlselect = uselump.textEquals("<select ");
if (select.selection instanceof UIBoundList && ishtmlselect) {
attrcopy.put("multiple", "true");
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (ishtmlselect) {
pos.print(">");
String[] values = select.optionlist.getValue();
String[] names = select.optionnames == null ? values
: select.optionnames.getValue();
for (int i = 0; i < names.length; ++i) {
pos.print("<option value=\"");
xmlw.write(values[i]);
if (select.selected.contains(values[i])) {
pos.print("\" selected=\"true");
}
pos.print("\">");
xmlw.write(names[i]);
pos.print("</option>\n");
}
closeTag(pos, uselump);
}
else {
dumpTemplateBody(rendercontext);
}
dumpBoundFields(select.selection, xmlw);
dumpBoundFields(select.optionlist, xmlw);
dumpBoundFields(select.optionnames, xmlw);
}
else if (torendero instanceof UISelectChoice) {
UISelectChoice torender = (UISelectChoice) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionlist.getValue()[torender.choiceindex];
// currently only peers with "input type="radio"".
attrcopy.put("name", torender.parentFullID +"-selection");
attrcopy.put("value", value);
attrcopy.remove("checked");
if (parent.selected.contains(value)) {
attrcopy.put("checked", "true");
}
replaceAttributes(rendercontext);
}
else if (torendero instanceof UISelectLabel) {
UISelectLabel torender = (UISelectLabel) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionnames.getValue()[torender.choiceindex];
replaceBody(value, rendercontext);
}
else if (torendero instanceof UILink) {
UILink torender = (UILink) torendero;
String attrname = URLRewriteSCR.getLinkAttribute(uselump);
if (attrname != null) {
String target = torender.target.getValue();
if (target == null || target.length() == 0) {
- throw new IllegalArgumentException("Empty URL in UILink at " + uselump.toDebugString());
+ throw new IllegalArgumentException("Empty URL in UILink at " + torender.getFullID());
}
URLRewriteSCR urlrewriter = (URLRewriteSCR) scrc.getSCR(URLRewriteSCR.NAME);
if (!URLUtil.isAbsolute(target)) {
String rewritten = urlrewriter.resolveURL(target);
if (rewritten != null) target = rewritten;
}
attrcopy.put(attrname, target);
}
String value = torender.linktext == null ? null
: torender.linktext.getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero instanceof UICommand) {
UICommand torender = (UICommand) torendero;
String value = RenderUtil.makeURLAttributes(torender.parameters);
// any desired "attributes" decoded for JUST THIS ACTION must be
// secretly
// bundled as this special attribute.
attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS
+ value);
String text = torender.commandtext;
boolean isbutton = lump.textEquals("<button ");
if (text != null && !isbutton) {
attrcopy.put("value", torender.commandtext);
text = null;
}
rewriteLeaf(text, rendercontext);
// RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD,
// torender.actionhandler, pos);
}
// Forms behave slightly oddly in the hierarchy - by the time they reach
// the renderer, they have been "shunted out" of line with their children,
// i.e. any "submitting" controls, if indeed they ever were there.
else if (torendero instanceof UIForm) {
UIForm torender = (UIForm) torendero;
if (attrcopy.get("method") == null) { // forms DEFAULT to be post
attrcopy.put("method", "post");
}
// form fixer guarantees that this URL is attribute free.
attrcopy.put("action", torender.targetURL);
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.println(">");
for (int i = 0; i < torender.parameters.size(); ++i) {
UIParameter param = torender.parameters.parameterAt(i);
RenderUtil.dumpHiddenField(param.name, param.value, xmlw);
}
// override "nextpos" - form is expected to contain numerous nested
// Components.
// this is the only ANOMALY!! Forms together with payload cannot work.
// the fact we are at the wrong recursion level will "come out in the
// wash"
// since we must return to the base recursion level before we exit this
// domain.
// Assuming there are no paths *IN* through forms that do not also lead
// *OUT* there will be no problem. Check what this *MEANS* tomorrow.
nextpos = endopen.lumpindex + 1;
}
else if (torendero instanceof UIVerbatim) {
UIVerbatim torender = (UIVerbatim) torendero;
String rendered = null;
// inefficient implementation for now, upgrade when we write bulk POS
// utils.
if (torender.markup instanceof InputStream) {
rendered = StreamCopyUtil
.streamToString((InputStream) torender.markup);
}
else if (torender.markup instanceof Reader) {
rendered = StreamCopyUtil.readerToString((Reader) torender.markup);
}
else if (torender.markup != null) {
rendered = torender.markup.toString();
}
if (rendered == null) {
renderUnchanged(rendercontext);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
pos.print(rendered);
closeTag(pos, uselump);
}
}
// if there is a payload, dump the postamble.
if (payload != null) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, pos);
}
}
return nextpos;
}
private void renderUnchanged(TagRenderContext c) {
RenderUtil.dumpTillLump(c.lumps, c.uselump.lumpindex + 1,
c.close.lumpindex + 1, c.pos);
}
private void rewriteLeaf(String value, TagRenderContext c) {
if (value != null && !UITypes.isPlaceholder(value)) replaceBody(value, c);
else replaceAttributes(c);
}
private void replaceBody(String value, TagRenderContext c) {
XMLUtil.dumpAttributes(c.attrcopy, c.xmlw);
c.pos.print(">");
c.xmlw.write(value);
closeTag(c.pos, c.uselump);
}
private void replaceAttributes(TagRenderContext c) {
XMLUtil.dumpAttributes(c.attrcopy, c.xmlw);
dumpTemplateBody(c);
}
private void dumpTemplateBody(TagRenderContext c) {
if (c.endopen.lumpindex == c.close.lumpindex) {
c.pos.print("/>");
}
else {
c.pos.print(">");
RenderUtil.dumpTillLump(c.lumps, c.endopen.lumpindex + 1,
c.close.lumpindex + 1, c.pos);
}
}
}
| true | true | public int renderComponent(UIComponent torendero, View view, XMLLump[] lumps,
int lumpindex, PrintOutputStream pos) {
XMLWriter xmlw = new XMLWriter(pos);
XMLLump lump = lumps[lumpindex];
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap
.headsForID(XMLLump.PAYLOAD_COMPONENT)
: null;
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr != null) {
int tagtype = scr.render(lumps, lumpindex, xmlw);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
}
if (lump.textEquals("<form ")) {
Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID
+ " and all children at " + lump.toDebugString()
+ " since no peer component");
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos);
lumpindex = payload.lumpindex;
}
String fullID = torendero.getFullID();
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
attrcopy.put("id", fullID);
attrcopy.remove(XMLLump.ID_ATTRIBUTE);
decoratormanager.decorate(torendero.decorators, uselump.getTag(), attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, lumps,
uselump, endopen, close, pos, xmlw);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
pos.write(uselump.buffer, uselump.start, uselump.length);
// TODO: Note that these are actually BOUND now. Create some kind of
// defaultBoundRenderer.
if (torendero instanceof UIBound) {
UIBound torender = (UIBound) torendero;
if (!torender.willinput) {
if (torendero.getClass() == UIOutput.class) {
String value = ((UIOutput) torendero).getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero.getClass() == UIOutputMultiline.class) {
StringList value = ((UIOutputMultiline) torendero).getValue();
if (value == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
for (int i = 0; i < value.size(); ++i) {
if (i != 0) {
pos.print("<br/>");
}
xmlw.write(value.stringAt(i));
}
closeTag(pos, uselump);
}
}
else if (torender.getClass() == UIAnchor.class) {
String value = ((UIAnchor) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
renderUnchanged(rendercontext);
}
else {
attrcopy.put("name", value);
replaceAttributes(rendercontext);
}
}
}
// factor out component-invariant processing of UIBound.
else { // Bound with willinput = true
attrcopy.put("name", fullID);
// attrcopy.put("id", fullID);
String value = "";
String body = null;
if (torendero instanceof UIInput) {
value = ((UIInput) torender).getValue();
if (uselump.textEquals("<textarea ")) {
body = value;
}
else {
attrcopy.put("value", value);
}
}
else if (torendero instanceof UIBoundBoolean) {
if (((UIBoundBoolean) torender).getValue()) {
attrcopy.put("checked", "yes");
}
else {
attrcopy.remove("checked");
}
attrcopy.put("value", "true");
}
rewriteLeaf(body, rendercontext);
// unify hidden field processing? ANY parameter children found must
// be dumped as hidden fields.
}
// dump any fossilized binding for this component.
dumpBoundFields(torender, xmlw);
} // end if UIBound
else if (torendero instanceof UISelect) {
UISelect select = (UISelect) torendero;
// The HTML submitted value from a <select> actually corresponds
// with the selection member, not the top-level component.
attrcopy.put("name", select.selection.submittingname);
attrcopy.put("id", select.selection.getFullID());
boolean ishtmlselect = uselump.textEquals("<select ");
if (select.selection instanceof UIBoundList && ishtmlselect) {
attrcopy.put("multiple", "true");
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (ishtmlselect) {
pos.print(">");
String[] values = select.optionlist.getValue();
String[] names = select.optionnames == null ? values
: select.optionnames.getValue();
for (int i = 0; i < names.length; ++i) {
pos.print("<option value=\"");
xmlw.write(values[i]);
if (select.selected.contains(values[i])) {
pos.print("\" selected=\"true");
}
pos.print("\">");
xmlw.write(names[i]);
pos.print("</option>\n");
}
closeTag(pos, uselump);
}
else {
dumpTemplateBody(rendercontext);
}
dumpBoundFields(select.selection, xmlw);
dumpBoundFields(select.optionlist, xmlw);
dumpBoundFields(select.optionnames, xmlw);
}
else if (torendero instanceof UISelectChoice) {
UISelectChoice torender = (UISelectChoice) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionlist.getValue()[torender.choiceindex];
// currently only peers with "input type="radio"".
attrcopy.put("name", torender.parentFullID +"-selection");
attrcopy.put("value", value);
attrcopy.remove("checked");
if (parent.selected.contains(value)) {
attrcopy.put("checked", "true");
}
replaceAttributes(rendercontext);
}
else if (torendero instanceof UISelectLabel) {
UISelectLabel torender = (UISelectLabel) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionnames.getValue()[torender.choiceindex];
replaceBody(value, rendercontext);
}
else if (torendero instanceof UILink) {
UILink torender = (UILink) torendero;
String attrname = URLRewriteSCR.getLinkAttribute(uselump);
if (attrname != null) {
String target = torender.target.getValue();
if (target == null || target.length() == 0) {
throw new IllegalArgumentException("Empty URL in UILink at " + uselump.toDebugString());
}
URLRewriteSCR urlrewriter = (URLRewriteSCR) scrc.getSCR(URLRewriteSCR.NAME);
if (!URLUtil.isAbsolute(target)) {
String rewritten = urlrewriter.resolveURL(target);
if (rewritten != null) target = rewritten;
}
attrcopy.put(attrname, target);
}
String value = torender.linktext == null ? null
: torender.linktext.getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero instanceof UICommand) {
UICommand torender = (UICommand) torendero;
String value = RenderUtil.makeURLAttributes(torender.parameters);
// any desired "attributes" decoded for JUST THIS ACTION must be
// secretly
// bundled as this special attribute.
attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS
+ value);
String text = torender.commandtext;
boolean isbutton = lump.textEquals("<button ");
if (text != null && !isbutton) {
attrcopy.put("value", torender.commandtext);
text = null;
}
rewriteLeaf(text, rendercontext);
// RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD,
// torender.actionhandler, pos);
}
// Forms behave slightly oddly in the hierarchy - by the time they reach
// the renderer, they have been "shunted out" of line with their children,
// i.e. any "submitting" controls, if indeed they ever were there.
else if (torendero instanceof UIForm) {
UIForm torender = (UIForm) torendero;
if (attrcopy.get("method") == null) { // forms DEFAULT to be post
attrcopy.put("method", "post");
}
// form fixer guarantees that this URL is attribute free.
attrcopy.put("action", torender.targetURL);
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.println(">");
for (int i = 0; i < torender.parameters.size(); ++i) {
UIParameter param = torender.parameters.parameterAt(i);
RenderUtil.dumpHiddenField(param.name, param.value, xmlw);
}
// override "nextpos" - form is expected to contain numerous nested
// Components.
// this is the only ANOMALY!! Forms together with payload cannot work.
// the fact we are at the wrong recursion level will "come out in the
// wash"
// since we must return to the base recursion level before we exit this
// domain.
// Assuming there are no paths *IN* through forms that do not also lead
// *OUT* there will be no problem. Check what this *MEANS* tomorrow.
nextpos = endopen.lumpindex + 1;
}
else if (torendero instanceof UIVerbatim) {
UIVerbatim torender = (UIVerbatim) torendero;
String rendered = null;
// inefficient implementation for now, upgrade when we write bulk POS
// utils.
if (torender.markup instanceof InputStream) {
rendered = StreamCopyUtil
.streamToString((InputStream) torender.markup);
}
else if (torender.markup instanceof Reader) {
rendered = StreamCopyUtil.readerToString((Reader) torender.markup);
}
else if (torender.markup != null) {
rendered = torender.markup.toString();
}
if (rendered == null) {
renderUnchanged(rendercontext);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
pos.print(rendered);
closeTag(pos, uselump);
}
}
// if there is a payload, dump the postamble.
if (payload != null) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, pos);
}
}
return nextpos;
}
| public int renderComponent(UIComponent torendero, View view, XMLLump[] lumps,
int lumpindex, PrintOutputStream pos) {
XMLWriter xmlw = new XMLWriter(pos);
XMLLump lump = lumps[lumpindex];
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap
.headsForID(XMLLump.PAYLOAD_COMPONENT)
: null;
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr != null) {
int tagtype = scr.render(lumps, lumpindex, xmlw);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
}
if (lump.textEquals("<form ")) {
Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID
+ " and all children at " + lump.toDebugString()
+ " since no peer component");
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos);
lumpindex = payload.lumpindex;
}
String fullID = torendero.getFullID();
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
attrcopy.put("id", fullID);
attrcopy.remove(XMLLump.ID_ATTRIBUTE);
decoratormanager.decorate(torendero.decorators, uselump.getTag(), attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, lumps,
uselump, endopen, close, pos, xmlw);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
pos.write(uselump.buffer, uselump.start, uselump.length);
// TODO: Note that these are actually BOUND now. Create some kind of
// defaultBoundRenderer.
if (torendero instanceof UIBound) {
UIBound torender = (UIBound) torendero;
if (!torender.willinput) {
if (torendero.getClass() == UIOutput.class) {
String value = ((UIOutput) torendero).getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero.getClass() == UIOutputMultiline.class) {
StringList value = ((UIOutputMultiline) torendero).getValue();
if (value == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
for (int i = 0; i < value.size(); ++i) {
if (i != 0) {
pos.print("<br/>");
}
xmlw.write(value.stringAt(i));
}
closeTag(pos, uselump);
}
}
else if (torender.getClass() == UIAnchor.class) {
String value = ((UIAnchor) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
renderUnchanged(rendercontext);
}
else {
attrcopy.put("name", value);
replaceAttributes(rendercontext);
}
}
}
// factor out component-invariant processing of UIBound.
else { // Bound with willinput = true
attrcopy.put("name", fullID);
// attrcopy.put("id", fullID);
String value = "";
String body = null;
if (torendero instanceof UIInput) {
value = ((UIInput) torender).getValue();
if (uselump.textEquals("<textarea ")) {
body = value;
}
else {
attrcopy.put("value", value);
}
}
else if (torendero instanceof UIBoundBoolean) {
if (((UIBoundBoolean) torender).getValue()) {
attrcopy.put("checked", "yes");
}
else {
attrcopy.remove("checked");
}
attrcopy.put("value", "true");
}
rewriteLeaf(body, rendercontext);
// unify hidden field processing? ANY parameter children found must
// be dumped as hidden fields.
}
// dump any fossilized binding for this component.
dumpBoundFields(torender, xmlw);
} // end if UIBound
else if (torendero instanceof UISelect) {
UISelect select = (UISelect) torendero;
// The HTML submitted value from a <select> actually corresponds
// with the selection member, not the top-level component.
attrcopy.put("name", select.selection.submittingname);
attrcopy.put("id", select.selection.getFullID());
boolean ishtmlselect = uselump.textEquals("<select ");
if (select.selection instanceof UIBoundList && ishtmlselect) {
attrcopy.put("multiple", "true");
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (ishtmlselect) {
pos.print(">");
String[] values = select.optionlist.getValue();
String[] names = select.optionnames == null ? values
: select.optionnames.getValue();
for (int i = 0; i < names.length; ++i) {
pos.print("<option value=\"");
xmlw.write(values[i]);
if (select.selected.contains(values[i])) {
pos.print("\" selected=\"true");
}
pos.print("\">");
xmlw.write(names[i]);
pos.print("</option>\n");
}
closeTag(pos, uselump);
}
else {
dumpTemplateBody(rendercontext);
}
dumpBoundFields(select.selection, xmlw);
dumpBoundFields(select.optionlist, xmlw);
dumpBoundFields(select.optionnames, xmlw);
}
else if (torendero instanceof UISelectChoice) {
UISelectChoice torender = (UISelectChoice) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionlist.getValue()[torender.choiceindex];
// currently only peers with "input type="radio"".
attrcopy.put("name", torender.parentFullID +"-selection");
attrcopy.put("value", value);
attrcopy.remove("checked");
if (parent.selected.contains(value)) {
attrcopy.put("checked", "true");
}
replaceAttributes(rendercontext);
}
else if (torendero instanceof UISelectLabel) {
UISelectLabel torender = (UISelectLabel) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionnames.getValue()[torender.choiceindex];
replaceBody(value, rendercontext);
}
else if (torendero instanceof UILink) {
UILink torender = (UILink) torendero;
String attrname = URLRewriteSCR.getLinkAttribute(uselump);
if (attrname != null) {
String target = torender.target.getValue();
if (target == null || target.length() == 0) {
throw new IllegalArgumentException("Empty URL in UILink at " + torender.getFullID());
}
URLRewriteSCR urlrewriter = (URLRewriteSCR) scrc.getSCR(URLRewriteSCR.NAME);
if (!URLUtil.isAbsolute(target)) {
String rewritten = urlrewriter.resolveURL(target);
if (rewritten != null) target = rewritten;
}
attrcopy.put(attrname, target);
}
String value = torender.linktext == null ? null
: torender.linktext.getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero instanceof UICommand) {
UICommand torender = (UICommand) torendero;
String value = RenderUtil.makeURLAttributes(torender.parameters);
// any desired "attributes" decoded for JUST THIS ACTION must be
// secretly
// bundled as this special attribute.
attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS
+ value);
String text = torender.commandtext;
boolean isbutton = lump.textEquals("<button ");
if (text != null && !isbutton) {
attrcopy.put("value", torender.commandtext);
text = null;
}
rewriteLeaf(text, rendercontext);
// RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD,
// torender.actionhandler, pos);
}
// Forms behave slightly oddly in the hierarchy - by the time they reach
// the renderer, they have been "shunted out" of line with their children,
// i.e. any "submitting" controls, if indeed they ever were there.
else if (torendero instanceof UIForm) {
UIForm torender = (UIForm) torendero;
if (attrcopy.get("method") == null) { // forms DEFAULT to be post
attrcopy.put("method", "post");
}
// form fixer guarantees that this URL is attribute free.
attrcopy.put("action", torender.targetURL);
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.println(">");
for (int i = 0; i < torender.parameters.size(); ++i) {
UIParameter param = torender.parameters.parameterAt(i);
RenderUtil.dumpHiddenField(param.name, param.value, xmlw);
}
// override "nextpos" - form is expected to contain numerous nested
// Components.
// this is the only ANOMALY!! Forms together with payload cannot work.
// the fact we are at the wrong recursion level will "come out in the
// wash"
// since we must return to the base recursion level before we exit this
// domain.
// Assuming there are no paths *IN* through forms that do not also lead
// *OUT* there will be no problem. Check what this *MEANS* tomorrow.
nextpos = endopen.lumpindex + 1;
}
else if (torendero instanceof UIVerbatim) {
UIVerbatim torender = (UIVerbatim) torendero;
String rendered = null;
// inefficient implementation for now, upgrade when we write bulk POS
// utils.
if (torender.markup instanceof InputStream) {
rendered = StreamCopyUtil
.streamToString((InputStream) torender.markup);
}
else if (torender.markup instanceof Reader) {
rendered = StreamCopyUtil.readerToString((Reader) torender.markup);
}
else if (torender.markup != null) {
rendered = torender.markup.toString();
}
if (rendered == null) {
renderUnchanged(rendercontext);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
pos.print(rendered);
closeTag(pos, uselump);
}
}
// if there is a payload, dump the postamble.
if (payload != null) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, pos);
}
}
return nextpos;
}
|
diff --git a/src/java/com/stackframe/sarariman/Sarariman.java b/src/java/com/stackframe/sarariman/Sarariman.java
index 58e21ce..b5083e7 100644
--- a/src/java/com/stackframe/sarariman/Sarariman.java
+++ b/src/java/com/stackframe/sarariman/Sarariman.java
@@ -1,177 +1,178 @@
/*
* Copyright (C) 2009-2010 StackFrame, LLC
* This code is licensed under GPLv2.
*/
package com.stackframe.sarariman;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;
/**
*
* @author mcculley
*/
public class Sarariman implements ServletContextListener {
private final String revision = "$Revision$"; // Do not edit this. It is set by Subversion.
private final Collection<Employee> administrators = new EmployeeTable(this, "administrators");
private final Collection<Employee> approvers = new EmployeeTable(this, "approvers");
private final Collection<Employee> invoiceManagers = new EmployeeTable(this, "invoice_managers");
private final Collection<LaborCategoryAssignment> projectBillRates = new LaborCategoryAssignmentTable(this);
private final Collection<LaborCategory> laborCategories = new LaborCategoryTable(this);
private LDAPDirectory directory;
private EmailDispatcher emailDispatcher;
private CronJobs cronJobs;
private String logoURL;
private String getRevision() {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < revision.length(); i++) {
char c = revision.charAt(i);
if (Character.isDigit(c)) {
buf.append(c);
}
}
return buf.toString();
}
public String getVersion() {
return "1.0.32r" + getRevision();
}
private static Properties lookupDirectoryProperties(Context envContext) throws NamingException {
Properties props = new Properties();
String[] propNames = new String[]{Context.INITIAL_CONTEXT_FACTORY, Context.PROVIDER_URL, Context.SECURITY_AUTHENTICATION,
Context.SECURITY_PRINCIPAL, Context.SECURITY_CREDENTIALS};
for (String s : propNames) {
props.put(s, envContext.lookup(s));
}
return props;
}
private static Properties lookupMailProperties(Context envContext) throws NamingException {
Properties props = new Properties();
String[] propNames = new String[]{"mail.from", "mail.smtp.host", "mail.smtp.port"};
for (String s : propNames) {
props.put(s, envContext.lookup(s));
}
return props;
}
public Connection openConnection() {
try {
DataSource source = (DataSource)new InitialContext().lookup("java:comp/env/jdbc/sarariman");
return source.getConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Directory getDirectory() {
return directory;
}
public EmailDispatcher getEmailDispatcher() {
return emailDispatcher;
}
public Collection<Employee> getApprovers() {
return approvers;
}
public Collection<Employee> getInvoiceManagers() {
return invoiceManagers;
}
public Map<Long, Customer> getCustomers() throws SQLException {
return Customer.getCustomers(this);
}
public Map<Long, Project> getProjects() throws SQLException {
return Project.getProjects(this);
}
public Collection<Task> getTasks() throws SQLException {
return Task.getTasks(this);
}
public Collection<Employee> getAdministrators() {
return administrators;
}
public String getLogoURL() {
return logoURL;
}
public Collection<LaborCategoryAssignment> getProjectBillRates() {
return projectBillRates;
}
public Map<Long, LaborCategory> getLaborCategories() {
Map<Long, LaborCategory> result = new HashMap<Long, LaborCategory>();
for (LaborCategory lc : laborCategories) {
result.put(lc.getId(), lc);
}
return result;
}
public void contextInitialized(ServletContextEvent sce) {
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:comp/env");
Properties directoryProperties = lookupDirectoryProperties(envContext);
directory = new LDAPDirectory(new InitialDirContext(directoryProperties), this);
boolean inhibitEmail = (Boolean)envContext.lookup("inhibitEmail");
emailDispatcher = new EmailDispatcher(lookupMailProperties(envContext), inhibitEmail);
logoURL = (String)envContext.lookup("logoURL");
} catch (NamingException ne) {
throw new RuntimeException(ne); // FIXME: Is this the best thing to throw here?
}
cronJobs = new CronJobs(this, directory, emailDispatcher);
ServletContext servletContext = sce.getServletContext();
servletContext.setAttribute("sarariman", this);
servletContext.setAttribute("directory", directory);
cronJobs.start();
String hostname;
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException uhe) {
- hostname = "unknown";
+ hostname = "unknown host";
}
for (Employee employee : directory.getByUserName().values()) {
if (employee.isAdministrator()) {
- emailDispatcher.send(employee.getEmail(), null, "sarariman started", "Sarariman has been started on " + hostname);
+ emailDispatcher.send(employee.getEmail(), null, "sarariman started",
+ String.format("Sarariman has been started on %s.", hostname));
}
}
}
public void contextDestroyed(ServletContextEvent sce) {
// FIXME: Should we worry about email that has been queued but not yet sent?
cronJobs.stop();
}
}
| false | true | public void contextInitialized(ServletContextEvent sce) {
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:comp/env");
Properties directoryProperties = lookupDirectoryProperties(envContext);
directory = new LDAPDirectory(new InitialDirContext(directoryProperties), this);
boolean inhibitEmail = (Boolean)envContext.lookup("inhibitEmail");
emailDispatcher = new EmailDispatcher(lookupMailProperties(envContext), inhibitEmail);
logoURL = (String)envContext.lookup("logoURL");
} catch (NamingException ne) {
throw new RuntimeException(ne); // FIXME: Is this the best thing to throw here?
}
cronJobs = new CronJobs(this, directory, emailDispatcher);
ServletContext servletContext = sce.getServletContext();
servletContext.setAttribute("sarariman", this);
servletContext.setAttribute("directory", directory);
cronJobs.start();
String hostname;
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException uhe) {
hostname = "unknown";
}
for (Employee employee : directory.getByUserName().values()) {
if (employee.isAdministrator()) {
emailDispatcher.send(employee.getEmail(), null, "sarariman started", "Sarariman has been started on " + hostname);
}
}
}
| public void contextInitialized(ServletContextEvent sce) {
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:comp/env");
Properties directoryProperties = lookupDirectoryProperties(envContext);
directory = new LDAPDirectory(new InitialDirContext(directoryProperties), this);
boolean inhibitEmail = (Boolean)envContext.lookup("inhibitEmail");
emailDispatcher = new EmailDispatcher(lookupMailProperties(envContext), inhibitEmail);
logoURL = (String)envContext.lookup("logoURL");
} catch (NamingException ne) {
throw new RuntimeException(ne); // FIXME: Is this the best thing to throw here?
}
cronJobs = new CronJobs(this, directory, emailDispatcher);
ServletContext servletContext = sce.getServletContext();
servletContext.setAttribute("sarariman", this);
servletContext.setAttribute("directory", directory);
cronJobs.start();
String hostname;
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException uhe) {
hostname = "unknown host";
}
for (Employee employee : directory.getByUserName().values()) {
if (employee.isAdministrator()) {
emailDispatcher.send(employee.getEmail(), null, "sarariman started",
String.format("Sarariman has been started on %s.", hostname));
}
}
}
|
diff --git a/src/main/java/net/rubygrapefruit/platform/internal/NativeLibraryLocator.java b/src/main/java/net/rubygrapefruit/platform/internal/NativeLibraryLocator.java
index c7dbd66..075ba39 100755
--- a/src/main/java/net/rubygrapefruit/platform/internal/NativeLibraryLocator.java
+++ b/src/main/java/net/rubygrapefruit/platform/internal/NativeLibraryLocator.java
@@ -1,107 +1,113 @@
/*
* Copyright 2012 Adam Murdoch
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.rubygrapefruit.platform.internal;
import net.rubygrapefruit.platform.NativeException;
import net.rubygrapefruit.platform.internal.jni.NativeLibraryFunctions;
import java.io.*;
import java.net.URL;
import java.nio.channels.FileLock;
public class NativeLibraryLocator {
private final File extractDir;
public NativeLibraryLocator(File extractDir) {
this.extractDir = extractDir;
}
public File find(LibraryDef libraryDef) throws IOException {
String resourceName = String.format("net/rubygrapefruit/platform/%s/%s", libraryDef.platform, libraryDef.name);
if (extractDir != null) {
File libFile = new File(extractDir, String.format("%s/%s", NativeLibraryFunctions.VERSION, libraryDef.name));
File lockFile = new File(libFile.getParentFile(), libFile.getName() + ".lock");
lockFile.getParentFile().mkdirs();
lockFile.createNewFile();
RandomAccessFile lockFileAccess = new RandomAccessFile(lockFile, "rw");
try {
// Take exclusive lock on lock file
FileLock lock = lockFileAccess.getChannel().lock();
if (lockFile.length() > 0 && lockFileAccess.readBoolean()) {
// Library has been extracted
return libFile;
}
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
// Extract library and write marker to lock file
libFile.getParentFile().mkdirs();
copy(resource, libFile);
lockFileAccess.seek(0);
lockFileAccess.writeBoolean(true);
return libFile;
}
} finally {
// Also releases lock
lockFileAccess.close();
}
} else {
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
File libFile;
File libDir = File.createTempFile("native-platform", "dir");
libDir.delete();
libDir.mkdirs();
libFile = new File(libDir, libraryDef.name);
libFile.deleteOnExit();
copy(resource, libFile);
return libFile;
}
}
- File libFile = new File(String.format("build/binaries/%s/%s", libraryDef.platform, libraryDef.name));
+ String componentName = libraryDef.name.replaceFirst("^lib", "").replaceFirst("\\.\\w+$", "");
+ int pos = componentName.indexOf("-");
+ while (pos >= 0) {
+ componentName = componentName.substring(0, pos) + Character.toUpperCase(componentName.charAt(pos + 1)) + componentName.substring(pos + 2);
+ pos = componentName.indexOf("-", pos);
+ }
+ File libFile = new File(String.format("build/binaries/%sSharedLibrary/%s/%s", componentName, libraryDef.platform.replace("-", "_"), libraryDef.name));
if (libFile.isFile()) {
return libFile;
}
return null;
}
private static void copy(URL source, File dest) {
try {
InputStream inputStream = source.openStream();
try {
OutputStream outputStream = new FileOutputStream(dest);
try {
byte[] buffer = new byte[4096];
while (true) {
int nread = inputStream.read(buffer);
if (nread < 0) {
break;
}
outputStream.write(buffer, 0, nread);
}
} finally {
outputStream.close();
}
} finally {
inputStream.close();
}
} catch (IOException e) {
throw new NativeException(String.format("Could not extract native JNI library."), e);
}
}
}
| true | true | public File find(LibraryDef libraryDef) throws IOException {
String resourceName = String.format("net/rubygrapefruit/platform/%s/%s", libraryDef.platform, libraryDef.name);
if (extractDir != null) {
File libFile = new File(extractDir, String.format("%s/%s", NativeLibraryFunctions.VERSION, libraryDef.name));
File lockFile = new File(libFile.getParentFile(), libFile.getName() + ".lock");
lockFile.getParentFile().mkdirs();
lockFile.createNewFile();
RandomAccessFile lockFileAccess = new RandomAccessFile(lockFile, "rw");
try {
// Take exclusive lock on lock file
FileLock lock = lockFileAccess.getChannel().lock();
if (lockFile.length() > 0 && lockFileAccess.readBoolean()) {
// Library has been extracted
return libFile;
}
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
// Extract library and write marker to lock file
libFile.getParentFile().mkdirs();
copy(resource, libFile);
lockFileAccess.seek(0);
lockFileAccess.writeBoolean(true);
return libFile;
}
} finally {
// Also releases lock
lockFileAccess.close();
}
} else {
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
File libFile;
File libDir = File.createTempFile("native-platform", "dir");
libDir.delete();
libDir.mkdirs();
libFile = new File(libDir, libraryDef.name);
libFile.deleteOnExit();
copy(resource, libFile);
return libFile;
}
}
File libFile = new File(String.format("build/binaries/%s/%s", libraryDef.platform, libraryDef.name));
if (libFile.isFile()) {
return libFile;
}
return null;
}
| public File find(LibraryDef libraryDef) throws IOException {
String resourceName = String.format("net/rubygrapefruit/platform/%s/%s", libraryDef.platform, libraryDef.name);
if (extractDir != null) {
File libFile = new File(extractDir, String.format("%s/%s", NativeLibraryFunctions.VERSION, libraryDef.name));
File lockFile = new File(libFile.getParentFile(), libFile.getName() + ".lock");
lockFile.getParentFile().mkdirs();
lockFile.createNewFile();
RandomAccessFile lockFileAccess = new RandomAccessFile(lockFile, "rw");
try {
// Take exclusive lock on lock file
FileLock lock = lockFileAccess.getChannel().lock();
if (lockFile.length() > 0 && lockFileAccess.readBoolean()) {
// Library has been extracted
return libFile;
}
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
// Extract library and write marker to lock file
libFile.getParentFile().mkdirs();
copy(resource, libFile);
lockFileAccess.seek(0);
lockFileAccess.writeBoolean(true);
return libFile;
}
} finally {
// Also releases lock
lockFileAccess.close();
}
} else {
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
File libFile;
File libDir = File.createTempFile("native-platform", "dir");
libDir.delete();
libDir.mkdirs();
libFile = new File(libDir, libraryDef.name);
libFile.deleteOnExit();
copy(resource, libFile);
return libFile;
}
}
String componentName = libraryDef.name.replaceFirst("^lib", "").replaceFirst("\\.\\w+$", "");
int pos = componentName.indexOf("-");
while (pos >= 0) {
componentName = componentName.substring(0, pos) + Character.toUpperCase(componentName.charAt(pos + 1)) + componentName.substring(pos + 2);
pos = componentName.indexOf("-", pos);
}
File libFile = new File(String.format("build/binaries/%sSharedLibrary/%s/%s", componentName, libraryDef.platform.replace("-", "_"), libraryDef.name));
if (libFile.isFile()) {
return libFile;
}
return null;
}
|
diff --git a/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/model/handlers/RemoveJSFNatureContribution.java b/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/model/handlers/RemoveJSFNatureContribution.java
index 9d18828d8..eaf47cf7e 100644
--- a/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/model/handlers/RemoveJSFNatureContribution.java
+++ b/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/model/handlers/RemoveJSFNatureContribution.java
@@ -1,59 +1,61 @@
package org.jboss.tools.jsf.model.handlers;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.jboss.tools.common.meta.action.SpecialWizard;
import org.jboss.tools.common.meta.action.impl.handlers.DefaultRemoveHandler;
import org.jboss.tools.common.model.XModel;
import org.jboss.tools.common.model.XModelObject;
import org.jboss.tools.common.model.util.EclipseResourceUtil;
import org.jboss.tools.jsf.JSFModelPlugin;
import org.jboss.tools.jsf.model.JSFConstants;
import org.jboss.tools.jst.web.kb.IKbProject;
import org.jboss.tools.jst.web.model.helpers.WebAppHelper;
public class RemoveJSFNatureContribution implements SpecialWizard {
XModel model = null;
public void setObject(Object object) {
if(object instanceof XModel) {
model = (XModel)object;
}
}
public int execute() {
if(model == null) return 1;
XModelObject webxml = WebAppHelper.getWebApp(model);
- XModelObject servlet = WebAppHelper.findServlet(webxml,
- JSFConstants.FACES_SERVLET_CLASS, "Faces Config"); //$NON-NLS-1$
- String servletName = servlet == null ? null : servlet.getAttributeValue("servlet-name"); //$NON-NLS-1$
- XModelObject mapping = WebAppHelper.findServletMapping(webxml, servletName);
+ if(webxml != null) {
+ XModelObject servlet = WebAppHelper.findServlet(webxml,
+ JSFConstants.FACES_SERVLET_CLASS, "Faces Config"); //$NON-NLS-1$
+ String servletName = servlet == null ? null : servlet.getAttributeValue("servlet-name"); //$NON-NLS-1$
+ XModelObject mapping = WebAppHelper.findServletMapping(webxml, servletName);
- if(servlet != null) {
- DefaultRemoveHandler.removeFromParent(servlet);
- }
- if(mapping != null) {
- DefaultRemoveHandler.removeFromParent(mapping);
- }
- XModelObject folder = webxml.getChildByPath("Context Params"); //$NON-NLS-1$
- XModelObject[] params = folder.getChildren();
- for (int i = 0; i < params.length; i++) {
- String name = params[i].getAttributeValue("param-name"); //$NON-NLS-1$
- if(name != null && name.startsWith("javax.faces.")) { //$NON-NLS-1$
- DefaultRemoveHandler.removeFromParent(params[i]);
+ if(servlet != null) {
+ DefaultRemoveHandler.removeFromParent(servlet);
+ }
+ if(mapping != null) {
+ DefaultRemoveHandler.removeFromParent(mapping);
+ }
+ XModelObject folder = webxml.getChildByPath("Context Params"); //$NON-NLS-1$
+ XModelObject[] params = folder.getChildren();
+ for (int i = 0; i < params.length; i++) {
+ String name = params[i].getAttributeValue("param-name"); //$NON-NLS-1$
+ if(name != null && name.startsWith("javax.faces.")) { //$NON-NLS-1$
+ DefaultRemoveHandler.removeFromParent(params[i]);
+ }
}
}
IProject project = EclipseResourceUtil.getProject(model.getRoot());
if(project != null) {
try {
EclipseResourceUtil.removeNatureFromProject(project, IKbProject.NATURE_ID);
} catch (CoreException e) {
JSFModelPlugin.getPluginLog().logError(e);
}
}
return 0;
}
}
| false | true | public int execute() {
if(model == null) return 1;
XModelObject webxml = WebAppHelper.getWebApp(model);
XModelObject servlet = WebAppHelper.findServlet(webxml,
JSFConstants.FACES_SERVLET_CLASS, "Faces Config"); //$NON-NLS-1$
String servletName = servlet == null ? null : servlet.getAttributeValue("servlet-name"); //$NON-NLS-1$
XModelObject mapping = WebAppHelper.findServletMapping(webxml, servletName);
if(servlet != null) {
DefaultRemoveHandler.removeFromParent(servlet);
}
if(mapping != null) {
DefaultRemoveHandler.removeFromParent(mapping);
}
XModelObject folder = webxml.getChildByPath("Context Params"); //$NON-NLS-1$
XModelObject[] params = folder.getChildren();
for (int i = 0; i < params.length; i++) {
String name = params[i].getAttributeValue("param-name"); //$NON-NLS-1$
if(name != null && name.startsWith("javax.faces.")) { //$NON-NLS-1$
DefaultRemoveHandler.removeFromParent(params[i]);
}
}
IProject project = EclipseResourceUtil.getProject(model.getRoot());
if(project != null) {
try {
EclipseResourceUtil.removeNatureFromProject(project, IKbProject.NATURE_ID);
} catch (CoreException e) {
JSFModelPlugin.getPluginLog().logError(e);
}
}
return 0;
}
| public int execute() {
if(model == null) return 1;
XModelObject webxml = WebAppHelper.getWebApp(model);
if(webxml != null) {
XModelObject servlet = WebAppHelper.findServlet(webxml,
JSFConstants.FACES_SERVLET_CLASS, "Faces Config"); //$NON-NLS-1$
String servletName = servlet == null ? null : servlet.getAttributeValue("servlet-name"); //$NON-NLS-1$
XModelObject mapping = WebAppHelper.findServletMapping(webxml, servletName);
if(servlet != null) {
DefaultRemoveHandler.removeFromParent(servlet);
}
if(mapping != null) {
DefaultRemoveHandler.removeFromParent(mapping);
}
XModelObject folder = webxml.getChildByPath("Context Params"); //$NON-NLS-1$
XModelObject[] params = folder.getChildren();
for (int i = 0; i < params.length; i++) {
String name = params[i].getAttributeValue("param-name"); //$NON-NLS-1$
if(name != null && name.startsWith("javax.faces.")) { //$NON-NLS-1$
DefaultRemoveHandler.removeFromParent(params[i]);
}
}
}
IProject project = EclipseResourceUtil.getProject(model.getRoot());
if(project != null) {
try {
EclipseResourceUtil.removeNatureFromProject(project, IKbProject.NATURE_ID);
} catch (CoreException e) {
JSFModelPlugin.getPluginLog().logError(e);
}
}
return 0;
}
|
diff --git a/src/main/java/com/jin/tpdb/persistence/DAO.java b/src/main/java/com/jin/tpdb/persistence/DAO.java
index d38998d..acc07fa 100755
--- a/src/main/java/com/jin/tpdb/persistence/DAO.java
+++ b/src/main/java/com/jin/tpdb/persistence/DAO.java
@@ -1,116 +1,116 @@
package com.jin.tpdb.persistence;
import java.util.List;
import javax.persistence.*;
import javax.persistence.criteria.*;
import com.jin.tpdb.entities.*;
public class DAO {
protected static EntityManagerFactory factory;
protected EntityManager em;
public DAO() {
if(DAO.getManagerFactory() == null) {
factory = Persistence.createEntityManagerFactory("jin");
DAO.setManagerFactory(factory);
} else {
factory = DAO.getManagerFactory();
}
}
protected static void setManagerFactory(EntityManagerFactory f){
factory = f;
}
protected static EntityManagerFactory getManagerFactory() {
return factory;
}
public void open() {
try {
em = factory.createEntityManager();
em.getTransaction().begin();
} catch(Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
em.getTransaction().commit();
em.close();
} catch(Exception e) {
e.printStackTrace();
}
}
public void save(Object o) {
em.persist(o);
}
public void rollback() {
em.getTransaction().rollback();
}
public static <T> T load(Class c, int i) {
DAO dao = new DAO();
dao.open();
T result = dao.get(c, i);
dao.close();
return result;
}
public static <T> List<T> getList(Class c) {
DAO dao = new DAO();
dao.open();
List<T> results = dao.list(c);
dao.close();
return results;
}
public <T> T get(Class c, int i) {
return (T)em.find(c, i);
}
protected <T> List<T> list(Class entity) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> query = cb.createQuery(entity);
TypedQuery<T> typedQuery = em.createQuery(
query.select(
query.from(entity)
)
);
return typedQuery.getResultList();
}
public Long getAlbumTotalComments(int id) {
/*$albums_query = "SELECT users.username, albums.album_id, albums.uploader_user_id, albums.album_name,
albums.upload_date, albums.cover, albums.description, artists.artist_name,
(SELECT COUNT( comment_id ) FROM comments WHERE comments.album_id = albums.album_id) AS total_comments
FROM albums, artists, users
WHERE artists.artist_id = albums.artist_id AND users.user_id
*/
- String qs = "SELECT COUNT(a) FROM AlbumComment a WHERE a.album_id = ?2";
+ String qs = "SELECT COUNT(a) FROM AlbumComment a WHERE album_id = ?2";
// num = 2
TypedQuery<Long> query = em.createQuery(qs, Long.class);
return query.getSingleResult();
/*Root<AlbumComment> root = cq.from(AlbumComment.class);
cq.select(qb.count(root));
Predicate predicate = qb.equal(root.get("album_id"), id);
cq.where(predicate);
return em.createQuery(cq).getSingleResult();*/
}
public static Long countAlbumComments(int id) {
DAO dao = new DAO();
dao.open();
Long count = dao.getAlbumTotalComments(id);
dao.close();
return count;
}
}
| true | true | public Long getAlbumTotalComments(int id) {
/*$albums_query = "SELECT users.username, albums.album_id, albums.uploader_user_id, albums.album_name,
albums.upload_date, albums.cover, albums.description, artists.artist_name,
(SELECT COUNT( comment_id ) FROM comments WHERE comments.album_id = albums.album_id) AS total_comments
FROM albums, artists, users
WHERE artists.artist_id = albums.artist_id AND users.user_id
*/
String qs = "SELECT COUNT(a) FROM AlbumComment a WHERE a.album_id = ?2";
// num = 2
TypedQuery<Long> query = em.createQuery(qs, Long.class);
return query.getSingleResult();
/*Root<AlbumComment> root = cq.from(AlbumComment.class);
cq.select(qb.count(root));
Predicate predicate = qb.equal(root.get("album_id"), id);
cq.where(predicate);
return em.createQuery(cq).getSingleResult();*/
}
| public Long getAlbumTotalComments(int id) {
/*$albums_query = "SELECT users.username, albums.album_id, albums.uploader_user_id, albums.album_name,
albums.upload_date, albums.cover, albums.description, artists.artist_name,
(SELECT COUNT( comment_id ) FROM comments WHERE comments.album_id = albums.album_id) AS total_comments
FROM albums, artists, users
WHERE artists.artist_id = albums.artist_id AND users.user_id
*/
String qs = "SELECT COUNT(a) FROM AlbumComment a WHERE album_id = ?2";
// num = 2
TypedQuery<Long> query = em.createQuery(qs, Long.class);
return query.getSingleResult();
/*Root<AlbumComment> root = cq.from(AlbumComment.class);
cq.select(qb.count(root));
Predicate predicate = qb.equal(root.get("album_id"), id);
cq.where(predicate);
return em.createQuery(cq).getSingleResult();*/
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/SynchronizeSelectedAction.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/SynchronizeSelectedAction.java
index f03c28051..2d67ac81f 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/SynchronizeSelectedAction.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/SynchronizeSelectedAction.java
@@ -1,115 +1,115 @@
/*******************************************************************************
* 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.internal.tasklist.ui;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.mylar.internal.tasklist.ui.views.TaskListView;
import org.eclipse.mylar.provisional.tasklist.AbstractQueryHit;
import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryConnector;
import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryQuery;
import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryTask;
import org.eclipse.mylar.provisional.tasklist.ITask;
import org.eclipse.mylar.provisional.tasklist.MylarTaskListPlugin;
import org.eclipse.mylar.provisional.tasklist.TaskCategory;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.PlatformUI;
/**
* @author Ken Sueda and Mik Kersten
*/
public class SynchronizeSelectedAction extends Action implements IViewActionDelegate {
private AbstractRepositoryQuery query = null;
private void checkSyncResult(final IJobChangeEvent event, final AbstractRepositoryQuery problemQuery) {
if (event.getResult().getException() != null) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openError(Display.getDefault().getActiveShell(), MylarTaskListPlugin.TITLE_DIALOG, event
.getResult().getMessage());
}
});
}
}
public void run(IAction action) {
if (query != null) {
AbstractRepositoryConnector connector = MylarTaskListPlugin.getRepositoryManager().getRepositoryConnector(
query.getRepositoryKind());
if (connector != null)
connector.synchronize(query, new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
checkSyncResult(event, query);
}
});
} else if (TaskListView.getFromActivePerspective() != null) {
ISelection selection = TaskListView.getFromActivePerspective().getViewer().getSelection();
for (Object obj : ((IStructuredSelection) selection).toList()) {
if (obj instanceof AbstractRepositoryQuery) {
final AbstractRepositoryQuery repositoryQuery = (AbstractRepositoryQuery) obj;
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(repositoryQuery.getRepositoryKind());
if (client != null)
client.synchronize(repositoryQuery, new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
checkSyncResult(event, repositoryQuery);
}
});
} else if (obj instanceof TaskCategory) {
TaskCategory cat = (TaskCategory) obj;
for (ITask task : cat.getChildren()) {
if (task instanceof AbstractRepositoryTask) {
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(((AbstractRepositoryTask) task).getRepositoryKind());
if (client != null)
client.forceRefresh((AbstractRepositoryTask) task);
}
}
} else if (obj instanceof AbstractRepositoryTask) {
AbstractRepositoryTask bugTask = (AbstractRepositoryTask) obj;
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(bugTask.getRepositoryKind());
if (client != null)
client.forceRefresh(bugTask);
} else if (obj instanceof AbstractQueryHit) {
AbstractQueryHit hit = (AbstractQueryHit) obj;
- if (hit.getCorrespondingTask() != null) {
+ if (hit.getOrCreateCorrespondingTask() != null) {
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(hit.getCorrespondingTask().getRepositoryKind());
if (client != null)
client.forceRefresh(hit.getCorrespondingTask());
}
}
}
}
if (TaskListView.getFromActivePerspective() != null) {
TaskListView.getFromActivePerspective().getViewer().refresh();
}
}
public void init(IViewPart view) {
// ignore
}
public void selectionChanged(IAction action, ISelection selection) {
// ignore
}
}
| true | true | public void run(IAction action) {
if (query != null) {
AbstractRepositoryConnector connector = MylarTaskListPlugin.getRepositoryManager().getRepositoryConnector(
query.getRepositoryKind());
if (connector != null)
connector.synchronize(query, new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
checkSyncResult(event, query);
}
});
} else if (TaskListView.getFromActivePerspective() != null) {
ISelection selection = TaskListView.getFromActivePerspective().getViewer().getSelection();
for (Object obj : ((IStructuredSelection) selection).toList()) {
if (obj instanceof AbstractRepositoryQuery) {
final AbstractRepositoryQuery repositoryQuery = (AbstractRepositoryQuery) obj;
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(repositoryQuery.getRepositoryKind());
if (client != null)
client.synchronize(repositoryQuery, new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
checkSyncResult(event, repositoryQuery);
}
});
} else if (obj instanceof TaskCategory) {
TaskCategory cat = (TaskCategory) obj;
for (ITask task : cat.getChildren()) {
if (task instanceof AbstractRepositoryTask) {
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(((AbstractRepositoryTask) task).getRepositoryKind());
if (client != null)
client.forceRefresh((AbstractRepositoryTask) task);
}
}
} else if (obj instanceof AbstractRepositoryTask) {
AbstractRepositoryTask bugTask = (AbstractRepositoryTask) obj;
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(bugTask.getRepositoryKind());
if (client != null)
client.forceRefresh(bugTask);
} else if (obj instanceof AbstractQueryHit) {
AbstractQueryHit hit = (AbstractQueryHit) obj;
if (hit.getCorrespondingTask() != null) {
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(hit.getCorrespondingTask().getRepositoryKind());
if (client != null)
client.forceRefresh(hit.getCorrespondingTask());
}
}
}
}
if (TaskListView.getFromActivePerspective() != null) {
TaskListView.getFromActivePerspective().getViewer().refresh();
}
}
| public void run(IAction action) {
if (query != null) {
AbstractRepositoryConnector connector = MylarTaskListPlugin.getRepositoryManager().getRepositoryConnector(
query.getRepositoryKind());
if (connector != null)
connector.synchronize(query, new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
checkSyncResult(event, query);
}
});
} else if (TaskListView.getFromActivePerspective() != null) {
ISelection selection = TaskListView.getFromActivePerspective().getViewer().getSelection();
for (Object obj : ((IStructuredSelection) selection).toList()) {
if (obj instanceof AbstractRepositoryQuery) {
final AbstractRepositoryQuery repositoryQuery = (AbstractRepositoryQuery) obj;
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(repositoryQuery.getRepositoryKind());
if (client != null)
client.synchronize(repositoryQuery, new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
checkSyncResult(event, repositoryQuery);
}
});
} else if (obj instanceof TaskCategory) {
TaskCategory cat = (TaskCategory) obj;
for (ITask task : cat.getChildren()) {
if (task instanceof AbstractRepositoryTask) {
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(((AbstractRepositoryTask) task).getRepositoryKind());
if (client != null)
client.forceRefresh((AbstractRepositoryTask) task);
}
}
} else if (obj instanceof AbstractRepositoryTask) {
AbstractRepositoryTask bugTask = (AbstractRepositoryTask) obj;
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(bugTask.getRepositoryKind());
if (client != null)
client.forceRefresh(bugTask);
} else if (obj instanceof AbstractQueryHit) {
AbstractQueryHit hit = (AbstractQueryHit) obj;
if (hit.getOrCreateCorrespondingTask() != null) {
AbstractRepositoryConnector client = MylarTaskListPlugin.getRepositoryManager()
.getRepositoryConnector(hit.getCorrespondingTask().getRepositoryKind());
if (client != null)
client.forceRefresh(hit.getCorrespondingTask());
}
}
}
}
if (TaskListView.getFromActivePerspective() != null) {
TaskListView.getFromActivePerspective().getViewer().refresh();
}
}
|
diff --git a/src/com/android/dialer/list/SmartDialSearchFragment.java b/src/com/android/dialer/list/SmartDialSearchFragment.java
index e3882ca50..a163f5db7 100644
--- a/src/com/android/dialer/list/SmartDialSearchFragment.java
+++ b/src/com/android/dialer/list/SmartDialSearchFragment.java
@@ -1,72 +1,70 @@
/*
* Copyright (C) 2013 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.dialer.list;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.android.contacts.common.list.ContactEntryListAdapter;
import com.android.dialer.dialpad.SmartDialCursorLoader;
/**
* Implements a fragment to load and display SmartDial search results.
*/
public class SmartDialSearchFragment extends SearchFragment {
private static final String TAG = SmartDialSearchFragment.class.getSimpleName();
/**
* Creates a SmartDialListAdapter to display and operate on search results.
*/
@Override
protected ContactEntryListAdapter createListAdapter() {
SmartDialNumberListAdapter adapter = new SmartDialNumberListAdapter(getActivity());
adapter.setUseCallableUri(super.usesCallableUri());
adapter.setQuickContactEnabled(true);
return adapter;
}
/**
* Creates a SmartDialCursorLoader object to load query results.
*/
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Smart dialing does not support Directory Load, falls back to normal search instead.
if (id == getDirectoryLoaderId()) {
- Log.v(TAG, "Directory load");
return super.onCreateLoader(id, args);
} else {
- Log.v(TAG, "Creating loader");
final SmartDialNumberListAdapter adapter = (SmartDialNumberListAdapter) getAdapter();
SmartDialCursorLoader loader = new SmartDialCursorLoader(super.getContext());
adapter.configureLoader(loader);
return loader;
}
}
/**
* Gets the Phone Uri of an entry for calling.
* @param position Location of the data of interest.
* @return Phone Uri to establish a phone call.
*/
@Override
protected Uri getPhoneUri(int position) {
final SmartDialNumberListAdapter adapter = (SmartDialNumberListAdapter) getAdapter();
return adapter.getDataUri(position);
}
}
| false | true | public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Smart dialing does not support Directory Load, falls back to normal search instead.
if (id == getDirectoryLoaderId()) {
Log.v(TAG, "Directory load");
return super.onCreateLoader(id, args);
} else {
Log.v(TAG, "Creating loader");
final SmartDialNumberListAdapter adapter = (SmartDialNumberListAdapter) getAdapter();
SmartDialCursorLoader loader = new SmartDialCursorLoader(super.getContext());
adapter.configureLoader(loader);
return loader;
}
}
| public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Smart dialing does not support Directory Load, falls back to normal search instead.
if (id == getDirectoryLoaderId()) {
return super.onCreateLoader(id, args);
} else {
final SmartDialNumberListAdapter adapter = (SmartDialNumberListAdapter) getAdapter();
SmartDialCursorLoader loader = new SmartDialCursorLoader(super.getContext());
adapter.configureLoader(loader);
return loader;
}
}
|
diff --git a/filters/xml/src/test/java/net/sf/okapi/filters/xml/XMLFilterTest.java b/filters/xml/src/test/java/net/sf/okapi/filters/xml/XMLFilterTest.java
index b4352fdf6..0e70b33b0 100644
--- a/filters/xml/src/test/java/net/sf/okapi/filters/xml/XMLFilterTest.java
+++ b/filters/xml/src/test/java/net/sf/okapi/filters/xml/XMLFilterTest.java
@@ -1,367 +1,367 @@
/*===========================================================================
Copyright (C) 2008-2009 by the Okapi Framework contributors
-----------------------------------------------------------------------------
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/
package net.sf.okapi.filters.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import net.sf.okapi.common.Event;
import net.sf.okapi.common.filters.FilterConfiguration;
import net.sf.okapi.common.filterwriter.GenericContent;
import net.sf.okapi.common.resource.RawDocument;
import net.sf.okapi.common.resource.StartDocument;
import net.sf.okapi.common.resource.TextUnit;
import net.sf.okapi.common.filters.FilterTestDriver;
import net.sf.okapi.common.filters.InputDocument;
import net.sf.okapi.common.filters.RoundTripComparison;
import net.sf.okapi.common.TestUtil;
import net.sf.okapi.filters.xml.XMLFilter;
import org.junit.Before;
import org.junit.Test;
public class XMLFilterTest {
private XMLFilter filter;
private GenericContent fmt;
private String root;
@Before
public void setUp() {
filter = new XMLFilter();
fmt = new GenericContent();
root = TestUtil.getParentDir(this.getClass(), "/test01.xml");
}
@Test
public void testComplexIdPointer () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><its:rules version=\"1.0\" xmlns:its=\"http://www.w3.org/2005/11/its\""
+ " xmlns:itsx=\"http://www.w3.org/2008/12/its-extensions\">"
+ "<its:translateRule selector=\"//doc\" translate=\"no\"/>"
+ "<its:translateRule selector=\"//src\" translate=\"yes\" itsx:idPointer=\"../../name/@id\"/>"
+ "</its:rules>"
+ "<grp><name id=\"id1\" /><u><src>text 1</src></u></grp>"
+ "<grp><name id=\"id1\" /><u><src xml:id=\"xid2\">text 2</src></u></grp>"
+ "</doc>";
ArrayList<Event> list = getEvents(snippet);
TextUnit tu = FilterTestDriver.getTextUnit(list, 1);
assertNotNull(tu);
assertEquals("id1", tu.getName());
tu = FilterTestDriver.getTextUnit(list, 2);
assertNotNull(tu);
assertEquals("xid2", tu.getName()); // xml:id overrides global rule
}
@Test
public void testIdPointer () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><its:rules version=\"1.0\" xmlns:its=\"http://www.w3.org/2005/11/its\""
+ " xmlns:itsx=\"http://www.w3.org/2008/12/its-extensions\">"
+ "<its:translateRule selector=\"//p\" translate=\"yes\" itsx:idPointer=\"@name\"/>"
+ "</its:rules>"
+ "<p name=\"id1\">text 1</p>"
+ "<p xml:id=\"xid2\">text 2</p>"
+ "<p xml:id=\"xid3\" name=\"id3\">text 3</p></doc>";
ArrayList<Event> list = getEvents(snippet);
TextUnit tu = FilterTestDriver.getTextUnit(list, 1);
assertNotNull(tu);
assertEquals("id1", tu.getName());
tu = FilterTestDriver.getTextUnit(list, 2);
assertNotNull(tu);
assertEquals("xid2", tu.getName()); // No 'name' attribute
tu = FilterTestDriver.getTextUnit(list, 3);
assertNotNull(tu);
assertEquals("xid3", tu.getName()); // xml:id overrides global rule
}
@Test
public void testSimpleEntities () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r"
+ "<!DOCTYPE doc ["
+ "<!ENTITY aWithRingAndAcute 'ǻ'>\r"
+ "<!ENTITY text 'TEXT'>\r"
+ "]>\r"
+ "<doc>"
+ "<p>&aWithRingAndAcute;=e1</p>"
+ "<p>&text;=e2</p>"
+ "</doc>";
assertEquals(snippet, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testComplexEntities () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r"
+ "<!DOCTYPE doc ["
+ "<!ENTITY entity1 '[&entity2;]'>\r"
+ "<!ENTITY entity2 'TEXT'>\r"
+ "]>\r"
+ "<doc>"
+ "<p>&entity1;=[TEXT]</p>"
+ "<p>&entity2;=TEXT</p>"
+ "</doc>";
assertEquals(snippet, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testSpecialEntities () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc>"
+ "<p><=lt >=gt "=quot '=apos</p>"
+ "</doc>";
assertEquals(snippet, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testDefaultInfo () {
assertNotNull(filter.getParameters());
assertNotNull(filter.getName());
List<FilterConfiguration> list = filter.getConfigurations();
assertNotNull(list);
assertTrue(list.size()>0);
}
@Test
public void testStartDocument () {
assertTrue("Problem in StartDocument", FilterTestDriver.testStartDocument(filter,
new InputDocument(root+"test01.xml", null),
"UTF-8", "en", "en"));
}
@Test
public void testStartDocumentFromList () {
String snippet = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r"
+ "<doc>text</doc>";
StartDocument sd = FilterTestDriver.getStartDocument(getEvents(snippet));
assertNotNull(sd);
assertNotNull(sd.getEncoding());
assertNotNull(sd.getType());
assertNotNull(sd.getMimeType());
assertNotNull(sd.getLanguage());
assertEquals("\r", sd.getLineBreak());
}
@Test
public void testOutputBasic_Comment () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><!--c--></doc>";
assertEquals(snippet, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testOutputBasic_PI () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><?pi ?></doc>";
assertEquals(snippet, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testOutputBasic_OneChar () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc>T</doc>";
assertEquals(snippet, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testOutputBasic_EmptyRoot () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc/>";
assertEquals(snippet, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testOutputSimpleContent () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p>test</p></doc>";
assertEquals(snippet, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testOutputSimpleContent_WithEscapes () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p>&=amp, <=lt, "=quot..</p></doc>";
assertEquals(snippet, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
//TODO: Implement language handling
/* @Test
public void testOutputSimpleContent_WithLang () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc xml:lang='en'>test</doc>";
String expect = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc xml:lang='FR'>test</doc>";
//TODO: Implement replacement of the lang value
//assertEquals(expect, FilterTestDriver.generateOutput(getEvents(snippet), snippet, "FR"));
}*/
@Test
public void testOutputSupplementalChars () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<p>[𠀀]=U+D840,U+DC00</p>";
String expect = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<p>[\uD840\uDC00]=U+D840,U+DC00</p>";
assertEquals(expect, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testCDATAParsing () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p><![CDATA[&=amp, <=lt, પ=not-a-ncr]]></p></doc>";
TextUnit tu = FilterTestDriver.getTextUnit(getEvents(snippet), 1);
assertNotNull(tu);
assertEquals(tu.getSourceContent().toString(), "&=amp, <=lt, પ=not-a-ncr");
}
@Test
public void testOutputCDATA () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p><![CDATA[&=amp, <=lt, પ=not-a-ncr]]></p></doc>";
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p>&=amp, <=lt, &#xaaa;=not-a-ncr</p></doc>";
assertEquals(expected, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testCommentParsing () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p>t1 <!--comment--> t2</p></doc>";
TextUnit tu = FilterTestDriver.getTextUnit(getEvents(snippet), 1);
assertNotNull(tu);
assertEquals(fmt.setContent(tu.getSourceContent()).toString(), "t1 <1/> t2");
}
@Test
public void testOutputComment () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p>t1 <!--comment--> t2</p></doc>";
assertEquals(snippet, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testPIParsing () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p>t1 <?abc attr=\"value\"?> t2</p></doc>";
TextUnit tu = FilterTestDriver.getTextUnit(getEvents(snippet), 1);
assertNotNull(tu);
assertEquals(fmt.setContent(tu.getSourceContent()).toString(), "t1 <1/> t2");
}
@Test
public void testOutputPI () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p>t1 <?abc attr=\"value\"?> t2</p></doc>";
assertEquals(snippet, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testOutputWhitespaces_Preserve () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p>part 1\npart 2</p>"
+ "<p xml:space=\"preserve\">part 1\npart 2</p></doc>";
String expect = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p>part 1 part 2</p>"
+ "<p xml:space=\"preserve\">part 1\npart 2</p></doc>";
assertEquals(expect, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testOutputWhitespaces_Default () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<p>part 1\npart 2\n part3\n\t part4</p>";
String expect = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<p>part 1 part 2 part3 part4</p>";
assertEquals(expect, FilterTestDriver.generateOutput(getEvents(snippet), "en"));
}
@Test
public void testSeveralUnits () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><p>text 1</p><p>text 2</p><p>text 3</p></doc>";
ArrayList<Event> list = getEvents(snippet);
TextUnit tu = FilterTestDriver.getTextUnit(list, 1);
assertNotNull(tu);
assertEquals("text 1", tu.getSource().toString());
tu = FilterTestDriver.getTextUnit(list, 2);
assertNotNull(tu);
assertEquals("text 2", tu.getSource().toString());
tu = FilterTestDriver.getTextUnit(list, 3);
assertNotNull(tu);
assertEquals("text 3", tu.getSource().toString());
}
@Test
public void testTranslatableAttributes () {
String snippet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<doc><its:rules version=\"1.0\" xmlns:its=\"http://www.w3.org/2005/11/its\">"
+ "<its:translateRule selector=\"//*/@text\" translate=\"yes\"/></its:rules>"
+ "<p text=\"value 1\">text 1</p><p>text 2</p><p>text 3</p></doc>";
ArrayList<Event> list = getEvents(snippet);
TextUnit tu = FilterTestDriver.getTextUnit(list, 1);
assertNotNull(tu);
assertEquals("value 1", tu.getSource().toString());
}
@Test
public void testDoubleExtraction () throws URISyntaxException {
// Read all files in the data directory
ArrayList<InputDocument> list = new ArrayList<InputDocument>();
list.add(new InputDocument(root+"test01.xml", null));
list.add(new InputDocument(root+"test02.xml", null));
list.add(new InputDocument(root+"test03.xml", null));
list.add(new InputDocument(root+"test04.xml", null));
list.add(new InputDocument(root+"test05.xml", null));
list.add(new InputDocument(root+"test06.xml", null));
list.add(new InputDocument(root+"LocNote-1.xml", null));
list.add(new InputDocument(root+"LocNote-2.xml", null));
list.add(new InputDocument(root+"LocNote-3.xml", null));
list.add(new InputDocument(root+"LocNote-4.xml", null));
list.add(new InputDocument(root+"LocNote-5.xml", null));
list.add(new InputDocument(root+"LocNote-6.xml", null));
list.add(new InputDocument(root+"AndroidTest1.xml", "[email protected]"));
list.add(new InputDocument(root+"AndroidTest2.xml", "[email protected]"));
list.add(new InputDocument(root+"JavaProperties.xml", "[email protected]"));
list.add(new InputDocument(root+"TestMultiLang.xml", null));
- list.add(new InputDocument(root+"Test01.resx", "[email protected]"));
+ list.add(new InputDocument(root+"Test01.resx", "[email protected]"));
list.add(new InputDocument(root+"MozillaRDFTest01.rdf", "[email protected]"));
list.add(new InputDocument(root+"XRTT-Source1.xml", null));
list.add(new InputDocument(root+"TestCDATA1.xml", null));
RoundTripComparison rtc = new RoundTripComparison();
assertTrue(rtc.executeCompare(filter, list, "UTF-8", "en", "en"));
}
private ArrayList<Event> getEvents(String snippet) {
ArrayList<Event> list = new ArrayList<Event>();
filter.open(new RawDocument(snippet, "en"));
while ( filter.hasNext() ) {
Event event = filter.next();
list.add(event);
}
filter.close();
return list;
}
}
| true | true | public void testDoubleExtraction () throws URISyntaxException {
// Read all files in the data directory
ArrayList<InputDocument> list = new ArrayList<InputDocument>();
list.add(new InputDocument(root+"test01.xml", null));
list.add(new InputDocument(root+"test02.xml", null));
list.add(new InputDocument(root+"test03.xml", null));
list.add(new InputDocument(root+"test04.xml", null));
list.add(new InputDocument(root+"test05.xml", null));
list.add(new InputDocument(root+"test06.xml", null));
list.add(new InputDocument(root+"LocNote-1.xml", null));
list.add(new InputDocument(root+"LocNote-2.xml", null));
list.add(new InputDocument(root+"LocNote-3.xml", null));
list.add(new InputDocument(root+"LocNote-4.xml", null));
list.add(new InputDocument(root+"LocNote-5.xml", null));
list.add(new InputDocument(root+"LocNote-6.xml", null));
list.add(new InputDocument(root+"AndroidTest1.xml", "[email protected]"));
list.add(new InputDocument(root+"AndroidTest2.xml", "[email protected]"));
list.add(new InputDocument(root+"JavaProperties.xml", "[email protected]"));
list.add(new InputDocument(root+"TestMultiLang.xml", null));
list.add(new InputDocument(root+"Test01.resx", "[email protected]"));
list.add(new InputDocument(root+"MozillaRDFTest01.rdf", "[email protected]"));
list.add(new InputDocument(root+"XRTT-Source1.xml", null));
list.add(new InputDocument(root+"TestCDATA1.xml", null));
RoundTripComparison rtc = new RoundTripComparison();
assertTrue(rtc.executeCompare(filter, list, "UTF-8", "en", "en"));
}
| public void testDoubleExtraction () throws URISyntaxException {
// Read all files in the data directory
ArrayList<InputDocument> list = new ArrayList<InputDocument>();
list.add(new InputDocument(root+"test01.xml", null));
list.add(new InputDocument(root+"test02.xml", null));
list.add(new InputDocument(root+"test03.xml", null));
list.add(new InputDocument(root+"test04.xml", null));
list.add(new InputDocument(root+"test05.xml", null));
list.add(new InputDocument(root+"test06.xml", null));
list.add(new InputDocument(root+"LocNote-1.xml", null));
list.add(new InputDocument(root+"LocNote-2.xml", null));
list.add(new InputDocument(root+"LocNote-3.xml", null));
list.add(new InputDocument(root+"LocNote-4.xml", null));
list.add(new InputDocument(root+"LocNote-5.xml", null));
list.add(new InputDocument(root+"LocNote-6.xml", null));
list.add(new InputDocument(root+"AndroidTest1.xml", "[email protected]"));
list.add(new InputDocument(root+"AndroidTest2.xml", "[email protected]"));
list.add(new InputDocument(root+"JavaProperties.xml", "[email protected]"));
list.add(new InputDocument(root+"TestMultiLang.xml", null));
list.add(new InputDocument(root+"Test01.resx", "[email protected]"));
list.add(new InputDocument(root+"MozillaRDFTest01.rdf", "[email protected]"));
list.add(new InputDocument(root+"XRTT-Source1.xml", null));
list.add(new InputDocument(root+"TestCDATA1.xml", null));
RoundTripComparison rtc = new RoundTripComparison();
assertTrue(rtc.executeCompare(filter, list, "UTF-8", "en", "en"));
}
|
diff --git a/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/AggregationFieldInput.java b/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/AggregationFieldInput.java
index 878a2d07..75f1395c 100644
--- a/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/AggregationFieldInput.java
+++ b/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/AggregationFieldInput.java
@@ -1,163 +1,163 @@
package eu.europeana.corelib.solr.server.importer.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.common.SolrInputDocument;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import eu.europeana.corelib.definitions.jibx.AggregatedCHO;
import eu.europeana.corelib.definitions.jibx.Aggregation;
import eu.europeana.corelib.definitions.jibx.DataProvider;
import eu.europeana.corelib.definitions.jibx.HasView;
import eu.europeana.corelib.definitions.jibx.IsShownAt;
import eu.europeana.corelib.definitions.jibx.IsShownBy;
import eu.europeana.corelib.definitions.jibx.Provider;
import eu.europeana.corelib.definitions.jibx.Rights;
import eu.europeana.corelib.definitions.jibx.Rights1;
import eu.europeana.corelib.definitions.jibx._Object;
import eu.europeana.corelib.definitions.model.EdmLabel;
import eu.europeana.corelib.solr.entity.AggregationImpl;
import eu.europeana.corelib.solr.entity.WebResourceImpl;
import eu.europeana.corelib.solr.server.MongoDBServer;
import eu.europeana.corelib.solr.utils.SolrUtil;
public class AggregationFieldInput {
public static SolrInputDocument createAggregationSolrFields(
Aggregation aggregation, SolrInputDocument solrInputDocument)
throws InstantiationException, IllegalAccessException {
solrInputDocument.addField(EdmLabel.ORE_AGGREGATION.toString(),
aggregation.getAbout());
solrInputDocument.addField(
EdmLabel.EDM_AGGREGATED_CHO.toString(),
SolrUtil.exists(AggregatedCHO.class,
(aggregation.getAggregatedCHO())).getResource());
solrInputDocument
.addField(
EdmLabel.EDM_OBJECT.toString(),
SolrUtil.exists(_Object.class,
(aggregation.getObject())).getResource());
solrInputDocument.addField(
EdmLabel.EDM_DATA_PROVIDER.toString(),
SolrUtil.exists(DataProvider.class,
((aggregation.getDataProvider()))).getString());
solrInputDocument.addField(EdmLabel.EDM_PROVIDER.toString(), SolrUtil
.exists(Provider.class, (aggregation.getProvider()))
.getString());
solrInputDocument.addField(EdmLabel.EDM_IS_SHOWN_AT.toString(),
SolrUtil.exists(IsShownAt.class, (aggregation.getIsShownAt()))
.getResource());
solrInputDocument.addField(EdmLabel.EDM_IS_SHOWN_BY.toString(),
SolrUtil.exists(IsShownBy.class, (aggregation.getIsShownBy()))
.getResource());
solrInputDocument.addField(EdmLabel.AGGR_EDM_RIGHTS.toString(),
SolrUtil.exists(Rights.class, (aggregation.getRights()))
.getString());
if (aggregation.getUgc() != null) {
solrInputDocument.addField(EdmLabel.EDM_UGC.toString(), aggregation
.getUgc().getUgc().toString());
}
if (aggregation.getRightList() != null) {
for (Rights1 rights : aggregation.getRightList()) {
solrInputDocument.addField(EdmLabel.AGGR_DC_RIGHTS.toString(),
rights.getString());
}
}
if (aggregation.getHasViewList() != null) {
for (HasView hasView : aggregation.getHasViewList()) {
solrInputDocument.addField(EdmLabel.EDM_HASVIEW.toString(),
hasView.getResource());
}
}
return solrInputDocument;
}
public static AggregationImpl appendWebResource(
List<AggregationImpl> aggregations, List<WebResourceImpl> webResources,
MongoDBServer mongoServer) throws InstantiationException,
IllegalAccessException {
AggregationImpl aggregation=findAggregation(aggregations, webResources.get(0));
aggregation.setWebResources(webResources);
UpdateOperations<AggregationImpl> ops = mongoServer.getDatastore()
.createUpdateOperations(AggregationImpl.class)
.set("webResources", webResources);
Query<AggregationImpl> query = mongoServer.getDatastore().find(AggregationImpl.class).filter("about", aggregation.getAbout());
mongoServer.getDatastore().update(query, ops);
return aggregation;
}
private static AggregationImpl findAggregation(
List<AggregationImpl> aggregations, WebResourceImpl webResource) {
for (AggregationImpl aggregation : aggregations) {
for (String hasView : aggregation.getHasView()) {
if (StringUtils.equals(hasView, webResource.getAbout())) {
return aggregation;
}
}
}
return null;
}
public static AggregationImpl createAggregationMongoFields(
eu.europeana.corelib.definitions.jibx.Aggregation aggregation,
MongoDBServer mongoServer) throws InstantiationException,
IllegalAccessException {
AggregationImpl mongoAggregation = new AggregationImpl();
mongoAggregation.setAbout(aggregation.getAbout());
mongoAggregation.setEdmDataProvider(SolrUtil.exists(DataProvider.class,
(aggregation.getDataProvider())).getString());
mongoAggregation.setEdmIsShownAt(SolrUtil.exists(IsShownAt.class,
(aggregation.getIsShownAt())).getResource());
mongoAggregation.setEdmIsShownBy(SolrUtil.exists(IsShownBy.class,
(aggregation.getIsShownBy())).getResource());
mongoAggregation.setEdmObject(SolrUtil.exists(_Object.class,
- (aggregation.getObject())).toString());
+ (aggregation.getObject())).getResource());
mongoAggregation.setEdmProvider(SolrUtil.exists(Provider.class,
(aggregation.getProvider())).getString());
mongoAggregation.setEdmRights(SolrUtil.exists(Rights.class,
(aggregation.getRights())).getString());
if (aggregation.getUgc() != null) {
mongoAggregation
.setEdmUgc(aggregation.getUgc().getUgc().toString());
}
mongoAggregation.setAggregatedCHO(SolrUtil.exists(AggregatedCHO.class,
(aggregation.getAggregatedCHO())).getResource());
if (aggregation.getRightList() != null) {
List<String> dcRightsList = new ArrayList<String>();
for (Rights1 rights : aggregation.getRightList()) {
dcRightsList.add(rights.getString());
}
mongoAggregation.setHasView(dcRightsList
.toArray(new String[dcRightsList.size()]));
}
if (aggregation.getHasViewList() != null) {
List<String> hasViewList = new ArrayList<String>();
for (HasView hasView : aggregation.getHasViewList()) {
hasViewList.add(hasView.getResource());
}
mongoAggregation.setHasView(hasViewList
.toArray(new String[hasViewList.size()]));
}
try{
mongoServer.getDatastore().save(mongoAggregation);
}
catch(Exception e){
//DUP UNIQUE IDENTIFIER
}
return mongoAggregation;
}
}
| true | true | public static AggregationImpl createAggregationMongoFields(
eu.europeana.corelib.definitions.jibx.Aggregation aggregation,
MongoDBServer mongoServer) throws InstantiationException,
IllegalAccessException {
AggregationImpl mongoAggregation = new AggregationImpl();
mongoAggregation.setAbout(aggregation.getAbout());
mongoAggregation.setEdmDataProvider(SolrUtil.exists(DataProvider.class,
(aggregation.getDataProvider())).getString());
mongoAggregation.setEdmIsShownAt(SolrUtil.exists(IsShownAt.class,
(aggregation.getIsShownAt())).getResource());
mongoAggregation.setEdmIsShownBy(SolrUtil.exists(IsShownBy.class,
(aggregation.getIsShownBy())).getResource());
mongoAggregation.setEdmObject(SolrUtil.exists(_Object.class,
(aggregation.getObject())).toString());
mongoAggregation.setEdmProvider(SolrUtil.exists(Provider.class,
(aggregation.getProvider())).getString());
mongoAggregation.setEdmRights(SolrUtil.exists(Rights.class,
(aggregation.getRights())).getString());
if (aggregation.getUgc() != null) {
mongoAggregation
.setEdmUgc(aggregation.getUgc().getUgc().toString());
}
mongoAggregation.setAggregatedCHO(SolrUtil.exists(AggregatedCHO.class,
(aggregation.getAggregatedCHO())).getResource());
if (aggregation.getRightList() != null) {
List<String> dcRightsList = new ArrayList<String>();
for (Rights1 rights : aggregation.getRightList()) {
dcRightsList.add(rights.getString());
}
mongoAggregation.setHasView(dcRightsList
.toArray(new String[dcRightsList.size()]));
}
if (aggregation.getHasViewList() != null) {
List<String> hasViewList = new ArrayList<String>();
for (HasView hasView : aggregation.getHasViewList()) {
hasViewList.add(hasView.getResource());
}
mongoAggregation.setHasView(hasViewList
.toArray(new String[hasViewList.size()]));
}
try{
mongoServer.getDatastore().save(mongoAggregation);
}
catch(Exception e){
//DUP UNIQUE IDENTIFIER
}
return mongoAggregation;
}
| public static AggregationImpl createAggregationMongoFields(
eu.europeana.corelib.definitions.jibx.Aggregation aggregation,
MongoDBServer mongoServer) throws InstantiationException,
IllegalAccessException {
AggregationImpl mongoAggregation = new AggregationImpl();
mongoAggregation.setAbout(aggregation.getAbout());
mongoAggregation.setEdmDataProvider(SolrUtil.exists(DataProvider.class,
(aggregation.getDataProvider())).getString());
mongoAggregation.setEdmIsShownAt(SolrUtil.exists(IsShownAt.class,
(aggregation.getIsShownAt())).getResource());
mongoAggregation.setEdmIsShownBy(SolrUtil.exists(IsShownBy.class,
(aggregation.getIsShownBy())).getResource());
mongoAggregation.setEdmObject(SolrUtil.exists(_Object.class,
(aggregation.getObject())).getResource());
mongoAggregation.setEdmProvider(SolrUtil.exists(Provider.class,
(aggregation.getProvider())).getString());
mongoAggregation.setEdmRights(SolrUtil.exists(Rights.class,
(aggregation.getRights())).getString());
if (aggregation.getUgc() != null) {
mongoAggregation
.setEdmUgc(aggregation.getUgc().getUgc().toString());
}
mongoAggregation.setAggregatedCHO(SolrUtil.exists(AggregatedCHO.class,
(aggregation.getAggregatedCHO())).getResource());
if (aggregation.getRightList() != null) {
List<String> dcRightsList = new ArrayList<String>();
for (Rights1 rights : aggregation.getRightList()) {
dcRightsList.add(rights.getString());
}
mongoAggregation.setHasView(dcRightsList
.toArray(new String[dcRightsList.size()]));
}
if (aggregation.getHasViewList() != null) {
List<String> hasViewList = new ArrayList<String>();
for (HasView hasView : aggregation.getHasViewList()) {
hasViewList.add(hasView.getResource());
}
mongoAggregation.setHasView(hasViewList
.toArray(new String[hasViewList.size()]));
}
try{
mongoServer.getDatastore().save(mongoAggregation);
}
catch(Exception e){
//DUP UNIQUE IDENTIFIER
}
return mongoAggregation;
}
|
diff --git a/pmd-eclipse-runtime/src/net/sourceforge/pmd/runtime/writer/impl/RuleSetWriterImpl.java b/pmd-eclipse-runtime/src/net/sourceforge/pmd/runtime/writer/impl/RuleSetWriterImpl.java
index 49a59ec96..f89234375 100644
--- a/pmd-eclipse-runtime/src/net/sourceforge/pmd/runtime/writer/impl/RuleSetWriterImpl.java
+++ b/pmd-eclipse-runtime/src/net/sourceforge/pmd/runtime/writer/impl/RuleSetWriterImpl.java
@@ -1,265 +1,267 @@
package net.sourceforge.pmd.runtime.writer.impl;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.runtime.writer.IRuleSetWriter;
import net.sourceforge.pmd.runtime.writer.WriterException;
import org.apache.xml.serialize.DOMSerializer;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.CDATASection;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Generate an XML rule set file from a rule set
* This class is a rewritting of the original from PMD engine
* that doesn't support xpath properties !
*
* @author Philippe Herlin
* @version $Revision$
*
* $Log$
* Revision 1.5 2007/06/24 16:41:31 phherlin
* Integrate PMD v4.0rc1
*
* Revision 1.4 2007/06/24 15:10:18 phherlin
* Integrate PMD v4.0rc1
* Prepare release 3.2.2
*
* Revision 1.3 2007/02/15 22:27:15 phherlin
* Fix 1641930 Creation of ruleset.xml file causes error in Eclipse
*
* Revision 1.2 2006/06/20 21:01:49 phherlin
* Enable PMD and fix error level violations
*
* Revision 1.1 2006/05/22 21:37:35 phherlin
* Refactor the plug-in architecture to better support future evolutions
*
* Revision 1.7 2005/06/11 22:09:57 phherlin
* Update to PMD 3.2: the symbol table attribute is no more used
*
* Revision 1.6 2005/05/07 13:32:06 phherlin
* Continuing refactoring
* Fix some PMD violations
* Fix Bug 1144793
* Fix Bug 1190624 (at least try)
*
* Revision 1.5 2005/01/31 23:39:37 phherlin
* Upgrading to PMD 2.2
*
* Revision 1.4 2005/01/16 22:53:03 phherlin
* Upgrade to PMD 2.1: take into account new rules attributes symboltable and dfa
*
* Revision 1.3 2003/12/18 23:58:37 phherlin
* Fixing malformed UTF-8 characters in generated xml files
*
* Revision 1.2 2003/11/30 22:57:43 phherlin
* Merging from eclipse-v2 development branch
*
* Revision 1.1.2.1 2003/11/07 14:31:48 phherlin
* Reverse to identation usage, remove dummy text nodes
*
* Revision 1.1 2003/10/16 22:26:37 phherlin
* Fix bug #810858.
* Complete refactoring of rule set generation. Using a DOM tree and the Xerces 2 serializer.
*
*
* -- Renaming to RuleSetWriterImpl --
*
* Revision 1.2 2003/10/14 21:26:32 phherlin
* Upgrading to PMD 1.2.2
*
* Revision 1.1 2003/06/30 20:16:06 phherlin
* Redesigning plugin configuration
*
*
*/
class RuleSetWriterImpl implements IRuleSetWriter {
/**
* Write a ruleset as an XML stream
* @param writer the output writer
* @param ruleSet the ruleset to serialize
*/
public void write(OutputStream outputStream, RuleSet ruleSet) throws WriterException {
try {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder documentBuilder = factory.newDocumentBuilder();
final Document doc = documentBuilder.newDocument();
final Element ruleSetElement = getRuleSetElement(doc, ruleSet);
doc.appendChild(ruleSetElement);
final OutputFormat outputFormat = new OutputFormat(doc, "UTF-8", true);
outputFormat.setLineWidth(0);
final DOMSerializer serializer = new XMLSerializer(outputStream, outputFormat);
serializer.serialize(doc);
} catch (DOMException e) {
throw new WriterException(e);
} catch (FactoryConfigurationError e) {
throw new WriterException(e);
} catch (ParserConfigurationException e) {
throw new WriterException(e);
} catch (IOException e) {
throw new WriterException(e);
}
}
/**
* Create an element from a ruleset
* @param doc the generated doc
* @param ruleSet a ruleset
* @return a ruleset element
*/
private Element getRuleSetElement(Document doc, RuleSet ruleSet) {
final Element ruleSetElement = doc.createElement("ruleset");
ruleSetElement.setAttribute("name", ruleSet.getName());
final Element descriptionElement = getDescriptionElement(doc, ruleSet.getDescription());
ruleSetElement.appendChild(descriptionElement);
final Iterator rules = ruleSet.getRules().iterator();
while (rules.hasNext()) {
final Rule rule = (Rule) rules.next();
final Element ruleElement = getRuleElement(doc, rule);
ruleSetElement.appendChild(ruleElement);
}
return ruleSetElement;
}
/**
* Get an element from a description
* @param doc the generated doc
* @param description a textual description
* @return a description element
*/
private Element getDescriptionElement(Document doc, String description) {
final Element descriptionElement = doc.createElement("description");
final Text text = doc.createTextNode(description);
descriptionElement.appendChild(text);
return descriptionElement;
}
/**
* Get an element from a rule
* @param doc the generated doc
* @param rule a rule
* @return a rule element
*/
private Element getRuleElement(Document doc, Rule rule) {
final Element ruleElement = doc.createElement("rule");
ruleElement.setAttribute("name", rule.getName());
ruleElement.setAttribute("message", rule.getMessage());
final String className = rule.getClass().getName();
// if (rule instanceof DynamicXPathRule) {
// className = XPathRule.class.getName();
// }
ruleElement.setAttribute("class", className);
if (rule.usesDFA()) {
ruleElement.setAttribute("dfa", "true");
}
if (rule.include()) {
ruleElement.setAttribute("include", "true");
}
final Element descriptionElement = getDescriptionElement(doc, rule.getDescription());
ruleElement.appendChild(descriptionElement);
- final Element exampleElement = getExampleElement(doc, rule.getExamples().get(0).toString());
- ruleElement.appendChild(exampleElement);
+ if (rule.getExamples().size() > 0) {
+ final Element exampleElement = getExampleElement(doc, rule.getExamples().get(0).toString());
+ ruleElement.appendChild(exampleElement);
+ }
final Element priorityElement = getPriorityElement(doc, rule.getPriority());
ruleElement.appendChild(priorityElement);
final Element propertiesElement = getPropertiesElement(doc, rule.getProperties());
ruleElement.appendChild(propertiesElement);
return ruleElement;
}
/**
* Get an element from an example
* @param doc the generated doc
* @param example a rule example
* @return an example element
*/
private Element getExampleElement(Document doc, String example) {
final Element exampleElement = doc.createElement("example");
final CDATASection cdataSection = doc.createCDATASection(example);
exampleElement.appendChild(cdataSection);
return exampleElement;
}
/**
* Get an element from a rule priority
* @param doc the generated doc
* @param priority a priotity
* @return a priority element
*/
private Element getPriorityElement(Document doc, int priority) {
final Element priorityElement = doc.createElement("priority");
final Text text = doc.createTextNode(String.valueOf(priority));
priorityElement.appendChild(text);
return priorityElement;
}
/**
* Get an element from rule properties
* @param doc the genetated doc
* @param properties rule properties
* @return a properties element
*/
private Element getPropertiesElement(Document doc, Properties properties) {
final Element propertiesElement = doc.createElement("properties");
final Enumeration keys = properties.keys();
while (keys.hasMoreElements()) {
final Object key = keys.nextElement();
final Element propertyElement = getPropertyElement(doc, (String) key, (String) properties.get(key));
propertiesElement.appendChild(propertyElement);
}
return propertiesElement;
}
/**
* Get an element from a rule property
* @param doc the generated doc
* @param key a property key
* @param value a property value
* @return a property element
*/
private Element getPropertyElement(Document doc, String key, String value) {
final Element propertyElement = doc.createElement("property");
propertyElement.setAttribute("name", key);
if ("xpath".equals(key)) {
final Element valueElement = doc.createElement("value");
final CDATASection cdataSection = doc.createCDATASection(value);
valueElement.appendChild(cdataSection);
propertyElement.appendChild(valueElement);
} else {
propertyElement.setAttribute("value", value);
}
return propertyElement;
}
}
| true | true | private Element getRuleElement(Document doc, Rule rule) {
final Element ruleElement = doc.createElement("rule");
ruleElement.setAttribute("name", rule.getName());
ruleElement.setAttribute("message", rule.getMessage());
final String className = rule.getClass().getName();
// if (rule instanceof DynamicXPathRule) {
// className = XPathRule.class.getName();
// }
ruleElement.setAttribute("class", className);
if (rule.usesDFA()) {
ruleElement.setAttribute("dfa", "true");
}
if (rule.include()) {
ruleElement.setAttribute("include", "true");
}
final Element descriptionElement = getDescriptionElement(doc, rule.getDescription());
ruleElement.appendChild(descriptionElement);
final Element exampleElement = getExampleElement(doc, rule.getExamples().get(0).toString());
ruleElement.appendChild(exampleElement);
final Element priorityElement = getPriorityElement(doc, rule.getPriority());
ruleElement.appendChild(priorityElement);
final Element propertiesElement = getPropertiesElement(doc, rule.getProperties());
ruleElement.appendChild(propertiesElement);
return ruleElement;
}
| private Element getRuleElement(Document doc, Rule rule) {
final Element ruleElement = doc.createElement("rule");
ruleElement.setAttribute("name", rule.getName());
ruleElement.setAttribute("message", rule.getMessage());
final String className = rule.getClass().getName();
// if (rule instanceof DynamicXPathRule) {
// className = XPathRule.class.getName();
// }
ruleElement.setAttribute("class", className);
if (rule.usesDFA()) {
ruleElement.setAttribute("dfa", "true");
}
if (rule.include()) {
ruleElement.setAttribute("include", "true");
}
final Element descriptionElement = getDescriptionElement(doc, rule.getDescription());
ruleElement.appendChild(descriptionElement);
if (rule.getExamples().size() > 0) {
final Element exampleElement = getExampleElement(doc, rule.getExamples().get(0).toString());
ruleElement.appendChild(exampleElement);
}
final Element priorityElement = getPriorityElement(doc, rule.getPriority());
ruleElement.appendChild(priorityElement);
final Element propertiesElement = getPropertiesElement(doc, rule.getProperties());
ruleElement.appendChild(propertiesElement);
return ruleElement;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.