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/com/noshufou/android/su/UninstallReceiver.java b/src/com/noshufou/android/su/UninstallReceiver.java
index 6a5659a..cbbd2d0 100644
--- a/src/com/noshufou/android/su/UninstallReceiver.java
+++ b/src/com/noshufou/android/su/UninstallReceiver.java
@@ -1,16 +1,17 @@
package com.noshufou.android.su;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class UninstallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
DBHelper db = new DBHelper(context);
int uid = intent.getIntExtra(Intent.EXTRA_UID, 0);
if (uid != 1 && !(intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
db.deleteByUid(uid);
}
+ db.close();
}
}
| true | true | public void onReceive(Context context, Intent intent) {
DBHelper db = new DBHelper(context);
int uid = intent.getIntExtra(Intent.EXTRA_UID, 0);
if (uid != 1 && !(intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
db.deleteByUid(uid);
}
}
| public void onReceive(Context context, Intent intent) {
DBHelper db = new DBHelper(context);
int uid = intent.getIntExtra(Intent.EXTRA_UID, 0);
if (uid != 1 && !(intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
db.deleteByUid(uid);
}
db.close();
}
|
diff --git a/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java b/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java
index 7f28572..1c4d289 100644
--- a/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java
+++ b/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java
@@ -1,168 +1,170 @@
package hudson.plugins.promoted_builds.conditions;
import hudson.CopyOnWrite;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import hudson.plugins.promoted_builds.JobPropertyImpl;
import hudson.plugins.promoted_builds.PromotionCondition;
import hudson.plugins.promoted_builds.PromotionConditionDescriptor;
import hudson.plugins.promoted_builds.PromotionCriterion;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Kohsuke Kawaguchi
*/
public class DownstreamPassCondition extends PromotionCondition {
/**
* List of downstream jobs that are used as the promotion criteria.
*
* Every job has to have at least one successful build for us to promote a build.
*/
private final String jobs;
public DownstreamPassCondition(String jobs) {
this.jobs = jobs;
}
public String getJobs() {
return jobs;
}
@Override
public boolean isMet(AbstractBuild<?,?> build) {
for (AbstractProject<?,?> j : getJobList()) {
boolean passed = false;
for( AbstractBuild<?,?> b : build.getDownstreamBuilds(j) ) {
if(b.getResult()== Result.SUCCESS) {
passed = true;
break;
}
}
if(!passed) // none of the builds of this job passed.
return false;
}
return true;
}
public PromotionConditionDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
/**
* List of downstream jobs that we need to monitor.
*
* @return never null.
*/
public List<AbstractProject<?,?>> getJobList() {
List<AbstractProject<?,?>> r = new ArrayList<AbstractProject<?,?>>();
for (String name : Util.tokenize(jobs,",")) {
AbstractProject job = Hudson.getInstance().getItemByFullName(name.trim(),AbstractProject.class);
if(job!=null) r.add(job);
}
return r;
}
/**
* Short-cut for {@code getJobList().contains(job)}.
*/
public boolean contains(AbstractProject<?,?> job) {
if(!jobs.contains(job.getFullName())) return false; // quick rejection test
for (String name : Util.tokenize(jobs,",")) {
if(name.trim().equals(job.getFullName()))
return true;
}
return false;
}
public static final class DescriptorImpl extends PromotionConditionDescriptor {
public DescriptorImpl() {
super(DownstreamPassCondition.class);
new RunListenerImpl().register();
}
public boolean isApplicable(AbstractProject<?,?> item) {
return true;
}
public String getDisplayName() {
return "When the following downstream projects build successfully";
}
public PromotionCondition newInstance(StaplerRequest req, JSONObject formData) throws FormException {
return new DownstreamPassCondition(formData.getString("jobs"));
}
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
}
/**
* {@link RunListener} to pick up completions of downstream builds.
*
* <p>
* This is a single instance that receives all the events everywhere in the system.
* @author Kohsuke Kawaguchi
*/
private static final class RunListenerImpl extends RunListener<AbstractBuild<?,?>> {
public RunListenerImpl() {
super((Class)AbstractBuild.class);
}
@Override
public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) {
// this is not terribly efficient,
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
JobPropertyImpl p = j.getProperty(JobPropertyImpl.class);
if(p!=null) {
for (PromotionCriterion c : p.getCriteria()) {
boolean considerPromotion = false;
for (PromotionCondition cond : c.getConditions()) {
if (cond instanceof DownstreamPassCondition) {
DownstreamPassCondition dpcond = (DownstreamPassCondition) cond;
if(dpcond.contains(build.getParent()))
considerPromotion = true;
}
}
if(considerPromotion) {
try {
- c.considerPromotion(build.getUpstreamRelationshipBuild(j));
+ AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j);
+ if(u!=null)
+ c.considerPromotion(u);
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to promote a build"));
}
}
}
}
}
}
/**
* List of downstream jobs that we are interested in.
*/
@CopyOnWrite
private static volatile Set<AbstractProject> DOWNSTREAM_JOBS = Collections.emptySet();
/**
* Called whenever some {@link JobPropertyImpl} changes to update {@link #DOWNSTREAM_JOBS}.
*/
public static void rebuildCache() {
Set<AbstractProject> downstreams = new HashSet<AbstractProject>();
DOWNSTREAM_JOBS = downstreams;
}
}
}
| true | true | public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) {
// this is not terribly efficient,
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
JobPropertyImpl p = j.getProperty(JobPropertyImpl.class);
if(p!=null) {
for (PromotionCriterion c : p.getCriteria()) {
boolean considerPromotion = false;
for (PromotionCondition cond : c.getConditions()) {
if (cond instanceof DownstreamPassCondition) {
DownstreamPassCondition dpcond = (DownstreamPassCondition) cond;
if(dpcond.contains(build.getParent()))
considerPromotion = true;
}
}
if(considerPromotion) {
try {
c.considerPromotion(build.getUpstreamRelationshipBuild(j));
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to promote a build"));
}
}
}
}
}
}
| public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) {
// this is not terribly efficient,
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
JobPropertyImpl p = j.getProperty(JobPropertyImpl.class);
if(p!=null) {
for (PromotionCriterion c : p.getCriteria()) {
boolean considerPromotion = false;
for (PromotionCondition cond : c.getConditions()) {
if (cond instanceof DownstreamPassCondition) {
DownstreamPassCondition dpcond = (DownstreamPassCondition) cond;
if(dpcond.contains(build.getParent()))
considerPromotion = true;
}
}
if(considerPromotion) {
try {
AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j);
if(u!=null)
c.considerPromotion(u);
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to promote a build"));
}
}
}
}
}
}
|
diff --git a/org/mailster/smtp/SmtpMessage.java b/org/mailster/smtp/SmtpMessage.java
index 602d72e..aefe7b9 100644
--- a/org/mailster/smtp/SmtpMessage.java
+++ b/org/mailster/smtp/SmtpMessage.java
@@ -1,378 +1,378 @@
/*
* Dumbster - a dummy SMTP server Copyright 2004 Jason Paul Kitchen 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.
*/
/**
* Mailster additions : Copyright (c) 2007 De Oliveira Edouard
* <p>
* Some modifications to original code have been made in order to get efficient
* parsing and to make bug corrections.
*/
package org.mailster.smtp;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import org.mailster.util.MailUtilities;
/**
* Container for a complete SMTP message - headers and message body.
*/
public class SmtpMessage
{
/**
* Variable used for MimeMessage conversion.
*/
private final static Session MAIL_SESSION = Session.getDefaultInstance(System.getProperties(), null);
/**
* Headers.
*/
private SmtpHeadersInterface headers;
/**
* Message body.
*/
private StringBuilder body;
/**
* Recipients (read from envelope)
*/
private List<String> recipients;
private SmtpMessagePart internalParts;
private StringBuilder rawMessage;
private String content;
private String oldPreferredContentType;
private String messageID;
private String internalDate;
private String charset;
//private Charset serverCharset = null;
private Boolean needsConversion = null;
/**
* Likewise, a global id for Message-ID generation.
*/
private static int id = 0;
/**
* Constructor. Initializes headers Map and body buffer.
*/
public SmtpMessage()
{
headers = new SmtpHeaders();
body = new StringBuilder();
rawMessage = new StringBuilder();
recipients = new ArrayList<String>();
}
/**
* Update the headers or body depending on the SmtpResponse object and line
* of input.
*
* @param response SmtpResponse object
* @param params remainder of input line after SMTP command has been removed
*/
public void store(SmtpResponse response, String params)
{
boolean log = response.getNextState() == SmtpState.DATA_HDR
|| response.getNextState() == SmtpState.DATA_BODY;
if (params != null)
{
if (SmtpState.DATA_HDR == response.getNextState())
headers.addHeaderLine(params);
else if (SmtpState.DATA_BODY == response.getNextState())
{
if (needsConversion == null)
{
- String charset = getBodyCharset();
- needsConversion = charset != null && SimpleSmtpServer.DEFAULT_CHARSET.equals(charset);
+ charset = getBodyCharset();
+ needsConversion = charset != null && !SimpleSmtpServer.DEFAULT_CHARSET.equals(charset);
/*if (charset != null && SimpleSmtpServer.DEFAULT_CHARSET.equals(charset))
serverCharset = Charset.forName(SimpleSmtpServer.DEFAULT_CHARSET);*/
}
if (Boolean.TRUE.equals(needsConversion))
{
try
{
params = new String(params.getBytes(SimpleSmtpServer.DEFAULT_CHARSET), charset);
// Since 1.6
//params = new String(params.getBytes(serverCharset), charset);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
body.append(params);
}
if (log)
{
rawMessage.append(params);
if (response.getNextState() != SmtpState.DATA_BODY)
rawMessage.append('\n');
}
}
else if (response.getNextState() == SmtpState.DATA_BODY)
rawMessage.append('\n');
}
/**
* Get a unique value to use 'as' a Message-ID. If the headers don't contain
* a Message-ID header value, this implementation generates it by
* concatenating the message object's <code>hashCode()</code>, a global
* ID (incremented on every use), the current time (in milliseconds), the
* string "Mailster", and this user's local address generated by
* <code>InetAddress.getLocalHost()</code>. (The address defaults to
* "localhost" if <code>getLocalHost()</code> returns null.)
*
* @see java.net.InetAddress
*/
public String getMessageID()
{
if (messageID == null)
{
messageID = getHeaderValue(SmtpHeadersInterface.MESSAGE_ID);
if (messageID == null)
{
StringBuilder s = new StringBuilder(hashCode());
s.append('.').append(id++).append(System.currentTimeMillis())
.append(".Mailster@");
try
{
InetAddress addr = InetAddress.getLocalHost();
if (addr != null)
s.append(addr.getAddress());
else
s.append("localhost");
}
catch (UnknownHostException e)
{
s.append("localhost");
}
// Unique string is
// <hashcode>.<id>.<currentTime>.Mailster@<host>
messageID = s.toString();
}
}
return messageID;
}
/**
* Get the value(s) associated with the given header name.
*
* @param name header name
* @return value(s) associated with the header name
*/
public String[] getHeaderValues(String name)
{
return headers.getHeaderValues(name);
}
/**
* Get the first value associated with a given header name.
*
* @param name header name
* @return first value associated with the header name
*/
public String getHeaderValue(String name)
{
return headers.getHeaderValue(name);
}
/**
* Get the message body.
*
* @return message body
*/
public String getBody()
{
return body.toString();
}
/**
* Converts from a <code>SmtpMessage</code> to a <code>MimeMessage</code>.
*
* @return a <code>MimeMessage</code> object
* @throws MessagingException if MimeMessage creation fails
* @throws UnsupportedEncodingException if charset is unknown
*/
public MimeMessage asMimeMessage() throws MessagingException, UnsupportedEncodingException
{
String charset = getBodyCharset();
if (charset == null)
charset = SimpleSmtpServer.DEFAULT_CHARSET;
return new MimeMessage(MAIL_SESSION,
new ByteArrayInputStream(getRawMessage().getBytes(charset)));
}
public String getRawMessage()
{
return rawMessage.toString();
}
/**
* String representation of the SmtpMessage.
*
* @return a String
*/
public String toString()
{
StringBuilder msg = new StringBuilder(headers.toString());
msg.append('\n').append(body).append('\n');
return msg.toString();
}
public SmtpHeadersInterface getHeaders()
{
return headers;
}
/**
* Note : this method generates and stores a date header if the mail doesn't have one.
*/
public String getDate()
{
String date = getHeaders().getHeaderValue(SmtpHeadersInterface.DATE);
if (date == null)
{
if (internalDate == null)
{
date = MailUtilities.getNonNullHeaderValue(getHeaders(), SmtpHeadersInterface.DATE);
internalDate = date;
}
else
date = internalDate;
}
return date;
}
public String getTo()
{
return getHeaderValue(SmtpHeadersInterface.TO);
}
public String getSubject()
{
return MailUtilities.getNonNullHeaderValue(getHeaders(),
SmtpHeadersInterface.SUBJECT);
}
public SmtpMessagePart getInternalParts()
{
if (internalParts == null)
internalParts = MailUtilities.parseInternalParts(this);
return internalParts;
}
public String getPreferredContent(String preferredContentType)
{
if (content == null
|| !oldPreferredContentType.equals(preferredContentType))
{
oldPreferredContentType = preferredContentType;
content = getInternalParts().getPreferredContent(preferredContentType);
if (content != null)
{
String upperContent = content.toUpperCase();
if (upperContent.indexOf("<HTML>") == -1)
{
if (upperContent.indexOf("<BODY>") == -1)
content = "<html><head> <style type=\"text/css\"><!--\n" +
"html,body {margin:2px;font: 10px Verdana;}" +
"--></style></head><body>"
+ content + "</body></html>";
else
content = "<html>"+content+"</html>";
}
}
}
return content == null ? "" : content;
}
/**
* Get the charset specified in Content-Type header.
*
* @return charset, null if none specified.
*/
public String getBodyCharset()
{
return MailUtilities.getHeaderParameterValue(headers,
SmtpHeadersInterface.CONTENT_TYPE,
SmtpHeadersInterface.CHARSET_PARAMETER);
}
/**
* Add a recipient to the list of recipients.
*/
protected void addRecipient(String recipient)
{
recipients.add(recipient);
}
/**
* Add a list of recipients to the list of recipients.
*/
public void addRecipients(List<String> l)
{
this.recipients.addAll(l);
}
/**
* Returns the recipients of this message (from the SMTP
* envelope). Bcc recipients are consequently exposed for testing.
*
* @return the list of recipients
*/
public List<String> getRecipients()
{
return recipients;
}
/**
* Return the size of the content of this message in bytes. Return -1 if the
* size cannot be determined.
* <p>
* Note that this number may not be an exact measure of the content size and
* may or may not account for any transfer encoding of the content.
* <p>
* This implementation returns the size of the message body (if not null),
* otherwise, it returns -1.
*
* @return size of content in bytes
*/
public int getSize()
{
String s = getBody();
if (s != null)
return s.length();
return -1;
}
}
| true | true | public void store(SmtpResponse response, String params)
{
boolean log = response.getNextState() == SmtpState.DATA_HDR
|| response.getNextState() == SmtpState.DATA_BODY;
if (params != null)
{
if (SmtpState.DATA_HDR == response.getNextState())
headers.addHeaderLine(params);
else if (SmtpState.DATA_BODY == response.getNextState())
{
if (needsConversion == null)
{
String charset = getBodyCharset();
needsConversion = charset != null && SimpleSmtpServer.DEFAULT_CHARSET.equals(charset);
/*if (charset != null && SimpleSmtpServer.DEFAULT_CHARSET.equals(charset))
serverCharset = Charset.forName(SimpleSmtpServer.DEFAULT_CHARSET);*/
}
if (Boolean.TRUE.equals(needsConversion))
{
try
{
params = new String(params.getBytes(SimpleSmtpServer.DEFAULT_CHARSET), charset);
// Since 1.6
//params = new String(params.getBytes(serverCharset), charset);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
body.append(params);
}
if (log)
{
rawMessage.append(params);
if (response.getNextState() != SmtpState.DATA_BODY)
rawMessage.append('\n');
}
}
else if (response.getNextState() == SmtpState.DATA_BODY)
rawMessage.append('\n');
}
| public void store(SmtpResponse response, String params)
{
boolean log = response.getNextState() == SmtpState.DATA_HDR
|| response.getNextState() == SmtpState.DATA_BODY;
if (params != null)
{
if (SmtpState.DATA_HDR == response.getNextState())
headers.addHeaderLine(params);
else if (SmtpState.DATA_BODY == response.getNextState())
{
if (needsConversion == null)
{
charset = getBodyCharset();
needsConversion = charset != null && !SimpleSmtpServer.DEFAULT_CHARSET.equals(charset);
/*if (charset != null && SimpleSmtpServer.DEFAULT_CHARSET.equals(charset))
serverCharset = Charset.forName(SimpleSmtpServer.DEFAULT_CHARSET);*/
}
if (Boolean.TRUE.equals(needsConversion))
{
try
{
params = new String(params.getBytes(SimpleSmtpServer.DEFAULT_CHARSET), charset);
// Since 1.6
//params = new String(params.getBytes(serverCharset), charset);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
body.append(params);
}
if (log)
{
rawMessage.append(params);
if (response.getNextState() != SmtpState.DATA_BODY)
rawMessage.append('\n');
}
}
else if (response.getNextState() == SmtpState.DATA_BODY)
rawMessage.append('\n');
}
|
diff --git a/src/com/android/nfc/NfcService.java b/src/com/android/nfc/NfcService.java
index b551829..9f6cd7f 100755
--- a/src/com/android/nfc/NfcService.java
+++ b/src/com/android/nfc/NfcService.java
@@ -1,2159 +1,2169 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.nfc;
import com.android.nfc.DeviceHost.DeviceHostListener;
import com.android.nfc.DeviceHost.LlcpConnectionlessSocket;
import com.android.nfc.DeviceHost.LlcpServerSocket;
import com.android.nfc.DeviceHost.LlcpSocket;
import com.android.nfc.DeviceHost.NfcDepEndpoint;
import com.android.nfc.DeviceHost.TagEndpoint;
import com.android.nfc.handover.HandoverManager;
import com.android.nfc.dhimpl.NativeNfcManager;
import com.android.nfc.dhimpl.NativeNfcSecureElement;
import android.app.Application;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources.NotFoundException;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.nfc.ErrorCodes;
import android.nfc.FormatException;
import android.nfc.INdefPushCallback;
import android.nfc.INfcAdapter;
import android.nfc.INfcAdapterExtras;
import android.nfc.INfcTag;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.TechListParcel;
import android.nfc.TransceiveResult;
import android.nfc.tech.Ndef;
import android.nfc.tech.TagTechnology;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.UserHandle;
import android.provider.Settings;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class NfcService implements DeviceHostListener {
private static final String ACTION_MASTER_CLEAR_NOTIFICATION = "android.intent.action.MASTER_CLEAR_NOTIFICATION";
static final boolean DBG = false;
static final String TAG = "NfcService";
public static final String SERVICE_NAME = "nfc";
/** Regular NFC permission */
private static final String NFC_PERM = android.Manifest.permission.NFC;
private static final String NFC_PERM_ERROR = "NFC permission required";
/** NFC ADMIN permission - only for system apps */
private static final String ADMIN_PERM = android.Manifest.permission.WRITE_SECURE_SETTINGS;
private static final String ADMIN_PERM_ERROR = "WRITE_SECURE_SETTINGS permission required";
public static final String PREF = "NfcServicePrefs";
static final String PREF_NFC_ON = "nfc_on";
static final boolean NFC_ON_DEFAULT = true;
static final String PREF_NDEF_PUSH_ON = "ndef_push_on";
static final boolean NDEF_PUSH_ON_DEFAULT = true;
static final String PREF_FIRST_BEAM = "first_beam";
static final String PREF_FIRST_BOOT = "first_boot";
static final String PREF_AIRPLANE_OVERRIDE = "airplane_override";
static final int MSG_NDEF_TAG = 0;
static final int MSG_CARD_EMULATION = 1;
static final int MSG_LLCP_LINK_ACTIVATION = 2;
static final int MSG_LLCP_LINK_DEACTIVATED = 3;
static final int MSG_TARGET_DESELECTED = 4;
static final int MSG_MOCK_NDEF = 7;
static final int MSG_SE_FIELD_ACTIVATED = 8;
static final int MSG_SE_FIELD_DEACTIVATED = 9;
static final int MSG_SE_APDU_RECEIVED = 10;
static final int MSG_SE_EMV_CARD_REMOVAL = 11;
static final int MSG_SE_MIFARE_ACCESS = 12;
static final int MSG_SE_LISTEN_ACTIVATED = 13;
static final int MSG_SE_LISTEN_DEACTIVATED = 14;
static final int MSG_LLCP_LINK_FIRST_PACKET = 15;
static final int TASK_ENABLE = 1;
static final int TASK_DISABLE = 2;
static final int TASK_BOOT = 3;
static final int TASK_EE_WIPE = 4;
// Screen state, used by mScreenState
static final int SCREEN_STATE_UNKNOWN = 0;
static final int SCREEN_STATE_OFF = 1;
static final int SCREEN_STATE_ON_LOCKED = 2;
static final int SCREEN_STATE_ON_UNLOCKED = 3;
// Copied from com.android.nfc_extras to avoid library dependency
// Must keep in sync with com.android.nfc_extras
static final int ROUTE_OFF = 1;
static final int ROUTE_ON_WHEN_SCREEN_ON = 2;
// Return values from NfcEe.open() - these are 1:1 mapped
// to the thrown EE_EXCEPTION_ exceptions in nfc-extras.
static final int EE_ERROR_IO = -1;
static final int EE_ERROR_ALREADY_OPEN = -2;
static final int EE_ERROR_INIT = -3;
static final int EE_ERROR_LISTEN_MODE = -4;
static final int EE_ERROR_EXT_FIELD = -5;
static final int EE_ERROR_NFC_DISABLED = -6;
/** minimum screen state that enables NFC polling (discovery) */
static final int POLLING_MODE = SCREEN_STATE_ON_UNLOCKED;
// Time to wait for NFC controller to initialize before watchdog
// goes off. This time is chosen large, because firmware download
// may be a part of initialization.
static final int INIT_WATCHDOG_MS = 90000;
// Time to wait for routing to be applied before watchdog
// goes off
static final int ROUTING_WATCHDOG_MS = 10000;
// for use with playSound()
public static final int SOUND_START = 0;
public static final int SOUND_END = 1;
public static final int SOUND_ERROR = 2;
public static final String ACTION_RF_FIELD_ON_DETECTED =
"com.android.nfc_extras.action.RF_FIELD_ON_DETECTED";
public static final String ACTION_RF_FIELD_OFF_DETECTED =
"com.android.nfc_extras.action.RF_FIELD_OFF_DETECTED";
public static final String ACTION_AID_SELECTED =
"com.android.nfc_extras.action.AID_SELECTED";
public static final String EXTRA_AID = "com.android.nfc_extras.extra.AID";
public static final String ACTION_APDU_RECEIVED =
"com.android.nfc_extras.action.APDU_RECEIVED";
public static final String EXTRA_APDU_BYTES =
"com.android.nfc_extras.extra.APDU_BYTES";
public static final String ACTION_EMV_CARD_REMOVAL =
"com.android.nfc_extras.action.EMV_CARD_REMOVAL";
public static final String ACTION_MIFARE_ACCESS_DETECTED =
"com.android.nfc_extras.action.MIFARE_ACCESS_DETECTED";
public static final String EXTRA_MIFARE_BLOCK =
"com.android.nfc_extras.extra.MIFARE_BLOCK";
public static final String ACTION_SE_LISTEN_ACTIVATED =
"com.android.nfc_extras.action.SE_LISTEN_ACTIVATED";
public static final String ACTION_SE_LISTEN_DEACTIVATED =
"com.android.nfc_extras.action.SE_LISTEN_DEACTIVATED";
// NFC Execution Environment
// fields below are protected by this
private NativeNfcSecureElement mSecureElement;
private OpenSecureElement mOpenEe; // null when EE closed
private int mEeRoutingState; // contactless interface routing
// fields below must be used only on the UI thread and therefore aren't synchronized
boolean mP2pStarted = false;
// fields below are used in multiple threads and protected by synchronized(this)
final HashMap<Integer, Object> mObjectMap = new HashMap<Integer, Object>();
// mSePackages holds packages that accessed the SE, but only for the owner user,
// as SE access is not granted for non-owner users.
HashSet<String> mSePackages = new HashSet<String>();
int mScreenState;
boolean mInProvisionMode; // whether we're in setup wizard and enabled NFC provisioning
boolean mIsNdefPushEnabled;
boolean mNfceeRouteEnabled; // current Device Host state of NFC-EE routing
boolean mNfcPollingEnabled; // current Device Host state of NFC-C polling
List<PackageInfo> mInstalledPackages; // cached version of installed packages
// mState is protected by this, however it is only modified in onCreate()
// and the default AsyncTask thread so it is read unprotected from that
// thread
int mState; // one of NfcAdapter.STATE_ON, STATE_TURNING_ON, etc
// fields below are final after onCreate()
Context mContext;
private DeviceHost mDeviceHost;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefsEditor;
private PowerManager.WakeLock mRoutingWakeLock;
private PowerManager.WakeLock mEeWakeLock;
int mStartSound;
int mEndSound;
int mErrorSound;
SoundPool mSoundPool; // playback synchronized on this
P2pLinkManager mP2pLinkManager;
TagService mNfcTagService;
NfcAdapterService mNfcAdapter;
NfcAdapterExtrasService mExtrasService;
boolean mIsAirplaneSensitive;
boolean mIsAirplaneToggleable;
NfceeAccessControl mNfceeAccessControl;
private NfcDispatcher mNfcDispatcher;
private PowerManager mPowerManager;
private KeyguardManager mKeyguard;
private HandoverManager mHandoverManager;
private ContentResolver mContentResolver;
private static NfcService sService;
public static void enforceAdminPerm(Context context) {
context.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
}
public void enforceNfceeAdminPerm(String pkg) {
if (pkg == null) {
throw new SecurityException("caller must pass a package name");
}
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
if (!mNfceeAccessControl.check(Binder.getCallingUid(), pkg)) {
throw new SecurityException(NfceeAccessControl.NFCEE_ACCESS_PATH +
" denies NFCEE access to " + pkg);
}
if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
throw new SecurityException("only the owner is allowed to call SE APIs");
}
}
public static NfcService getInstance() {
return sService;
}
@Override
public void onRemoteEndpointDiscovered(TagEndpoint tag) {
sendMessage(NfcService.MSG_NDEF_TAG, tag);
}
/**
* Notifies transaction
*/
@Override
public void onCardEmulationDeselected() {
sendMessage(NfcService.MSG_TARGET_DESELECTED, null);
}
/**
* Notifies transaction
*/
@Override
public void onCardEmulationAidSelected(byte[] aid) {
sendMessage(NfcService.MSG_CARD_EMULATION, aid);
}
/**
* Notifies P2P Device detected, to activate LLCP link
*/
@Override
public void onLlcpLinkActivated(NfcDepEndpoint device) {
sendMessage(NfcService.MSG_LLCP_LINK_ACTIVATION, device);
}
/**
* Notifies P2P Device detected, to activate LLCP link
*/
@Override
public void onLlcpLinkDeactivated(NfcDepEndpoint device) {
sendMessage(NfcService.MSG_LLCP_LINK_DEACTIVATED, device);
}
/**
* Notifies P2P Device detected, first packet received over LLCP link
*/
@Override
public void onLlcpFirstPacketReceived(NfcDepEndpoint device) {
sendMessage(NfcService.MSG_LLCP_LINK_FIRST_PACKET, device);
}
@Override
public void onRemoteFieldActivated() {
sendMessage(NfcService.MSG_SE_FIELD_ACTIVATED, null);
}
@Override
public void onRemoteFieldDeactivated() {
sendMessage(NfcService.MSG_SE_FIELD_DEACTIVATED, null);
}
@Override
public void onSeListenActivated() {
sendMessage(NfcService.MSG_SE_LISTEN_ACTIVATED, null);
}
@Override
public void onSeListenDeactivated() {
sendMessage(NfcService.MSG_SE_LISTEN_DEACTIVATED, null);
}
@Override
public void onSeApduReceived(byte[] apdu) {
sendMessage(NfcService.MSG_SE_APDU_RECEIVED, apdu);
}
@Override
public void onSeEmvCardRemoval() {
sendMessage(NfcService.MSG_SE_EMV_CARD_REMOVAL, null);
}
@Override
public void onSeMifareAccess(byte[] block) {
sendMessage(NfcService.MSG_SE_MIFARE_ACCESS, block);
}
public NfcService(Application nfcApplication) {
mNfcTagService = new TagService();
mNfcAdapter = new NfcAdapterService();
mExtrasService = new NfcAdapterExtrasService();
Log.i(TAG, "Starting NFC service");
sService = this;
mContext = nfcApplication;
mContentResolver = mContext.getContentResolver();
mDeviceHost = new NativeNfcManager(mContext, this);
mHandoverManager = new HandoverManager(mContext);
boolean isNfcProvisioningEnabled = false;
try {
isNfcProvisioningEnabled = mContext.getResources().getBoolean(
R.bool.enable_nfc_provisioning);
} catch (NotFoundException e) {
}
if (isNfcProvisioningEnabled) {
mInProvisionMode = Settings.Secure.getInt(mContentResolver,
Settings.Global.DEVICE_PROVISIONED, 0) == 0;
} else {
mInProvisionMode = false;
}
mHandoverManager.setEnabled(!mInProvisionMode);
mNfcDispatcher = new NfcDispatcher(mContext, mHandoverManager, mInProvisionMode);
mP2pLinkManager = new P2pLinkManager(mContext, mHandoverManager,
mDeviceHost.getDefaultLlcpMiu(), mDeviceHost.getDefaultLlcpRwSize());
mSecureElement = new NativeNfcSecureElement(mContext);
mEeRoutingState = ROUTE_OFF;
mNfceeAccessControl = new NfceeAccessControl(mContext);
mPrefs = mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE);
mPrefsEditor = mPrefs.edit();
mState = NfcAdapter.STATE_OFF;
mIsNdefPushEnabled = mPrefs.getBoolean(PREF_NDEF_PUSH_ON, NDEF_PUSH_ON_DEFAULT);
mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
mRoutingWakeLock = mPowerManager.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "NfcService:mRoutingWakeLock");
mEeWakeLock = mPowerManager.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "NfcService:mEeWakeLock");
mKeyguard = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
mScreenState = checkScreenState();
ServiceManager.addService(SERVICE_NAME, mNfcAdapter);
// Intents only for owner
IntentFilter ownerFilter = new IntentFilter(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
ownerFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
ownerFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
ownerFilter.addAction(ACTION_MASTER_CLEAR_NOTIFICATION);
mContext.registerReceiver(mOwnerReceiver, ownerFilter);
ownerFilter = new IntentFilter();
ownerFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
ownerFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
ownerFilter.addDataScheme("package");
mContext.registerReceiver(mOwnerReceiver, ownerFilter);
// Intents for all users
IntentFilter filter = new IntentFilter(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_USER_SWITCHED);
registerForAirplaneMode(filter);
mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, null);
updatePackageCache();
new EnableDisableTask().execute(TASK_BOOT); // do blocking boot tasks
}
void initSoundPool() {
synchronized(this) {
if (mSoundPool == null) {
mSoundPool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 0);
mStartSound = mSoundPool.load(mContext, R.raw.start, 1);
mEndSound = mSoundPool.load(mContext, R.raw.end, 1);
mErrorSound = mSoundPool.load(mContext, R.raw.error, 1);
}
}
}
void releaseSoundPool() {
synchronized(this) {
if (mSoundPool != null) {
mSoundPool.release();
mSoundPool = null;
}
}
}
void registerForAirplaneMode(IntentFilter filter) {
final String airplaneModeRadios = Settings.System.getString(mContentResolver,
Settings.Global.AIRPLANE_MODE_RADIOS);
final String toggleableRadios = Settings.System.getString(mContentResolver,
Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
mIsAirplaneSensitive = airplaneModeRadios == null ? true :
airplaneModeRadios.contains(Settings.Global.RADIO_NFC);
mIsAirplaneToggleable = toggleableRadios == null ? false :
toggleableRadios.contains(Settings.Global.RADIO_NFC);
if (mIsAirplaneSensitive) {
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
}
}
void updatePackageCache() {
PackageManager pm = mContext.getPackageManager();
List<PackageInfo> packages = pm.getInstalledPackages(0, UserHandle.USER_OWNER);
synchronized (this) {
mInstalledPackages = packages;
}
}
int checkScreenState() {
if (!mPowerManager.isScreenOn()) {
return SCREEN_STATE_OFF;
} else if (mKeyguard.isKeyguardLocked()) {
return SCREEN_STATE_ON_LOCKED;
} else {
return SCREEN_STATE_ON_UNLOCKED;
}
}
int doOpenSecureElementConnection() {
mEeWakeLock.acquire();
try {
return mSecureElement.doOpenSecureElementConnection();
} finally {
mEeWakeLock.release();
}
}
byte[] doTransceive(int handle, byte[] cmd) {
mEeWakeLock.acquire();
try {
return doTransceiveNoLock(handle, cmd);
} finally {
mEeWakeLock.release();
}
}
byte[] doTransceiveNoLock(int handle, byte[] cmd) {
return mSecureElement.doTransceive(handle, cmd);
}
void doDisconnect(int handle) {
mEeWakeLock.acquire();
try {
mSecureElement.doDisconnect(handle);
} finally {
mEeWakeLock.release();
}
}
/**
* Manages tasks that involve turning on/off the NFC controller.
*
* <p>All work that might turn the NFC adapter on or off must be done
* through this task, to keep the handling of mState simple.
* In other words, mState is only modified in these tasks (and we
* don't need a lock to read it in these tasks).
*
* <p>These tasks are all done on the same AsyncTask background
* thread, so they are serialized. Each task may temporarily transition
* mState to STATE_TURNING_OFF or STATE_TURNING_ON, but must exit in
* either STATE_ON or STATE_OFF. This way each task can be guaranteed
* of starting in either STATE_OFF or STATE_ON, without needing to hold
* NfcService.this for the entire task.
*
* <p>AsyncTask's are also implicitly queued. This is useful for corner
* cases like turning airplane mode on while TASK_ENABLE is in progress.
* The TASK_DISABLE triggered by airplane mode will be correctly executed
* immediately after TASK_ENABLE is complete. This seems like the most sane
* way to deal with these situations.
*
* <p>{@link #TASK_ENABLE} enables the NFC adapter, without changing
* preferences
* <p>{@link #TASK_DISABLE} disables the NFC adapter, without changing
* preferences
* <p>{@link #TASK_BOOT} does first boot work and may enable NFC
* <p>{@link #TASK_EE_WIPE} wipes the Execution Environment, and in the
* process may temporarily enable the NFC adapter
*/
class EnableDisableTask extends AsyncTask<Integer, Void, Void> {
@Override
protected Void doInBackground(Integer... params) {
// Sanity check mState
switch (mState) {
case NfcAdapter.STATE_TURNING_OFF:
case NfcAdapter.STATE_TURNING_ON:
Log.e(TAG, "Processing EnableDisable task " + params[0] + " from bad state " +
mState);
return null;
}
/* AsyncTask sets this thread to THREAD_PRIORITY_BACKGROUND,
* override with the default. THREAD_PRIORITY_BACKGROUND causes
* us to service software I2C too slow for firmware download
* with the NXP PN544.
* TODO: move this to the DAL I2C layer in libnfc-nxp, since this
* problem only occurs on I2C platforms using PN544
*/
Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
switch (params[0].intValue()) {
case TASK_ENABLE:
enableInternal();
break;
case TASK_DISABLE:
disableInternal();
break;
case TASK_BOOT:
Log.d(TAG,"checking on firmware download");
boolean airplaneOverride = mPrefs.getBoolean(PREF_AIRPLANE_OVERRIDE, false);
if (mPrefs.getBoolean(PREF_NFC_ON, NFC_ON_DEFAULT) &&
(!mIsAirplaneSensitive || !isAirplaneModeOn() || airplaneOverride)) {
Log.d(TAG,"NFC is on. Doing normal stuff");
enableInternal();
} else {
Log.d(TAG,"NFC is off. Checking firmware version");
mDeviceHost.checkFirmware();
}
if (mPrefs.getBoolean(PREF_FIRST_BOOT, true)) {
Log.i(TAG, "First Boot");
mPrefsEditor.putBoolean(PREF_FIRST_BOOT, false);
mPrefsEditor.apply();
executeEeWipe();
}
break;
case TASK_EE_WIPE:
executeEeWipe();
break;
}
// Restore default AsyncTask priority
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
return null;
}
/**
* Enable NFC adapter functions.
* Does not toggle preferences.
*/
boolean enableInternal() {
if (mState == NfcAdapter.STATE_ON) {
return true;
}
Log.i(TAG, "Enabling NFC");
updateState(NfcAdapter.STATE_TURNING_ON);
WatchDogThread watchDog = new WatchDogThread("enableInternal", INIT_WATCHDOG_MS);
watchDog.start();
try {
mRoutingWakeLock.acquire();
try {
if (!mDeviceHost.initialize()) {
Log.w(TAG, "Error enabling NFC");
updateState(NfcAdapter.STATE_OFF);
return false;
}
} finally {
mRoutingWakeLock.release();
}
} finally {
watchDog.cancel();
}
synchronized(NfcService.this) {
mObjectMap.clear();
mP2pLinkManager.enableDisable(mIsNdefPushEnabled, true);
updateState(NfcAdapter.STATE_ON);
}
initSoundPool();
/* Start polling loop */
applyRouting(true);
return true;
}
/**
* Disable all NFC adapter functions.
* Does not toggle preferences.
*/
boolean disableInternal() {
if (mState == NfcAdapter.STATE_OFF) {
return true;
}
Log.i(TAG, "Disabling NFC");
updateState(NfcAdapter.STATE_TURNING_OFF);
/* Sometimes mDeviceHost.deinitialize() hangs, use a watch-dog.
* Implemented with a new thread (instead of a Handler or AsyncTask),
* because the UI Thread and AsyncTask thread-pools can also get hung
* when the NFC controller stops responding */
WatchDogThread watchDog = new WatchDogThread("disableInternal", ROUTING_WATCHDOG_MS);
watchDog.start();
mP2pLinkManager.enableDisable(false, false);
synchronized (NfcService.this) {
if (mOpenEe != null) {
try {
_nfcEeClose(-1, mOpenEe.binder);
} catch (IOException e) { }
}
}
// Stop watchdog if tag present
// A convenient way to stop the watchdog properly consists of
// disconnecting the tag. The polling loop shall be stopped before
// to avoid the tag being discovered again.
maybeDisconnectTarget();
mNfcDispatcher.setForegroundDispatch(null, null, null);
boolean result = mDeviceHost.deinitialize();
if (DBG) Log.d(TAG, "mDeviceHost.deinitialize() = " + result);
watchDog.cancel();
updateState(NfcAdapter.STATE_OFF);
releaseSoundPool();
return result;
}
void executeEeWipe() {
// TODO: read SE reset list from /system/etc
byte[][]apdus = mDeviceHost.getWipeApdus();
if (apdus == null) {
Log.d(TAG, "No wipe APDUs found");
return;
}
boolean tempEnable = mState == NfcAdapter.STATE_OFF;
// Hold a wake-lock over the entire wipe procedure
mEeWakeLock.acquire();
try {
if (tempEnable && !enableInternal()) {
Log.w(TAG, "Could not enable NFC to wipe NFC-EE");
return;
}
try {
// NFC enabled
int handle = 0;
try {
Log.i(TAG, "Executing SE wipe");
handle = doOpenSecureElementConnection();
if (handle == 0) {
Log.w(TAG, "Could not open the secure element");
return;
}
// TODO: remove this hack
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
mDeviceHost.setTimeout(TagTechnology.ISO_DEP, 10000);
try {
for (byte[] cmd : apdus) {
byte[] resp = doTransceiveNoLock(handle, cmd);
if (resp == null) {
Log.w(TAG, "Transceive failed, could not wipe NFC-EE");
break;
}
}
} finally {
mDeviceHost.resetTimeouts();
}
} finally {
if (handle != 0) {
doDisconnect(handle);
}
}
} finally {
if (tempEnable) {
disableInternal();
}
}
} finally {
mEeWakeLock.release();
}
Log.i(TAG, "SE wipe done");
}
void updateState(int newState) {
synchronized (NfcService.this) {
if (newState == mState) {
return;
}
mState = newState;
Intent intent = new Intent(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
intent.putExtra(NfcAdapter.EXTRA_ADAPTER_STATE, mState);
mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
}
}
}
void saveNfcOnSetting(boolean on) {
synchronized (NfcService.this) {
mPrefsEditor.putBoolean(PREF_NFC_ON, on);
mPrefsEditor.apply();
}
}
public void playSound(int sound) {
synchronized (this) {
if (mSoundPool == null) {
Log.w(TAG, "Not playing sound when NFC is disabled");
return;
}
switch (sound) {
case SOUND_START:
mSoundPool.play(mStartSound, 1.0f, 1.0f, 0, 0, 1.0f);
break;
case SOUND_END:
mSoundPool.play(mEndSound, 1.0f, 1.0f, 0, 0, 1.0f);
break;
case SOUND_ERROR:
mSoundPool.play(mErrorSound, 1.0f, 1.0f, 0, 0, 1.0f);
break;
}
}
}
final class NfcAdapterService extends INfcAdapter.Stub {
@Override
public boolean enable() throws RemoteException {
NfcService.enforceAdminPerm(mContext);
saveNfcOnSetting(true);
if (mIsAirplaneSensitive && isAirplaneModeOn()) {
if (!mIsAirplaneToggleable) {
Log.i(TAG, "denying enable() request (airplane mode)");
return false;
}
// Make sure the override survives a reboot
mPrefsEditor.putBoolean(PREF_AIRPLANE_OVERRIDE, true);
mPrefsEditor.apply();
}
new EnableDisableTask().execute(TASK_ENABLE);
return true;
}
@Override
public boolean disable(boolean saveState) throws RemoteException {
NfcService.enforceAdminPerm(mContext);
if (saveState) {
saveNfcOnSetting(false);
}
new EnableDisableTask().execute(TASK_DISABLE);
return true;
}
@Override
public boolean isNdefPushEnabled() throws RemoteException {
synchronized (NfcService.this) {
return mState == NfcAdapter.STATE_ON && mIsNdefPushEnabled;
}
}
@Override
public boolean enableNdefPush() throws RemoteException {
NfcService.enforceAdminPerm(mContext);
synchronized(NfcService.this) {
if (mIsNdefPushEnabled) {
return true;
}
Log.i(TAG, "enabling NDEF Push");
mPrefsEditor.putBoolean(PREF_NDEF_PUSH_ON, true);
mPrefsEditor.apply();
mIsNdefPushEnabled = true;
if (isNfcEnabled()) {
mP2pLinkManager.enableDisable(true, true);
}
}
return true;
}
@Override
public boolean disableNdefPush() throws RemoteException {
NfcService.enforceAdminPerm(mContext);
synchronized(NfcService.this) {
if (!mIsNdefPushEnabled) {
return true;
}
Log.i(TAG, "disabling NDEF Push");
mPrefsEditor.putBoolean(PREF_NDEF_PUSH_ON, false);
mPrefsEditor.apply();
mIsNdefPushEnabled = false;
if (isNfcEnabled()) {
mP2pLinkManager.enableDisable(false, true);
}
}
return true;
}
@Override
public void setForegroundDispatch(PendingIntent intent,
IntentFilter[] filters, TechListParcel techListsParcel) {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Short-cut the disable path
if (intent == null && filters == null && techListsParcel == null) {
mNfcDispatcher.setForegroundDispatch(null, null, null);
return;
}
// Validate the IntentFilters
if (filters != null) {
if (filters.length == 0) {
filters = null;
} else {
for (IntentFilter filter : filters) {
if (filter == null) {
throw new IllegalArgumentException("null IntentFilter");
}
}
}
}
// Validate the tech lists
String[][] techLists = null;
if (techListsParcel != null) {
techLists = techListsParcel.getTechLists();
}
mNfcDispatcher.setForegroundDispatch(intent, filters, techLists);
}
@Override
public void setNdefPushCallback(INdefPushCallback callback) {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
mP2pLinkManager.setNdefCallback(callback, Binder.getCallingUid());
}
@Override
public INfcTag getNfcTagInterface() throws RemoteException {
return mNfcTagService;
}
@Override
public INfcAdapterExtras getNfcAdapterExtrasInterface(String pkg) {
NfcService.this.enforceNfceeAdminPerm(pkg);
return mExtrasService;
}
@Override
public int getState() throws RemoteException {
synchronized (NfcService.this) {
return mState;
}
}
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
NfcService.this.dump(fd, pw, args);
}
@Override
public void dispatch(Tag tag) throws RemoteException {
enforceAdminPerm(mContext);
mNfcDispatcher.dispatchTag(tag);
}
@Override
public void setP2pModes(int initiatorModes, int targetModes) throws RemoteException {
enforceAdminPerm(mContext);
mDeviceHost.setP2pInitiatorModes(initiatorModes);
mDeviceHost.setP2pTargetModes(targetModes);
mDeviceHost.disableDiscovery();
mDeviceHost.enableDiscovery();
}
}
final class TagService extends INfcTag.Stub {
@Override
public int close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
TagEndpoint tag = null;
if (!isNfcEnabled()) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (TagEndpoint) findObject(nativeHandle);
if (tag != null) {
/* Remove the device from the hmap */
unregisterObject(nativeHandle);
tag.disconnect();
return ErrorCodes.SUCCESS;
}
/* Restart polling loop for notification */
applyRouting(true);
return ErrorCodes.ERROR_DISCONNECT;
}
@Override
public int connect(int nativeHandle, int technology) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
TagEndpoint tag = null;
if (!isNfcEnabled()) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (TagEndpoint) findObject(nativeHandle);
if (tag == null) {
return ErrorCodes.ERROR_DISCONNECT;
}
if (!tag.isPresent()) {
return ErrorCodes.ERROR_DISCONNECT;
}
// Note that on most tags, all technologies are behind a single
// handle. This means that the connect at the lower levels
// will do nothing, as the tag is already connected to that handle.
if (tag.connect(technology)) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_DISCONNECT;
}
}
@Override
public int reconnect(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
TagEndpoint tag = null;
// Check if NFC is enabled
if (!isNfcEnabled()) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (TagEndpoint) findObject(nativeHandle);
if (tag != null) {
if (tag.reconnect()) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_DISCONNECT;
}
}
return ErrorCodes.ERROR_DISCONNECT;
}
@Override
public int[] getTechList(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!isNfcEnabled()) {
return null;
}
/* find the tag in the hmap */
TagEndpoint tag = (TagEndpoint) findObject(nativeHandle);
if (tag != null) {
return tag.getTechList();
}
return null;
}
@Override
public boolean isPresent(int nativeHandle) throws RemoteException {
TagEndpoint tag = null;
// Check if NFC is enabled
if (!isNfcEnabled()) {
return false;
}
/* find the tag in the hmap */
tag = (TagEndpoint) findObject(nativeHandle);
if (tag == null) {
return false;
}
return tag.isPresent();
}
@Override
public boolean isNdef(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
TagEndpoint tag = null;
// Check if NFC is enabled
if (!isNfcEnabled()) {
return false;
}
/* find the tag in the hmap */
tag = (TagEndpoint) findObject(nativeHandle);
int[] ndefInfo = new int[2];
if (tag == null) {
return false;
}
return tag.checkNdef(ndefInfo);
}
@Override
public TransceiveResult transceive(int nativeHandle, byte[] data, boolean raw)
throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
TagEndpoint tag = null;
byte[] response;
// Check if NFC is enabled
if (!isNfcEnabled()) {
return null;
}
/* find the tag in the hmap */
tag = (TagEndpoint) findObject(nativeHandle);
if (tag != null) {
// Check if length is within limits
if (data.length > getMaxTransceiveLength(tag.getConnectedTechnology())) {
return new TransceiveResult(TransceiveResult.RESULT_EXCEEDED_LENGTH, null);
}
int[] targetLost = new int[1];
response = tag.transceive(data, raw, targetLost);
int result;
if (response != null) {
result = TransceiveResult.RESULT_SUCCESS;
} else if (targetLost[0] == 1) {
result = TransceiveResult.RESULT_TAGLOST;
} else {
result = TransceiveResult.RESULT_FAILURE;
}
return new TransceiveResult(result, response);
}
return null;
}
@Override
public NdefMessage ndefRead(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
TagEndpoint tag;
// Check if NFC is enabled
if (!isNfcEnabled()) {
return null;
}
/* find the tag in the hmap */
tag = (TagEndpoint) findObject(nativeHandle);
if (tag != null) {
byte[] buf = tag.readNdef();
if (buf == null) {
return null;
}
/* Create an NdefMessage */
try {
return new NdefMessage(buf);
} catch (FormatException e) {
return null;
}
}
return null;
}
@Override
public int ndefWrite(int nativeHandle, NdefMessage msg) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
TagEndpoint tag;
// Check if NFC is enabled
if (!isNfcEnabled()) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (TagEndpoint) findObject(nativeHandle);
if (tag == null) {
return ErrorCodes.ERROR_IO;
}
if (msg == null) return ErrorCodes.ERROR_INVALID_PARAM;
if (tag.writeNdef(msg.toByteArray())) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public boolean ndefIsWritable(int nativeHandle) throws RemoteException {
throw new UnsupportedOperationException();
}
@Override
public int ndefMakeReadOnly(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
TagEndpoint tag;
// Check if NFC is enabled
if (!isNfcEnabled()) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (TagEndpoint) findObject(nativeHandle);
if (tag == null) {
return ErrorCodes.ERROR_IO;
}
if (tag.makeReadOnly()) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public int formatNdef(int nativeHandle, byte[] key) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
TagEndpoint tag;
// Check if NFC is enabled
if (!isNfcEnabled()) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (TagEndpoint) findObject(nativeHandle);
if (tag == null) {
return ErrorCodes.ERROR_IO;
}
if (tag.formatNdef(key)) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public Tag rediscover(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
TagEndpoint tag = null;
// Check if NFC is enabled
if (!isNfcEnabled()) {
return null;
}
/* find the tag in the hmap */
tag = (TagEndpoint) findObject(nativeHandle);
if (tag != null) {
// For now the prime usecase for rediscover() is to be able
// to access the NDEF technology after formatting without
// having to remove the tag from the field, or similar
// to have access to NdefFormatable in case low-level commands
// were used to remove NDEF. So instead of doing a full stack
// rediscover (which is poorly supported at the moment anyway),
// we simply remove these two technologies and detect them
// again.
tag.removeTechnology(TagTechnology.NDEF);
tag.removeTechnology(TagTechnology.NDEF_FORMATABLE);
tag.findAndReadNdef();
// Build a new Tag object to return
Tag newTag = new Tag(tag.getUid(), tag.getTechList(),
tag.getTechExtras(), tag.getHandle(), this);
return newTag;
}
return null;
}
@Override
public int setTimeout(int tech, int timeout) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
boolean success = mDeviceHost.setTimeout(tech, timeout);
if (success) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_INVALID_PARAM;
}
}
@Override
public int getTimeout(int tech) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mDeviceHost.getTimeout(tech);
}
@Override
public void resetTimeouts() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
mDeviceHost.resetTimeouts();
}
@Override
public boolean canMakeReadOnly(int ndefType) throws RemoteException {
return mDeviceHost.canMakeReadOnly(ndefType);
}
@Override
public int getMaxTransceiveLength(int tech) throws RemoteException {
return mDeviceHost.getMaxTransceiveLength(tech);
}
@Override
public boolean getExtendedLengthApdusSupported() throws RemoteException {
return mDeviceHost.getExtendedLengthApdusSupported();
}
}
void _nfcEeClose(int callingPid, IBinder binder) throws IOException {
// Blocks until a pending open() or transceive() times out.
//TODO: This is incorrect behavior - the close should interrupt pending
// operations. However this is not supported by current hardware.
synchronized (NfcService.this) {
if (!isNfcEnabledOrShuttingDown()) {
throw new IOException("NFC adapter is disabled");
}
if (mOpenEe == null) {
throw new IOException("NFC EE closed");
}
if (callingPid != -1 && callingPid != mOpenEe.pid) {
throw new SecurityException("Wrong PID");
}
if (mOpenEe.binder != binder) {
throw new SecurityException("Wrong binder handle");
}
binder.unlinkToDeath(mOpenEe, 0);
mDeviceHost.resetTimeouts();
doDisconnect(mOpenEe.handle);
mOpenEe = null;
applyRouting(true);
}
}
final class NfcAdapterExtrasService extends INfcAdapterExtras.Stub {
private Bundle writeNoException() {
Bundle p = new Bundle();
p.putInt("e", 0);
return p;
}
private Bundle writeEeException(int exceptionType, String message) {
Bundle p = new Bundle();
p.putInt("e", exceptionType);
p.putString("m", message);
return p;
}
@Override
public Bundle open(String pkg, IBinder b) throws RemoteException {
NfcService.this.enforceNfceeAdminPerm(pkg);
Bundle result;
int handle = _open(b);
if (handle < 0) {
result = writeEeException(handle, "NFCEE open exception.");
} else {
result = writeNoException();
}
return result;
}
/**
* Opens a connection to the secure element.
*
* @return A handle with a value >= 0 in case of success, or a
* negative value in case of failure.
*/
private int _open(IBinder b) {
synchronized(NfcService.this) {
if (!isNfcEnabled()) {
return EE_ERROR_NFC_DISABLED;
}
if (mOpenEe != null) {
return EE_ERROR_ALREADY_OPEN;
}
int handle = doOpenSecureElementConnection();
if (handle < 0) {
return handle;
}
mDeviceHost.setTimeout(TagTechnology.ISO_DEP, 30000);
mOpenEe = new OpenSecureElement(getCallingPid(), handle, b);
try {
b.linkToDeath(mOpenEe, 0);
} catch (RemoteException e) {
mOpenEe.binderDied();
}
// Add the calling package to the list of packages that have accessed
// the secure element.
for (String packageName : mContext.getPackageManager().getPackagesForUid(getCallingUid())) {
mSePackages.add(packageName);
}
return handle;
}
}
@Override
public Bundle close(String pkg, IBinder binder) throws RemoteException {
NfcService.this.enforceNfceeAdminPerm(pkg);
Bundle result;
try {
_nfcEeClose(getCallingPid(), binder);
result = writeNoException();
} catch (IOException e) {
result = writeEeException(EE_ERROR_IO, e.getMessage());
}
return result;
}
@Override
public Bundle transceive(String pkg, byte[] in) throws RemoteException {
NfcService.this.enforceNfceeAdminPerm(pkg);
Bundle result;
byte[] out;
try {
out = _transceive(in);
result = writeNoException();
result.putByteArray("out", out);
} catch (IOException e) {
result = writeEeException(EE_ERROR_IO, e.getMessage());
}
return result;
}
private byte[] _transceive(byte[] data) throws IOException {
synchronized(NfcService.this) {
if (!isNfcEnabled()) {
throw new IOException("NFC is not enabled");
}
if (mOpenEe == null) {
throw new IOException("NFC EE is not open");
}
if (getCallingPid() != mOpenEe.pid) {
throw new SecurityException("Wrong PID");
}
}
return doTransceive(mOpenEe.handle, data);
}
@Override
public int getCardEmulationRoute(String pkg) throws RemoteException {
NfcService.this.enforceNfceeAdminPerm(pkg);
return mEeRoutingState;
}
@Override
public void setCardEmulationRoute(String pkg, int route) throws RemoteException {
NfcService.this.enforceNfceeAdminPerm(pkg);
mEeRoutingState = route;
ApplyRoutingTask applyRoutingTask = new ApplyRoutingTask();
applyRoutingTask.execute();
try {
// Block until route is set
applyRoutingTask.get();
} catch (ExecutionException e) {
Log.e(TAG, "failed to set card emulation mode");
} catch (InterruptedException e) {
Log.e(TAG, "failed to set card emulation mode");
}
}
@Override
public void authenticate(String pkg, byte[] token) throws RemoteException {
NfcService.this.enforceNfceeAdminPerm(pkg);
}
@Override
public String getDriverName(String pkg) throws RemoteException {
NfcService.this.enforceNfceeAdminPerm(pkg);
return mDeviceHost.getName();
}
}
/** resources kept while secure element is open */
private class OpenSecureElement implements IBinder.DeathRecipient {
public int pid; // pid that opened SE
// binder handle used for DeathReceipient. Must keep
// a reference to this, otherwise it can get GC'd and
// the binder stub code might create a different BinderProxy
// for the same remote IBinder, causing mismatched
// link()/unlink()
public IBinder binder;
public int handle; // low-level handle
public OpenSecureElement(int pid, int handle, IBinder binder) {
this.pid = pid;
this.handle = handle;
this.binder = binder;
}
@Override
public void binderDied() {
synchronized (NfcService.this) {
Log.i(TAG, "Tracked app " + pid + " died");
pid = -1;
try {
_nfcEeClose(-1, binder);
} catch (IOException e) { /* already closed */ }
}
}
@Override
public String toString() {
return new StringBuilder('@').append(Integer.toHexString(hashCode())).append("[pid=")
.append(pid).append(" handle=").append(handle).append("]").toString();
}
}
boolean isNfcEnabledOrShuttingDown() {
synchronized (this) {
return (mState == NfcAdapter.STATE_ON || mState == NfcAdapter.STATE_TURNING_OFF);
}
}
boolean isNfcEnabled() {
synchronized (this) {
return mState == NfcAdapter.STATE_ON;
}
}
class WatchDogThread extends Thread {
final Object mCancelWaiter = new Object();
final int mTimeout;
boolean mCanceled = false;
public WatchDogThread(String threadName, int timeout) {
super(threadName);
mTimeout = timeout;
}
@Override
public void run() {
try {
synchronized (mCancelWaiter) {
mCancelWaiter.wait(mTimeout);
if (mCanceled) {
return;
}
}
} catch (InterruptedException e) {
// Should not happen; fall-through to abort.
Log.w(TAG, "Watchdog thread interruped.");
interrupt();
}
Log.e(TAG, "Watchdog triggered, aborting.");
mDeviceHost.doAbort();
}
public synchronized void cancel() {
synchronized (mCancelWaiter) {
mCanceled = true;
mCancelWaiter.notify();
}
}
}
/**
* Read mScreenState and apply NFC-C polling and NFC-EE routing
*/
void applyRouting(boolean force) {
synchronized (this) {
if (!isNfcEnabledOrShuttingDown() || mOpenEe != null) {
// PN544 cannot be reconfigured while EE is open
return;
}
WatchDogThread watchDog = new WatchDogThread("applyRouting", ROUTING_WATCHDOG_MS);
if (mInProvisionMode) {
mInProvisionMode = Settings.Secure.getInt(mContentResolver,
Settings.Global.DEVICE_PROVISIONED, 0) == 0;
if (!mInProvisionMode) {
// Notify dispatcher it's fine to dispatch to any package now
// and allow handover transfers.
mNfcDispatcher.disableProvisioningMode();
mHandoverManager.setEnabled(true);
}
}
try {
watchDog.start();
if (mDeviceHost.enablePN544Quirks() && mScreenState == SCREEN_STATE_OFF) {
/* TODO undo this after the LLCP stack is fixed.
* Use a different sequence when turning the screen off to
* workaround race conditions in pn544 libnfc. The race occurs
* when we change routing while there is a P2P target connect.
* The async LLCP callback will crash since the routing code
* is overwriting globals it relies on.
*/
if (POLLING_MODE > SCREEN_STATE_OFF) {
if (force || mNfcPollingEnabled) {
Log.d(TAG, "NFC-C OFF, disconnect");
mNfcPollingEnabled = false;
mDeviceHost.disableDiscovery();
maybeDisconnectTarget();
}
}
if (mEeRoutingState == ROUTE_ON_WHEN_SCREEN_ON) {
if (force || mNfceeRouteEnabled) {
Log.d(TAG, "NFC-EE OFF");
mNfceeRouteEnabled = false;
mDeviceHost.doDeselectSecureElement();
}
}
return;
}
// configure NFC-EE routing
if (mScreenState >= SCREEN_STATE_ON_LOCKED &&
mEeRoutingState == ROUTE_ON_WHEN_SCREEN_ON) {
if (force || !mNfceeRouteEnabled) {
Log.d(TAG, "NFC-EE ON");
mNfceeRouteEnabled = true;
mDeviceHost.doSelectSecureElement();
}
} else {
if (force || mNfceeRouteEnabled) {
Log.d(TAG, "NFC-EE OFF");
mNfceeRouteEnabled = false;
mDeviceHost.doDeselectSecureElement();
}
}
// configure NFC-C polling
if (mScreenState >= POLLING_MODE) {
if (force || !mNfcPollingEnabled) {
Log.d(TAG, "NFC-C ON");
mNfcPollingEnabled = true;
mDeviceHost.enableDiscovery();
}
} else if (mInProvisionMode && mScreenState >= SCREEN_STATE_ON_LOCKED) {
// Special case for setup provisioning
if (!mNfcPollingEnabled) {
Log.d(TAG, "NFC-C ON");
mNfcPollingEnabled = true;
mDeviceHost.enableDiscovery();
}
} else {
if (force || mNfcPollingEnabled) {
Log.d(TAG, "NFC-C OFF");
mNfcPollingEnabled = false;
mDeviceHost.disableDiscovery();
}
}
} finally {
watchDog.cancel();
}
}
}
/** Disconnect any target if present */
void maybeDisconnectTarget() {
if (!isNfcEnabledOrShuttingDown()) {
return;
}
Object[] objectsToDisconnect;
synchronized (this) {
Object[] objectValues = mObjectMap.values().toArray();
// Copy the array before we clear mObjectMap,
// just in case the HashMap values are backed by the same array
objectsToDisconnect = Arrays.copyOf(objectValues, objectValues.length);
mObjectMap.clear();
}
for (Object o : objectsToDisconnect) {
if (DBG) Log.d(TAG, "disconnecting " + o.getClass().getName());
if (o instanceof TagEndpoint) {
// Disconnect from tags
TagEndpoint tag = (TagEndpoint) o;
tag.disconnect();
} else if (o instanceof NfcDepEndpoint) {
// Disconnect from P2P devices
NfcDepEndpoint device = (NfcDepEndpoint) o;
if (device.getMode() == NfcDepEndpoint.MODE_P2P_TARGET) {
// Remote peer is target, request disconnection
device.disconnect();
} else {
// Remote peer is initiator, we cannot disconnect
// Just wait for field removal
}
}
}
}
Object findObject(int key) {
synchronized (this) {
Object device = mObjectMap.get(key);
if (device == null) {
Log.w(TAG, "Handle not found");
}
return device;
}
}
void registerTagObject(TagEndpoint tag) {
synchronized (this) {
mObjectMap.put(tag.getHandle(), tag);
}
}
void unregisterObject(int handle) {
synchronized (this) {
mObjectMap.remove(handle);
}
}
/** For use by code in this process */
public LlcpSocket createLlcpSocket(int sap, int miu, int rw, int linearBufferLength)
throws LlcpException {
return mDeviceHost.createLlcpSocket(sap, miu, rw, linearBufferLength);
}
/** For use by code in this process */
public LlcpConnectionlessSocket createLlcpConnectionLessSocket(int sap, String sn)
throws LlcpException {
return mDeviceHost.createLlcpConnectionlessSocket(sap, sn);
}
/** For use by code in this process */
public LlcpServerSocket createLlcpServerSocket(int sap, String sn, int miu, int rw,
int linearBufferLength) throws LlcpException {
return mDeviceHost.createLlcpServerSocket(sap, sn, miu, rw, linearBufferLength);
}
public void sendMockNdefTag(NdefMessage msg) {
sendMessage(MSG_MOCK_NDEF, msg);
}
void sendMessage(int what, Object obj) {
Message msg = mHandler.obtainMessage();
msg.what = what;
msg.obj = obj;
mHandler.sendMessage(msg);
}
final class NfcServiceHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF: {
NdefMessage ndefMsg = (NdefMessage) msg.obj;
Bundle extras = new Bundle();
extras.putParcelable(Ndef.EXTRA_NDEF_MSG, ndefMsg);
extras.putInt(Ndef.EXTRA_NDEF_MAXLENGTH, 0);
extras.putInt(Ndef.EXTRA_NDEF_CARDSTATE, Ndef.NDEF_MODE_READ_ONLY);
extras.putInt(Ndef.EXTRA_NDEF_TYPE, Ndef.TYPE_OTHER);
Tag tag = Tag.createMockTag(new byte[] { 0x00 },
new int[] { TagTechnology.NDEF },
new Bundle[] { extras });
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
boolean delivered = mNfcDispatcher.dispatchTag(tag);
if (delivered) {
playSound(SOUND_END);
} else {
playSound(SOUND_ERROR);
}
break;
}
case MSG_NDEF_TAG:
if (DBG) Log.d(TAG, "Tag detected, notifying applications");
TagEndpoint tag = (TagEndpoint) msg.obj;
playSound(SOUND_START);
+ if (tag.getConnectedTechnology() == TagTechnology.NFC_BARCODE) {
+ // When these tags start containing NDEF, they will require
+ // the stack to deal with them in a different way, since
+ // they are activated only really shortly.
+ // For now, don't consider NDEF on these.
+ if (DBG) Log.d(TAG, "Skipping NDEF detection for NFC Barcode");
+ tag.startPresenceChecking();
+ dispatchTagEndpoint(tag);
+ break;
+ }
NdefMessage ndefMsg = tag.findAndReadNdef();
if (ndefMsg != null) {
tag.startPresenceChecking();
dispatchTagEndpoint(tag);
} else {
if (tag.reconnect()) {
tag.startPresenceChecking();
dispatchTagEndpoint(tag);
} else {
tag.disconnect();
playSound(SOUND_ERROR);
}
}
break;
case MSG_CARD_EMULATION:
if (DBG) Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast */
Intent aidIntent = new Intent();
aidIntent.setAction(ACTION_AID_SELECTED);
aidIntent.putExtra(EXTRA_AID, aid);
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_AID_SELECTED);
sendSeBroadcast(aidIntent);
break;
case MSG_SE_EMV_CARD_REMOVAL:
if (DBG) Log.d(TAG, "Card Removal message");
/* Send broadcast */
Intent cardRemovalIntent = new Intent();
cardRemovalIntent.setAction(ACTION_EMV_CARD_REMOVAL);
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_EMV_CARD_REMOVAL);
sendSeBroadcast(cardRemovalIntent);
break;
case MSG_SE_APDU_RECEIVED:
if (DBG) Log.d(TAG, "APDU Received message");
byte[] apduBytes = (byte[]) msg.obj;
/* Send broadcast */
Intent apduReceivedIntent = new Intent();
apduReceivedIntent.setAction(ACTION_APDU_RECEIVED);
if (apduBytes != null && apduBytes.length > 0) {
apduReceivedIntent.putExtra(EXTRA_APDU_BYTES, apduBytes);
}
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_APDU_RECEIVED);
sendSeBroadcast(apduReceivedIntent);
break;
case MSG_SE_MIFARE_ACCESS:
if (DBG) Log.d(TAG, "MIFARE access message");
/* Send broadcast */
byte[] mifareCmd = (byte[]) msg.obj;
Intent mifareAccessIntent = new Intent();
mifareAccessIntent.setAction(ACTION_MIFARE_ACCESS_DETECTED);
if (mifareCmd != null && mifareCmd.length > 1) {
int mifareBlock = mifareCmd[1] & 0xff;
if (DBG) Log.d(TAG, "Mifare Block=" + mifareBlock);
mifareAccessIntent.putExtra(EXTRA_MIFARE_BLOCK, mifareBlock);
}
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_MIFARE_ACCESS_DETECTED);
sendSeBroadcast(mifareAccessIntent);
break;
case MSG_LLCP_LINK_ACTIVATION:
llcpActivated((NfcDepEndpoint) msg.obj);
break;
case MSG_LLCP_LINK_DEACTIVATED:
NfcDepEndpoint device = (NfcDepEndpoint) msg.obj;
boolean needsDisconnect = false;
Log.d(TAG, "LLCP Link Deactivated message. Restart polling loop.");
synchronized (NfcService.this) {
/* Check if the device has been already unregistered */
if (mObjectMap.remove(device.getHandle()) != null) {
/* Disconnect if we are initiator */
if (device.getMode() == NfcDepEndpoint.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "disconnecting from target");
needsDisconnect = true;
} else {
if (DBG) Log.d(TAG, "not disconnecting from initiator");
}
}
}
if (needsDisconnect) {
device.disconnect(); // restarts polling loop
}
mP2pLinkManager.onLlcpDeactivated();
break;
case MSG_LLCP_LINK_FIRST_PACKET:
mP2pLinkManager.onLlcpFirstPacketReceived();
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
if (DBG) Log.d(TAG, "Target Deselected");
Intent intent = new Intent();
intent.setAction(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
if (DBG) Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(intent, NFC_PERM);
break;
case MSG_SE_FIELD_ACTIVATED: {
if (DBG) Log.d(TAG, "SE FIELD ACTIVATED");
Intent eventFieldOnIntent = new Intent();
eventFieldOnIntent.setAction(ACTION_RF_FIELD_ON_DETECTED);
sendSeBroadcast(eventFieldOnIntent);
break;
}
case MSG_SE_FIELD_DEACTIVATED: {
if (DBG) Log.d(TAG, "SE FIELD DEACTIVATED");
Intent eventFieldOffIntent = new Intent();
eventFieldOffIntent.setAction(ACTION_RF_FIELD_OFF_DETECTED);
sendSeBroadcast(eventFieldOffIntent);
break;
}
case MSG_SE_LISTEN_ACTIVATED: {
if (DBG) Log.d(TAG, "SE LISTEN MODE ACTIVATED");
Intent listenModeActivated = new Intent();
listenModeActivated.setAction(ACTION_SE_LISTEN_ACTIVATED);
sendSeBroadcast(listenModeActivated);
break;
}
case MSG_SE_LISTEN_DEACTIVATED: {
if (DBG) Log.d(TAG, "SE LISTEN MODE DEACTIVATED");
Intent listenModeDeactivated = new Intent();
listenModeDeactivated.setAction(ACTION_SE_LISTEN_DEACTIVATED);
sendSeBroadcast(listenModeDeactivated);
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
private void sendSeBroadcast(Intent intent) {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
// Resume app switches so the receivers can start activites without delay
mNfcDispatcher.resumeAppSwitches();
synchronized(this) {
for (PackageInfo pkg : mInstalledPackages) {
if (pkg != null && pkg.applicationInfo != null) {
if (mNfceeAccessControl.check(pkg.applicationInfo)) {
intent.setPackage(pkg.packageName);
mContext.sendBroadcast(intent);
}
}
}
}
}
private boolean llcpActivated(NfcDepEndpoint device) {
Log.d(TAG, "LLCP Activation message");
if (device.getMode() == NfcDepEndpoint.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_TARGET");
if (device.connect()) {
/* Check LLCP compliancy */
if (mDeviceHost.doCheckLlcp()) {
/* Activate LLCP Link */
if (mDeviceHost.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Initiator Activate LLCP OK");
synchronized (NfcService.this) {
// Register P2P device
mObjectMap.put(device.getHandle(), device);
}
mP2pLinkManager.onLlcpActivated();
return true;
} else {
/* should not happen */
Log.w(TAG, "Initiator LLCP activation failed. Disconnect.");
device.disconnect();
}
} else {
if (DBG) Log.d(TAG, "Remote Target does not support LLCP. Disconnect.");
device.disconnect();
}
} else {
if (DBG) Log.d(TAG, "Cannot connect remote Target. Polling loop restarted.");
/*
* The polling loop should have been restarted in failing
* doConnect
*/
}
} else if (device.getMode() == NfcDepEndpoint.MODE_P2P_INITIATOR) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_INITIATOR");
/* Check LLCP compliancy */
if (mDeviceHost.doCheckLlcp()) {
/* Activate LLCP Link */
if (mDeviceHost.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Target Activate LLCP OK");
synchronized (NfcService.this) {
// Register P2P device
mObjectMap.put(device.getHandle(), device);
}
mP2pLinkManager.onLlcpActivated();
return true;
}
} else {
Log.w(TAG, "checkLlcp failed");
}
}
return false;
}
private void dispatchTagEndpoint(TagEndpoint tagEndpoint) {
Tag tag = new Tag(tagEndpoint.getUid(), tagEndpoint.getTechList(),
tagEndpoint.getTechExtras(), tagEndpoint.getHandle(), mNfcTagService);
registerTagObject(tagEndpoint);
if (!mNfcDispatcher.dispatchTag(tag)) {
unregisterObject(tagEndpoint.getHandle());
playSound(SOUND_ERROR);
} else {
playSound(SOUND_END);
}
}
}
private NfcServiceHandler mHandler = new NfcServiceHandler();
class ApplyRoutingTask extends AsyncTask<Integer, Void, Void> {
@Override
protected Void doInBackground(Integer... params) {
synchronized (NfcService.this) {
if (params == null || params.length != 1) {
// force apply current routing
applyRouting(true);
return null;
}
mScreenState = params[0].intValue();
mRoutingWakeLock.acquire();
try {
applyRouting(false);
} finally {
mRoutingWakeLock.release();
}
return null;
}
}
}
private final BroadcastReceiver mOwnerReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_PACKAGE_REMOVED) ||
action.equals(Intent.ACTION_PACKAGE_ADDED) ||
action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE) ||
action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
updatePackageCache();
if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
// Clear the NFCEE access cache in case a UID gets recycled
mNfceeAccessControl.invalidateCache();
boolean dataRemoved = intent.getBooleanExtra(Intent.EXTRA_DATA_REMOVED, false);
if (dataRemoved) {
Uri data = intent.getData();
if (data == null) return;
String packageName = data.getSchemeSpecificPart();
synchronized (NfcService.this) {
if (mSePackages.contains(packageName)) {
new EnableDisableTask().execute(TASK_EE_WIPE);
mSePackages.remove(packageName);
}
}
}
}
} else if (action.equals(ACTION_MASTER_CLEAR_NOTIFICATION)) {
EnableDisableTask eeWipeTask = new EnableDisableTask();
eeWipeTask.execute(TASK_EE_WIPE);
try {
eeWipeTask.get(); // blocks until EE wipe is complete
} catch (ExecutionException e) {
Log.w(TAG, "failed to wipe NFC-EE");
} catch (InterruptedException e) {
Log.w(TAG, "failed to wipe NFC-EE");
}
}
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(
NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION)) {
// Perform applyRouting() in AsyncTask to serialize blocking calls
new ApplyRoutingTask().execute();
} else if (action.equals(Intent.ACTION_SCREEN_ON)
|| action.equals(Intent.ACTION_SCREEN_OFF)
|| action.equals(Intent.ACTION_USER_PRESENT)) {
// Perform applyRouting() in AsyncTask to serialize blocking calls
int screenState = SCREEN_STATE_OFF;
if (action.equals(Intent.ACTION_SCREEN_OFF)) {
screenState = SCREEN_STATE_OFF;
} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
screenState = mKeyguard.isKeyguardLocked() ?
SCREEN_STATE_ON_LOCKED : SCREEN_STATE_ON_UNLOCKED;
} else if (action.equals(Intent.ACTION_USER_PRESENT)) {
screenState = SCREEN_STATE_ON_UNLOCKED;
}
new ApplyRoutingTask().execute(Integer.valueOf(screenState));
} else if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
boolean isAirplaneModeOn = intent.getBooleanExtra("state", false);
// Query the airplane mode from Settings.System just to make sure that
// some random app is not sending this intent
if (isAirplaneModeOn != isAirplaneModeOn()) {
return;
}
if (!mIsAirplaneSensitive) {
return;
}
mPrefsEditor.putBoolean(PREF_AIRPLANE_OVERRIDE, false);
mPrefsEditor.apply();
if (isAirplaneModeOn) {
new EnableDisableTask().execute(TASK_DISABLE);
} else if (!isAirplaneModeOn && mPrefs.getBoolean(PREF_NFC_ON, NFC_ON_DEFAULT)) {
new EnableDisableTask().execute(TASK_ENABLE);
}
} else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
mP2pLinkManager.onUserSwitched();
}
}
};
/** Returns true if airplane mode is currently on */
boolean isAirplaneModeOn() {
return Settings.System.getInt(mContentResolver,
Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
}
/** for debugging only - no i18n */
static String stateToString(int state) {
switch (state) {
case NfcAdapter.STATE_OFF:
return "off";
case NfcAdapter.STATE_TURNING_ON:
return "turning on";
case NfcAdapter.STATE_ON:
return "on";
case NfcAdapter.STATE_TURNING_OFF:
return "turning off";
default:
return "<error>";
}
}
/** For debugging only - no i18n */
static String screenStateToString(int screenState) {
switch (screenState) {
case SCREEN_STATE_OFF:
return "OFF";
case SCREEN_STATE_ON_LOCKED:
return "ON_LOCKED";
case SCREEN_STATE_ON_UNLOCKED:
return "ON_UNLOCKED";
default:
return "UNKNOWN";
}
}
void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
!= PackageManager.PERMISSION_GRANTED) {
pw.println("Permission Denial: can't dump nfc from from pid="
+ Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
+ " without permission " + android.Manifest.permission.DUMP);
return;
}
synchronized (this) {
pw.println("mState=" + stateToString(mState));
pw.println("mIsZeroClickRequested=" + mIsNdefPushEnabled);
pw.println("mScreenState=" + screenStateToString(mScreenState));
pw.println("mNfcPollingEnabled=" + mNfcPollingEnabled);
pw.println("mNfceeRouteEnabled=" + mNfceeRouteEnabled);
pw.println("mIsAirplaneSensitive=" + mIsAirplaneSensitive);
pw.println("mIsAirplaneToggleable=" + mIsAirplaneToggleable);
pw.println("mOpenEe=" + mOpenEe);
mP2pLinkManager.dump(fd, pw, args);
mNfceeAccessControl.dump(fd, pw, args);
mNfcDispatcher.dump(fd, pw, args);
pw.println(mDeviceHost.dump());
}
}
}
| true | true | public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF: {
NdefMessage ndefMsg = (NdefMessage) msg.obj;
Bundle extras = new Bundle();
extras.putParcelable(Ndef.EXTRA_NDEF_MSG, ndefMsg);
extras.putInt(Ndef.EXTRA_NDEF_MAXLENGTH, 0);
extras.putInt(Ndef.EXTRA_NDEF_CARDSTATE, Ndef.NDEF_MODE_READ_ONLY);
extras.putInt(Ndef.EXTRA_NDEF_TYPE, Ndef.TYPE_OTHER);
Tag tag = Tag.createMockTag(new byte[] { 0x00 },
new int[] { TagTechnology.NDEF },
new Bundle[] { extras });
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
boolean delivered = mNfcDispatcher.dispatchTag(tag);
if (delivered) {
playSound(SOUND_END);
} else {
playSound(SOUND_ERROR);
}
break;
}
case MSG_NDEF_TAG:
if (DBG) Log.d(TAG, "Tag detected, notifying applications");
TagEndpoint tag = (TagEndpoint) msg.obj;
playSound(SOUND_START);
NdefMessage ndefMsg = tag.findAndReadNdef();
if (ndefMsg != null) {
tag.startPresenceChecking();
dispatchTagEndpoint(tag);
} else {
if (tag.reconnect()) {
tag.startPresenceChecking();
dispatchTagEndpoint(tag);
} else {
tag.disconnect();
playSound(SOUND_ERROR);
}
}
break;
case MSG_CARD_EMULATION:
if (DBG) Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast */
Intent aidIntent = new Intent();
aidIntent.setAction(ACTION_AID_SELECTED);
aidIntent.putExtra(EXTRA_AID, aid);
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_AID_SELECTED);
sendSeBroadcast(aidIntent);
break;
case MSG_SE_EMV_CARD_REMOVAL:
if (DBG) Log.d(TAG, "Card Removal message");
/* Send broadcast */
Intent cardRemovalIntent = new Intent();
cardRemovalIntent.setAction(ACTION_EMV_CARD_REMOVAL);
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_EMV_CARD_REMOVAL);
sendSeBroadcast(cardRemovalIntent);
break;
case MSG_SE_APDU_RECEIVED:
if (DBG) Log.d(TAG, "APDU Received message");
byte[] apduBytes = (byte[]) msg.obj;
/* Send broadcast */
Intent apduReceivedIntent = new Intent();
apduReceivedIntent.setAction(ACTION_APDU_RECEIVED);
if (apduBytes != null && apduBytes.length > 0) {
apduReceivedIntent.putExtra(EXTRA_APDU_BYTES, apduBytes);
}
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_APDU_RECEIVED);
sendSeBroadcast(apduReceivedIntent);
break;
case MSG_SE_MIFARE_ACCESS:
if (DBG) Log.d(TAG, "MIFARE access message");
/* Send broadcast */
byte[] mifareCmd = (byte[]) msg.obj;
Intent mifareAccessIntent = new Intent();
mifareAccessIntent.setAction(ACTION_MIFARE_ACCESS_DETECTED);
if (mifareCmd != null && mifareCmd.length > 1) {
int mifareBlock = mifareCmd[1] & 0xff;
if (DBG) Log.d(TAG, "Mifare Block=" + mifareBlock);
mifareAccessIntent.putExtra(EXTRA_MIFARE_BLOCK, mifareBlock);
}
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_MIFARE_ACCESS_DETECTED);
sendSeBroadcast(mifareAccessIntent);
break;
case MSG_LLCP_LINK_ACTIVATION:
llcpActivated((NfcDepEndpoint) msg.obj);
break;
case MSG_LLCP_LINK_DEACTIVATED:
NfcDepEndpoint device = (NfcDepEndpoint) msg.obj;
boolean needsDisconnect = false;
Log.d(TAG, "LLCP Link Deactivated message. Restart polling loop.");
synchronized (NfcService.this) {
/* Check if the device has been already unregistered */
if (mObjectMap.remove(device.getHandle()) != null) {
/* Disconnect if we are initiator */
if (device.getMode() == NfcDepEndpoint.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "disconnecting from target");
needsDisconnect = true;
} else {
if (DBG) Log.d(TAG, "not disconnecting from initiator");
}
}
}
if (needsDisconnect) {
device.disconnect(); // restarts polling loop
}
mP2pLinkManager.onLlcpDeactivated();
break;
case MSG_LLCP_LINK_FIRST_PACKET:
mP2pLinkManager.onLlcpFirstPacketReceived();
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
if (DBG) Log.d(TAG, "Target Deselected");
Intent intent = new Intent();
intent.setAction(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
if (DBG) Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(intent, NFC_PERM);
break;
case MSG_SE_FIELD_ACTIVATED: {
if (DBG) Log.d(TAG, "SE FIELD ACTIVATED");
Intent eventFieldOnIntent = new Intent();
eventFieldOnIntent.setAction(ACTION_RF_FIELD_ON_DETECTED);
sendSeBroadcast(eventFieldOnIntent);
break;
}
case MSG_SE_FIELD_DEACTIVATED: {
if (DBG) Log.d(TAG, "SE FIELD DEACTIVATED");
Intent eventFieldOffIntent = new Intent();
eventFieldOffIntent.setAction(ACTION_RF_FIELD_OFF_DETECTED);
sendSeBroadcast(eventFieldOffIntent);
break;
}
case MSG_SE_LISTEN_ACTIVATED: {
if (DBG) Log.d(TAG, "SE LISTEN MODE ACTIVATED");
Intent listenModeActivated = new Intent();
listenModeActivated.setAction(ACTION_SE_LISTEN_ACTIVATED);
sendSeBroadcast(listenModeActivated);
break;
}
case MSG_SE_LISTEN_DEACTIVATED: {
if (DBG) Log.d(TAG, "SE LISTEN MODE DEACTIVATED");
Intent listenModeDeactivated = new Intent();
listenModeDeactivated.setAction(ACTION_SE_LISTEN_DEACTIVATED);
sendSeBroadcast(listenModeDeactivated);
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
| public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF: {
NdefMessage ndefMsg = (NdefMessage) msg.obj;
Bundle extras = new Bundle();
extras.putParcelable(Ndef.EXTRA_NDEF_MSG, ndefMsg);
extras.putInt(Ndef.EXTRA_NDEF_MAXLENGTH, 0);
extras.putInt(Ndef.EXTRA_NDEF_CARDSTATE, Ndef.NDEF_MODE_READ_ONLY);
extras.putInt(Ndef.EXTRA_NDEF_TYPE, Ndef.TYPE_OTHER);
Tag tag = Tag.createMockTag(new byte[] { 0x00 },
new int[] { TagTechnology.NDEF },
new Bundle[] { extras });
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
boolean delivered = mNfcDispatcher.dispatchTag(tag);
if (delivered) {
playSound(SOUND_END);
} else {
playSound(SOUND_ERROR);
}
break;
}
case MSG_NDEF_TAG:
if (DBG) Log.d(TAG, "Tag detected, notifying applications");
TagEndpoint tag = (TagEndpoint) msg.obj;
playSound(SOUND_START);
if (tag.getConnectedTechnology() == TagTechnology.NFC_BARCODE) {
// When these tags start containing NDEF, they will require
// the stack to deal with them in a different way, since
// they are activated only really shortly.
// For now, don't consider NDEF on these.
if (DBG) Log.d(TAG, "Skipping NDEF detection for NFC Barcode");
tag.startPresenceChecking();
dispatchTagEndpoint(tag);
break;
}
NdefMessage ndefMsg = tag.findAndReadNdef();
if (ndefMsg != null) {
tag.startPresenceChecking();
dispatchTagEndpoint(tag);
} else {
if (tag.reconnect()) {
tag.startPresenceChecking();
dispatchTagEndpoint(tag);
} else {
tag.disconnect();
playSound(SOUND_ERROR);
}
}
break;
case MSG_CARD_EMULATION:
if (DBG) Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast */
Intent aidIntent = new Intent();
aidIntent.setAction(ACTION_AID_SELECTED);
aidIntent.putExtra(EXTRA_AID, aid);
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_AID_SELECTED);
sendSeBroadcast(aidIntent);
break;
case MSG_SE_EMV_CARD_REMOVAL:
if (DBG) Log.d(TAG, "Card Removal message");
/* Send broadcast */
Intent cardRemovalIntent = new Intent();
cardRemovalIntent.setAction(ACTION_EMV_CARD_REMOVAL);
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_EMV_CARD_REMOVAL);
sendSeBroadcast(cardRemovalIntent);
break;
case MSG_SE_APDU_RECEIVED:
if (DBG) Log.d(TAG, "APDU Received message");
byte[] apduBytes = (byte[]) msg.obj;
/* Send broadcast */
Intent apduReceivedIntent = new Intent();
apduReceivedIntent.setAction(ACTION_APDU_RECEIVED);
if (apduBytes != null && apduBytes.length > 0) {
apduReceivedIntent.putExtra(EXTRA_APDU_BYTES, apduBytes);
}
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_APDU_RECEIVED);
sendSeBroadcast(apduReceivedIntent);
break;
case MSG_SE_MIFARE_ACCESS:
if (DBG) Log.d(TAG, "MIFARE access message");
/* Send broadcast */
byte[] mifareCmd = (byte[]) msg.obj;
Intent mifareAccessIntent = new Intent();
mifareAccessIntent.setAction(ACTION_MIFARE_ACCESS_DETECTED);
if (mifareCmd != null && mifareCmd.length > 1) {
int mifareBlock = mifareCmd[1] & 0xff;
if (DBG) Log.d(TAG, "Mifare Block=" + mifareBlock);
mifareAccessIntent.putExtra(EXTRA_MIFARE_BLOCK, mifareBlock);
}
if (DBG) Log.d(TAG, "Broadcasting " + ACTION_MIFARE_ACCESS_DETECTED);
sendSeBroadcast(mifareAccessIntent);
break;
case MSG_LLCP_LINK_ACTIVATION:
llcpActivated((NfcDepEndpoint) msg.obj);
break;
case MSG_LLCP_LINK_DEACTIVATED:
NfcDepEndpoint device = (NfcDepEndpoint) msg.obj;
boolean needsDisconnect = false;
Log.d(TAG, "LLCP Link Deactivated message. Restart polling loop.");
synchronized (NfcService.this) {
/* Check if the device has been already unregistered */
if (mObjectMap.remove(device.getHandle()) != null) {
/* Disconnect if we are initiator */
if (device.getMode() == NfcDepEndpoint.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "disconnecting from target");
needsDisconnect = true;
} else {
if (DBG) Log.d(TAG, "not disconnecting from initiator");
}
}
}
if (needsDisconnect) {
device.disconnect(); // restarts polling loop
}
mP2pLinkManager.onLlcpDeactivated();
break;
case MSG_LLCP_LINK_FIRST_PACKET:
mP2pLinkManager.onLlcpFirstPacketReceived();
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
if (DBG) Log.d(TAG, "Target Deselected");
Intent intent = new Intent();
intent.setAction(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
if (DBG) Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(intent, NFC_PERM);
break;
case MSG_SE_FIELD_ACTIVATED: {
if (DBG) Log.d(TAG, "SE FIELD ACTIVATED");
Intent eventFieldOnIntent = new Intent();
eventFieldOnIntent.setAction(ACTION_RF_FIELD_ON_DETECTED);
sendSeBroadcast(eventFieldOnIntent);
break;
}
case MSG_SE_FIELD_DEACTIVATED: {
if (DBG) Log.d(TAG, "SE FIELD DEACTIVATED");
Intent eventFieldOffIntent = new Intent();
eventFieldOffIntent.setAction(ACTION_RF_FIELD_OFF_DETECTED);
sendSeBroadcast(eventFieldOffIntent);
break;
}
case MSG_SE_LISTEN_ACTIVATED: {
if (DBG) Log.d(TAG, "SE LISTEN MODE ACTIVATED");
Intent listenModeActivated = new Intent();
listenModeActivated.setAction(ACTION_SE_LISTEN_ACTIVATED);
sendSeBroadcast(listenModeActivated);
break;
}
case MSG_SE_LISTEN_DEACTIVATED: {
if (DBG) Log.d(TAG, "SE LISTEN MODE DEACTIVATED");
Intent listenModeDeactivated = new Intent();
listenModeDeactivated.setAction(ACTION_SE_LISTEN_DEACTIVATED);
sendSeBroadcast(listenModeDeactivated);
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
|
diff --git a/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/indexer/index/LuceneDirectoryFactory.java b/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/indexer/index/LuceneDirectoryFactory.java
index d15fbe1c..78e59e95 100644
--- a/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/indexer/index/LuceneDirectoryFactory.java
+++ b/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/indexer/index/LuceneDirectoryFactory.java
@@ -1,167 +1,171 @@
package com.gentics.cr.lucene.indexer.index;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.log4j.Logger;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockFactory;
import org.apache.lucene.store.RAMDirectory;
import com.gentics.cr.CRConfig;
import com.gentics.cr.util.generics.Instanciator;
/**
* Creates and caches directories.
* @author Christopher
*
*/
public final class LuceneDirectoryFactory {
/**
* Logger.
*/
protected static final Logger LOG = Logger.getLogger(LuceneDirectoryFactory.class);
/**
* Key that determines if a directory should be created in memory.
*/
protected static final String RAM_IDENTIFICATION_KEY = "RAM";
/**
* Key to fetch the configured lock factory class.
*/
protected static final String LOCK_FACTORY_CLASS_KEY = "lockFactoryClass";
/**
* ConcurrentHashMap to cache directories.
*/
private static ConcurrentHashMap<String, Directory> cachedDirectories = new ConcurrentHashMap<String, Directory>();
/**
* Private constructor.
*/
private LuceneDirectoryFactory() {
}
/**
* Fetches a directory for the given location.
* If there is none it creates a directory
* on the given location. Directories will be cached by its location.
* @param directoyLocation String pointing to the location.
* If the string starts with RAM,
* the directory will be created in memory.
* @param config Configuration that may contain a configured lock factory.
* @return directory.
*/
public static Directory getDirectory(final String directoyLocation, final CRConfig config) {
Directory dir = cachedDirectories.get(directoyLocation);
if (dir == null) {
dir = createNewDirectory(directoyLocation, config);
}
return dir;
}
/**
* Fetches a directory for the given location.
* If there is none it creates a directory
* on the given location. Directories will be cached by its location.
* @param directoyLocation String pointing to the location.
* If the string starts with RAM,
* the directory will be created in memory.
* @return directory.
*/
public static Directory getDirectory(final String directoyLocation) {
return getDirectory(directoyLocation, null);
}
/**
* Create a new directory.
* @param directoyLocation directoryLocation.
* @param config configuration that may contain the configured lock factory.
* @return new directory
*/
private static synchronized Directory createNewDirectory(
final String directoyLocation,
final CRConfig config) {
Directory dir = cachedDirectories.get(directoyLocation);
if (dir == null) {
Directory newDir = createDirectory(directoyLocation, config);
dir = cachedDirectories.putIfAbsent(directoyLocation, newDir);
if (dir == null) {
dir = newDir;
}
}
return dir;
}
/**
* Creates a new directory.
* @param directoryLocation location
* @param config configuration that may contain a configured lock factory.
* @return directory
*/
private static Directory createDirectory(final String directoryLocation, final CRConfig config) {
Directory dir;
if (RAM_IDENTIFICATION_KEY.equalsIgnoreCase(directoryLocation)
|| directoryLocation == null
|| directoryLocation.startsWith(RAM_IDENTIFICATION_KEY)) {
dir = createRAMDirectory(directoryLocation);
} else {
File indexLoc = new File(directoryLocation);
try {
dir = createFSDirectory(indexLoc, directoryLocation);
if (dir == null) {
dir = createRAMDirectory(directoryLocation);
}
} catch (IOException ioe) {
dir = createRAMDirectory(directoryLocation);
}
}
if (config != null) {
String lockFactoryClass = config.getString(LOCK_FACTORY_CLASS_KEY);
if (lockFactoryClass != null && !"".equals(lockFactoryClass)) {
LockFactory lockFactory = (LockFactory) Instanciator.getInstance(lockFactoryClass, new Object[][] {
new Object[] {},
new Object[] {config}
});
- try {
- dir.setLockFactory(lockFactory);
- } catch (IOException e) {
- LOG.error("Error while setting lock factory.", e);
+ if (lockFactory != null) {
+ try {
+ dir.setLockFactory(lockFactory);
+ } catch (IOException e) {
+ LOG.error("Error while setting lock factory.", e);
+ }
+ } else {
+ LOG.error("Could not set lock factory because it could not be created. Check debug output.");
}
}
}
return dir;
}
/**
* Creates a FSDirectory on the given location.
* @param indexLoc location.
* @param name name for logging
* @return FSDirectory
* @throws IOException on error.
*/
protected static Directory createFSDirectory(final File indexLoc,
final String name) throws IOException {
if (!indexLoc.exists()) {
LOG.debug("Indexlocation did not exist. Creating directories...");
indexLoc.mkdirs();
}
Directory dir = FSDirectory.open(indexLoc);
LOG.debug("Creating FS Directory for Index [" + name + "]");
return (dir);
}
/**
* Creates a Directory in memory.
* @param name name of the directory
* @return directory.
*/
protected static Directory createRAMDirectory(final String name) {
Directory dir = new RAMDirectory();
LOG.debug("Creating RAM Directory for Index [" + name + "]");
return (dir);
}
}
| true | true | private static Directory createDirectory(final String directoryLocation, final CRConfig config) {
Directory dir;
if (RAM_IDENTIFICATION_KEY.equalsIgnoreCase(directoryLocation)
|| directoryLocation == null
|| directoryLocation.startsWith(RAM_IDENTIFICATION_KEY)) {
dir = createRAMDirectory(directoryLocation);
} else {
File indexLoc = new File(directoryLocation);
try {
dir = createFSDirectory(indexLoc, directoryLocation);
if (dir == null) {
dir = createRAMDirectory(directoryLocation);
}
} catch (IOException ioe) {
dir = createRAMDirectory(directoryLocation);
}
}
if (config != null) {
String lockFactoryClass = config.getString(LOCK_FACTORY_CLASS_KEY);
if (lockFactoryClass != null && !"".equals(lockFactoryClass)) {
LockFactory lockFactory = (LockFactory) Instanciator.getInstance(lockFactoryClass, new Object[][] {
new Object[] {},
new Object[] {config}
});
try {
dir.setLockFactory(lockFactory);
} catch (IOException e) {
LOG.error("Error while setting lock factory.", e);
}
}
}
return dir;
}
| private static Directory createDirectory(final String directoryLocation, final CRConfig config) {
Directory dir;
if (RAM_IDENTIFICATION_KEY.equalsIgnoreCase(directoryLocation)
|| directoryLocation == null
|| directoryLocation.startsWith(RAM_IDENTIFICATION_KEY)) {
dir = createRAMDirectory(directoryLocation);
} else {
File indexLoc = new File(directoryLocation);
try {
dir = createFSDirectory(indexLoc, directoryLocation);
if (dir == null) {
dir = createRAMDirectory(directoryLocation);
}
} catch (IOException ioe) {
dir = createRAMDirectory(directoryLocation);
}
}
if (config != null) {
String lockFactoryClass = config.getString(LOCK_FACTORY_CLASS_KEY);
if (lockFactoryClass != null && !"".equals(lockFactoryClass)) {
LockFactory lockFactory = (LockFactory) Instanciator.getInstance(lockFactoryClass, new Object[][] {
new Object[] {},
new Object[] {config}
});
if (lockFactory != null) {
try {
dir.setLockFactory(lockFactory);
} catch (IOException e) {
LOG.error("Error while setting lock factory.", e);
}
} else {
LOG.error("Could not set lock factory because it could not be created. Check debug output.");
}
}
}
return dir;
}
|
diff --git a/plugins/sonar-squid-java-plugin/src/test/java/org/sonar/java/bytecode/loader/JarLoaderTest.java b/plugins/sonar-squid-java-plugin/src/test/java/org/sonar/java/bytecode/loader/JarLoaderTest.java
index 4fd70f11f9..efde0f4d36 100644
--- a/plugins/sonar-squid-java-plugin/src/test/java/org/sonar/java/bytecode/loader/JarLoaderTest.java
+++ b/plugins/sonar-squid-java-plugin/src/test/java/org/sonar/java/bytecode/loader/JarLoaderTest.java
@@ -1,56 +1,56 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2011 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Sonar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.java.bytecode.loader;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.sonar.java.ast.SquidTestUtils;
public class JarLoaderTest {
@Test
public void testFindResource() throws Exception {
File jar = SquidTestUtils.getFile("/bytecode/lib/hello.jar");
JarLoader jarLoader = new JarLoader(jar);
URL url = jarLoader.findResource("META-INF/MANIFEST.MF");
- assertThat(url.toString(), allOf(startsWith("jar:"), endsWith("/bytecode/lib/hello.jar!/META-INF/MANIFEST.MF")));
+ assertThat(url.toString(), allOf(startsWith("jar:"), endsWith("hello.jar!/META-INF/MANIFEST.MF")));
InputStream is = url.openStream();
try {
assertThat(IOUtils.readLines(is), hasItem("Manifest-Version: 1.0"));
} finally {
IOUtils.closeQuietly(is);
}
jarLoader.close();
}
}
| true | true | public void testFindResource() throws Exception {
File jar = SquidTestUtils.getFile("/bytecode/lib/hello.jar");
JarLoader jarLoader = new JarLoader(jar);
URL url = jarLoader.findResource("META-INF/MANIFEST.MF");
assertThat(url.toString(), allOf(startsWith("jar:"), endsWith("/bytecode/lib/hello.jar!/META-INF/MANIFEST.MF")));
InputStream is = url.openStream();
try {
assertThat(IOUtils.readLines(is), hasItem("Manifest-Version: 1.0"));
} finally {
IOUtils.closeQuietly(is);
}
jarLoader.close();
}
| public void testFindResource() throws Exception {
File jar = SquidTestUtils.getFile("/bytecode/lib/hello.jar");
JarLoader jarLoader = new JarLoader(jar);
URL url = jarLoader.findResource("META-INF/MANIFEST.MF");
assertThat(url.toString(), allOf(startsWith("jar:"), endsWith("hello.jar!/META-INF/MANIFEST.MF")));
InputStream is = url.openStream();
try {
assertThat(IOUtils.readLines(is), hasItem("Manifest-Version: 1.0"));
} finally {
IOUtils.closeQuietly(is);
}
jarLoader.close();
}
|
diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java
index 463d161f0..0d9a8cb8a 100644
--- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java
+++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java
@@ -1,486 +1,487 @@
/*
* 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.backends.android;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLSurfaceView.EGLConfigChooser;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.backends.android.surfaceview.*;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.WindowedMean;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.MathUtils;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import java.io.InputStream;
/**
* An implementation of {@link Graphics} for Android.
*
* @author mzechner
*/
public final class AndroidGraphics implements Graphics, Renderer {
final View view;
int width;
int height;
AndroidApplication app;
GLCommon gl;
GL10 gl10;
GL11 gl11;
GL20 gl20;
GLU glu;
private long lastFrameTime = System.nanoTime();
private float deltaTime = 0;
private long frameStart = System.nanoTime();
private int frames = 0;
private int fps;
private WindowedMean mean = new WindowedMean(5);
volatile boolean created = false;
volatile boolean running = false;
volatile boolean pause = false;
volatile boolean resume = false;
volatile boolean destroy = false;
private float ppiX = 0;
private float ppiY = 0;
private float ppcX = 0;
private float ppcY = 0;
public AndroidGraphics(AndroidApplication activity, boolean useGL2IfAvailable, ResolutionStrategy resolutionStrategy) {
view = createGLSurfaceView(activity, useGL2IfAvailable, resolutionStrategy);
this.app = activity;
}
private View createGLSurfaceView(Activity activity, boolean useGL2, ResolutionStrategy resolutionStrategy) {
EGLConfigChooser configChooser = getEglConfigChooser();
if (useGL2 && checkGL20()) {
GLSurfaceView20 view = new GLSurfaceView20(activity, resolutionStrategy);
if (configChooser != null) view.setEGLConfigChooser(configChooser);
view.setRenderer(this);
return view;
} else {
if (Integer.parseInt(android.os.Build.VERSION.SDK) <= 4) {
GLSurfaceViewCupcake view = new GLSurfaceViewCupcake(activity, resolutionStrategy);
if (configChooser != null) view.setEGLConfigChooser(configChooser);
view.setRenderer(this);
return view;
} else {
android.opengl.GLSurfaceView view = new DefaultGLSurfaceView(activity, resolutionStrategy);
if (configChooser != null) view.setEGLConfigChooser(configChooser);
view.setRenderer(this);
return view;
}
}
}
private EGLConfigChooser getEglConfigChooser() {
if (!Build.DEVICE.equalsIgnoreCase("GT-I7500"))
return null;
else
return new android.opengl.GLSurfaceView.EGLConfigChooser() {
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
// Ensure that we get a 16bit depth-buffer. Otherwise, we'll fall
// back to Pixelflinger on some device (read: Samsung I7500)
int[] attributes = new int[]{EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_NONE};
EGLConfig[] configs = new EGLConfig[1];
int[] result = new int[1];
egl.eglChooseConfig(display, attributes, configs, 1, result);
return configs[0];
}
};
}
private void updatePpi() {
DisplayMetrics metrics = new DisplayMetrics();
app.getWindowManager().getDefaultDisplay().getMetrics(metrics);
ppiX = metrics.xdpi;
ppiY = metrics.ydpi;
ppcX = metrics.xdpi / 2.54f;
ppcY = metrics.ydpi / 2.54f;
}
private boolean checkGL20() {
EGL10 egl = (EGL10) EGLContext.getEGL();
EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(display, version);
int EGL_OPENGL_ES2_BIT = 4;
int[] configAttribs = {EGL10.EGL_RED_SIZE, 4, EGL10.EGL_GREEN_SIZE, 4, EGL10.EGL_BLUE_SIZE, 4, EGL10.EGL_RENDERABLE_TYPE,
EGL_OPENGL_ES2_BIT, EGL10.EGL_NONE};
EGLConfig[] configs = new EGLConfig[10];
int[] num_config = new int[1];
egl.eglChooseConfig(display, configAttribs, configs, 10, num_config);
egl.eglTerminate(display);
return num_config[0] > 0;
}
/**
* {@inheritDoc}
*/
@Override
public GL10 getGL10() {
return gl10;
}
/**
* {@inheritDoc}
*/
@Override
public GL11 getGL11() {
return gl11;
}
/**
* {@inheritDoc}
*/
@Override
public GL20 getGL20() {
return gl20;
}
/**
* {@inheritDoc}
*/
@Override
public int getHeight() {
return height;
}
/**
* {@inheritDoc}
*/
@Override
public int getWidth() {
return width;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isGL11Available() {
return gl11 != null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isGL20Available() {
return gl20 != null;
}
private static boolean isPowerOfTwo(int value) {
return ((value != 0) && (value & (value - 1)) == 0);
}
/**
* This instantiates the GL10, GL11 and GL20 instances. Includes the check for certain devices that pretend to support GL11 but
* fuck up vertex buffer objects. This includes the pixelflinger which segfaults when buffers are deleted as well as the
* Motorola CLIQ and the Samsung Behold II.
*
* @param gl
*/
private void setupGL(javax.microedition.khronos.opengles.GL10 gl) {
if (gl10 != null || gl20 != null) return;
if (view instanceof GLSurfaceView20) {
gl20 = new AndroidGL20();
this.gl = gl20;
} else {
gl10 = new AndroidGL10(gl);
this.gl = gl10;
if (gl instanceof javax.microedition.khronos.opengles.GL11) {
String renderer = gl.glGetString(GL10.GL_RENDERER);
if (!renderer.toLowerCase().contains("pixelflinger")
&& !(android.os.Build.MODEL.equals("MB200") || android.os.Build.MODEL.equals("MB220") || android.os.Build.MODEL
.contains("Behold"))) {
gl11 = new AndroidGL11((javax.microedition.khronos.opengles.GL11) gl);
gl10 = gl11;
}
}
}
this.glu = new AndroidGLU();
Gdx.gl = this.gl;
Gdx.gl10 = gl10;
Gdx.gl11 = gl11;
Gdx.gl20 = gl20;
Gdx.glu = glu;
Gdx.app.log("AndroidGraphics", "OGL renderer: " + gl.glGetString(GL10.GL_RENDERER));
Gdx.app.log("AndroidGraphics", "OGL vendor: " + gl.glGetString(GL10.GL_VENDOR));
Gdx.app.log("AndroidGraphics", "OGL version: " + gl.glGetString(GL10.GL_VERSION));
Gdx.app.log("AndroidGraphics", "OGL extensions: " + gl.glGetString(GL10.GL_EXTENSIONS));
}
@Override
public void onSurfaceChanged(javax.microedition.khronos.opengles.GL10 gl, int width, int height) {
this.width = width;
this.height = height;
updatePpi();
gl.glViewport(0, 0, this.width, this.height);
app.listener.resize(width, height);
}
@Override
public void onSurfaceCreated(javax.microedition.khronos.opengles.GL10 gl, EGLConfig config) {
setupGL(gl);
logConfig(config);
updatePpi();
Mesh.invalidateAllMeshes();
Texture.invalidateAllTextures();
ShaderProgram.invalidateAllShaderPrograms();
FrameBuffer.invalidateAllFrameBuffers();
Display display = app.getWindowManager().getDefaultDisplay();
this.width = display.getWidth();
this.height = display.getHeight();
mean = new WindowedMean(5);
this.lastFrameTime = System.nanoTime();
gl.glViewport(0, 0, this.width, this.height);
if (created == false) {
app.listener.create();
created = true;
synchronized (this) {
running = true;
}
}
}
private void logConfig(EGLConfig config) {
EGL10 egl = (EGL10) EGLContext.getEGL();
EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int r = getAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
int g = getAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
int b = getAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
int a = getAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
int d = getAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
int s = getAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
Gdx.app.log("AndroidGraphics", "framebuffer: (" + r + ", " + g + ", " + b + ", " + a + ")");
Gdx.app.log("AndroidGraphics", "depthbuffer: (" + d + ")");
Gdx.app.log("AndroidGraphics", "stencilbuffer: (" + s + ")");
}
int[] value = new int[1];
private int getAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attrib, int defValue) {
if (egl.eglGetConfigAttrib(display, config, attrib, value)) {
return value[0];
}
return defValue;
}
Object synch = new Object();
void resume() {
synchronized (synch) {
running = true;
resume = true;
}
}
void pause() {
synchronized (synch) {
running = false;
pause = true;
while (pause) {
try {
synch.wait();
} catch (InterruptedException ignored) {
}
}
}
}
void destroy() {
synchronized (synch) {
running = false;
destroy = true;
while (destroy) {
try {
synch.wait();
} catch (InterruptedException ex) {
}
}
}
}
@Override
public void onDrawFrame(javax.microedition.khronos.opengles.GL10 gl) {
long time = System.nanoTime();
deltaTime = (time - lastFrameTime) / 1000000000.0f;
lastFrameTime = time;
mean.addValue(deltaTime);
boolean lrunning = false;
boolean lpause = false;
boolean ldestroy = false;
boolean lresume = false;
synchronized (synch) {
lrunning = running;
lpause = pause;
ldestroy = destroy;
lresume = resume;
if (resume) {
resume = false;
}
if (pause) {
pause = false;
synch.notifyAll();
}
if (destroy) {
destroy = false;
synch.notifyAll();
}
}
if (lresume) {
app.listener.resume();
Gdx.app.log("AndroidGraphics", "resumed");
}
if (lrunning) {
synchronized(app.runnables) {
for(int i = 0; i < app.runnables.size(); i++) {
app.runnables.get(i).run();
}
app.runnables.clear();
}
app.input.processEvents();
app.listener.render();
}
if (lpause) {
app.listener.pause();
Gdx.app.log("AndroidGraphics", "paused");
}
if (ldestroy) {
app.listener.dispose();
((AndroidApplication)app).audio.dispose();
+ ((AndroidApplication)app).audio = null;
Gdx.app.log("AndroidGraphics", "destroyed");
}
if (time - frameStart > 1000000000) {
fps = frames;
frames = 0;
frameStart = time;
}
frames++;
}
/**
* {@inheritDoc}
*/
@Override
public float getDeltaTime() {
return mean.getMean() == 0 ? deltaTime : mean.getMean();
}
/**
* {@inheritDoc}
*/
@Override
public GraphicsType getType() {
return GraphicsType.AndroidGL;
}
/**
* {@inheritDoc}
*/
@Override
public int getFramesPerSecond() {
return fps;
}
public void clearManagedCaches() {
Mesh.clearAllMeshes();
Texture.clearAllTextures();
ShaderProgram.clearAllShaderPrograms();
FrameBuffer.clearAllFrameBuffers();
}
public View getView() {
return view;
}
/**
* {@inheritDoc}
*/
@Override
public GLCommon getGLCommon() {
return gl;
}
@Override
public float getPpiX() {
return ppiX;
}
@Override
public float getPpiY() {
return ppiY;
}
@Override
public float getPpcX() {
return ppcX;
}
@Override
public float getPpcY() {
return ppcY;
}
@Override public GLU getGLU () {
return null;
}
}
| true | true | public void onDrawFrame(javax.microedition.khronos.opengles.GL10 gl) {
long time = System.nanoTime();
deltaTime = (time - lastFrameTime) / 1000000000.0f;
lastFrameTime = time;
mean.addValue(deltaTime);
boolean lrunning = false;
boolean lpause = false;
boolean ldestroy = false;
boolean lresume = false;
synchronized (synch) {
lrunning = running;
lpause = pause;
ldestroy = destroy;
lresume = resume;
if (resume) {
resume = false;
}
if (pause) {
pause = false;
synch.notifyAll();
}
if (destroy) {
destroy = false;
synch.notifyAll();
}
}
if (lresume) {
app.listener.resume();
Gdx.app.log("AndroidGraphics", "resumed");
}
if (lrunning) {
synchronized(app.runnables) {
for(int i = 0; i < app.runnables.size(); i++) {
app.runnables.get(i).run();
}
app.runnables.clear();
}
app.input.processEvents();
app.listener.render();
}
if (lpause) {
app.listener.pause();
Gdx.app.log("AndroidGraphics", "paused");
}
if (ldestroy) {
app.listener.dispose();
((AndroidApplication)app).audio.dispose();
Gdx.app.log("AndroidGraphics", "destroyed");
}
if (time - frameStart > 1000000000) {
fps = frames;
frames = 0;
frameStart = time;
}
frames++;
}
| public void onDrawFrame(javax.microedition.khronos.opengles.GL10 gl) {
long time = System.nanoTime();
deltaTime = (time - lastFrameTime) / 1000000000.0f;
lastFrameTime = time;
mean.addValue(deltaTime);
boolean lrunning = false;
boolean lpause = false;
boolean ldestroy = false;
boolean lresume = false;
synchronized (synch) {
lrunning = running;
lpause = pause;
ldestroy = destroy;
lresume = resume;
if (resume) {
resume = false;
}
if (pause) {
pause = false;
synch.notifyAll();
}
if (destroy) {
destroy = false;
synch.notifyAll();
}
}
if (lresume) {
app.listener.resume();
Gdx.app.log("AndroidGraphics", "resumed");
}
if (lrunning) {
synchronized(app.runnables) {
for(int i = 0; i < app.runnables.size(); i++) {
app.runnables.get(i).run();
}
app.runnables.clear();
}
app.input.processEvents();
app.listener.render();
}
if (lpause) {
app.listener.pause();
Gdx.app.log("AndroidGraphics", "paused");
}
if (ldestroy) {
app.listener.dispose();
((AndroidApplication)app).audio.dispose();
((AndroidApplication)app).audio = null;
Gdx.app.log("AndroidGraphics", "destroyed");
}
if (time - frameStart > 1000000000) {
fps = frames;
frames = 0;
frameStart = time;
}
frames++;
}
|
diff --git a/src/org/apache/xerces/jaxp/validation/ValidatorHandlerImpl.java b/src/org/apache/xerces/jaxp/validation/ValidatorHandlerImpl.java
index ee4f3ff5e..a9ed4f515 100644
--- a/src/org/apache/xerces/jaxp/validation/ValidatorHandlerImpl.java
+++ b/src/org/apache/xerces/jaxp/validation/ValidatorHandlerImpl.java
@@ -1,1139 +1,1139 @@
/*
* 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.xerces.jaxp.validation;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.TypeInfoProvider;
import javax.xml.validation.ValidatorHandler;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.XMLEntityManager;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.impl.dv.XSSimpleType;
import org.apache.xerces.impl.validation.EntityState;
import org.apache.xerces.impl.validation.ValidationManager;
import org.apache.xerces.impl.xs.XMLSchemaValidator;
import org.apache.xerces.util.AttributesProxy;
import org.apache.xerces.util.SAXLocatorWrapper;
import org.apache.xerces.util.SAXMessageFormatter;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.URI;
import org.apache.xerces.util.XMLAttributesImpl;
import org.apache.xerces.util.XMLSymbols;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDocumentSource;
import org.apache.xerces.xni.parser.XMLParseException;
import org.apache.xerces.xs.AttributePSVI;
import org.apache.xerces.xs.ElementPSVI;
import org.apache.xerces.xs.ItemPSVI;
import org.apache.xerces.xs.PSVIProvider;
import org.apache.xerces.xs.XSTypeDefinition;
import org.w3c.dom.TypeInfo;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.Attributes2;
import org.xml.sax.ext.EntityResolver2;
import org.xml.sax.ext.LexicalHandler;
/**
* <p>Implementation of ValidatorHandler for W3C XML Schemas and
* also a validator helper for <code>SAXSource</code>s.</p>
*
* @author Kohsuke Kawaguchi ([email protected])
* @author Michael Glavassevich, IBM
*
* @version $Id$
*/
final class ValidatorHandlerImpl extends ValidatorHandler implements
DTDHandler, EntityState, PSVIProvider, ValidatorHelper, XMLDocumentHandler {
// feature identifiers
/** Feature identifier: namespace prefixes. */
private static final String NAMESPACE_PREFIXES =
Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACE_PREFIXES_FEATURE;
/** Feature identifier: string interning. */
private static final String STRING_INTERNING =
Constants.SAX_FEATURE_PREFIX + Constants.STRING_INTERNING_FEATURE;
/** Feature identifier: strings interned. */
private static final String STRINGS_INTERNED =
Constants.XERCES_FEATURE_PREFIX + Constants.STRINGS_INTERNED_FEATURE;
// property identifiers
/** Property identifier: error reporter. */
private static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: lexical handler. */
private static final String LEXICAL_HANDLER =
Constants.SAX_PROPERTY_PREFIX + Constants.LEXICAL_HANDLER_PROPERTY;
/** Property identifier: namespace context. */
private static final String NAMESPACE_CONTEXT =
Constants.XERCES_PROPERTY_PREFIX + Constants.NAMESPACE_CONTEXT_PROPERTY;
/** Property identifier: XML Schema validator. */
private static final String SCHEMA_VALIDATOR =
Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_VALIDATOR_PROPERTY;
/** Property identifier: security manager. */
private static final String SECURITY_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY;
/** Property identifier: symbol table. */
private static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
/** Property identifier: validation manager. */
private static final String VALIDATION_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
//
// Data
//
/** Error reporter. */
private final XMLErrorReporter fErrorReporter;
/** The namespace context of this document: stores namespaces in scope */
private final NamespaceContext fNamespaceContext;
/** Schema validator. **/
private final XMLSchemaValidator fSchemaValidator;
/** Symbol table **/
private final SymbolTable fSymbolTable;
/** Validation manager. */
private final ValidationManager fValidationManager;
/** Component manager. **/
private final XMLSchemaValidatorComponentManager fComponentManager;
/** XML Locator wrapper for SAX. **/
private final SAXLocatorWrapper fSAXLocatorWrapper = new SAXLocatorWrapper();
/** Flag used to track whether the namespace context needs to be pushed. */
private boolean fNeedPushNSContext = true;
/** Map for tracking unparsed entities. */
private HashMap fUnparsedEntities = null;
/** Flag used to track whether XML names and Namespace URIs have been internalized. */
private boolean fStringsInternalized = false;
/** Fields for start element, end element and characters. */
private final QName fElementQName = new QName();
private final QName fAttributeQName = new QName();
private final XMLAttributesImpl fAttributes = new XMLAttributesImpl();
private final AttributesProxy fAttrAdapter = new AttributesProxy(fAttributes);
private final XMLString fTempString = new XMLString();
//
// User Objects
//
private ContentHandler fContentHandler = null;
/*
* Constructors
*/
public ValidatorHandlerImpl(XSGrammarPoolContainer grammarContainer) {
this(new XMLSchemaValidatorComponentManager(grammarContainer));
fComponentManager.addRecognizedFeatures(new String [] {NAMESPACE_PREFIXES});
fComponentManager.setFeature(NAMESPACE_PREFIXES, false);
setErrorHandler(null);
setResourceResolver(null);
}
public ValidatorHandlerImpl(XMLSchemaValidatorComponentManager componentManager) {
fComponentManager = componentManager;
fErrorReporter = (XMLErrorReporter) fComponentManager.getProperty(ERROR_REPORTER);
fNamespaceContext = (NamespaceContext) fComponentManager.getProperty(NAMESPACE_CONTEXT);
fSchemaValidator = (XMLSchemaValidator) fComponentManager.getProperty(SCHEMA_VALIDATOR);
fSymbolTable = (SymbolTable) fComponentManager.getProperty(SYMBOL_TABLE);
fValidationManager = (ValidationManager) fComponentManager.getProperty(VALIDATION_MANAGER);
}
/*
* ValidatorHandler methods
*/
public void setContentHandler(ContentHandler receiver) {
fContentHandler = receiver;
}
public ContentHandler getContentHandler() {
return fContentHandler;
}
public void setErrorHandler(ErrorHandler errorHandler) {
fComponentManager.setErrorHandler(errorHandler);
}
public ErrorHandler getErrorHandler() {
return fComponentManager.getErrorHandler();
}
public void setResourceResolver(LSResourceResolver resourceResolver) {
fComponentManager.setResourceResolver(resourceResolver);
}
public LSResourceResolver getResourceResolver() {
return fComponentManager.getResourceResolver();
}
public TypeInfoProvider getTypeInfoProvider() {
return fTypeInfoProvider;
}
public boolean getFeature(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(),
"FeatureNameNull", null));
}
if (STRINGS_INTERNED.equals(name)) {
return fStringsInternalized;
}
try {
return fComponentManager.getFeature(name);
}
catch (XMLConfigurationException e) {
final String identifier = e.getIdentifier();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(
SAXMessageFormatter.formatMessage(fComponentManager.getLocale(),
"feature-not-recognized", new Object [] {identifier}));
}
else {
throw new SAXNotSupportedException(
SAXMessageFormatter.formatMessage(fComponentManager.getLocale(),
"feature-not-supported", new Object [] {identifier}));
}
}
}
public void setFeature(String name, boolean value)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(),
"FeatureNameNull", null));
}
if (STRINGS_INTERNED.equals(name)) {
fStringsInternalized = value;
return;
}
try {
fComponentManager.setFeature(name, value);
}
catch (XMLConfigurationException e) {
final String identifier = e.getIdentifier();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(
SAXMessageFormatter.formatMessage(fComponentManager.getLocale(),
"feature-not-recognized", new Object [] {identifier}));
}
else {
throw new SAXNotSupportedException(
SAXMessageFormatter.formatMessage(fComponentManager.getLocale(),
"feature-not-supported", new Object [] {identifier}));
}
}
}
public Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(),
"ProperyNameNull", null));
}
try {
return fComponentManager.getProperty(name);
}
catch (XMLConfigurationException e) {
final String identifier = e.getIdentifier();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(
SAXMessageFormatter.formatMessage(fComponentManager.getLocale(),
"property-not-recognized", new Object [] {identifier}));
}
else {
throw new SAXNotSupportedException(
SAXMessageFormatter.formatMessage(fComponentManager.getLocale(),
"property-not-supported", new Object [] {identifier}));
}
}
}
public void setProperty(String name, Object object)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(),
"ProperyNameNull", null));
}
try {
fComponentManager.setProperty(name, object);
}
catch (XMLConfigurationException e) {
final String identifier = e.getIdentifier();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(
SAXMessageFormatter.formatMessage(fComponentManager.getLocale(),
"property-not-recognized", new Object [] {identifier}));
}
else {
throw new SAXNotSupportedException(
SAXMessageFormatter.formatMessage(fComponentManager.getLocale(),
"property-not-supported", new Object [] {identifier}));
}
}
}
/*
* EntityState methods
*/
public boolean isEntityDeclared(String name) {
return false;
}
public boolean isEntityUnparsed(String name) {
if (fUnparsedEntities != null) {
return fUnparsedEntities.containsKey(name);
}
return false;
}
/*
* XMLDocumentHandler methods
*/
public void startDocument(XMLLocator locator, String encoding,
NamespaceContext namespaceContext, Augmentations augs)
throws XNIException {
if (fContentHandler != null) {
try {
fContentHandler.startDocument();
}
catch (SAXException e) {
throw new XNIException(e);
}
}
}
public void xmlDecl(String version, String encoding, String standalone,
Augmentations augs) throws XNIException {}
public void doctypeDecl(String rootElement, String publicId,
String systemId, Augmentations augs) throws XNIException {}
public void comment(XMLString text, Augmentations augs) throws XNIException {}
public void processingInstruction(String target, XMLString data,
Augmentations augs) throws XNIException {
if (fContentHandler != null) {
try {
fContentHandler.processingInstruction(target, data.toString());
}
catch (SAXException e) {
throw new XNIException(e);
}
}
}
public void startElement(QName element, XMLAttributes attributes,
Augmentations augs) throws XNIException {
if (fContentHandler != null) {
try {
fTypeInfoProvider.beginStartElement(augs, attributes);
fContentHandler.startElement((element.uri != null) ? element.uri : XMLSymbols.EMPTY_STRING,
element.localpart, element.rawname, fAttrAdapter);
}
catch (SAXException e) {
throw new XNIException(e);
}
finally {
fTypeInfoProvider.finishStartElement();
}
}
}
public void emptyElement(QName element, XMLAttributes attributes,
Augmentations augs) throws XNIException {
/** Split empty element event. **/
startElement(element, attributes, augs);
endElement(element, augs);
}
public void startGeneralEntity(String name,
XMLResourceIdentifier identifier, String encoding,
Augmentations augs) throws XNIException {}
public void textDecl(String version, String encoding, Augmentations augs)
throws XNIException {}
public void endGeneralEntity(String name, Augmentations augs)
throws XNIException {}
public void characters(XMLString text, Augmentations augs)
throws XNIException {
if (fContentHandler != null) {
// if the type is union it is possible that we receive
// a character call with empty data
if (text.length == 0) {
return;
}
try {
fContentHandler.characters(text.ch, text.offset, text.length);
}
catch (SAXException e) {
throw new XNIException(e);
}
}
}
public void ignorableWhitespace(XMLString text, Augmentations augs)
throws XNIException {
if (fContentHandler != null) {
try {
fContentHandler.ignorableWhitespace(text.ch, text.offset, text.length);
}
catch (SAXException e) {
throw new XNIException(e);
}
}
}
public void endElement(QName element, Augmentations augs)
throws XNIException {
if (fContentHandler != null) {
try {
fTypeInfoProvider.beginEndElement(augs);
fContentHandler.endElement((element.uri != null) ? element.uri : XMLSymbols.EMPTY_STRING,
element.localpart, element.rawname);
}
catch (SAXException e) {
throw new XNIException(e);
}
finally {
fTypeInfoProvider.finishEndElement();
}
}
}
public void startCDATA(Augmentations augs) throws XNIException {}
public void endCDATA(Augmentations augs) throws XNIException {}
public void endDocument(Augmentations augs) throws XNIException {
if (fContentHandler != null) {
try {
fContentHandler.endDocument();
}
catch (SAXException e) {
throw new XNIException(e);
}
}
}
// NO-OP
public void setDocumentSource(XMLDocumentSource source) {}
public XMLDocumentSource getDocumentSource() {
return fSchemaValidator;
}
/*
* ContentHandler methods
*/
public void setDocumentLocator(Locator locator) {
fSAXLocatorWrapper.setLocator(locator);
if (fContentHandler != null) {
fContentHandler.setDocumentLocator(locator);
}
}
public void startDocument() throws SAXException {
fComponentManager.reset();
fSchemaValidator.setDocumentHandler(this);
fValidationManager.setEntityState(this);
fTypeInfoProvider.finishStartElement(); // cleans up TypeInfoProvider
fNeedPushNSContext = true;
if (fUnparsedEntities != null && !fUnparsedEntities.isEmpty()) {
// should only clear this if the last document contained unparsed entities
fUnparsedEntities.clear();
}
fErrorReporter.setDocumentLocator(fSAXLocatorWrapper);
try {
fSchemaValidator.startDocument(fSAXLocatorWrapper, fSAXLocatorWrapper.getEncoding(), fNamespaceContext, null);
}
catch (XMLParseException e) {
throw Util.toSAXParseException(e);
}
catch (XNIException e) {
throw Util.toSAXException(e);
}
}
public void endDocument() throws SAXException {
fSAXLocatorWrapper.setLocator(null);
try {
fSchemaValidator.endDocument(null);
}
catch (XMLParseException e) {
throw Util.toSAXParseException(e);
}
catch (XNIException e) {
throw Util.toSAXException(e);
}
}
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
String prefixSymbol;
String uriSymbol;
if (!fStringsInternalized) {
prefixSymbol = (prefix != null) ? fSymbolTable.addSymbol(prefix) : XMLSymbols.EMPTY_STRING;
uriSymbol = (uri != null && uri.length() > 0) ? fSymbolTable.addSymbol(uri) : null;
}
else {
prefixSymbol = (prefix != null) ? prefix : XMLSymbols.EMPTY_STRING;
uriSymbol = (uri != null && uri.length() > 0) ? uri : null;
}
if (fNeedPushNSContext) {
fNeedPushNSContext = false;
fNamespaceContext.pushContext();
}
fNamespaceContext.declarePrefix(prefixSymbol, uriSymbol);
if (fContentHandler != null) {
fContentHandler.startPrefixMapping(prefix, uri);
}
}
public void endPrefixMapping(String prefix) throws SAXException {
if (fContentHandler != null) {
fContentHandler.endPrefixMapping(prefix);
}
}
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
if (fNeedPushNSContext) {
fNamespaceContext.pushContext();
}
fNeedPushNSContext = true;
// Fill element QName
fillQName(fElementQName, uri, localName, qName);
// Fill XMLAttributes
if (atts instanceof Attributes2) {
fillXMLAttributes2((Attributes2) atts);
}
else {
fillXMLAttributes(atts);
}
try {
fSchemaValidator.startElement(fElementQName, fAttributes, null);
}
catch (XMLParseException e) {
throw Util.toSAXParseException(e);
}
catch (XNIException e) {
throw Util.toSAXException(e);
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
fillQName(fElementQName, uri, localName, qName);
try {
fSchemaValidator.endElement(fElementQName, null);
}
catch (XMLParseException e) {
throw Util.toSAXParseException(e);
}
catch (XNIException e) {
throw Util.toSAXException(e);
}
finally {
fNamespaceContext.popContext();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
try {
fTempString.setValues(ch, start, length);
fSchemaValidator.characters(fTempString, null);
}
catch (XMLParseException e) {
throw Util.toSAXParseException(e);
}
catch (XNIException e) {
throw Util.toSAXException(e);
}
}
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
try {
fTempString.setValues(ch, start, length);
fSchemaValidator.ignorableWhitespace(fTempString, null);
}
catch (XMLParseException e) {
throw Util.toSAXParseException(e);
}
catch (XNIException e) {
throw Util.toSAXException(e);
}
}
public void processingInstruction(String target, String data)
throws SAXException {
/**
* Processing instructions do not participate in schema validation,
* so just forward the event to the application's content
* handler.
*/
if (fContentHandler != null) {
fContentHandler.processingInstruction(target, data);
}
}
public void skippedEntity(String name) throws SAXException {
// there seems to be no corresponding method on XMLDocumentFilter.
// just pass it down to the output, if any.
if (fContentHandler != null) {
fContentHandler.skippedEntity(name);
}
}
/*
* DTDHandler methods
*/
public void notationDecl(String name, String publicId,
String systemId) throws SAXException {}
public void unparsedEntityDecl(String name, String publicId,
String systemId, String notationName) throws SAXException {
if (fUnparsedEntities == null) {
fUnparsedEntities = new HashMap();
}
fUnparsedEntities.put(name, name);
}
/*
* ValidatorHelper methods
*/
public void validate(Source source, Result result)
throws SAXException, IOException {
if (result instanceof SAXResult || result == null) {
final SAXSource saxSource = (SAXSource) source;
final SAXResult saxResult = (SAXResult) result;
LexicalHandler lh = null;
if (result != null) {
ContentHandler ch = saxResult.getHandler();
lh = saxResult.getLexicalHandler();
/** If the lexical handler is not set try casting the ContentHandler. **/
if (lh == null && ch instanceof LexicalHandler) {
lh = (LexicalHandler) ch;
}
setContentHandler(ch);
}
XMLReader reader = null;
try {
reader = saxSource.getXMLReader();
if (reader == null) {
// create one now
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
try {
reader = spf.newSAXParser().getXMLReader();
// If this is a Xerces SAX parser, set the security manager if there is one
if (reader instanceof org.apache.xerces.parsers.SAXParser) {
- SecurityManager securityManager = (SecurityManager) fComponentManager.getProperty(SECURITY_MANAGER);
+ Object securityManager = fComponentManager.getProperty(SECURITY_MANAGER);
if (securityManager != null) {
try {
reader.setProperty(SECURITY_MANAGER, securityManager);
}
// Ignore the exception if the security manager cannot be set.
catch (SAXException exc) {}
}
}
}
catch (Exception e) {
// this is impossible, but better safe than sorry
throw new FactoryConfigurationError(e);
}
}
// If XML names and Namespace URIs are already internalized we
// can avoid running them through the SymbolTable.
try {
fStringsInternalized = reader.getFeature(STRING_INTERNING);
}
catch (SAXException exc) {
// The feature isn't recognized or getting it is not supported.
// In either case, assume that strings are not internalized.
fStringsInternalized = false;
}
ErrorHandler errorHandler = fComponentManager.getErrorHandler();
reader.setErrorHandler(errorHandler != null ? errorHandler : DraconianErrorHandler.getInstance());
reader.setEntityResolver(fResolutionForwarder);
fResolutionForwarder.setEntityResolver(fComponentManager.getResourceResolver());
reader.setContentHandler(this);
reader.setDTDHandler(this);
try {
reader.setProperty(LEXICAL_HANDLER, lh);
}
// Ignore the exception if the lexical handler cannot be set.
catch (SAXException exc) {}
InputSource is = saxSource.getInputSource();
reader.parse(is);
}
finally {
// Release the reference to user's ContentHandler ASAP
setContentHandler(null);
// Disconnect the validator and other objects from the XMLReader
if (reader != null) {
try {
reader.setContentHandler(null);
reader.setDTDHandler(null);
reader.setErrorHandler(null);
reader.setEntityResolver(null);
fResolutionForwarder.setEntityResolver(null);
reader.setProperty(LEXICAL_HANDLER, null);
}
// Ignore the exception if the lexical handler cannot be unset.
catch (Exception exc) {}
}
}
return;
}
throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(),
"SourceResultMismatch",
new Object [] {source.getClass().getName(), result.getClass().getName()}));
}
/*
* PSVIProvider methods
*/
public ElementPSVI getElementPSVI() {
return fTypeInfoProvider.getElementPSVI();
}
public AttributePSVI getAttributePSVI(int index) {
return fTypeInfoProvider.getAttributePSVI(index);
}
public AttributePSVI getAttributePSVIByName(String uri, String localname) {
return fTypeInfoProvider.getAttributePSVIByName(uri, localname);
}
//
//
// helper methods
//
//
/** Fills in a QName object. */
private void fillQName(QName toFill, String uri, String localpart, String raw) {
if (!fStringsInternalized) {
uri = (uri != null && uri.length() > 0) ? fSymbolTable.addSymbol(uri) : null;
localpart = (localpart != null) ? fSymbolTable.addSymbol(localpart) : XMLSymbols.EMPTY_STRING;
raw = (raw != null) ? fSymbolTable.addSymbol(raw) : XMLSymbols.EMPTY_STRING;
}
else {
if (uri != null && uri.length() == 0) {
uri = null;
}
if (localpart == null) {
localpart = XMLSymbols.EMPTY_STRING;
}
if (raw == null) {
raw = XMLSymbols.EMPTY_STRING;
}
}
String prefix = XMLSymbols.EMPTY_STRING;
int prefixIdx = raw.indexOf(':');
if (prefixIdx != -1) {
prefix = fSymbolTable.addSymbol(raw.substring(0, prefixIdx));
}
toFill.setValues(prefix, localpart, raw, uri);
}
/** Fills in the XMLAttributes object. */
private void fillXMLAttributes(Attributes att) {
fAttributes.removeAllAttributes();
final int len = att.getLength();
for (int i = 0; i < len; ++i) {
fillXMLAttribute(att, i);
fAttributes.setSpecified(i, true);
}
}
/** Fills in the XMLAttributes object. */
private void fillXMLAttributes2(Attributes2 att) {
fAttributes.removeAllAttributes();
final int len = att.getLength();
for (int i = 0; i < len; ++i) {
fillXMLAttribute(att, i);
fAttributes.setSpecified(i, att.isSpecified(i));
if (att.isDeclared(i)) {
fAttributes.getAugmentations(i).putItem(Constants.ATTRIBUTE_DECLARED, Boolean.TRUE);
}
}
}
/** Adds an attribute to the XMLAttributes object. */
private void fillXMLAttribute(Attributes att, int index) {
fillQName(fAttributeQName, att.getURI(index), att.getLocalName(index), att.getQName(index));
String type = att.getType(index);
fAttributes.addAttributeNS(fAttributeQName, (type != null) ? type : XMLSymbols.fCDATASymbol, att.getValue(index));
}
/**
* {@link TypeInfoProvider} implementation.
*
* REVISIT: I'm not sure if this code should belong here.
*/
private final XMLSchemaTypeInfoProvider fTypeInfoProvider = new XMLSchemaTypeInfoProvider();
private class XMLSchemaTypeInfoProvider extends TypeInfoProvider {
/** Element augmentations: contains ElementPSVI. **/
private Augmentations fElementAugs;
/** Attributes: augmentations for each attribute contain AttributePSVI. **/
private XMLAttributes fAttributes;
/** In start element. **/
private boolean fInStartElement = false;
private boolean fInEndElement = false;
/** Initializes the TypeInfoProvider with type information for the current element. **/
void beginStartElement(Augmentations elementAugs, XMLAttributes attributes) {
fInStartElement = true;
fElementAugs = elementAugs;
fAttributes = attributes;
}
/** Cleanup at the end of start element. **/
void finishStartElement() {
fInStartElement = false;
fElementAugs = null;
fAttributes = null;
}
/** Initializes the TypeInfoProvider with type information for the current element. **/
void beginEndElement(Augmentations elementAugs) {
fInEndElement = true;
fElementAugs = elementAugs;
}
/** Cleanup at the end of end element. **/
void finishEndElement() {
fInEndElement = false;
fElementAugs = null;
}
/**
* Throws a {@link IllegalStateException} if we are not in
* the startElement callback. the JAXP API requires this
* for most of the public methods which access attribute
* type information.
*/
private void checkStateAttribute() {
if (!fInStartElement) {
throw new IllegalStateException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(),
"TypeInfoProviderIllegalStateAttribute", null));
}
}
/**
* Throws a {@link IllegalStateException} if we are not in
* the startElement or endElement callbacks. the JAXP API requires
* this for the public methods which access element type information.
*/
private void checkStateElement() {
if (!fInStartElement && !fInEndElement) {
throw new IllegalStateException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(),
"TypeInfoProviderIllegalStateElement", null));
}
}
public TypeInfo getAttributeTypeInfo(int index) {
checkStateAttribute();
return getAttributeType(index);
}
private TypeInfo getAttributeType( int index ) {
checkStateAttribute();
if (index < 0 || fAttributes.getLength() <= index) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
Augmentations augs = fAttributes.getAugmentations(index);
if (augs == null) {
return null;
}
AttributePSVI psvi = (AttributePSVI)augs.getItem(Constants.ATTRIBUTE_PSVI);
return getTypeInfoFromPSVI(psvi);
}
public TypeInfo getAttributeTypeInfo(String attributeUri, String attributeLocalName) {
checkStateAttribute();
return getAttributeTypeInfo(fAttributes.getIndex(attributeUri,attributeLocalName));
}
public TypeInfo getAttributeTypeInfo(String attributeQName) {
checkStateAttribute();
return getAttributeTypeInfo(fAttributes.getIndex(attributeQName));
}
public TypeInfo getElementTypeInfo() {
checkStateElement();
if (fElementAugs == null) {
return null;
}
ElementPSVI psvi = (ElementPSVI)fElementAugs.getItem(Constants.ELEMENT_PSVI);
return getTypeInfoFromPSVI(psvi);
}
private TypeInfo getTypeInfoFromPSVI(ItemPSVI psvi) {
if (psvi == null) {
return null;
}
// TODO: make sure if this is correct.
// TODO: since the number of types in a schema is quite limited,
// TypeInfoImpl should be pooled. Even better, it should be a part
// of the element decl.
if (psvi.getValidity() == ItemPSVI.VALIDITY_VALID) {
XSTypeDefinition t = psvi.getMemberTypeDefinition();
if (t != null) {
return (t instanceof TypeInfo) ? (TypeInfo) t : null;
}
}
XSTypeDefinition t = psvi.getTypeDefinition();
// TODO: can t be null?
if (t != null) {
return (t instanceof TypeInfo) ? (TypeInfo) t : null;
}
return null;
}
public boolean isIdAttribute(int index) {
checkStateAttribute();
XSSimpleType type = (XSSimpleType)getAttributeType(index);
if (type == null) {
return false;
}
return type.isIDType();
}
public boolean isSpecified(int index) {
checkStateAttribute();
return fAttributes.isSpecified(index);
}
/*
* Other methods
*/
// PSVIProvider support
ElementPSVI getElementPSVI() {
return (fElementAugs != null) ? (ElementPSVI) fElementAugs.getItem(Constants.ELEMENT_PSVI) : null;
}
AttributePSVI getAttributePSVI(int index) {
if (fAttributes != null) {
Augmentations augs = fAttributes.getAugmentations(index);
if (augs != null) {
return (AttributePSVI) augs.getItem(Constants.ATTRIBUTE_PSVI);
}
}
return null;
}
AttributePSVI getAttributePSVIByName(String uri, String localname) {
if (fAttributes != null) {
Augmentations augs = fAttributes.getAugmentations(uri, localname);
if (augs != null) {
return (AttributePSVI) augs.getItem(Constants.ATTRIBUTE_PSVI);
}
}
return null;
}
}
/** SAX adapter for an LSResourceResolver. */
private final ResolutionForwarder fResolutionForwarder = new ResolutionForwarder(null);
static final class ResolutionForwarder
implements EntityResolver2 {
//
// Data
//
/** XML 1.0 type constant according to DOM L3 LS REC spec "http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/" */
private static final String XML_TYPE = "http://www.w3.org/TR/REC-xml";
/** The DOM entity resolver. */
protected LSResourceResolver fEntityResolver;
//
// Constructors
//
/** Default constructor. */
public ResolutionForwarder() {}
/** Wraps the specified DOM entity resolver. */
public ResolutionForwarder(LSResourceResolver entityResolver) {
setEntityResolver(entityResolver);
}
//
// Public methods
//
/** Sets the DOM entity resolver. */
public void setEntityResolver(LSResourceResolver entityResolver) {
fEntityResolver = entityResolver;
} // setEntityResolver(LSResourceResolver)
/** Returns the DOM entity resolver. */
public LSResourceResolver getEntityResolver() {
return fEntityResolver;
} // getEntityResolver():LSResourceResolver
/**
* Always returns <code>null</code>. An LSResourceResolver has no corresponding method.
*/
public InputSource getExternalSubset(String name, String baseURI)
throws SAXException, IOException {
return null;
}
/**
* Resolves the given resource and adapts the <code>LSInput</code>
* returned into an <code>InputSource</code>.
*/
public InputSource resolveEntity(String name, String publicId,
String baseURI, String systemId) throws SAXException, IOException {
if (fEntityResolver != null) {
LSInput lsInput = fEntityResolver.resolveResource(XML_TYPE, null, publicId, systemId, baseURI);
if (lsInput != null) {
final String pubId = lsInput.getPublicId();
final String sysId = lsInput.getSystemId();
final String baseSystemId = lsInput.getBaseURI();
final Reader charStream = lsInput.getCharacterStream();
final InputStream byteStream = lsInput.getByteStream();
final String data = lsInput.getStringData();
final String encoding = lsInput.getEncoding();
/**
* An LSParser looks at inputs specified in LSInput in
* the following order: characterStream, byteStream,
* stringData, systemId, publicId. For consistency
* with the DOM Level 3 Load and Save Recommendation
* use the same lookup order here.
*/
InputSource inputSource = new InputSource();
inputSource.setPublicId(pubId);
inputSource.setSystemId((baseSystemId != null) ? resolveSystemId(sysId, baseSystemId) : sysId);
if (charStream != null) {
inputSource.setCharacterStream(charStream);
}
else if (byteStream != null) {
inputSource.setByteStream(byteStream);
}
else if (data != null && data.length() != 0) {
inputSource.setCharacterStream(new StringReader(data));
}
inputSource.setEncoding(encoding);
return inputSource;
}
}
return null;
}
/** Delegates to EntityResolver2.resolveEntity(String, String, String, String). */
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
return resolveEntity(null, publicId, null, systemId);
}
/** Resolves a system identifier against a base URI. */
private String resolveSystemId(String systemId, String baseURI) {
try {
return XMLEntityManager.expandSystemId(systemId, baseURI, false);
}
// In the event that resolution failed against the
// base URI, just return the system id as is. There's not
// much else we can do.
catch (URI.MalformedURIException ex) {
return systemId;
}
}
}
}
| true | true | public void validate(Source source, Result result)
throws SAXException, IOException {
if (result instanceof SAXResult || result == null) {
final SAXSource saxSource = (SAXSource) source;
final SAXResult saxResult = (SAXResult) result;
LexicalHandler lh = null;
if (result != null) {
ContentHandler ch = saxResult.getHandler();
lh = saxResult.getLexicalHandler();
/** If the lexical handler is not set try casting the ContentHandler. **/
if (lh == null && ch instanceof LexicalHandler) {
lh = (LexicalHandler) ch;
}
setContentHandler(ch);
}
XMLReader reader = null;
try {
reader = saxSource.getXMLReader();
if (reader == null) {
// create one now
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
try {
reader = spf.newSAXParser().getXMLReader();
// If this is a Xerces SAX parser, set the security manager if there is one
if (reader instanceof org.apache.xerces.parsers.SAXParser) {
SecurityManager securityManager = (SecurityManager) fComponentManager.getProperty(SECURITY_MANAGER);
if (securityManager != null) {
try {
reader.setProperty(SECURITY_MANAGER, securityManager);
}
// Ignore the exception if the security manager cannot be set.
catch (SAXException exc) {}
}
}
}
catch (Exception e) {
// this is impossible, but better safe than sorry
throw new FactoryConfigurationError(e);
}
}
// If XML names and Namespace URIs are already internalized we
// can avoid running them through the SymbolTable.
try {
fStringsInternalized = reader.getFeature(STRING_INTERNING);
}
catch (SAXException exc) {
// The feature isn't recognized or getting it is not supported.
// In either case, assume that strings are not internalized.
fStringsInternalized = false;
}
ErrorHandler errorHandler = fComponentManager.getErrorHandler();
reader.setErrorHandler(errorHandler != null ? errorHandler : DraconianErrorHandler.getInstance());
reader.setEntityResolver(fResolutionForwarder);
fResolutionForwarder.setEntityResolver(fComponentManager.getResourceResolver());
reader.setContentHandler(this);
reader.setDTDHandler(this);
try {
reader.setProperty(LEXICAL_HANDLER, lh);
}
// Ignore the exception if the lexical handler cannot be set.
catch (SAXException exc) {}
InputSource is = saxSource.getInputSource();
reader.parse(is);
}
finally {
// Release the reference to user's ContentHandler ASAP
setContentHandler(null);
// Disconnect the validator and other objects from the XMLReader
if (reader != null) {
try {
reader.setContentHandler(null);
reader.setDTDHandler(null);
reader.setErrorHandler(null);
reader.setEntityResolver(null);
fResolutionForwarder.setEntityResolver(null);
reader.setProperty(LEXICAL_HANDLER, null);
}
// Ignore the exception if the lexical handler cannot be unset.
catch (Exception exc) {}
}
}
return;
}
throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(),
"SourceResultMismatch",
new Object [] {source.getClass().getName(), result.getClass().getName()}));
}
| public void validate(Source source, Result result)
throws SAXException, IOException {
if (result instanceof SAXResult || result == null) {
final SAXSource saxSource = (SAXSource) source;
final SAXResult saxResult = (SAXResult) result;
LexicalHandler lh = null;
if (result != null) {
ContentHandler ch = saxResult.getHandler();
lh = saxResult.getLexicalHandler();
/** If the lexical handler is not set try casting the ContentHandler. **/
if (lh == null && ch instanceof LexicalHandler) {
lh = (LexicalHandler) ch;
}
setContentHandler(ch);
}
XMLReader reader = null;
try {
reader = saxSource.getXMLReader();
if (reader == null) {
// create one now
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
try {
reader = spf.newSAXParser().getXMLReader();
// If this is a Xerces SAX parser, set the security manager if there is one
if (reader instanceof org.apache.xerces.parsers.SAXParser) {
Object securityManager = fComponentManager.getProperty(SECURITY_MANAGER);
if (securityManager != null) {
try {
reader.setProperty(SECURITY_MANAGER, securityManager);
}
// Ignore the exception if the security manager cannot be set.
catch (SAXException exc) {}
}
}
}
catch (Exception e) {
// this is impossible, but better safe than sorry
throw new FactoryConfigurationError(e);
}
}
// If XML names and Namespace URIs are already internalized we
// can avoid running them through the SymbolTable.
try {
fStringsInternalized = reader.getFeature(STRING_INTERNING);
}
catch (SAXException exc) {
// The feature isn't recognized or getting it is not supported.
// In either case, assume that strings are not internalized.
fStringsInternalized = false;
}
ErrorHandler errorHandler = fComponentManager.getErrorHandler();
reader.setErrorHandler(errorHandler != null ? errorHandler : DraconianErrorHandler.getInstance());
reader.setEntityResolver(fResolutionForwarder);
fResolutionForwarder.setEntityResolver(fComponentManager.getResourceResolver());
reader.setContentHandler(this);
reader.setDTDHandler(this);
try {
reader.setProperty(LEXICAL_HANDLER, lh);
}
// Ignore the exception if the lexical handler cannot be set.
catch (SAXException exc) {}
InputSource is = saxSource.getInputSource();
reader.parse(is);
}
finally {
// Release the reference to user's ContentHandler ASAP
setContentHandler(null);
// Disconnect the validator and other objects from the XMLReader
if (reader != null) {
try {
reader.setContentHandler(null);
reader.setDTDHandler(null);
reader.setErrorHandler(null);
reader.setEntityResolver(null);
fResolutionForwarder.setEntityResolver(null);
reader.setProperty(LEXICAL_HANDLER, null);
}
// Ignore the exception if the lexical handler cannot be unset.
catch (Exception exc) {}
}
}
return;
}
throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(),
"SourceResultMismatch",
new Object [] {source.getClass().getName(), result.getClass().getName()}));
}
|
diff --git a/src/java/org/infoglue/deliver/taglib/common/XSLTransformTag.java b/src/java/org/infoglue/deliver/taglib/common/XSLTransformTag.java
index aa23e6870..1f65f6db6 100755
--- a/src/java/org/infoglue/deliver/taglib/common/XSLTransformTag.java
+++ b/src/java/org/infoglue/deliver/taglib/common/XSLTransformTag.java
@@ -1,342 +1,342 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
* Place, Suite 330 / Boston, MA 02111-1307 / USA.
*
* ===============================================================================
*/
package org.infoglue.deliver.taglib.common;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.tinytree.TinyBuilder;
import net.sf.saxon.tinytree.TinyDocumentImpl;
import org.apache.log4j.Logger;
import org.infoglue.deliver.taglib.TemplateControllerTag;
import org.infoglue.deliver.util.CacheController;
import org.infoglue.deliver.util.Timer;
import org.w3c.dom.Document;
/**
* This tag help modifying texts in different ways. An example is to html-encode strings or replace all
* whitespaces with or replacing linebreaks with <br/>
*/
public class XSLTransformTag extends TemplateControllerTag
{
private final static Logger logger = Logger.getLogger(XSLTransformTag.class.getName());
/**
* The universal version identifier.
*/
private static final long serialVersionUID = 8603406098980150888L;
private Object xml;
private String xmlFile;
private String xmlString;
private Object source;
private boolean cacheStyle = true;
private String styleFile;
private String styleString;
private String outputFormat = "string";
private Map parameters = new HashMap();
/**
* Default constructor.
*/
public XSLTransformTag()
{
super();
}
/**
* Initializes the parameters to make it accessible for the children tags (if any).
*
* @return indication of whether to evaluate the body or not.
* @throws JspException if an error occurred while processing this tag.
*/
public int doStartTag() throws JspException
{
return EVAL_BODY_INCLUDE;
}
/**
* Process the end tag. Modifies the string according to settings made.
*
* @return indication of whether to continue evaluating the JSP page.
* @throws JspException if an error occurred while processing this tag.
*/
public int doEndTag() throws JspException
{
Timer timer = new Timer();
java.lang.System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
Source xmlSource = null;
if(xml != null)
{
if(xml instanceof String)
xmlSource = new StreamSource(new StringReader(this.xmlString));
else if(xml instanceof Reader)
xmlSource = new StreamSource((Reader)xml);
}
else if(this.source != null)
{
if(logger.isDebugEnabled())
logger.info("Input:" + this.source.getClass().getName());
if(this.source instanceof DOMResult)
xmlSource = new DOMSource(((DOMResult)this.source).getNode());
else if(this.source instanceof DOMSource)
xmlSource = (DOMSource)this.source;
else if(this.source instanceof SAXSource)
xmlSource = (SAXSource)this.source;
else if(this.source instanceof StreamSource)
xmlSource = (StreamSource)this.source;
else if(this.source instanceof Document)
xmlSource = new DOMSource((Document)this.source);
else if(this.source instanceof NodeInfo)
xmlSource = (Source)this.source;
else if(this.source instanceof TinyDocumentImpl)
xmlSource = (TinyDocumentImpl)this.source;
else
throw new JspException("Bad source - must be either org.w3c.Document or javax.xml.transform.Source");
}
else if(this.xmlFile != null)
{
xmlSource = new StreamSource(new File(this.xmlFile));
}
else if(this.xmlString != null)
{
xmlSource = new StreamSource(new StringReader(this.xmlString));
}
Templates pss = null;
Transformer transformer = null;
try
{
pss = tryCache(this.styleFile, this.styleString, cacheStyle);
transformer = pss.newTransformer();
if(logger.isDebugEnabled())
logger.info("outputFormat:" + this.outputFormat);
if(this.outputFormat.equalsIgnoreCase("string"))
{
java.io.ByteArrayOutputStream outputXmlResult = new java.io.ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(outputXmlResult);
Iterator parametersIterator = parameters.keySet().iterator();
while(parametersIterator.hasNext())
{
String name = (String)parametersIterator.next();
Object value = parameters.get(name);
transformer.setParameter(name, value);
}
transformer.transform(xmlSource, new StreamResult(bos));
bos.close();
String result = outputXmlResult.toString();
setResultAttribute(result);
}
else if(this.outputFormat.equalsIgnoreCase("document"))
{
DOMResult domResult = new DOMResult();
Iterator parametersIterator = parameters.keySet().iterator();
while(parametersIterator.hasNext())
{
String name = (String)parametersIterator.next();
Object value = parameters.get(name);
transformer.setParameter(name, value);
}
transformer.transform(xmlSource, domResult);
setResultAttribute(domResult.getNode());
}
else if(this.outputFormat.equalsIgnoreCase("tinyDocument"))
{
Iterator parametersIterator = parameters.keySet().iterator();
while(parametersIterator.hasNext())
{
String name = (String)parametersIterator.next();
Object value = parameters.get(name);
transformer.setParameter(name, value);
}
TinyBuilder builder = new TinyBuilder();
transformer.transform(xmlSource, builder);
setResultAttribute(builder.getCurrentRoot());
}
if(logger.isInfoEnabled())
timer.printElapsedTime("Saxon Transform to dom document took");
}
catch (Exception e)
{
logger.error("Error transforming with SAXON:" + e.getMessage(), e);
}
finally
{
try
{
transformer.clearParameters();
transformer.reset();
parameters.clear();
}
catch (NoSuchMethodError e)
{
logger.warn("Problem resetting transformer -wrong java version:" + e.getMessage());
}
catch (Exception e)
{
logger.warn("Problem resetting transformer:" + e.getMessage(), e);
}
transformer = null;
pss = null;
xmlSource = null;
this.xml = null;
this.xmlFile = null;
this.source = null;
this.xmlString = null;
this.styleFile = null;
this.styleString = null;
- this.outputFormat = null;
+ this.outputFormat = "string";
this.cacheStyle = true;
java.lang.System.clearProperty("javax.xml.transform.TransformerFactory");
}
return EVAL_PAGE;
}
/**
* Maintain prepared stylesheets in memory for reuse
*/
private synchronized Templates tryCache(String url, String xslString, boolean cacheTemplate) throws Exception
{
Templates x = null;
if(url != null)
{
String path = this.getController().getHttpServletRequest().getRealPath(url);
if (path==null)
{
throw new Exception("Stylesheet " + url + " not found");
}
x = (Templates)CacheController.getCachedObject("XSLTemplatesCache", path);
if (x==null)
{
TransformerFactory factory = TransformerFactory.newInstance();
x = factory.newTemplates(new StreamSource(new File(path)));
if(cacheTemplate)
CacheController.cacheObject("XSLTemplatesCache", path, x);
}
}
else if(xslString != null)
{
x = (Templates)CacheController.getCachedObject("XSLTemplatesCache", xslString.hashCode());
if (x==null)
{
TransformerFactory factory = TransformerFactory.newInstance();
x = factory.newTemplates(new StreamSource(new StringReader(xslString)));
if(cacheTemplate)
CacheController.cacheObject("XSLTemplatesCache", xslString.hashCode(), x);
}
}
return x;
}
public void setXml(String xml) throws JspException
{
this.xml = evaluate("XSLTransform", "xmlFile", xmlFile, Object.class);
}
public void setXmlFile(String xmlFile) throws JspException
{
this.xmlFile = evaluateString("XSLTransform", "xmlFile", xmlFile);
}
public void setXmlString(String xmlString) throws JspException
{
this.xmlString = evaluateString("XSLTransform", "xmlString", xmlString);
}
public void setSource(String source) throws JspException
{
this.source = evaluate("XSLTransform", "source", source, Object.class);
}
public void setStyleFile(String styleFile) throws JspException
{
this.styleFile = evaluateString("XSLTransform", "styleFile", styleFile);
}
public void setStyleString(String styleString) throws JspException
{
this.styleString = evaluateString("XSLTransform", "styleString", styleString);
}
public void setCacheStyle(boolean cacheStyle) throws JspException
{
this.cacheStyle = cacheStyle;
}
public void setOutputFormat(String outputFormat) throws JspException
{
this.outputFormat = evaluateString("XSLTransform", "outputFormat", outputFormat);
}
protected final void addParameter(final String name, final Object value)
{
parameters.put(name, value);
}
}
| true | true | public int doEndTag() throws JspException
{
Timer timer = new Timer();
java.lang.System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
Source xmlSource = null;
if(xml != null)
{
if(xml instanceof String)
xmlSource = new StreamSource(new StringReader(this.xmlString));
else if(xml instanceof Reader)
xmlSource = new StreamSource((Reader)xml);
}
else if(this.source != null)
{
if(logger.isDebugEnabled())
logger.info("Input:" + this.source.getClass().getName());
if(this.source instanceof DOMResult)
xmlSource = new DOMSource(((DOMResult)this.source).getNode());
else if(this.source instanceof DOMSource)
xmlSource = (DOMSource)this.source;
else if(this.source instanceof SAXSource)
xmlSource = (SAXSource)this.source;
else if(this.source instanceof StreamSource)
xmlSource = (StreamSource)this.source;
else if(this.source instanceof Document)
xmlSource = new DOMSource((Document)this.source);
else if(this.source instanceof NodeInfo)
xmlSource = (Source)this.source;
else if(this.source instanceof TinyDocumentImpl)
xmlSource = (TinyDocumentImpl)this.source;
else
throw new JspException("Bad source - must be either org.w3c.Document or javax.xml.transform.Source");
}
else if(this.xmlFile != null)
{
xmlSource = new StreamSource(new File(this.xmlFile));
}
else if(this.xmlString != null)
{
xmlSource = new StreamSource(new StringReader(this.xmlString));
}
Templates pss = null;
Transformer transformer = null;
try
{
pss = tryCache(this.styleFile, this.styleString, cacheStyle);
transformer = pss.newTransformer();
if(logger.isDebugEnabled())
logger.info("outputFormat:" + this.outputFormat);
if(this.outputFormat.equalsIgnoreCase("string"))
{
java.io.ByteArrayOutputStream outputXmlResult = new java.io.ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(outputXmlResult);
Iterator parametersIterator = parameters.keySet().iterator();
while(parametersIterator.hasNext())
{
String name = (String)parametersIterator.next();
Object value = parameters.get(name);
transformer.setParameter(name, value);
}
transformer.transform(xmlSource, new StreamResult(bos));
bos.close();
String result = outputXmlResult.toString();
setResultAttribute(result);
}
else if(this.outputFormat.equalsIgnoreCase("document"))
{
DOMResult domResult = new DOMResult();
Iterator parametersIterator = parameters.keySet().iterator();
while(parametersIterator.hasNext())
{
String name = (String)parametersIterator.next();
Object value = parameters.get(name);
transformer.setParameter(name, value);
}
transformer.transform(xmlSource, domResult);
setResultAttribute(domResult.getNode());
}
else if(this.outputFormat.equalsIgnoreCase("tinyDocument"))
{
Iterator parametersIterator = parameters.keySet().iterator();
while(parametersIterator.hasNext())
{
String name = (String)parametersIterator.next();
Object value = parameters.get(name);
transformer.setParameter(name, value);
}
TinyBuilder builder = new TinyBuilder();
transformer.transform(xmlSource, builder);
setResultAttribute(builder.getCurrentRoot());
}
if(logger.isInfoEnabled())
timer.printElapsedTime("Saxon Transform to dom document took");
}
catch (Exception e)
{
logger.error("Error transforming with SAXON:" + e.getMessage(), e);
}
finally
{
try
{
transformer.clearParameters();
transformer.reset();
parameters.clear();
}
catch (NoSuchMethodError e)
{
logger.warn("Problem resetting transformer -wrong java version:" + e.getMessage());
}
catch (Exception e)
{
logger.warn("Problem resetting transformer:" + e.getMessage(), e);
}
transformer = null;
pss = null;
xmlSource = null;
this.xml = null;
this.xmlFile = null;
this.source = null;
this.xmlString = null;
this.styleFile = null;
this.styleString = null;
this.outputFormat = null;
this.cacheStyle = true;
java.lang.System.clearProperty("javax.xml.transform.TransformerFactory");
}
return EVAL_PAGE;
}
| public int doEndTag() throws JspException
{
Timer timer = new Timer();
java.lang.System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
Source xmlSource = null;
if(xml != null)
{
if(xml instanceof String)
xmlSource = new StreamSource(new StringReader(this.xmlString));
else if(xml instanceof Reader)
xmlSource = new StreamSource((Reader)xml);
}
else if(this.source != null)
{
if(logger.isDebugEnabled())
logger.info("Input:" + this.source.getClass().getName());
if(this.source instanceof DOMResult)
xmlSource = new DOMSource(((DOMResult)this.source).getNode());
else if(this.source instanceof DOMSource)
xmlSource = (DOMSource)this.source;
else if(this.source instanceof SAXSource)
xmlSource = (SAXSource)this.source;
else if(this.source instanceof StreamSource)
xmlSource = (StreamSource)this.source;
else if(this.source instanceof Document)
xmlSource = new DOMSource((Document)this.source);
else if(this.source instanceof NodeInfo)
xmlSource = (Source)this.source;
else if(this.source instanceof TinyDocumentImpl)
xmlSource = (TinyDocumentImpl)this.source;
else
throw new JspException("Bad source - must be either org.w3c.Document or javax.xml.transform.Source");
}
else if(this.xmlFile != null)
{
xmlSource = new StreamSource(new File(this.xmlFile));
}
else if(this.xmlString != null)
{
xmlSource = new StreamSource(new StringReader(this.xmlString));
}
Templates pss = null;
Transformer transformer = null;
try
{
pss = tryCache(this.styleFile, this.styleString, cacheStyle);
transformer = pss.newTransformer();
if(logger.isDebugEnabled())
logger.info("outputFormat:" + this.outputFormat);
if(this.outputFormat.equalsIgnoreCase("string"))
{
java.io.ByteArrayOutputStream outputXmlResult = new java.io.ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(outputXmlResult);
Iterator parametersIterator = parameters.keySet().iterator();
while(parametersIterator.hasNext())
{
String name = (String)parametersIterator.next();
Object value = parameters.get(name);
transformer.setParameter(name, value);
}
transformer.transform(xmlSource, new StreamResult(bos));
bos.close();
String result = outputXmlResult.toString();
setResultAttribute(result);
}
else if(this.outputFormat.equalsIgnoreCase("document"))
{
DOMResult domResult = new DOMResult();
Iterator parametersIterator = parameters.keySet().iterator();
while(parametersIterator.hasNext())
{
String name = (String)parametersIterator.next();
Object value = parameters.get(name);
transformer.setParameter(name, value);
}
transformer.transform(xmlSource, domResult);
setResultAttribute(domResult.getNode());
}
else if(this.outputFormat.equalsIgnoreCase("tinyDocument"))
{
Iterator parametersIterator = parameters.keySet().iterator();
while(parametersIterator.hasNext())
{
String name = (String)parametersIterator.next();
Object value = parameters.get(name);
transformer.setParameter(name, value);
}
TinyBuilder builder = new TinyBuilder();
transformer.transform(xmlSource, builder);
setResultAttribute(builder.getCurrentRoot());
}
if(logger.isInfoEnabled())
timer.printElapsedTime("Saxon Transform to dom document took");
}
catch (Exception e)
{
logger.error("Error transforming with SAXON:" + e.getMessage(), e);
}
finally
{
try
{
transformer.clearParameters();
transformer.reset();
parameters.clear();
}
catch (NoSuchMethodError e)
{
logger.warn("Problem resetting transformer -wrong java version:" + e.getMessage());
}
catch (Exception e)
{
logger.warn("Problem resetting transformer:" + e.getMessage(), e);
}
transformer = null;
pss = null;
xmlSource = null;
this.xml = null;
this.xmlFile = null;
this.source = null;
this.xmlString = null;
this.styleFile = null;
this.styleString = null;
this.outputFormat = "string";
this.cacheStyle = true;
java.lang.System.clearProperty("javax.xml.transform.TransformerFactory");
}
return EVAL_PAGE;
}
|
diff --git a/cost-server/src/main/java/com/unisys/ch/jax/costserver/controller/CostController.java b/cost-server/src/main/java/com/unisys/ch/jax/costserver/controller/CostController.java
index 66c6b32..58cffed 100644
--- a/cost-server/src/main/java/com/unisys/ch/jax/costserver/controller/CostController.java
+++ b/cost-server/src/main/java/com/unisys/ch/jax/costserver/controller/CostController.java
@@ -1,85 +1,85 @@
package com.unisys.ch.jax.costserver.controller;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.unisys.ch.jax.costserver.model.Cost;
import com.unisys.ch.jax.costserver.service.CostService;
@Controller
@RequestMapping("/costs")
public class CostController {
@Autowired
CostService toDoService;
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Cost read(@PathVariable Long id) {
Cost todo = toDoService.findById(id);
if (todo == null) {
throw new IllegalArgumentException(String.format("Unable to find ToDo with id: %d", id));
}
return todo;
}
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public Collection<Cost> list(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "pageSize", required = false) Integer pageSize) {
if (page == null) {
page = 1;
}
if (pageSize == null){
- pageSize = Integer.MAX_VALUE;
+ pageSize = 100000;
}
return toDoService.findAll(pageSize * (page - 1), pageSize);
}
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public Cost create(@RequestBody Cost todo) {
return toDoService.save(todo);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void update(@PathVariable(value = "id") Long id, @RequestBody Cost todo) {
if (todo.getId() == null || !todo.getId().equals(id)) {
throw new IllegalArgumentException(String.format("The id of given ToDo doesn't match URL id: %d", id));
}
toDoService.save(todo);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete(@PathVariable(value = "id") Long id) {
toDoService.delete(id);
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleClientErrors(Exception ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
return String.format("<html><head></head><body><h1>Client Error occured: %s</h1><p>%s</p>", ex.getMessage(), sw.toString());
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public String handleServerErrors(Exception ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
return String.format("<html><head></head><body><h1>Server Error occured: %s</h1><p>%s</p>", ex.getMessage(), sw.toString());
}
}
| true | true | public Collection<Cost> list(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "pageSize", required = false) Integer pageSize) {
if (page == null) {
page = 1;
}
if (pageSize == null){
pageSize = Integer.MAX_VALUE;
}
return toDoService.findAll(pageSize * (page - 1), pageSize);
}
| public Collection<Cost> list(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "pageSize", required = false) Integer pageSize) {
if (page == null) {
page = 1;
}
if (pageSize == null){
pageSize = 100000;
}
return toDoService.findAll(pageSize * (page - 1), pageSize);
}
|
diff --git a/src/main/java/org/londonsburning/proxy/ProxyPrinterRunner.java b/src/main/java/org/londonsburning/proxy/ProxyPrinterRunner.java
index 544bef8..9aa833e 100644
--- a/src/main/java/org/londonsburning/proxy/ProxyPrinterRunner.java
+++ b/src/main/java/org/londonsburning/proxy/ProxyPrinterRunner.java
@@ -1,45 +1,46 @@
/*
* Copyright (C) 2012 David Hudson
*
* 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.londonsburning.proxy;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Runs the ProxyPrinter.
*/
public final class ProxyPrinterRunner {
/**
*
*/
private ProxyPrinterRunner() {
}
/**
* @param args FileName
*/
public static void main(final String[] args) {
String applicationContext = "applicationContext.xml";
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(applicationContext);
FlagParser flagParser = (FlagParser) context.getBean("flagParser");
flagParser.setFlags(args);
flagParser.parse();
ProxyPrinter printer =
(ProxyPrinter) context.getBean("proxyPrinter");
printer.printProxies(flagParser);
+ context.close();
}
}
| true | true | public static void main(final String[] args) {
String applicationContext = "applicationContext.xml";
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(applicationContext);
FlagParser flagParser = (FlagParser) context.getBean("flagParser");
flagParser.setFlags(args);
flagParser.parse();
ProxyPrinter printer =
(ProxyPrinter) context.getBean("proxyPrinter");
printer.printProxies(flagParser);
}
| public static void main(final String[] args) {
String applicationContext = "applicationContext.xml";
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(applicationContext);
FlagParser flagParser = (FlagParser) context.getBean("flagParser");
flagParser.setFlags(args);
flagParser.parse();
ProxyPrinter printer =
(ProxyPrinter) context.getBean("proxyPrinter");
printer.printProxies(flagParser);
context.close();
}
|
diff --git a/graylog2-server/src/test/java/org/graylog2/plugin/MessageTest.java b/graylog2-server/src/test/java/org/graylog2/plugin/MessageTest.java
index d7701ab28..e14eecd83 100644
--- a/graylog2-server/src/test/java/org/graylog2/plugin/MessageTest.java
+++ b/graylog2-server/src/test/java/org/graylog2/plugin/MessageTest.java
@@ -1,71 +1,71 @@
/**
* Copyright 2013 Lennart Koopmann <[email protected]>
*
* This file is part of Graylog2.
*
* Graylog2 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.
*
* Graylog2 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 Graylog2. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.graylog2.plugin;
import org.joda.time.DateTime;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;
/**
* @author Lennart Koopmann <[email protected]>
*/
public class MessageTest {
@Test
public void testAddFieldDoesOnlyAcceptAlphanumericKeys() throws Exception {
Message m = new Message("foo", "bar", new DateTime());
m.addField("some_thing", "bar");
assertEquals("bar", m.getField("some_thing"));
m = new Message("foo", "bar", new DateTime());
m.addField("some-thing", "bar");
- assertNull(m.getField("some-thing"));
+ assertEquals("bar", m.getField("some-thing"));
m = new Message("foo", "bar", new DateTime());
m.addField("somethin$g", "bar");
assertNull(m.getField("somethin$g"));
m = new Message("foo", "bar", new DateTime());
m.addField("someäthing", "bar");
assertNull(m.getField("someäthing"));
}
@Test
public void testAddFieldTrimsValue() throws Exception {
Message m = new Message("foo", "bar", new DateTime());
m.addField("something", " bar ");
assertEquals("bar", m.getField("something"));
m.addField("something2", " bar");
assertEquals("bar", m.getField("something2"));
m.addField("something3", "bar ");
assertEquals("bar", m.getField("something3"));
}
@Test
public void testAddFieldWorksWithIntegers() throws Exception {
Message m = new Message("foo", "bar", new DateTime());
m.addField("something", 3);
assertEquals(3, m.getField("something"));
}
}
| true | true | public void testAddFieldDoesOnlyAcceptAlphanumericKeys() throws Exception {
Message m = new Message("foo", "bar", new DateTime());
m.addField("some_thing", "bar");
assertEquals("bar", m.getField("some_thing"));
m = new Message("foo", "bar", new DateTime());
m.addField("some-thing", "bar");
assertNull(m.getField("some-thing"));
m = new Message("foo", "bar", new DateTime());
m.addField("somethin$g", "bar");
assertNull(m.getField("somethin$g"));
m = new Message("foo", "bar", new DateTime());
m.addField("someäthing", "bar");
assertNull(m.getField("someäthing"));
}
| public void testAddFieldDoesOnlyAcceptAlphanumericKeys() throws Exception {
Message m = new Message("foo", "bar", new DateTime());
m.addField("some_thing", "bar");
assertEquals("bar", m.getField("some_thing"));
m = new Message("foo", "bar", new DateTime());
m.addField("some-thing", "bar");
assertEquals("bar", m.getField("some-thing"));
m = new Message("foo", "bar", new DateTime());
m.addField("somethin$g", "bar");
assertNull(m.getField("somethin$g"));
m = new Message("foo", "bar", new DateTime());
m.addField("someäthing", "bar");
assertNull(m.getField("someäthing"));
}
|
diff --git a/src/com/android/camera/Util.java b/src/com/android/camera/Util.java
index d6ebb0a5..c7d85830 100644
--- a/src/com/android/camera/Util.java
+++ b/src/com/android/camera/Util.java
@@ -1,718 +1,718 @@
/*
* 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.camera;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.admin.DevicePolicyManager;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
/**
* Collection of utility functions used in this package.
*/
public class Util {
private static final String TAG = "Util";
private static final int DIRECTION_LEFT = 0;
private static final int DIRECTION_RIGHT = 1;
private static final int DIRECTION_UP = 2;
private static final int DIRECTION_DOWN = 3;
// The brightness setting used when it is set to automatic in the system.
// The reason why it is set to 0.7 is just because 1.0 is too bright.
// Use the same setting among the Camera, VideoCamera and Panorama modes.
private static final float DEFAULT_CAMERA_BRIGHTNESS = 0.7f;
// Orientation hysteresis amount used in rounding, in degrees
public static final int ORIENTATION_HYSTERESIS = 5;
public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
// Private intent extras. Test only.
private static final String EXTRAS_CAMERA_FACING =
"android.intent.extras.CAMERA_FACING";
private static boolean sIsTabletUI;
private static float sPixelDensity = 1;
private static ImageFileNamer sImageFileNamer;
private Util() {
}
public static void initialize(Context context) {
sIsTabletUI = (context.getResources().getConfiguration().smallestScreenWidthDp >= 600);
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager)
context.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
sPixelDensity = metrics.density;
sImageFileNamer = new ImageFileNamer(
context.getString(R.string.image_file_name_format));
}
public static boolean isTabletUI() {
return sIsTabletUI;
}
public static int dpToPixel(int dp) {
return Math.round(sPixelDensity * dp);
}
// Rotates the bitmap by the specified degree.
// If a new bitmap is created, the original bitmap is recycled.
public static Bitmap rotate(Bitmap b, int degrees) {
return rotateAndMirror(b, degrees, false);
}
// Rotates and/or mirrors the bitmap. If a new bitmap is created, the
// original bitmap is recycled.
public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) {
if ((degrees != 0 || mirror) && b != null) {
Matrix m = new Matrix();
// Mirror first.
// horizontal flip + rotation = -rotation + horizontal flip
if (mirror) {
m.postScale(-1, 1);
degrees = (degrees + 360) % 360;
if (degrees == 0 || degrees == 180) {
m.postTranslate((float) b.getWidth(), 0);
} else if (degrees == 90 || degrees == 270) {
m.postTranslate((float) b.getHeight(), 0);
} else {
throw new IllegalArgumentException("Invalid degrees=" + degrees);
}
}
if (degrees != 0) {
// clockwise
m.postRotate(degrees,
(float) b.getWidth() / 2, (float) b.getHeight() / 2);
}
try {
Bitmap b2 = Bitmap.createBitmap(
b, 0, 0, b.getWidth(), b.getHeight(), m, true);
if (b != b2) {
b.recycle();
b = b2;
}
} catch (OutOfMemoryError ex) {
// We have no memory to rotate. Return the original bitmap.
}
}
return b;
}
/*
* Compute the sample size as a function of minSideLength
* and maxNumOfPixels.
* minSideLength is used to specify that minimal width or height of a
* bitmap.
* maxNumOfPixels is used to specify the maximal size in pixels that is
* tolerable in terms of memory usage.
*
* The function returns a sample size based on the constraints.
* Both size and minSideLength can be passed in as -1
* which indicates no care of the corresponding constraint.
* The functions prefers returning a sample size that
* generates a smaller bitmap, unless minSideLength = -1.
*
* Also, the function rounds up the sample size to a power of 2 or multiple
* of 8 because BitmapFactory only honors sample size this way.
* For example, BitmapFactory downsamples an image by 2 even though the
* request is 3. So we round up the sample size to avoid OOM.
*/
public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels < 0) ? 1 :
(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength < 0) ? 128 :
(int) Math.min(Math.floor(w / minSideLength),
Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if (maxNumOfPixels < 0 && minSideLength < 0) {
return 1;
} else if (minSideLength < 0) {
return lowerBound;
} else {
return upperBound;
}
}
public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
options);
if (options.mCancel || options.outWidth == -1
|| options.outHeight == -1) {
return null;
}
options.inSampleSize = computeSampleSize(
options, -1, maxNumOfPixels);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
options);
} catch (OutOfMemoryError ex) {
Log.e(TAG, "Got oom exception ", ex);
return null;
}
}
public static void closeSilently(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (Throwable t) {
// do nothing
}
}
public static void Assert(boolean cond) {
if (!cond) {
throw new AssertionError();
}
}
public static android.hardware.Camera openCamera(Activity activity, int cameraId)
throws CameraHardwareException, CameraDisabledException {
// Check if device policy has disabled the camera.
DevicePolicyManager dpm = (DevicePolicyManager) activity.getSystemService(
Context.DEVICE_POLICY_SERVICE);
if (dpm.getCameraDisabled(null)) {
throw new CameraDisabledException();
}
try {
return CameraHolder.instance().open(cameraId);
} catch (CameraHardwareException e) {
// In eng build, we throw the exception so that test tool
// can detect it and report it
if ("eng".equals(Build.TYPE)) {
throw new RuntimeException("openCamera failed", e);
} else {
throw e;
}
}
}
public static void showErrorAndFinish(final Activity activity, int msgId) {
DialogInterface.OnClickListener buttonListener =
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
activity.finish();
}
};
new AlertDialog.Builder(activity)
.setCancelable(false)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle(R.string.camera_error_title)
.setMessage(msgId)
.setNeutralButton(R.string.dialog_ok, buttonListener)
.show();
}
public static <T> T checkNotNull(T object) {
if (object == null) throw new NullPointerException();
return object;
}
public static boolean equals(Object a, Object b) {
return (a == b) || (a == null ? false : a.equals(b));
}
public static int nextPowerOf2(int n) {
n -= 1;
n |= n >>> 16;
n |= n >>> 8;
n |= n >>> 4;
n |= n >>> 2;
n |= n >>> 1;
return n + 1;
}
public static float distance(float x, float y, float sx, float sy) {
float dx = x - sx;
float dy = y - sy;
return (float) Math.sqrt(dx * dx + dy * dy);
}
public static int clamp(int x, int min, int max) {
if (x > max) return max;
if (x < min) return min;
return x;
}
public static int getDisplayRotation(Activity activity) {
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
switch (rotation) {
case Surface.ROTATION_0: return 0;
case Surface.ROTATION_90: return 90;
case Surface.ROTATION_180: return 180;
case Surface.ROTATION_270: return 270;
}
return 0;
}
public static int getDisplayOrientation(int degrees, int cameraId) {
// See android.hardware.Camera.setDisplayOrientation for
// documentation.
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
return result;
}
public static int getCameraOrientation(int cameraId) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
return info.orientation;
}
public static int roundOrientation(int orientation, int orientationHistory) {
boolean changeOrientation = false;
if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) {
changeOrientation = true;
} else {
int dist = Math.abs(orientation - orientationHistory);
dist = Math.min( dist, 360 - dist );
changeOrientation = ( dist >= 45 + ORIENTATION_HYSTERESIS );
}
if (changeOrientation) {
return ((orientation + 45) / 90 * 90) % 360;
}
return orientationHistory;
}
public static Size getOptimalPreviewSize(Activity currentActivity,
List<Size> sizes, double targetRatio) {
- // Use a very small tolerance because we want an exact match.
- final double ASPECT_TOLERANCE = 0.001;
+ // Not too small tolerance, some camera use 848, 854 or 864 for 480p
+ final double ASPECT_TOLERANCE = 0.05;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
// Because of bugs of overlay and layout, we sometimes will try to
// layout the viewfinder in the portrait orientation and thus get the
// wrong size of mSurfaceView. When we change the preview size, the
// new overlay will be created before the old one closed, which causes
// an exception. For now, just get the screen size
Display display = currentActivity.getWindowManager().getDefaultDisplay();
int targetHeight = Math.min(display.getHeight(), display.getWidth());
if (targetHeight <= 0) {
// We don't know the size of SurfaceView, use screen height
targetHeight = display.getHeight();
}
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio. This should not happen.
// Ignore the requirement.
if (optimalSize == null) {
Log.w(TAG, "No preview size match the aspect ratio");
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
// Returns the largest picture size which matches the given aspect ratio.
public static Size getOptimalVideoSnapshotPictureSize(
List<Size> sizes, double targetRatio) {
// Use a very small tolerance because we want an exact match.
final double ASPECT_TOLERANCE = 0.001;
if (sizes == null) return null;
Size optimalSize = null;
// Try to find a size matches aspect ratio and has the largest width
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (optimalSize == null || size.width > optimalSize.width) {
optimalSize = size;
}
}
// Cannot find one that matches the aspect ratio. This should not happen.
// Ignore the requirement.
if (optimalSize == null) {
Log.w(TAG, "No picture size match the aspect ratio");
for (Size size : sizes) {
if (optimalSize == null || size.width > optimalSize.width) {
optimalSize = size;
}
}
}
return optimalSize;
}
public static void dumpParameters(Parameters parameters) {
String flattened = parameters.flatten();
StringTokenizer tokenizer = new StringTokenizer(flattened, ";");
Log.d(TAG, "Dump all camera parameters:");
while (tokenizer.hasMoreElements()) {
Log.d(TAG, tokenizer.nextToken());
}
}
/**
* Returns whether the device is voice-capable (meaning, it can do MMS).
*/
public static boolean isMmsCapable(Context context) {
TelephonyManager telephonyManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager == null) {
return false;
}
try {
Class partypes[] = new Class[0];
Method sIsVoiceCapable = TelephonyManager.class.getMethod(
"isVoiceCapable", partypes);
Object arglist[] = new Object[0];
Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist);
return (Boolean) retobj;
} catch (java.lang.reflect.InvocationTargetException ite) {
// Failure, must be another device.
// Assume that it is voice capable.
} catch (IllegalAccessException iae) {
// Failure, must be an other device.
// Assume that it is voice capable.
} catch (NoSuchMethodException nsme) {
}
return true;
}
// This is for test only. Allow the camera to launch the specific camera.
public static int getCameraFacingIntentExtras(Activity currentActivity) {
int cameraId = -1;
int intentCameraId =
currentActivity.getIntent().getIntExtra(Util.EXTRAS_CAMERA_FACING, -1);
if (isFrontCameraIntent(intentCameraId)) {
// Check if the front camera exist
int frontCameraId = CameraHolder.instance().getFrontCameraId();
if (frontCameraId != -1) {
cameraId = frontCameraId;
}
} else if (isBackCameraIntent(intentCameraId)) {
// Check if the back camera exist
int backCameraId = CameraHolder.instance().getBackCameraId();
if (backCameraId != -1) {
cameraId = backCameraId;
}
}
return cameraId;
}
private static boolean isFrontCameraIntent(int intentCameraId) {
return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
}
private static boolean isBackCameraIntent(int intentCameraId) {
return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);
}
private static int mLocation[] = new int[2];
// This method is not thread-safe.
public static boolean pointInView(float x, float y, View v) {
v.getLocationInWindow(mLocation);
return x >= mLocation[0] && x < (mLocation[0] + v.getWidth())
&& y >= mLocation[1] && y < (mLocation[1] + v.getHeight());
}
public static boolean isUriValid(Uri uri, ContentResolver resolver) {
if (uri == null) return false;
try {
ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
if (pfd == null) {
Log.e(TAG, "Fail to open URI. URI=" + uri);
return false;
}
pfd.close();
} catch (IOException ex) {
return false;
}
return true;
}
public static void viewUri(Uri uri, Context context) {
if (!isUriValid(uri, context.getContentResolver())) {
Log.e(TAG, "Uri invalid. uri=" + uri);
return;
}
try {
context.startActivity(new Intent(Util.REVIEW_ACTION, uri));
} catch (ActivityNotFoundException ex) {
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
} catch (ActivityNotFoundException e) {
Log.e(TAG, "review image fail. uri=" + uri, e);
}
}
}
public static void dumpRect(RectF rect, String msg) {
Log.v(TAG, msg + "=(" + rect.left + "," + rect.top
+ "," + rect.right + "," + rect.bottom + ")");
}
public static void rectFToRect(RectF rectF, Rect rect) {
rect.left = Math.round(rectF.left);
rect.top = Math.round(rectF.top);
rect.right = Math.round(rectF.right);
rect.bottom = Math.round(rectF.bottom);
}
public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,
int viewWidth, int viewHeight) {
// Need mirror for front camera.
matrix.setScale(mirror ? -1 : 1, 1);
// This is the value for android.hardware.Camera.setDisplayOrientation.
matrix.postRotate(displayOrientation);
// Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
// UI coordinates range from (0, 0) to (width, height).
matrix.postScale(viewWidth / 2000f, viewHeight / 2000f);
matrix.postTranslate(viewWidth / 2f, viewHeight / 2f);
}
public static String createJpegName(long dateTaken) {
synchronized (sImageFileNamer) {
return sImageFileNamer.generateName(dateTaken);
}
}
public static void broadcastNewPicture(Context context, Uri uri) {
context.sendBroadcast(new Intent(android.hardware.Camera.ACTION_NEW_PICTURE, uri));
// Keep compatibility
context.sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri));
}
public static void fadeIn(View view) {
if (view.getVisibility() == View.VISIBLE) return;
view.setVisibility(View.VISIBLE);
Animation animation = new AlphaAnimation(0F, 1F);
animation.setDuration(400);
view.startAnimation(animation);
}
public static void fadeOut(View view) {
if (view.getVisibility() != View.VISIBLE) return;
Animation animation = new AlphaAnimation(1F, 0F);
animation.setDuration(400);
view.startAnimation(animation);
view.setVisibility(View.GONE);
}
public static void setRotationParameter(Parameters parameters, int cameraId, int orientation) {
// See android.hardware.Camera.Parameters.setRotation for
// documentation.
int rotation = 0;
if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
CameraInfo info = CameraHolder.instance().getCameraInfo()[cameraId];
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
rotation = (info.orientation - orientation + 360) % 360;
} else { // back-facing camera
rotation = (info.orientation + orientation) % 360;
}
}
parameters.setRotation(rotation);
}
public static void setGpsParameters(Parameters parameters, Location loc) {
// Clear previous GPS location from the parameters.
parameters.removeGpsData();
// We always encode GpsTimeStamp
parameters.setGpsTimestamp(System.currentTimeMillis() / 1000);
// Set GPS location.
if (loc != null) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
if (hasLatLon) {
Log.d(TAG, "Set gps location");
parameters.setGpsLatitude(lat);
parameters.setGpsLongitude(lon);
parameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());
if (loc.hasAltitude()) {
parameters.setGpsAltitude(loc.getAltitude());
} else {
// for NETWORK_PROVIDER location provider, we may have
// no altitude information, but the driver needs it, so
// we fake one.
parameters.setGpsAltitude(0);
}
if (loc.getTime() != 0) {
// Location.getTime() is UTC in milliseconds.
// gps-timestamp is UTC in seconds.
long utcTimeSeconds = loc.getTime() / 1000;
parameters.setGpsTimestamp(utcTimeSeconds);
}
} else {
loc = null;
}
}
}
public static void enterLightsOutMode(Window window) {
WindowManager.LayoutParams params = window.getAttributes();
params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
window.setAttributes(params);
}
public static void initializeScreenBrightness(Window win, ContentResolver resolver) {
// Overright the brightness settings if it is automatic
int mode = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
WindowManager.LayoutParams winParams = win.getAttributes();
winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS;
win.setAttributes(winParams);
}
}
private static class ImageFileNamer {
private SimpleDateFormat mFormat;
// The date (in milliseconds) used to generate the last name.
private long mLastDate;
// Number of names generated for the same second.
private int mSameSecondCount;
public ImageFileNamer(String format) {
mFormat = new SimpleDateFormat(format);
}
public String generateName(long dateTaken) {
Date date = new Date(dateTaken);
String result = mFormat.format(date);
// If the last name was generated for the same second,
// we append _1, _2, etc to the name.
if (dateTaken / 1000 == mLastDate / 1000) {
mSameSecondCount++;
result += "_" + mSameSecondCount;
} else {
mLastDate = dateTaken;
mSameSecondCount = 0;
}
return result;
}
}
}
| true | true | public static Size getOptimalPreviewSize(Activity currentActivity,
List<Size> sizes, double targetRatio) {
// Use a very small tolerance because we want an exact match.
final double ASPECT_TOLERANCE = 0.001;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
// Because of bugs of overlay and layout, we sometimes will try to
// layout the viewfinder in the portrait orientation and thus get the
// wrong size of mSurfaceView. When we change the preview size, the
// new overlay will be created before the old one closed, which causes
// an exception. For now, just get the screen size
Display display = currentActivity.getWindowManager().getDefaultDisplay();
int targetHeight = Math.min(display.getHeight(), display.getWidth());
if (targetHeight <= 0) {
// We don't know the size of SurfaceView, use screen height
targetHeight = display.getHeight();
}
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio. This should not happen.
// Ignore the requirement.
if (optimalSize == null) {
Log.w(TAG, "No preview size match the aspect ratio");
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
| public static Size getOptimalPreviewSize(Activity currentActivity,
List<Size> sizes, double targetRatio) {
// Not too small tolerance, some camera use 848, 854 or 864 for 480p
final double ASPECT_TOLERANCE = 0.05;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
// Because of bugs of overlay and layout, we sometimes will try to
// layout the viewfinder in the portrait orientation and thus get the
// wrong size of mSurfaceView. When we change the preview size, the
// new overlay will be created before the old one closed, which causes
// an exception. For now, just get the screen size
Display display = currentActivity.getWindowManager().getDefaultDisplay();
int targetHeight = Math.min(display.getHeight(), display.getWidth());
if (targetHeight <= 0) {
// We don't know the size of SurfaceView, use screen height
targetHeight = display.getHeight();
}
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio. This should not happen.
// Ignore the requirement.
if (optimalSize == null) {
Log.w(TAG, "No preview size match the aspect ratio");
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
|
diff --git a/src/main/java/org/otherobjects/cms/validation/TypeDefConfiguredValidator.java b/src/main/java/org/otherobjects/cms/validation/TypeDefConfiguredValidator.java
index d4f4fcf7..63f096f3 100644
--- a/src/main/java/org/otherobjects/cms/validation/TypeDefConfiguredValidator.java
+++ b/src/main/java/org/otherobjects/cms/validation/TypeDefConfiguredValidator.java
@@ -1,145 +1,145 @@
package org.otherobjects.cms.validation;
import java.util.List;
import javax.annotation.Resource;
import org.otherobjects.cms.OtherObjectsException;
import org.otherobjects.cms.model.BaseNode;
import org.otherobjects.cms.types.PropertyDef;
import org.otherobjects.cms.types.TypeDef;
import org.otherobjects.cms.types.TypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springmodules.validation.valang.ValangValidator;
/**
* Validates objects using their TypeDef.
*
*/
@SuppressWarnings("unchecked")
public class TypeDefConfiguredValidator implements Validator
{
private final Logger logger = LoggerFactory.getLogger(TypeDefConfiguredValidator.class);
@Resource
private TypeService typeService;
public boolean supports(Class clazz)
{
return typeService.getType(clazz) != null || BaseNode.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors)
{
TypeDef typeDef;
if (target instanceof BaseNode)
typeDef = ((BaseNode)target).getTypeDef();
else
typeDef = typeService.getType(target.getClass());
StringBuffer valangRules = new StringBuffer();
for (PropertyDef propertyDef : typeDef.getProperties())
{
String fieldName = propertyDef.getFieldName();
Object value = errors.getFieldValue(fieldName);
if (propertyDef.getType().equals(PropertyDef.LIST))
{
String collectionElementType = propertyDef.getCollectionElementType();
Assert.isTrue(collectionElementType != null, "If this property is a collection the collectionElementType needs to have been set");
if (collectionElementType.equals(PropertyDef.COMPONENT))
{
if (value != null && List.class.isAssignableFrom(value.getClass()))
{
int i = 0;
List<Object> objectList = (List<Object>) value;
for (Object object : objectList)
{
validateComponent(fieldName + "[" + i + "]", propertyDef, object, errors);
i++;
}
}
}
}
else if (propertyDef.getType().equals(PropertyDef.COMPONENT))
{
validateComponent(fieldName, propertyDef, value, errors);
}
else
{
if (propertyDef.isRequired())
ValidationUtils.rejectIfEmptyOrWhitespace(errors, fieldName, "field.required");
int size = propertyDef.getSize();
- if (size > -1)
+ if (size > -1 && value != null)
{
int actualSize = value.toString().length();
if (value != null && actualSize > size)
errors.rejectValue(fieldName, "field.value.too.long", new Object[]{size, actualSize}, "Value too long. Must be less that {0}");
}
// if we have a valang property, insert the fieldName into it and append it to the valang rules buffer
if (StringUtils.hasText(propertyDef.getValang()))
{
// Only replace first one as a convenience. Note ? may appear in function arguments esp in matches(regexp)
valangRules.append(propertyDef.getValang().replaceFirst("\\?", fieldName));
}
}
}
// if there were any valang rules create a valang validator from those
if (valangRules.length() > 0)
{
try
{
//FIXME this is not nice as it is implementation specific
ValangValidator val = new ValangValidator();
String rules = valangRules.toString();
// if(logger.isDebugEnabled())
logger.debug("Valang rules for " + typeDef.getName() + ": " + rules);
val.setValang(rules);
val.afterPropertiesSet();
val.validate(target, errors);
}
catch (Throwable e)
{
throw new OtherObjectsException("Incorrect validation rules on: "+ typeDef.getName(), e);
}
}
}
private void validateComponent(String fieldName, PropertyDef propertyDef, Object valueObject, Errors errors)
{
if (valueObject == null)
{
if (propertyDef.isRequired())
errors.rejectValue(fieldName, "field.required");
return;
}
Assert.notNull(typeService.getType(valueObject.getClass()), "No TypeDef for valueObject of property " + fieldName + ". Perhaps there is a conflicting parameter in the request?");
try
{
errors.pushNestedPath(fieldName);
ValidationUtils.invokeValidator(this, valueObject, errors);
}
finally
{
errors.popNestedPath();
}
}
public void setTypeService(TypeService typeService)
{
this.typeService = typeService;
}
}
| true | true | public void validate(Object target, Errors errors)
{
TypeDef typeDef;
if (target instanceof BaseNode)
typeDef = ((BaseNode)target).getTypeDef();
else
typeDef = typeService.getType(target.getClass());
StringBuffer valangRules = new StringBuffer();
for (PropertyDef propertyDef : typeDef.getProperties())
{
String fieldName = propertyDef.getFieldName();
Object value = errors.getFieldValue(fieldName);
if (propertyDef.getType().equals(PropertyDef.LIST))
{
String collectionElementType = propertyDef.getCollectionElementType();
Assert.isTrue(collectionElementType != null, "If this property is a collection the collectionElementType needs to have been set");
if (collectionElementType.equals(PropertyDef.COMPONENT))
{
if (value != null && List.class.isAssignableFrom(value.getClass()))
{
int i = 0;
List<Object> objectList = (List<Object>) value;
for (Object object : objectList)
{
validateComponent(fieldName + "[" + i + "]", propertyDef, object, errors);
i++;
}
}
}
}
else if (propertyDef.getType().equals(PropertyDef.COMPONENT))
{
validateComponent(fieldName, propertyDef, value, errors);
}
else
{
if (propertyDef.isRequired())
ValidationUtils.rejectIfEmptyOrWhitespace(errors, fieldName, "field.required");
int size = propertyDef.getSize();
if (size > -1)
{
int actualSize = value.toString().length();
if (value != null && actualSize > size)
errors.rejectValue(fieldName, "field.value.too.long", new Object[]{size, actualSize}, "Value too long. Must be less that {0}");
}
// if we have a valang property, insert the fieldName into it and append it to the valang rules buffer
if (StringUtils.hasText(propertyDef.getValang()))
{
// Only replace first one as a convenience. Note ? may appear in function arguments esp in matches(regexp)
valangRules.append(propertyDef.getValang().replaceFirst("\\?", fieldName));
}
}
}
// if there were any valang rules create a valang validator from those
if (valangRules.length() > 0)
{
try
{
//FIXME this is not nice as it is implementation specific
ValangValidator val = new ValangValidator();
String rules = valangRules.toString();
// if(logger.isDebugEnabled())
logger.debug("Valang rules for " + typeDef.getName() + ": " + rules);
val.setValang(rules);
val.afterPropertiesSet();
val.validate(target, errors);
}
catch (Throwable e)
{
throw new OtherObjectsException("Incorrect validation rules on: "+ typeDef.getName(), e);
}
}
}
| public void validate(Object target, Errors errors)
{
TypeDef typeDef;
if (target instanceof BaseNode)
typeDef = ((BaseNode)target).getTypeDef();
else
typeDef = typeService.getType(target.getClass());
StringBuffer valangRules = new StringBuffer();
for (PropertyDef propertyDef : typeDef.getProperties())
{
String fieldName = propertyDef.getFieldName();
Object value = errors.getFieldValue(fieldName);
if (propertyDef.getType().equals(PropertyDef.LIST))
{
String collectionElementType = propertyDef.getCollectionElementType();
Assert.isTrue(collectionElementType != null, "If this property is a collection the collectionElementType needs to have been set");
if (collectionElementType.equals(PropertyDef.COMPONENT))
{
if (value != null && List.class.isAssignableFrom(value.getClass()))
{
int i = 0;
List<Object> objectList = (List<Object>) value;
for (Object object : objectList)
{
validateComponent(fieldName + "[" + i + "]", propertyDef, object, errors);
i++;
}
}
}
}
else if (propertyDef.getType().equals(PropertyDef.COMPONENT))
{
validateComponent(fieldName, propertyDef, value, errors);
}
else
{
if (propertyDef.isRequired())
ValidationUtils.rejectIfEmptyOrWhitespace(errors, fieldName, "field.required");
int size = propertyDef.getSize();
if (size > -1 && value != null)
{
int actualSize = value.toString().length();
if (value != null && actualSize > size)
errors.rejectValue(fieldName, "field.value.too.long", new Object[]{size, actualSize}, "Value too long. Must be less that {0}");
}
// if we have a valang property, insert the fieldName into it and append it to the valang rules buffer
if (StringUtils.hasText(propertyDef.getValang()))
{
// Only replace first one as a convenience. Note ? may appear in function arguments esp in matches(regexp)
valangRules.append(propertyDef.getValang().replaceFirst("\\?", fieldName));
}
}
}
// if there were any valang rules create a valang validator from those
if (valangRules.length() > 0)
{
try
{
//FIXME this is not nice as it is implementation specific
ValangValidator val = new ValangValidator();
String rules = valangRules.toString();
// if(logger.isDebugEnabled())
logger.debug("Valang rules for " + typeDef.getName() + ": " + rules);
val.setValang(rules);
val.afterPropertiesSet();
val.validate(target, errors);
}
catch (Throwable e)
{
throw new OtherObjectsException("Incorrect validation rules on: "+ typeDef.getName(), e);
}
}
}
|
diff --git a/FileList.java b/FileList.java
index 3372251..c180343 100644
--- a/FileList.java
+++ b/FileList.java
@@ -1,76 +1,88 @@
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.text.*;
import java.util.Date;
import SevenZip.Compression.LZMA.Decoder;
public class FileList {
private static FileList instance = null;
private byte[] data;
private int offset;
private FileList() {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
- RandomAccessFile in = new RandomAccessFile("files.lzma", "r");
- MappedByteBuffer buf = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, in.length());
+ //TODO: less ugliness here
+ File tmp = File.createTempFile("files", ".lzma");
+ {
+ InputStream tmpin = this.getClass().getClassLoader().getResourceAsStream("files.lzma");
+ FileOutputStream tmpout = new FileOutputStream(tmp);
+ byte[] buf = new byte[1024];
+ int i = 0;
+ while ((i = tmpin.read(buf)) != -1) {
+ tmpout.write(buf, 0, i);
+ }
+ }
+ FileInputStream in = new FileInputStream(tmp);
+ MappedByteBuffer buf = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, in.getChannel().size());
in.close();
+ tmp.delete();
Decoder decoder = new Decoder();
decoder.SetDecoderProperties(Unpack.readProps(buf));
//from LzmaAlone.java
int len = 0;
for (int i = 0; i < 8; i++)
{
int v = buf.get() & 0xFF;
len |= ((long)v) << (8 * i);
}
decoder.Code(buf, out, len);
data = out.toByteArray();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static FileList getInstance() {
return instance == null ? new FileList() : instance;
}
public FileLocation nextFile(){
int start = offset;
while (data[offset] != '\n') {
if (offset+2 == data.length)
return null;
offset++;
}
String line[] = new String(data, start, offset-start).split(";");
offset++;
DateFormat df = new SimpleDateFormat("yyyy.MM.dd kk:mm");
try {
Date mtime = df.parse(line[1]);
return new FileLocation(line[0], Integer.parseInt(line[2]), Integer.parseInt(line[3]), Integer.parseInt(line[4]), Integer.parseInt(line[6]), Integer.parseInt(line[7]), mtime);
} catch (ParseException e) {
return null;
}
}
public static class FileLocation {
public String fileName;
public int firstSlice, lastSlice;
public int startOffset, originalSize, compressedSize;
public Date mtime;
private FileLocation(String fileName, int firstSlice, int lastSlice, int startOffset, int originalSize, int compressedSize, Date mtime) {
this.fileName = fileName;
this.firstSlice = firstSlice;
this.lastSlice = lastSlice;
this.startOffset = startOffset;
this.originalSize = originalSize;
this.compressedSize = compressedSize;
this.mtime = mtime;
}
}
}
| false | true | private FileList() {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
RandomAccessFile in = new RandomAccessFile("files.lzma", "r");
MappedByteBuffer buf = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, in.length());
in.close();
Decoder decoder = new Decoder();
decoder.SetDecoderProperties(Unpack.readProps(buf));
//from LzmaAlone.java
int len = 0;
for (int i = 0; i < 8; i++)
{
int v = buf.get() & 0xFF;
len |= ((long)v) << (8 * i);
}
decoder.Code(buf, out, len);
data = out.toByteArray();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
| private FileList() {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
//TODO: less ugliness here
File tmp = File.createTempFile("files", ".lzma");
{
InputStream tmpin = this.getClass().getClassLoader().getResourceAsStream("files.lzma");
FileOutputStream tmpout = new FileOutputStream(tmp);
byte[] buf = new byte[1024];
int i = 0;
while ((i = tmpin.read(buf)) != -1) {
tmpout.write(buf, 0, i);
}
}
FileInputStream in = new FileInputStream(tmp);
MappedByteBuffer buf = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, in.getChannel().size());
in.close();
tmp.delete();
Decoder decoder = new Decoder();
decoder.SetDecoderProperties(Unpack.readProps(buf));
//from LzmaAlone.java
int len = 0;
for (int i = 0; i < 8; i++)
{
int v = buf.get() & 0xFF;
len |= ((long)v) << (8 * i);
}
decoder.Code(buf, out, len);
data = out.toByteArray();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/src/state/Octodude.java b/src/state/Octodude.java
index 2e3d7cc..76bdd8f 100644
--- a/src/state/Octodude.java
+++ b/src/state/Octodude.java
@@ -1,80 +1,87 @@
/**
*
*/
package state;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.io.Serializable;
import javax.swing.ImageIcon;
import UI.Display;
/**
* @author findlaconn
*
*/
public class Octodude extends Dude implements Serializable{
private Image img[];
public Octodude(World world, int x, int y, int width, int height,
String image) {
super(world, x, y, width, height, image);
}
@Override
protected void loadImage(String image) {
img = new Image[4];
img[RIGHT] = new ImageIcon("Assets/Characters/Enemies/AlienOctopus/EyeFrontRight.png").getImage();
img[DOWN] = new ImageIcon("Assets/Characters/Enemies/AlienOctopus/EyeFrontLeft.png").getImage();
img[UP] = new ImageIcon("Assets/Characters/Enemies/AlienOctopus/EyeBackRight.png").getImage();
img[LEFT] = new ImageIcon("Assets/Characters/Enemies/AlienOctopus/EyeBackLeft.png").getImage();
}
@Override
public void draw(Graphics g, Display d, int bottomPixelX, int bottomPixelY,
boolean drawHealth){
double percentMoved = count * 0.25;
// Tile coordinates of The Dude (x,y)
- double x = this.oldX + (this.x - this.oldX) * percentMoved;
- double y = this.oldY + (this.y - this.oldY) * percentMoved;
+ double x, y;
+ if(attacking == null) {
+ x = this.oldX + (this.x - this.oldX) * percentMoved;
+ y = this.oldY + (this.y - this.oldY) * percentMoved;
+ } else {
+ double dist = (count % 2 == 1) ? 0.2 : 0.1;
+ x = this.x + (facing == LEFT ? -1 : facing == RIGHT ? 1 : 0) * dist;
+ y = this.y + (facing == UP ? -1 : facing == DOWN ? 1 : 0) * dist;
+ }
// Pixel coordinates (on screen) of the Dude (i,j)
Point pt = d.tileToDisplayCoordinates(x, y);
int height = world.getTile(this.x, this.y).getHeight();
int oldHeight = world.getTile(oldX, oldY).getHeight();
pt.y -= TILE_HEIGHT * (oldHeight + (height - oldHeight) * percentMoved);
pt.y -= TILE_HEIGHT / 2;
Image i = img[(facing + d.getRotation()) % 4];
// Draw image at (i,j)
int posX = pt.x - i.getWidth(null) / 2;
int posY = pt.y - i.getHeight(null);
g.drawImage(i, posX, posY, null);
if (drawHealth) {
int tall = 10;
int hHeight = 4;
int hWidth = 16;
g.setColor(Color.red);
g.fillRect(posX, posY - tall, hWidth, hHeight);
g.setColor(Color.green);
g.fillRect(posX, posY - tall, (int)(hWidth * currentHealth / (float)maxHealth), hHeight);
}
}
private static final long serialVersionUID = -5458456094734079547L;
}
| true | true | public void draw(Graphics g, Display d, int bottomPixelX, int bottomPixelY,
boolean drawHealth){
double percentMoved = count * 0.25;
// Tile coordinates of The Dude (x,y)
double x = this.oldX + (this.x - this.oldX) * percentMoved;
double y = this.oldY + (this.y - this.oldY) * percentMoved;
// Pixel coordinates (on screen) of the Dude (i,j)
Point pt = d.tileToDisplayCoordinates(x, y);
int height = world.getTile(this.x, this.y).getHeight();
int oldHeight = world.getTile(oldX, oldY).getHeight();
pt.y -= TILE_HEIGHT * (oldHeight + (height - oldHeight) * percentMoved);
pt.y -= TILE_HEIGHT / 2;
Image i = img[(facing + d.getRotation()) % 4];
// Draw image at (i,j)
int posX = pt.x - i.getWidth(null) / 2;
int posY = pt.y - i.getHeight(null);
g.drawImage(i, posX, posY, null);
if (drawHealth) {
int tall = 10;
int hHeight = 4;
int hWidth = 16;
g.setColor(Color.red);
g.fillRect(posX, posY - tall, hWidth, hHeight);
g.setColor(Color.green);
g.fillRect(posX, posY - tall, (int)(hWidth * currentHealth / (float)maxHealth), hHeight);
}
}
| public void draw(Graphics g, Display d, int bottomPixelX, int bottomPixelY,
boolean drawHealth){
double percentMoved = count * 0.25;
// Tile coordinates of The Dude (x,y)
double x, y;
if(attacking == null) {
x = this.oldX + (this.x - this.oldX) * percentMoved;
y = this.oldY + (this.y - this.oldY) * percentMoved;
} else {
double dist = (count % 2 == 1) ? 0.2 : 0.1;
x = this.x + (facing == LEFT ? -1 : facing == RIGHT ? 1 : 0) * dist;
y = this.y + (facing == UP ? -1 : facing == DOWN ? 1 : 0) * dist;
}
// Pixel coordinates (on screen) of the Dude (i,j)
Point pt = d.tileToDisplayCoordinates(x, y);
int height = world.getTile(this.x, this.y).getHeight();
int oldHeight = world.getTile(oldX, oldY).getHeight();
pt.y -= TILE_HEIGHT * (oldHeight + (height - oldHeight) * percentMoved);
pt.y -= TILE_HEIGHT / 2;
Image i = img[(facing + d.getRotation()) % 4];
// Draw image at (i,j)
int posX = pt.x - i.getWidth(null) / 2;
int posY = pt.y - i.getHeight(null);
g.drawImage(i, posX, posY, null);
if (drawHealth) {
int tall = 10;
int hHeight = 4;
int hWidth = 16;
g.setColor(Color.red);
g.fillRect(posX, posY - tall, hWidth, hHeight);
g.setColor(Color.green);
g.fillRect(posX, posY - tall, (int)(hWidth * currentHealth / (float)maxHealth), hHeight);
}
}
|
diff --git a/src/ibis/satin/impl/Statistics.java b/src/ibis/satin/impl/Statistics.java
index 9d633a06..3772d3ba 100644
--- a/src/ibis/satin/impl/Statistics.java
+++ b/src/ibis/satin/impl/Statistics.java
@@ -1,766 +1,766 @@
/* $Id: StatsMessage.java 3698 2006-04-28 11:27:17Z rob $ */
package ibis.satin.impl;
import ibis.ipl.IbisIdentifier;
import ibis.util.Timer;
public final class Statistics implements java.io.Serializable, Config {
/**
* Generated
*/
private static final long serialVersionUID = 7954856934035669311L;
public long spawns;
public long syncs;
public long abortsDone;
public long jobsExecuted;
public long abortedJobs;
public long abortMessages;
public long stealAttempts;
public long stealSuccess;
public long asyncStealAttempts;
public long asyncStealSuccess;
public long stolenJobs;
public long stealRequests;
public long interClusterMessages;
public long intraClusterMessages;
public long interClusterBytes;
public long intraClusterBytes;
public double stealTime;
public double handleStealTime;
public double abortTime;
public double idleTime;
public long idleCount;
public long pollCount;
public double invocationRecordWriteTime;
public long invocationRecordWriteCount;
public double returnRecordWriteTime;
public long returnRecordWriteCount;
public double invocationRecordReadTime;
public long invocationRecordReadCount;
public double returnRecordReadTime;
public long returnRecordReadCount;
public long returnRecordBytes;
//fault tolerance
public long tableResultUpdates;
public long tableLockUpdates;
public long tableUpdateMessages;
public long tableLookups;
public long tableSuccessfulLookups;
public long tableRemoteLookups;
public long tableMaxEntries;
public long killedOrphans;
public long restartedJobs;
public double tableLookupTime;
public double tableUpdateTime;
public double tableHandleUpdateTime;
public double tableHandleLookupTime;
public double tableSerializationTime;
public double tableDeserializationTime;
public double tableCheckTime;
public double crashHandlingTime;
public int numCrashesHandled;
//shared objects
public long soInvocations;
public long soInvocationsBytes;
public long soTransfers;
public long soTransfersBytes;
public double broadcastSOInvocationsTime;
public double handleSOInvocationsTime;
public double getSOReferencesTime;
public double soInvocationDeserializationTime;
public double soTransferTime;
public double soSerializationTime;
public double soDeserializationTime;
public double soBcastTime;
public double soBcastSerializationTime;
public double soBcastDeserializationTime;
public double soGuardTime;
public long soGuards;
public long soRealMessageCount;
public long soBcasts;
public long soBcastBytes;
public long handleSOInvocations;
public long getSOReferences;
public Timer totalTimer = Timer.createTimer();
public Timer stealTimer = Timer.createTimer();
public Timer handleStealTimer = Timer.createTimer();
public Timer abortTimer = Timer.createTimer();
public Timer idleTimer = Timer.createTimer();
public Timer pollTimer = Timer.createTimer();
public Timer invocationRecordWriteTimer = Timer.createTimer();
public Timer returnRecordWriteTimer = Timer.createTimer();
public Timer invocationRecordReadTimer = Timer.createTimer();
public Timer returnRecordReadTimer = Timer.createTimer();
public Timer lookupTimer = Timer.createTimer();
public Timer updateTimer = Timer.createTimer();
public Timer handleUpdateTimer = Timer.createTimer();
public Timer handleLookupTimer = Timer.createTimer();
public Timer tableSerializationTimer = Timer.createTimer();
public Timer tableDeserializationTimer = Timer.createTimer();
public Timer crashTimer = Timer.createTimer();
public Timer redoTimer = Timer.createTimer();
public Timer handleSOInvocationsTimer = Timer.createTimer();
public Timer getSOReferencesTimer = Timer.createTimer();
public Timer broadcastSOInvocationsTimer = Timer.createTimer();
public Timer soTransferTimer = Timer.createTimer();
public Timer soSerializationTimer = Timer.createTimer();
public Timer soDeserializationTimer = Timer.createTimer();
public Timer soBroadcastDeserializationTimer = Timer.createTimer();
public Timer soBroadcastSerializationTimer = Timer.createTimer();
public Timer soBroadcastTransferTimer = Timer.createTimer();
public Timer soInvocationDeserializationTimer = Timer.createTimer();
public Timer soGuardTimer = Timer.createTimer();
public void add(Statistics s) {
spawns += s.spawns;
jobsExecuted += s.jobsExecuted;
syncs += s.syncs;
abortsDone += s.abortsDone;
abortMessages += s.abortMessages;
abortedJobs += s.abortedJobs;
stealAttempts += s.stealAttempts;
stealSuccess += s.stealSuccess;
asyncStealAttempts += s.asyncStealAttempts;
asyncStealSuccess += s.asyncStealSuccess;
stolenJobs += s.stolenJobs;
stealRequests += s.stealRequests;
interClusterMessages += s.interClusterMessages;
intraClusterMessages += s.intraClusterMessages;
interClusterBytes += s.interClusterBytes;
intraClusterBytes += s.intraClusterBytes;
stealTime += s.stealTime;
handleStealTime += s.handleStealTime;
abortTime += s.abortTime;
idleTime += s.idleTime;
idleCount += s.idleCount;
pollCount += s.pollCount;
invocationRecordWriteTime += s.invocationRecordWriteTime;
invocationRecordWriteCount += s.invocationRecordWriteCount;
invocationRecordReadTime += s.invocationRecordReadTime;
invocationRecordReadCount += s.invocationRecordReadCount;
returnRecordWriteTime += s.returnRecordWriteTime;
returnRecordWriteCount += s.returnRecordWriteCount;
returnRecordReadTime += s.returnRecordReadTime;
returnRecordReadCount += s.returnRecordReadCount;
returnRecordBytes += s.returnRecordBytes;
//fault tolerance
tableResultUpdates += s.tableResultUpdates;
tableLockUpdates += s.tableLockUpdates;
tableUpdateMessages += s.tableUpdateMessages;
tableLookups += s.tableLookups;
tableSuccessfulLookups += s.tableSuccessfulLookups;
tableRemoteLookups += s.tableRemoteLookups;
killedOrphans += s.killedOrphans;
restartedJobs += s.restartedJobs;
tableLookupTime += s.tableLookupTime;
tableUpdateTime += s.tableUpdateTime;
tableHandleUpdateTime += s.tableHandleUpdateTime;
tableHandleLookupTime += s.tableHandleLookupTime;
tableSerializationTime += s.tableSerializationTime;
tableDeserializationTime += s.tableDeserializationTime;
tableCheckTime += s.tableCheckTime;
tableMaxEntries += s.tableMaxEntries;
crashHandlingTime += s.crashHandlingTime;
numCrashesHandled += s.numCrashesHandled;
//shared objects
soInvocations += s.soInvocations;
soInvocationsBytes += s.soInvocationsBytes;
soTransfers += s.soTransfers;
soTransfersBytes += s.soTransfersBytes;
broadcastSOInvocationsTime += s.broadcastSOInvocationsTime;
handleSOInvocationsTime += s.handleSOInvocationsTime;
handleSOInvocations += s.handleSOInvocations;
getSOReferencesTime += s.getSOReferencesTime;
getSOReferences += s.getSOReferences;
soInvocationDeserializationTime += s.soInvocationDeserializationTime;
soTransferTime += s.soTransferTime;
soSerializationTime += s.soSerializationTime;
soDeserializationTime += s.soDeserializationTime;
soBcastTime += s.soBcastTime;
soBcastSerializationTime += s.soBcastSerializationTime;
soBcastDeserializationTime += s.soBcastDeserializationTime;
soRealMessageCount += s.soRealMessageCount;
soBcasts += s.soBcasts;
soBcastBytes += s.soBcastBytes;
soGuards += s.soGuards;
soGuardTime += s.soGuardTime;
}
public void fillInStats() {
stealTime = stealTimer.totalTimeVal();
handleStealTime = handleStealTimer.totalTimeVal();
abortTime = abortTimer.totalTimeVal();
idleTime = idleTimer.totalTimeVal();
idleCount = idleTimer.nrTimes();
pollCount = pollTimer.nrTimes();
invocationRecordWriteTime = invocationRecordWriteTimer.totalTimeVal();
invocationRecordWriteCount = invocationRecordWriteTimer.nrTimes();
invocationRecordReadTime = invocationRecordReadTimer.totalTimeVal();
invocationRecordReadCount = invocationRecordReadTimer.nrTimes();
returnRecordWriteTime = returnRecordWriteTimer.totalTimeVal();
returnRecordWriteCount = returnRecordWriteTimer.nrTimes();
returnRecordReadTime = returnRecordReadTimer.totalTimeVal();
returnRecordReadCount = returnRecordReadTimer.nrTimes();
tableLookupTime = lookupTimer.totalTimeVal();
tableUpdateTime = updateTimer.totalTimeVal();
tableHandleUpdateTime = handleUpdateTimer.totalTimeVal();
tableHandleLookupTime = handleLookupTimer.totalTimeVal();
tableSerializationTime = tableSerializationTimer.totalTimeVal();
tableDeserializationTime = tableDeserializationTimer.totalTimeVal();
tableCheckTime = redoTimer.totalTimeVal();
crashHandlingTime = crashTimer.totalTimeVal();
handleSOInvocations = handleSOInvocationsTimer.nrTimes();
handleSOInvocationsTime = handleSOInvocationsTimer.totalTimeVal();
getSOReferences = getSOReferencesTimer.nrTimes();
getSOReferencesTime = getSOReferencesTimer.totalTimeVal();
soInvocationDeserializationTime = soInvocationDeserializationTimer
.totalTimeVal();
broadcastSOInvocationsTime = broadcastSOInvocationsTimer.totalTimeVal();
soTransferTime = soTransferTimer.totalTimeVal();
soSerializationTime = soSerializationTimer.totalTimeVal();
soDeserializationTime = soDeserializationTimer.totalTimeVal();
soBcastTime = soBroadcastTransferTimer.totalTimeVal();
soBcastSerializationTime = soBroadcastSerializationTimer.totalTimeVal();
soBcastDeserializationTime = soBroadcastDeserializationTimer
.totalTimeVal();
soGuardTime = soGuardTimer.totalTimeVal();
soGuards = soGuardTimer.nrTimes();
}
protected void printStats(int size, double totalTime) {
java.io.PrintStream out = System.out;
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
boolean haveAborts = abortsDone > 0 || abortedJobs > 0;
- boolean haveSteals = stealAttempts > 0;
+ boolean haveSteals = stealAttempts > 0 || asyncStealAttempts > 0;
boolean haveCrashes = tableResultUpdates > 0 || tableLookups > 0
|| restartedJobs > 0;
boolean haveSO = soInvocations > 0 || soTransfers > 0 || soBcasts > 0;
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
out.println("SATIN: SPAWN: " + nf.format(spawns) + " spawns, "
+ nf.format(jobsExecuted) + " executed, " + nf.format(syncs)
+ " syncs");
if (haveAborts) {
out.println("SATIN: ABORT: " + nf.format(abortsDone)
+ " aborts, " + nf.format(abortMessages) + " abort msgs, "
+ nf.format(abortedJobs) + " aborted jobs");
}
if (haveSteals) {
out.println("SATIN: STEAL: " + nf.format(stealAttempts)
+ " attempts, " + nf.format(stealSuccess) + " successes ("
+ pf.format(perStats(stealSuccess, stealAttempts) * 100.0)
+ " %)");
if (asyncStealAttempts != 0) {
out
.println("SATIN: ASYNCSTEAL: "
+ nf.format(asyncStealAttempts)
+ " attempts, "
+ nf.format(asyncStealSuccess)
+ " successes ("
+ pf.format(perStats(asyncStealSuccess,
asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(intraClusterMessages) + " msgs, "
+ nf.format(intraClusterBytes) + " bytes; inter "
+ nf.format(interClusterMessages) + " msgs, "
+ nf.format(interClusterBytes) + " bytes");
}
if (haveCrashes) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(tableResultUpdates) + ",update messages "
+ nf.format(tableUpdateMessages) + ", lock updates "
+ nf.format(tableLockUpdates) + ",lookups "
+ nf.format(tableLookups) + ",successful "
+ nf.format(tableSuccessfulLookups) + ",remote "
+ nf.format(tableRemoteLookups));
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(restartedJobs));
}
if (haveSO) {
out.println("SATIN: SO_CALLS: " + nf.format(soInvocations)
+ " invocations, " + nf.format(soInvocationsBytes) + " bytes, "
+ nf.format(soRealMessageCount) + " messages");
out.println("SATIN: SO_TRANSFER: " + nf.format(soTransfers)
+ " transfers, " + nf.format(soTransfersBytes) + " bytes ");
out.println("SATIN: SO_BCAST: " + nf.format(soBcasts)
+ " bcasts, " + nf.format(soBcastBytes) + " bytes ");
out.println("SATIN: SO_GUARDS: " + nf.format(soGuards)
+ " guards executed");
}
if (haveAborts || haveSteals || haveCrashes || haveSO) {
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
}
if (haveSteals) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(stealTime) + " time/req "
+ Timer.format(perStats(stealTime, stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(handleStealTime) + " time/handle "
+ Timer.format(perStats(handleStealTime, stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(invocationRecordWriteTime)
+ " time/write "
+ Timer
.format(perStats(invocationRecordWriteTime, stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(invocationRecordReadTime)
+ " time/read "
+ Timer
.format(perStats(invocationRecordReadTime, stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(returnRecordWriteTime,
returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(returnRecordReadTime,
returnRecordReadCount)));
}
if (haveAborts) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(abortTime) + " time/abort "
+ Timer.format(perStats(abortTime, abortsDone)));
}
if (haveCrashes) {
out.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(tableUpdateTime)
+ " time/update "
+ Timer.format(perStats(tableUpdateTime,
(tableResultUpdates + tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(tableLookupTime) + " time/lookup "
+ Timer.format(perStats(tableLookupTime, tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(tableHandleUpdateTime,
tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(tableHandleLookupTime,
tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(tableCheckTime) + " time/check "
+ Timer.format(perStats(tableCheckTime, tableLookups)));
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(crashHandlingTime));
}
if (haveSO) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(broadcastSOInvocationsTime,
soInvocations)));
out.println("SATIN: DESERIALIZE_SO_INVOCATIONS: total "
+ Timer.format(soInvocationDeserializationTime)
+ " time/inv "
+ Timer.format(perStats(soInvocationDeserializationTime,
handleSOInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(handleSOInvocationsTime,
handleSOInvocations)));
out.println("SATIN: GET_SO_REFERENCES: total "
+ Timer.format(getSOReferencesTime)
+ " time/inv "
+ Timer.format(perStats(getSOReferencesTime,
getSOReferences)));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(soTransferTime) + " time/transf "
+ Timer.format(perStats(soTransferTime, soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(soSerializationTime) + " time/transf "
+ Timer.format(perStats(soSerializationTime, soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(soDeserializationTime) + " time/transf "
+ Timer.format(perStats(soDeserializationTime, soTransfers)));
out.println("SATIN: SO_BCASTS: total "
+ Timer.format(soBcastTime) + " time/bcast "
+ Timer.format(perStats(soBcastTime, soBcasts)));
out.println("SATIN: SO_BCAST_SERIALIZATION: total "
+ Timer.format(soBcastSerializationTime) + " time/bcast "
+ Timer.format(perStats(soBcastSerializationTime, soBcasts)));
out.println("SATIN: SO_BCAST_DESERIALIZATION: total "
+ Timer.format(soBcastDeserializationTime) + " time/bcast "
+ Timer.format(perStats(soBcastDeserializationTime, soBcasts)));
out.println("SATIN: SO_GUARDS: total "
+ Timer.format(soGuardTime) + " time/guard "
+ Timer.format(perStats(soGuardTime, soGuards)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTime));
double lbTime = (stealTime - invocationRecordReadTime
- invocationRecordWriteTime - returnRecordReadTime - returnRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTime * 100.0;
double serTimeAvg = (invocationRecordWriteTime
+ invocationRecordReadTime + returnRecordWriteTime + returnRecordReadTime)
/ size;
double serPerc = serTimeAvg / totalTime * 100.0;
double abortTimeAvg = abortTime / size;
double abortPerc = abortTimeAvg / totalTime * 100.0;
double tableUpdateTimeAvg = tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTimeAvg / totalTime * 100.0;
double tableLookupTimeAvg = tableLookupTime / size;
double tableLookupPerc = tableLookupTimeAvg / totalTime * 100.0;
double tableHandleUpdateTimeAvg = tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTimeAvg / totalTime
* 100.0;
double tableHandleLookupTimeAvg = tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTimeAvg / totalTime
* 100.0;
double tableSerializationTimeAvg = tableSerializationTime / size;
double tableSerializationPerc = tableSerializationTimeAvg / totalTime
* 100;
double tableDeserializationTimeAvg = tableDeserializationTime / size;
double tableDeserializationPerc = tableDeserializationTimeAvg
/ totalTime * 100;
double crashHandlingTimeAvg = crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTimeAvg / totalTime * 100.0;
double broadcastSOInvocationsTimeAvg = broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTimeAvg
/ totalTime * 100;
double handleSOInvocationsTimeAvg = handleSOInvocationsTime / size;
double handleSOInvocationsPerc = handleSOInvocationsTimeAvg / totalTime
* 100;
double soInvocationDeserializationTimeAvg = soInvocationDeserializationTime
/ size;
double soInvocationDeserializationPerc = soInvocationDeserializationTimeAvg
/ totalTime * 100;
double soTransferTimeAvg = soTransferTime / size;
double soTransferPerc = soTransferTimeAvg / totalTime * 100;
double soSerializationTimeAvg = soSerializationTime / size;
double soSerializationPerc = soSerializationTimeAvg / totalTime * 100;
double soDeserializationTimeAvg = soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTimeAvg / totalTime
* 100;
double soBcastTimeAvg = soBcastTime / size;
double soBcastPerc = soBcastTimeAvg / totalTime * 100;
double soBcastSerializationTimeAvg = soBcastSerializationTime / size;
double soBcastSerializationPerc = soBcastSerializationTimeAvg
/ totalTime * 100;
double soBcastDeserializationTimeAvg = soBcastDeserializationTime
/ size;
double soBcastDeserializationPerc = soBcastDeserializationTimeAvg
/ totalTime * 100;
double soGuardTimeAvg = soGuardTime / size;
double soGuardPerc = soGuardTimeAvg / totalTime * 100;
double totalOverheadAvg = (abortTimeAvg + tableUpdateTimeAvg
+ tableLookupTimeAvg + tableHandleUpdateTimeAvg
+ tableHandleLookupTimeAvg + handleSOInvocationsTimeAvg
+ broadcastSOInvocationsTimeAvg + soTransferTimeAvg
+ soBcastTimeAvg + soBcastDeserializationTimeAvg + stealTime + soGuardTimeAvg)
/ size;
double totalPerc = totalOverheadAvg / totalTime * 100.0;
double appTime = totalTime - totalOverheadAvg;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTime * 100.0;
if (haveSteals) {
out.println("SATIN: LOAD_BALANCING_TIME: agv. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: agv. per machine "
+ Timer.format(serTimeAvg) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (haveAborts) {
out.println("SATIN: ABORT_TIME: agv. per machine "
+ Timer.format(abortTimeAvg) + " ("
+ (abortPerc < 10 ? " " : "") + pf.format(abortPerc) + " %)");
}
if (haveCrashes) {
out.println("SATIN: GRT_UPDATE_TIME: agv. per machine "
+ Timer.format(tableUpdateTimeAvg) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: agv. per machine "
+ Timer.format(tableLookupTimeAvg) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: agv. per machine "
+ Timer.format(tableHandleUpdateTimeAvg) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: agv. per machine "
+ Timer.format(tableHandleLookupTimeAvg) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: agv. per machine "
+ Timer.format(tableSerializationTimeAvg) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: agv. per machine "
+ Timer.format(tableDeserializationTimeAvg) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
out.println("SATIN: CRASH_HANDLING_TIME: agv. per machine "
+ Timer.format(crashHandlingTimeAvg) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (haveSO) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: agv. per machine "
+ Timer.format(broadcastSOInvocationsTimeAvg) + " ("
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: agv. per machine "
+ Timer.format(handleSOInvocationsTimeAvg) + " ("
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: DESERIALIZE_SO_INVOCATIONS: agv. per machine "
+ Timer.format(soInvocationDeserializationTimeAvg) + " ( "
+ pf.format(soInvocationDeserializationPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: agv. per machine "
+ Timer.format(soTransferTimeAvg) + " ("
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: agv. per machine "
+ Timer.format(soSerializationTimeAvg) + " ("
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: agv. per machine "
+ Timer.format(soDeserializationTimeAvg) + " ("
+ pf.format(soDeserializationPerc) + " %)");
out.println("SATIN: SO_BCASTS: agv. per machine "
+ Timer.format(soBcastTimeAvg) + " (" + pf.format(soBcastPerc)
+ " %)");
out.println("SATIN: SO_BCAST_SERIALIZATION: agv. per machine "
+ Timer.format(soBcastSerializationTimeAvg) + " ("
+ pf.format(soBcastSerializationPerc) + " %)");
out.println("SATIN: SO_BCAST_DESERIALIZATION: agv. per machine "
+ Timer.format(soBcastDeserializationTimeAvg) + " ("
+ pf.format(soBcastDeserializationPerc) + " %)");
out.println("SATIN: SO_GUARD: agv. per machine "
+ Timer.format(soGuardTimeAvg) + " ("
+ pf.format(soGuardPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: agv. per machine "
+ Timer.format(totalOverheadAvg) + " ("
+ (totalPerc < 10 ? " " : "") + pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: agv. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
public void printDetailedStats(IbisIdentifier ident) {
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
java.io.PrintStream out = System.out;
out.println("SATIN '" + ident + "': SPAWN_STATS: spawns = " + spawns
+ " executed = " + jobsExecuted + " syncs = " + syncs + " aborts = "
+ abortsDone + " abort msgs = " + abortMessages
+ " aborted jobs = " + abortedJobs + " total time = " + abortTimer.totalTime());
out.println("SATIN '" + ident + "': MSG_STATS: intra = "
+ intraClusterMessages + ", bytes = "
+ nf.format(intraClusterBytes) +
" inter = "
+ interClusterMessages + ", bytes = "
+ nf.format(interClusterBytes));
out.println("SATIN '" + ident + "': STEAL_STATS: attempts = "
+ stealAttempts + " success = " + stealSuccess + " ("
+ (perStats(stealSuccess, stealAttempts) * 100.0) + " %)"
+ " time = " + stealTimer.totalTime()
+ " requests = " + stealRequests + " jobs stolen = " + stolenJobs
+ " time = "
+ handleStealTimer.totalTime());
out.println("SATIN '" + ident
+ "': SERIALIZATION_STATS: invocationRecordWrites = "
+ invocationRecordWriteTimer.nrTimes() + " total time = "
+ invocationRecordWriteTimer.totalTime()
+ " invocationRecordReads = "
+ invocationRecordReadTimer.nrTimes() + " total time = "
+ invocationRecordReadTimer.totalTime()
+ " returnRecordWrites = "
+ returnRecordWriteTimer.nrTimes() + " total time = "
+ returnRecordWriteTimer.totalTime()
+ " returnRecordReads = "
+ returnRecordReadTimer.nrTimes() + " total time = "
+ returnRecordReadTimer.totalTime() );
out.println("SATIN '" + ident +
"': GRT_STATS: updates = " + tableResultUpdates
+ " lock updates = " + tableLockUpdates
+ " update time = " + updateTimer.totalTime()
+ " handle update time = " + handleUpdateTimer.totalTime()
+ " msgs = " + tableUpdateMessages
+ " lookups = " + tableLookups
+ " lookup time = " + lookupTimer.totalTime()
+ " handle lookup time = " + lookupTimer.totalTime()
+ " remote lookups = " + tableRemoteLookups
+ " successful lookups = " + tableSuccessfulLookups
+ " max size = " + tableMaxEntries);
out.println("SATIN '" + ident + "': FT_STATS:"
+ " handle crash time = " + crashTimer.totalTime()
+ " redo time = " + redoTimer.totalTime()
+ " orphans killed = " + killedOrphans
+ " jobs restarted = " + restartedJobs);
out.println("SATIN '" + ident + "': SO_STATS: "
+ " invocations = " + soInvocations
+ " size = " + soInvocationsBytes
+ " time = " + broadcastSOInvocationsTimer.totalTime()
+ " transfers = " + soTransfers
+ " size = " + soTransfersBytes
+ " time = " + soTransferTimer.totalTime());
}
private double perStats(double tm, long cnt) {
if (cnt == 0) {
return 0.0;
}
return tm / cnt;
}
}
| true | true | protected void printStats(int size, double totalTime) {
java.io.PrintStream out = System.out;
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
boolean haveAborts = abortsDone > 0 || abortedJobs > 0;
boolean haveSteals = stealAttempts > 0;
boolean haveCrashes = tableResultUpdates > 0 || tableLookups > 0
|| restartedJobs > 0;
boolean haveSO = soInvocations > 0 || soTransfers > 0 || soBcasts > 0;
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
out.println("SATIN: SPAWN: " + nf.format(spawns) + " spawns, "
+ nf.format(jobsExecuted) + " executed, " + nf.format(syncs)
+ " syncs");
if (haveAborts) {
out.println("SATIN: ABORT: " + nf.format(abortsDone)
+ " aborts, " + nf.format(abortMessages) + " abort msgs, "
+ nf.format(abortedJobs) + " aborted jobs");
}
if (haveSteals) {
out.println("SATIN: STEAL: " + nf.format(stealAttempts)
+ " attempts, " + nf.format(stealSuccess) + " successes ("
+ pf.format(perStats(stealSuccess, stealAttempts) * 100.0)
+ " %)");
if (asyncStealAttempts != 0) {
out
.println("SATIN: ASYNCSTEAL: "
+ nf.format(asyncStealAttempts)
+ " attempts, "
+ nf.format(asyncStealSuccess)
+ " successes ("
+ pf.format(perStats(asyncStealSuccess,
asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(intraClusterMessages) + " msgs, "
+ nf.format(intraClusterBytes) + " bytes; inter "
+ nf.format(interClusterMessages) + " msgs, "
+ nf.format(interClusterBytes) + " bytes");
}
if (haveCrashes) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(tableResultUpdates) + ",update messages "
+ nf.format(tableUpdateMessages) + ", lock updates "
+ nf.format(tableLockUpdates) + ",lookups "
+ nf.format(tableLookups) + ",successful "
+ nf.format(tableSuccessfulLookups) + ",remote "
+ nf.format(tableRemoteLookups));
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(restartedJobs));
}
if (haveSO) {
out.println("SATIN: SO_CALLS: " + nf.format(soInvocations)
+ " invocations, " + nf.format(soInvocationsBytes) + " bytes, "
+ nf.format(soRealMessageCount) + " messages");
out.println("SATIN: SO_TRANSFER: " + nf.format(soTransfers)
+ " transfers, " + nf.format(soTransfersBytes) + " bytes ");
out.println("SATIN: SO_BCAST: " + nf.format(soBcasts)
+ " bcasts, " + nf.format(soBcastBytes) + " bytes ");
out.println("SATIN: SO_GUARDS: " + nf.format(soGuards)
+ " guards executed");
}
if (haveAborts || haveSteals || haveCrashes || haveSO) {
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
}
if (haveSteals) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(stealTime) + " time/req "
+ Timer.format(perStats(stealTime, stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(handleStealTime) + " time/handle "
+ Timer.format(perStats(handleStealTime, stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(invocationRecordWriteTime)
+ " time/write "
+ Timer
.format(perStats(invocationRecordWriteTime, stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(invocationRecordReadTime)
+ " time/read "
+ Timer
.format(perStats(invocationRecordReadTime, stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(returnRecordWriteTime,
returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(returnRecordReadTime,
returnRecordReadCount)));
}
if (haveAborts) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(abortTime) + " time/abort "
+ Timer.format(perStats(abortTime, abortsDone)));
}
if (haveCrashes) {
out.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(tableUpdateTime)
+ " time/update "
+ Timer.format(perStats(tableUpdateTime,
(tableResultUpdates + tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(tableLookupTime) + " time/lookup "
+ Timer.format(perStats(tableLookupTime, tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(tableHandleUpdateTime,
tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(tableHandleLookupTime,
tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(tableCheckTime) + " time/check "
+ Timer.format(perStats(tableCheckTime, tableLookups)));
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(crashHandlingTime));
}
if (haveSO) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(broadcastSOInvocationsTime,
soInvocations)));
out.println("SATIN: DESERIALIZE_SO_INVOCATIONS: total "
+ Timer.format(soInvocationDeserializationTime)
+ " time/inv "
+ Timer.format(perStats(soInvocationDeserializationTime,
handleSOInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(handleSOInvocationsTime,
handleSOInvocations)));
out.println("SATIN: GET_SO_REFERENCES: total "
+ Timer.format(getSOReferencesTime)
+ " time/inv "
+ Timer.format(perStats(getSOReferencesTime,
getSOReferences)));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(soTransferTime) + " time/transf "
+ Timer.format(perStats(soTransferTime, soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(soSerializationTime) + " time/transf "
+ Timer.format(perStats(soSerializationTime, soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(soDeserializationTime) + " time/transf "
+ Timer.format(perStats(soDeserializationTime, soTransfers)));
out.println("SATIN: SO_BCASTS: total "
+ Timer.format(soBcastTime) + " time/bcast "
+ Timer.format(perStats(soBcastTime, soBcasts)));
out.println("SATIN: SO_BCAST_SERIALIZATION: total "
+ Timer.format(soBcastSerializationTime) + " time/bcast "
+ Timer.format(perStats(soBcastSerializationTime, soBcasts)));
out.println("SATIN: SO_BCAST_DESERIALIZATION: total "
+ Timer.format(soBcastDeserializationTime) + " time/bcast "
+ Timer.format(perStats(soBcastDeserializationTime, soBcasts)));
out.println("SATIN: SO_GUARDS: total "
+ Timer.format(soGuardTime) + " time/guard "
+ Timer.format(perStats(soGuardTime, soGuards)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTime));
double lbTime = (stealTime - invocationRecordReadTime
- invocationRecordWriteTime - returnRecordReadTime - returnRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTime * 100.0;
double serTimeAvg = (invocationRecordWriteTime
+ invocationRecordReadTime + returnRecordWriteTime + returnRecordReadTime)
/ size;
double serPerc = serTimeAvg / totalTime * 100.0;
double abortTimeAvg = abortTime / size;
double abortPerc = abortTimeAvg / totalTime * 100.0;
double tableUpdateTimeAvg = tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTimeAvg / totalTime * 100.0;
double tableLookupTimeAvg = tableLookupTime / size;
double tableLookupPerc = tableLookupTimeAvg / totalTime * 100.0;
double tableHandleUpdateTimeAvg = tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTimeAvg / totalTime
* 100.0;
double tableHandleLookupTimeAvg = tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTimeAvg / totalTime
* 100.0;
double tableSerializationTimeAvg = tableSerializationTime / size;
double tableSerializationPerc = tableSerializationTimeAvg / totalTime
* 100;
double tableDeserializationTimeAvg = tableDeserializationTime / size;
double tableDeserializationPerc = tableDeserializationTimeAvg
/ totalTime * 100;
double crashHandlingTimeAvg = crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTimeAvg / totalTime * 100.0;
double broadcastSOInvocationsTimeAvg = broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTimeAvg
/ totalTime * 100;
double handleSOInvocationsTimeAvg = handleSOInvocationsTime / size;
double handleSOInvocationsPerc = handleSOInvocationsTimeAvg / totalTime
* 100;
double soInvocationDeserializationTimeAvg = soInvocationDeserializationTime
/ size;
double soInvocationDeserializationPerc = soInvocationDeserializationTimeAvg
/ totalTime * 100;
double soTransferTimeAvg = soTransferTime / size;
double soTransferPerc = soTransferTimeAvg / totalTime * 100;
double soSerializationTimeAvg = soSerializationTime / size;
double soSerializationPerc = soSerializationTimeAvg / totalTime * 100;
double soDeserializationTimeAvg = soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTimeAvg / totalTime
* 100;
double soBcastTimeAvg = soBcastTime / size;
double soBcastPerc = soBcastTimeAvg / totalTime * 100;
double soBcastSerializationTimeAvg = soBcastSerializationTime / size;
double soBcastSerializationPerc = soBcastSerializationTimeAvg
/ totalTime * 100;
double soBcastDeserializationTimeAvg = soBcastDeserializationTime
/ size;
double soBcastDeserializationPerc = soBcastDeserializationTimeAvg
/ totalTime * 100;
double soGuardTimeAvg = soGuardTime / size;
double soGuardPerc = soGuardTimeAvg / totalTime * 100;
double totalOverheadAvg = (abortTimeAvg + tableUpdateTimeAvg
+ tableLookupTimeAvg + tableHandleUpdateTimeAvg
+ tableHandleLookupTimeAvg + handleSOInvocationsTimeAvg
+ broadcastSOInvocationsTimeAvg + soTransferTimeAvg
+ soBcastTimeAvg + soBcastDeserializationTimeAvg + stealTime + soGuardTimeAvg)
/ size;
double totalPerc = totalOverheadAvg / totalTime * 100.0;
double appTime = totalTime - totalOverheadAvg;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTime * 100.0;
if (haveSteals) {
out.println("SATIN: LOAD_BALANCING_TIME: agv. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: agv. per machine "
+ Timer.format(serTimeAvg) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (haveAborts) {
out.println("SATIN: ABORT_TIME: agv. per machine "
+ Timer.format(abortTimeAvg) + " ("
+ (abortPerc < 10 ? " " : "") + pf.format(abortPerc) + " %)");
}
if (haveCrashes) {
out.println("SATIN: GRT_UPDATE_TIME: agv. per machine "
+ Timer.format(tableUpdateTimeAvg) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: agv. per machine "
+ Timer.format(tableLookupTimeAvg) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: agv. per machine "
+ Timer.format(tableHandleUpdateTimeAvg) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: agv. per machine "
+ Timer.format(tableHandleLookupTimeAvg) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: agv. per machine "
+ Timer.format(tableSerializationTimeAvg) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: agv. per machine "
+ Timer.format(tableDeserializationTimeAvg) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
out.println("SATIN: CRASH_HANDLING_TIME: agv. per machine "
+ Timer.format(crashHandlingTimeAvg) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (haveSO) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: agv. per machine "
+ Timer.format(broadcastSOInvocationsTimeAvg) + " ("
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: agv. per machine "
+ Timer.format(handleSOInvocationsTimeAvg) + " ("
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: DESERIALIZE_SO_INVOCATIONS: agv. per machine "
+ Timer.format(soInvocationDeserializationTimeAvg) + " ( "
+ pf.format(soInvocationDeserializationPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: agv. per machine "
+ Timer.format(soTransferTimeAvg) + " ("
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: agv. per machine "
+ Timer.format(soSerializationTimeAvg) + " ("
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: agv. per machine "
+ Timer.format(soDeserializationTimeAvg) + " ("
+ pf.format(soDeserializationPerc) + " %)");
out.println("SATIN: SO_BCASTS: agv. per machine "
+ Timer.format(soBcastTimeAvg) + " (" + pf.format(soBcastPerc)
+ " %)");
out.println("SATIN: SO_BCAST_SERIALIZATION: agv. per machine "
+ Timer.format(soBcastSerializationTimeAvg) + " ("
+ pf.format(soBcastSerializationPerc) + " %)");
out.println("SATIN: SO_BCAST_DESERIALIZATION: agv. per machine "
+ Timer.format(soBcastDeserializationTimeAvg) + " ("
+ pf.format(soBcastDeserializationPerc) + " %)");
out.println("SATIN: SO_GUARD: agv. per machine "
+ Timer.format(soGuardTimeAvg) + " ("
+ pf.format(soGuardPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: agv. per machine "
+ Timer.format(totalOverheadAvg) + " ("
+ (totalPerc < 10 ? " " : "") + pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: agv. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
| protected void printStats(int size, double totalTime) {
java.io.PrintStream out = System.out;
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
boolean haveAborts = abortsDone > 0 || abortedJobs > 0;
boolean haveSteals = stealAttempts > 0 || asyncStealAttempts > 0;
boolean haveCrashes = tableResultUpdates > 0 || tableLookups > 0
|| restartedJobs > 0;
boolean haveSO = soInvocations > 0 || soTransfers > 0 || soBcasts > 0;
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
out.println("SATIN: SPAWN: " + nf.format(spawns) + " spawns, "
+ nf.format(jobsExecuted) + " executed, " + nf.format(syncs)
+ " syncs");
if (haveAborts) {
out.println("SATIN: ABORT: " + nf.format(abortsDone)
+ " aborts, " + nf.format(abortMessages) + " abort msgs, "
+ nf.format(abortedJobs) + " aborted jobs");
}
if (haveSteals) {
out.println("SATIN: STEAL: " + nf.format(stealAttempts)
+ " attempts, " + nf.format(stealSuccess) + " successes ("
+ pf.format(perStats(stealSuccess, stealAttempts) * 100.0)
+ " %)");
if (asyncStealAttempts != 0) {
out
.println("SATIN: ASYNCSTEAL: "
+ nf.format(asyncStealAttempts)
+ " attempts, "
+ nf.format(asyncStealSuccess)
+ " successes ("
+ pf.format(perStats(asyncStealSuccess,
asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(intraClusterMessages) + " msgs, "
+ nf.format(intraClusterBytes) + " bytes; inter "
+ nf.format(interClusterMessages) + " msgs, "
+ nf.format(interClusterBytes) + " bytes");
}
if (haveCrashes) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(tableResultUpdates) + ",update messages "
+ nf.format(tableUpdateMessages) + ", lock updates "
+ nf.format(tableLockUpdates) + ",lookups "
+ nf.format(tableLookups) + ",successful "
+ nf.format(tableSuccessfulLookups) + ",remote "
+ nf.format(tableRemoteLookups));
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(restartedJobs));
}
if (haveSO) {
out.println("SATIN: SO_CALLS: " + nf.format(soInvocations)
+ " invocations, " + nf.format(soInvocationsBytes) + " bytes, "
+ nf.format(soRealMessageCount) + " messages");
out.println("SATIN: SO_TRANSFER: " + nf.format(soTransfers)
+ " transfers, " + nf.format(soTransfersBytes) + " bytes ");
out.println("SATIN: SO_BCAST: " + nf.format(soBcasts)
+ " bcasts, " + nf.format(soBcastBytes) + " bytes ");
out.println("SATIN: SO_GUARDS: " + nf.format(soGuards)
+ " guards executed");
}
if (haveAborts || haveSteals || haveCrashes || haveSO) {
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
}
if (haveSteals) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(stealTime) + " time/req "
+ Timer.format(perStats(stealTime, stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(handleStealTime) + " time/handle "
+ Timer.format(perStats(handleStealTime, stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(invocationRecordWriteTime)
+ " time/write "
+ Timer
.format(perStats(invocationRecordWriteTime, stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(invocationRecordReadTime)
+ " time/read "
+ Timer
.format(perStats(invocationRecordReadTime, stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(returnRecordWriteTime,
returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(returnRecordReadTime,
returnRecordReadCount)));
}
if (haveAborts) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(abortTime) + " time/abort "
+ Timer.format(perStats(abortTime, abortsDone)));
}
if (haveCrashes) {
out.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(tableUpdateTime)
+ " time/update "
+ Timer.format(perStats(tableUpdateTime,
(tableResultUpdates + tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(tableLookupTime) + " time/lookup "
+ Timer.format(perStats(tableLookupTime, tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(tableHandleUpdateTime,
tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(tableHandleLookupTime,
tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(tableCheckTime) + " time/check "
+ Timer.format(perStats(tableCheckTime, tableLookups)));
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(crashHandlingTime));
}
if (haveSO) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(broadcastSOInvocationsTime,
soInvocations)));
out.println("SATIN: DESERIALIZE_SO_INVOCATIONS: total "
+ Timer.format(soInvocationDeserializationTime)
+ " time/inv "
+ Timer.format(perStats(soInvocationDeserializationTime,
handleSOInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(handleSOInvocationsTime,
handleSOInvocations)));
out.println("SATIN: GET_SO_REFERENCES: total "
+ Timer.format(getSOReferencesTime)
+ " time/inv "
+ Timer.format(perStats(getSOReferencesTime,
getSOReferences)));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(soTransferTime) + " time/transf "
+ Timer.format(perStats(soTransferTime, soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(soSerializationTime) + " time/transf "
+ Timer.format(perStats(soSerializationTime, soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(soDeserializationTime) + " time/transf "
+ Timer.format(perStats(soDeserializationTime, soTransfers)));
out.println("SATIN: SO_BCASTS: total "
+ Timer.format(soBcastTime) + " time/bcast "
+ Timer.format(perStats(soBcastTime, soBcasts)));
out.println("SATIN: SO_BCAST_SERIALIZATION: total "
+ Timer.format(soBcastSerializationTime) + " time/bcast "
+ Timer.format(perStats(soBcastSerializationTime, soBcasts)));
out.println("SATIN: SO_BCAST_DESERIALIZATION: total "
+ Timer.format(soBcastDeserializationTime) + " time/bcast "
+ Timer.format(perStats(soBcastDeserializationTime, soBcasts)));
out.println("SATIN: SO_GUARDS: total "
+ Timer.format(soGuardTime) + " time/guard "
+ Timer.format(perStats(soGuardTime, soGuards)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTime));
double lbTime = (stealTime - invocationRecordReadTime
- invocationRecordWriteTime - returnRecordReadTime - returnRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTime * 100.0;
double serTimeAvg = (invocationRecordWriteTime
+ invocationRecordReadTime + returnRecordWriteTime + returnRecordReadTime)
/ size;
double serPerc = serTimeAvg / totalTime * 100.0;
double abortTimeAvg = abortTime / size;
double abortPerc = abortTimeAvg / totalTime * 100.0;
double tableUpdateTimeAvg = tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTimeAvg / totalTime * 100.0;
double tableLookupTimeAvg = tableLookupTime / size;
double tableLookupPerc = tableLookupTimeAvg / totalTime * 100.0;
double tableHandleUpdateTimeAvg = tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTimeAvg / totalTime
* 100.0;
double tableHandleLookupTimeAvg = tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTimeAvg / totalTime
* 100.0;
double tableSerializationTimeAvg = tableSerializationTime / size;
double tableSerializationPerc = tableSerializationTimeAvg / totalTime
* 100;
double tableDeserializationTimeAvg = tableDeserializationTime / size;
double tableDeserializationPerc = tableDeserializationTimeAvg
/ totalTime * 100;
double crashHandlingTimeAvg = crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTimeAvg / totalTime * 100.0;
double broadcastSOInvocationsTimeAvg = broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTimeAvg
/ totalTime * 100;
double handleSOInvocationsTimeAvg = handleSOInvocationsTime / size;
double handleSOInvocationsPerc = handleSOInvocationsTimeAvg / totalTime
* 100;
double soInvocationDeserializationTimeAvg = soInvocationDeserializationTime
/ size;
double soInvocationDeserializationPerc = soInvocationDeserializationTimeAvg
/ totalTime * 100;
double soTransferTimeAvg = soTransferTime / size;
double soTransferPerc = soTransferTimeAvg / totalTime * 100;
double soSerializationTimeAvg = soSerializationTime / size;
double soSerializationPerc = soSerializationTimeAvg / totalTime * 100;
double soDeserializationTimeAvg = soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTimeAvg / totalTime
* 100;
double soBcastTimeAvg = soBcastTime / size;
double soBcastPerc = soBcastTimeAvg / totalTime * 100;
double soBcastSerializationTimeAvg = soBcastSerializationTime / size;
double soBcastSerializationPerc = soBcastSerializationTimeAvg
/ totalTime * 100;
double soBcastDeserializationTimeAvg = soBcastDeserializationTime
/ size;
double soBcastDeserializationPerc = soBcastDeserializationTimeAvg
/ totalTime * 100;
double soGuardTimeAvg = soGuardTime / size;
double soGuardPerc = soGuardTimeAvg / totalTime * 100;
double totalOverheadAvg = (abortTimeAvg + tableUpdateTimeAvg
+ tableLookupTimeAvg + tableHandleUpdateTimeAvg
+ tableHandleLookupTimeAvg + handleSOInvocationsTimeAvg
+ broadcastSOInvocationsTimeAvg + soTransferTimeAvg
+ soBcastTimeAvg + soBcastDeserializationTimeAvg + stealTime + soGuardTimeAvg)
/ size;
double totalPerc = totalOverheadAvg / totalTime * 100.0;
double appTime = totalTime - totalOverheadAvg;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTime * 100.0;
if (haveSteals) {
out.println("SATIN: LOAD_BALANCING_TIME: agv. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: agv. per machine "
+ Timer.format(serTimeAvg) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (haveAborts) {
out.println("SATIN: ABORT_TIME: agv. per machine "
+ Timer.format(abortTimeAvg) + " ("
+ (abortPerc < 10 ? " " : "") + pf.format(abortPerc) + " %)");
}
if (haveCrashes) {
out.println("SATIN: GRT_UPDATE_TIME: agv. per machine "
+ Timer.format(tableUpdateTimeAvg) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: agv. per machine "
+ Timer.format(tableLookupTimeAvg) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: agv. per machine "
+ Timer.format(tableHandleUpdateTimeAvg) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: agv. per machine "
+ Timer.format(tableHandleLookupTimeAvg) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: agv. per machine "
+ Timer.format(tableSerializationTimeAvg) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: agv. per machine "
+ Timer.format(tableDeserializationTimeAvg) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
out.println("SATIN: CRASH_HANDLING_TIME: agv. per machine "
+ Timer.format(crashHandlingTimeAvg) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (haveSO) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: agv. per machine "
+ Timer.format(broadcastSOInvocationsTimeAvg) + " ("
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: agv. per machine "
+ Timer.format(handleSOInvocationsTimeAvg) + " ("
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: DESERIALIZE_SO_INVOCATIONS: agv. per machine "
+ Timer.format(soInvocationDeserializationTimeAvg) + " ( "
+ pf.format(soInvocationDeserializationPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: agv. per machine "
+ Timer.format(soTransferTimeAvg) + " ("
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: agv. per machine "
+ Timer.format(soSerializationTimeAvg) + " ("
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: agv. per machine "
+ Timer.format(soDeserializationTimeAvg) + " ("
+ pf.format(soDeserializationPerc) + " %)");
out.println("SATIN: SO_BCASTS: agv. per machine "
+ Timer.format(soBcastTimeAvg) + " (" + pf.format(soBcastPerc)
+ " %)");
out.println("SATIN: SO_BCAST_SERIALIZATION: agv. per machine "
+ Timer.format(soBcastSerializationTimeAvg) + " ("
+ pf.format(soBcastSerializationPerc) + " %)");
out.println("SATIN: SO_BCAST_DESERIALIZATION: agv. per machine "
+ Timer.format(soBcastDeserializationTimeAvg) + " ("
+ pf.format(soBcastDeserializationPerc) + " %)");
out.println("SATIN: SO_GUARD: agv. per machine "
+ Timer.format(soGuardTimeAvg) + " ("
+ pf.format(soGuardPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: agv. per machine "
+ Timer.format(totalOverheadAvg) + " ("
+ (totalPerc < 10 ? " " : "") + pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: agv. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
|
diff --git a/src/com/android/email/MessagingController.java b/src/com/android/email/MessagingController.java
index 02996f98..a706ab92 100644
--- a/src/com/android/email/MessagingController.java
+++ b/src/com/android/email/MessagingController.java
@@ -1,2107 +1,2112 @@
/*
* 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.email;
import com.android.email.mail.FetchProfile;
import com.android.email.mail.Flag;
import com.android.email.mail.Folder;
import com.android.email.mail.Message;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Part;
import com.android.email.mail.Sender;
import com.android.email.mail.Store;
import com.android.email.mail.StoreSynchronizer;
import com.android.email.mail.Folder.FolderType;
import com.android.email.mail.Folder.MessageRetrievalListener;
import com.android.email.mail.Folder.OpenMode;
import com.android.email.mail.internet.MimeBodyPart;
import com.android.email.mail.internet.MimeHeader;
import com.android.email.mail.internet.MimeMultipart;
import com.android.email.mail.internet.MimeUtility;
import com.android.email.provider.AttachmentProvider;
import com.android.email.provider.EmailContent;
import com.android.email.provider.EmailContent.Attachment;
import com.android.email.provider.EmailContent.AttachmentColumns;
import com.android.email.provider.EmailContent.Mailbox;
import com.android.email.provider.EmailContent.MailboxColumns;
import com.android.email.provider.EmailContent.MessageColumns;
import com.android.email.provider.EmailContent.SyncColumns;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Process;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Starts a long running (application) Thread that will run through commands
* that require remote mailbox access. This class is used to serialize and
* prioritize these commands. Each method that will submit a command requires a
* MessagingListener instance to be provided. It is expected that that listener
* has also been added as a registered listener using addListener(). When a
* command is to be executed, if the listener that was provided with the command
* is no longer registered the command is skipped. The design idea for the above
* is that when an Activity starts it registers as a listener. When it is paused
* it removes itself. Thus, any commands that that activity submitted are
* removed from the queue once the activity is no longer active.
*/
public class MessagingController implements Runnable {
/**
* The maximum message size that we'll consider to be "small". A small message is downloaded
* in full immediately instead of in pieces. Anything over this size will be downloaded in
* pieces with attachments being left off completely and downloaded on demand.
*
*
* 25k for a "small" message was picked by educated trial and error.
* http://answers.google.com/answers/threadview?id=312463 claims that the
* average size of an email is 59k, which I feel is too large for our
* blind download. The following tests were performed on a download of
* 25 random messages.
* <pre>
* 5k - 61 seconds,
* 25k - 51 seconds,
* 55k - 53 seconds,
* </pre>
* So 25k gives good performance and a reasonable data footprint. Sounds good to me.
*/
private static final int MAX_SMALL_MESSAGE_SIZE = (25 * 1024);
private static final Flag[] FLAG_LIST_SEEN = new Flag[] { Flag.SEEN };
private static final Flag[] FLAG_LIST_FLAGGED = new Flag[] { Flag.FLAGGED };
/**
* We write this into the serverId field of messages that will never be upsynced.
*/
private static final String LOCAL_SERVERID_PREFIX = "Local-";
/**
* Projections & CVs used by pruneCachedAttachments
*/
private static final String[] PRUNE_ATTACHMENT_PROJECTION = new String[] {
AttachmentColumns.LOCATION
};
private static final ContentValues PRUNE_ATTACHMENT_CV = new ContentValues();
static {
PRUNE_ATTACHMENT_CV.putNull(AttachmentColumns.CONTENT_URI);
}
private static MessagingController sInstance = null;
private final BlockingQueue<Command> mCommands = new LinkedBlockingQueue<Command>();
private final Thread mThread;
/**
* All access to mListeners *must* be synchronized
*/
private final GroupMessagingListener mListeners = new GroupMessagingListener();
private boolean mBusy;
private final Context mContext;
private final Controller mController;
protected MessagingController(Context _context, Controller _controller) {
mContext = _context.getApplicationContext();
mController = _controller;
mThread = new Thread(this);
mThread.start();
}
/**
* Gets or creates the singleton instance of MessagingController. Application is used to
* provide a Context to classes that need it.
*/
public synchronized static MessagingController getInstance(Context _context,
Controller _controller) {
if (sInstance == null) {
sInstance = new MessagingController(_context, _controller);
}
return sInstance;
}
/**
* Inject a mock controller. Used only for testing. Affects future calls to getInstance().
*/
public static void injectMockController(MessagingController mockController) {
sInstance = mockController;
}
// TODO: seems that this reading of mBusy isn't thread-safe
public boolean isBusy() {
return mBusy;
}
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
// TODO: add an end test to this infinite loop
while (true) {
Command command;
try {
command = mCommands.take();
} catch (InterruptedException e) {
continue; //re-test the condition on the eclosing while
}
if (command.listener == null || isActiveListener(command.listener)) {
mBusy = true;
command.runnable.run();
mListeners.controllerCommandCompleted(mCommands.size() > 0);
}
mBusy = false;
}
}
private void put(String description, MessagingListener listener, Runnable runnable) {
try {
Command command = new Command();
command.listener = listener;
command.runnable = runnable;
command.description = description;
mCommands.add(command);
}
catch (IllegalStateException ie) {
throw new Error(ie);
}
}
public void addListener(MessagingListener listener) {
mListeners.addListener(listener);
}
public void removeListener(MessagingListener listener) {
mListeners.removeListener(listener);
}
private boolean isActiveListener(MessagingListener listener) {
return mListeners.isActiveListener(listener);
}
/**
* Lightweight class for capturing local mailboxes in an account. Just the columns
* necessary for a sync.
*/
private static class LocalMailboxInfo {
private static final int COLUMN_ID = 0;
private static final int COLUMN_DISPLAY_NAME = 1;
private static final int COLUMN_ACCOUNT_KEY = 2;
private static final int COLUMN_TYPE = 3;
private static final String[] PROJECTION = new String[] {
EmailContent.RECORD_ID,
MailboxColumns.DISPLAY_NAME, MailboxColumns.ACCOUNT_KEY, MailboxColumns.TYPE,
};
final long mId;
final String mDisplayName;
final long mAccountKey;
final int mType;
public LocalMailboxInfo(Cursor c) {
mId = c.getLong(COLUMN_ID);
mDisplayName = c.getString(COLUMN_DISPLAY_NAME);
mAccountKey = c.getLong(COLUMN_ACCOUNT_KEY);
mType = c.getInt(COLUMN_TYPE);
}
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method should be called from
* a Thread as it may take several seconds to list the local folders.
*
* TODO this needs to cache the remote folder list
* TODO break out an inner listFoldersSynchronized which could simplify checkMail
*
* @param account
* @param listener
* @throws MessagingException
*/
public void listFolders(final long accountId, MessagingListener listener) {
final EmailContent.Account account =
EmailContent.Account.restoreAccountWithId(mContext, accountId);
if (account == null) {
return;
}
mListeners.listFoldersStarted(accountId);
put("listFolders", listener, new Runnable() {
public void run() {
Cursor localFolderCursor = null;
try {
// Step 1: Get remote folders, make a list, and add any local folders
// that don't already exist.
Store store = Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder[] remoteFolders = store.getPersonalNamespaces();
HashSet<String> remoteFolderNames = new HashSet<String>();
for (int i = 0, count = remoteFolders.length; i < count; i++) {
remoteFolderNames.add(remoteFolders[i].getName());
}
HashMap<String, LocalMailboxInfo> localFolders =
new HashMap<String, LocalMailboxInfo>();
HashSet<String> localFolderNames = new HashSet<String>();
localFolderCursor = mContext.getContentResolver().query(
EmailContent.Mailbox.CONTENT_URI,
LocalMailboxInfo.PROJECTION,
EmailContent.MailboxColumns.ACCOUNT_KEY + "=?",
new String[] { String.valueOf(account.mId) },
null);
while (localFolderCursor.moveToNext()) {
LocalMailboxInfo info = new LocalMailboxInfo(localFolderCursor);
localFolders.put(info.mDisplayName, info);
localFolderNames.add(info.mDisplayName);
}
// Short circuit the rest if the sets are the same (the usual case)
if (!remoteFolderNames.equals(localFolderNames)) {
// They are different, so we have to do some adds and drops
// Drops first, to make things smaller rather than larger
HashSet<String> localsToDrop = new HashSet<String>(localFolderNames);
localsToDrop.removeAll(remoteFolderNames);
for (String localNameToDrop : localsToDrop) {
LocalMailboxInfo localInfo = localFolders.get(localNameToDrop);
// Exclusion list - never delete local special folders, irrespective
// of server-side existence.
switch (localInfo.mType) {
case Mailbox.TYPE_INBOX:
case Mailbox.TYPE_DRAFTS:
case Mailbox.TYPE_OUTBOX:
case Mailbox.TYPE_SENT:
case Mailbox.TYPE_TRASH:
break;
default:
// Drop all attachment files related to this mailbox
AttachmentProvider.deleteAllMailboxAttachmentFiles(
mContext, accountId, localInfo.mId);
// Delete the mailbox. Triggers will take care of
// related Message, Body and Attachment records.
Uri uri = ContentUris.withAppendedId(
EmailContent.Mailbox.CONTENT_URI, localInfo.mId);
mContext.getContentResolver().delete(uri, null, null);
break;
}
}
// Now do the adds
remoteFolderNames.removeAll(localFolderNames);
for (String remoteNameToAdd : remoteFolderNames) {
EmailContent.Mailbox box = new EmailContent.Mailbox();
box.mDisplayName = remoteNameToAdd;
// box.mServerId;
// box.mParentServerId;
box.mAccountKey = account.mId;
box.mType = LegacyConversions.inferMailboxTypeFromName(
mContext, remoteNameToAdd);
// box.mDelimiter;
// box.mSyncKey;
// box.mSyncLookback;
// box.mSyncFrequency;
// box.mSyncTime;
// box.mUnreadCount;
box.mFlagVisible = true;
// box.mFlags;
box.mVisibleLimit = Email.VISIBLE_LIMIT_DEFAULT;
box.save(mContext);
}
}
mListeners.listFoldersFinished(accountId);
} catch (Exception e) {
mListeners.listFoldersFailed(accountId, "");
} finally {
if (localFolderCursor != null) {
localFolderCursor.close();
}
}
}
});
}
/**
* Start background synchronization of the specified folder.
* @param account
* @param folder
* @param listener
*/
public void synchronizeMailbox(final EmailContent.Account account,
final EmailContent.Mailbox folder, MessagingListener listener) {
/*
* We don't ever sync the Outbox.
*/
if (folder.mType == EmailContent.Mailbox.TYPE_OUTBOX) {
return;
}
mListeners.synchronizeMailboxStarted(account.mId, folder.mId);
put("synchronizeMailbox", listener, new Runnable() {
public void run() {
synchronizeMailboxSynchronous(account, folder);
}
});
}
/**
* Start foreground synchronization of the specified folder. This is called by
* synchronizeMailbox or checkMail.
* TODO this should use ID's instead of fully-restored objects
* @param account
* @param folder
*/
private void synchronizeMailboxSynchronous(final EmailContent.Account account,
final EmailContent.Mailbox folder) {
mListeners.synchronizeMailboxStarted(account.mId, folder.mId);
try {
processPendingActionsSynchronous(account);
StoreSynchronizer.SyncResults results;
// Select generic sync or store-specific sync
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
StoreSynchronizer customSync = remoteStore.getMessageSynchronizer();
if (customSync == null) {
results = synchronizeMailboxGeneric(account, folder);
} else {
results = customSync.SynchronizeMessagesSynchronous(
account, folder, mListeners, mContext);
}
mListeners.synchronizeMailboxFinished(account.mId, folder.mId,
results.mTotalMessages,
results.mNewMessages);
} catch (MessagingException e) {
if (Email.LOGD) {
Log.v(Email.LOG_TAG, "synchronizeMailbox", e);
}
mListeners.synchronizeMailboxFailed(account.mId, folder.mId, e);
}
}
/**
* Lightweight record for the first pass of message sync, where I'm just seeing if
* the local message requires sync. Later (for messages that need syncing) we'll do a full
* readout from the DB.
*/
private static class LocalMessageInfo {
private static final int COLUMN_ID = 0;
private static final int COLUMN_FLAG_READ = 1;
private static final int COLUMN_FLAG_FAVORITE = 2;
private static final int COLUMN_FLAG_LOADED = 3;
private static final int COLUMN_SERVER_ID = 4;
private static final String[] PROJECTION = new String[] {
EmailContent.RECORD_ID,
MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE, MessageColumns.FLAG_LOADED,
SyncColumns.SERVER_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY
};
final int mCursorIndex;
final long mId;
final boolean mFlagRead;
final boolean mFlagFavorite;
final int mFlagLoaded;
final String mServerId;
public LocalMessageInfo(Cursor c) {
mCursorIndex = c.getPosition();
mId = c.getLong(COLUMN_ID);
mFlagRead = c.getInt(COLUMN_FLAG_READ) != 0;
mFlagFavorite = c.getInt(COLUMN_FLAG_FAVORITE) != 0;
mFlagLoaded = c.getInt(COLUMN_FLAG_LOADED);
mServerId = c.getString(COLUMN_SERVER_ID);
// Note: mailbox key and account key not needed - they are projected for the SELECT
}
}
private void saveOrUpdate(EmailContent content, Context context) {
if (content.isSaved()) {
content.update(context, content.toContentValues());
} else {
content.save(context);
}
}
/**
* Generic synchronizer - used for POP3 and IMAP.
*
* TODO Break this method up into smaller chunks.
*
* @param account the account to sync
* @param folder the mailbox to sync
* @return results of the sync pass
* @throws MessagingException
*/
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric(
final EmailContent.Account account, final EmailContent.Mailbox folder)
throws MessagingException {
Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***");
ContentResolver resolver = mContext.getContentResolver();
// 0. We do not ever sync DRAFTS or OUTBOX (down or up)
if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) {
int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null);
return new StoreSynchronizer.SyncResults(totalMessages, 0);
}
// 1. Get the message list from the local store and create an index of the uids
Cursor localUidCursor = null;
HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>();
try {
localUidCursor = resolver.query(
EmailContent.Message.CONTENT_URI,
LocalMessageInfo.PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
},
null);
while (localUidCursor.moveToNext()) {
LocalMessageInfo info = new LocalMessageInfo(localUidCursor);
localMessageMap.put(info.mServerId, info);
}
} finally {
if (localUidCursor != null) {
localUidCursor.close();
}
}
// 1a. Count the unread messages before changing anything
int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?" +
" AND " + MessageColumns.FLAG_READ + "=0",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
});
// 2. Open the remote folder and create the remote folder if necessary
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
|| folder.mType == Mailbox.TYPE_DRAFTS) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return new StoreSynchronizer.SyncResults(0, 0);
}
}
}
// 3, Open the remote folder. This pre-loads certain metadata like message count.
remoteFolder.open(OpenMode.READ_WRITE, null);
// 4. Trash any remote messages that are marked as trashed locally.
// TODO - this comment was here, but no code was here.
// 5. Get the remote message count.
int remoteMessageCount = remoteFolder.getMessageCount();
// 6. Determine the limit # of messages to download
int visibleLimit = folder.mVisibleLimit;
if (visibleLimit <= 0) {
Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
mContext);
visibleLimit = info.mVisibleLimitDefault;
}
// 7. Create a list of messages to download
Message[] remoteMessages = new Message[0];
final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
int newMessageCount = 0;
if (remoteMessageCount > 0) {
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message message : remoteMessages) {
remoteUidMap.put(message.getUid(), message);
}
/*
* Get a list of the messages that are in the remote list but not on the
* local store, or messages that are in the local store but failed to download
* on the last sync. These are the new messages that we will download.
* Note, we also skip syncing messages which are flagged as "deleted message" sentinels,
* because they are locally deleted and we don't need or want the old message from
* the server.
*/
for (Message message : remoteMessages) {
LocalMessageInfo localMessage = localMessageMap.get(message.getUid());
if (localMessage == null) {
newMessageCount++;
}
- if (localMessage == null
- || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)
- || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_PARTIAL)) {
+ // localMessage == null -> message has never been created (not even headers)
+ // mFlagLoaded = UNLOADED -> message created, but none of body loaded
+ // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded
+ // mFlagLoaded = COMPLETE -> message body has been completely loaded
+ // mFlagLoaded = DELETED -> message has been deleted
+ // Only the first two of these are "unsynced", so let's retrieve them
+ if (localMessage == null ||
+ (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) {
unsyncedMessages.add(message);
}
}
}
// 8. Download basic info about the new/unloaded messages (if any)
/*
* A list of messages that were downloaded and which did not have the Seen flag set.
* This will serve to indicate the true "new" message count that will be reported to
* the user via notification.
*/
final ArrayList<Message> newMessages = new ArrayList<Message>();
/*
* Fetch the flags and envelope only of the new messages. This is intended to get us
* critical data as fast as possible, and then we'll fill in the details.
*/
if (unsyncedMessages.size() > 0) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
fp.add(FetchProfile.Item.ENVELOPE);
final HashMap<String, LocalMessageInfo> localMapCopy =
new HashMap<String, LocalMessageInfo>(localMessageMap);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
try {
// Determine if the new message was already known (e.g. partial)
// And create or reload the full message info
LocalMessageInfo localMessageInfo =
localMapCopy.get(message.getUid());
EmailContent.Message localMessage = null;
if (localMessageInfo == null) {
localMessage = new EmailContent.Message();
} else {
localMessage = EmailContent.Message.restoreMessageWithId(
mContext, localMessageInfo.mId);
}
if (localMessage != null) {
try {
// Copy the fields that are available into the message
LegacyConversions.updateMessageFields(localMessage,
message, account.mId, folder.mId);
// Commit the message to the local store
saveOrUpdate(localMessage, mContext);
// Track the "new" ness of the downloaded message
if (!message.isSet(Flag.SEEN)) {
newMessages.add(message);
}
} catch (MessagingException me) {
Log.e(Email.LOG_TAG,
"Error while copying downloaded message." + me);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG,
"Error while storing downloaded message." + e.toString());
}
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
}
// 9. Refresh the flags for any messages in the local store that we didn't just download.
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(remoteMessages, fp, null);
boolean remoteSupportsSeen = false;
boolean remoteSupportsFlagged = false;
for (Flag flag : remoteFolder.getPermanentFlags()) {
if (flag == Flag.SEEN) {
remoteSupportsSeen = true;
}
if (flag == Flag.FLAGGED) {
remoteSupportsFlagged = true;
}
}
// Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3)
if (remoteSupportsSeen || remoteSupportsFlagged) {
for (Message remoteMessage : remoteMessages) {
LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid());
if (localMessageInfo == null) {
continue;
}
boolean localSeen = localMessageInfo.mFlagRead;
boolean remoteSeen = remoteMessage.isSet(Flag.SEEN);
boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen));
boolean localFlagged = localMessageInfo.mFlagFavorite;
boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED);
boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged));
if (newSeen || newFlagged) {
Uri uri = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, localMessageInfo.mId);
ContentValues updateValues = new ContentValues();
updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen);
updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged);
resolver.update(uri, updateValues, null, null);
}
}
}
// 10. Compute and store the unread message count.
// -- no longer necessary - Provider uses DB triggers to keep track
// int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
// if (remoteUnreadMessageCount == -1) {
// if (remoteSupportsSeenFlag) {
// /*
// * If remote folder doesn't supported unread message count but supports
// * seen flag, use local folder's unread message count and the size of
// * new messages. This mode is not used for POP3, or IMAP.
// */
//
// remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size();
// } else {
// /*
// * If remote folder doesn't supported unread message count and doesn't
// * support seen flag, use localUnreadCount and newMessageCount which
// * don't rely on remote SEEN flag. This mode is used by POP3.
// */
// remoteUnreadMessageCount = localUnreadCount + newMessageCount;
// }
// } else {
// /*
// * If remote folder supports unread message count, use remoteUnreadMessageCount.
// * This mode is used by IMAP.
// */
// }
// Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId);
// ContentValues updateValues = new ContentValues();
// updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount);
// resolver.update(uri, updateValues, null, null);
// 11. Remove any messages that are in the local store but no longer on the remote store.
HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet());
localUidsToDelete.removeAll(remoteUidMap.keySet());
for (String uidToDelete : localUidsToDelete) {
LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete);
// Delete associated data (attachment files)
// Attachment & Body records are auto-deleted when we delete the Message record
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId);
// Delete the message itself
Uri uriToDelete = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, infoToDelete.mId);
resolver.delete(uriToDelete, null, null);
// Delete extra rows (e.g. synced or deleted)
Uri syncRowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(syncRowToDelete, null, null);
Uri deletERowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(deletERowToDelete, null, null);
}
// 12. Divide the unsynced messages into small & large (by size)
// TODO doing this work here (synchronously) is problematic because it prevents the UI
// from affecting the order (e.g. download a message because the user requested it.) Much
// of this logic should move out to a different sync loop that attempts to update small
// groups of messages at a time, as a background task. However, we can't just return
// (yet) because POP messages don't have an envelope yet....
ArrayList<Message> largeMessages = new ArrayList<Message>();
ArrayList<Message> smallMessages = new ArrayList<Message>();
for (Message message : unsyncedMessages) {
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
}
// 13. Download small messages
// TODO Problems with this implementation. 1. For IMAP, where we get a real envelope,
// this is going to be inefficient and duplicate work we've already done. 2. It's going
// back to the DB for a local message that we already had (and discarded).
// For small messages, we specify "body", which returns everything (incl. attachments)
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
// 14. Download large messages. We ask the server to give us the message structure,
// but not all of the attachments.
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
// POP doesn't support STRUCTURE mode, so we'll just do a partial download
// (hopefully enough to see some/all of the body) and mark the message for
// further download.
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
// TODO a good optimization here would be to make sure that all Stores set
// the proper size after this fetch and compare the before and after size. If
// they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the partially-loaded message and mark it partially loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_PARTIAL);
} else {
// We have a structure to deal with, from which
// we can pull down the parts we want to actually store.
// Build a list of parts we are interested in. Text parts will be downloaded
// right now, attachments will be left for later.
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
// Download the viewables immediately
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
}
// 15. Clean up and report results
remoteFolder.close(false);
// TODO - more
// Original sync code. Using for reference, will delete when done.
if (false) {
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
// localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
// localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// Update the listener with what we've found
// synchronized (mListeners) {
// for (MessagingListener l : mListeners) {
// l.synchronizeMailboxNewMessage(
// account,
// folder,
// localFolder.getMessage(message.getUid()));
// }
// }
}
/*
* Report successful sync
*/
StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults(
remoteFolder.getMessageCount(), newMessages.size());
remoteFolder.close(false);
// localFolder.close(false);
return results;
}
return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size());
}
/**
* Copy one downloaded message (which may have partially-loaded sections)
* into a newly created EmailProvider Message, given the account and mailbox
*
* @param message the remote message we've just downloaded
* @param account the account it will be stored into
* @param folder the mailbox it will be stored into
* @param loadStatus when complete, the message will be marked with this status (e.g.
* EmailContent.Message.LOADED)
*/
public void copyOneMessageToProvider(Message message, EmailContent.Account account,
EmailContent.Mailbox folder, int loadStatus) {
EmailContent.Message localMessage = null;
Cursor c = null;
try {
c = mContext.getContentResolver().query(
EmailContent.Message.CONTENT_URI,
EmailContent.Message.CONTENT_PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?" +
" AND " + SyncColumns.SERVER_ID + "=?",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId),
String.valueOf(message.getUid())
},
null);
if (c.moveToNext()) {
localMessage = EmailContent.getContent(c, EmailContent.Message.class);
localMessage.mMailboxKey = folder.mId;
localMessage.mAccountKey = account.mId;
copyOneMessageToProvider(message, localMessage, loadStatus, mContext);
}
} finally {
if (c != null) {
c.close();
}
}
}
/**
* Copy one downloaded message (which may have partially-loaded sections)
* into an already-created EmailProvider Message
*
* @param message the remote message we've just downloaded
* @param localMessage the EmailProvider Message, already created
* @param loadStatus when complete, the message will be marked with this status (e.g.
* EmailContent.Message.LOADED)
* @param context the context to be used for EmailProvider
*/
public void copyOneMessageToProvider(Message message, EmailContent.Message localMessage,
int loadStatus, Context context) {
try {
EmailContent.Body body = EmailContent.Body.restoreBodyWithMessageId(context,
localMessage.mId);
if (body == null) {
body = new EmailContent.Body();
}
try {
// Copy the fields that are available into the message object
LegacyConversions.updateMessageFields(localMessage, message,
localMessage.mAccountKey, localMessage.mMailboxKey);
// Now process body parts & attachments
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
LegacyConversions.updateBodyFields(body, localMessage, viewables);
// Commit the message & body to the local store immediately
saveOrUpdate(localMessage, context);
saveOrUpdate(body, context);
// process (and save) attachments
LegacyConversions.updateAttachments(context, localMessage,
attachments, false);
// One last update of message with two updated flags
localMessage.mFlagLoaded = loadStatus;
ContentValues cv = new ContentValues();
cv.put(EmailContent.MessageColumns.FLAG_ATTACHMENT, localMessage.mFlagAttachment);
cv.put(EmailContent.MessageColumns.FLAG_LOADED, localMessage.mFlagLoaded);
Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI,
localMessage.mId);
context.getContentResolver().update(uri, cv, null, null);
} catch (MessagingException me) {
Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me);
}
} catch (RuntimeException rte) {
Log.e(Email.LOG_TAG, "Error while storing downloaded message." + rte.toString());
} catch (IOException ioe) {
Log.e(Email.LOG_TAG, "Error while storing attachment." + ioe.toString());
}
}
public void processPendingActions(final long accountId) {
put("processPendingActions", null, new Runnable() {
public void run() {
try {
EmailContent.Account account =
EmailContent.Account.restoreAccountWithId(mContext, accountId);
if (account == null) {
return;
}
processPendingActionsSynchronous(account);
}
catch (MessagingException me) {
if (Email.LOGD) {
Log.v(Email.LOG_TAG, "processPendingActions", me);
}
/*
* Ignore any exceptions from the commands. Commands will be processed
* on the next round.
*/
}
}
});
}
/**
* Find messages in the updated table that need to be written back to server.
*
* Handles:
* Read/Unread
* Flagged
* Append (upload)
* Move To Trash
* Empty trash
* TODO:
* Move
*
* @param account the account to scan for pending actions
* @throws MessagingException
*/
private void processPendingActionsSynchronous(EmailContent.Account account)
throws MessagingException {
ContentResolver resolver = mContext.getContentResolver();
String[] accountIdArgs = new String[] { Long.toString(account.mId) };
// Handle deletes first, it's always better to get rid of things first
processPendingDeletesSynchronous(account, resolver, accountIdArgs);
// Handle uploads (currently, only to sent messages)
processPendingUploadsSynchronous(account, resolver, accountIdArgs);
// Now handle updates / upsyncs
processPendingUpdatesSynchronous(account, resolver, accountIdArgs);
}
/**
* Scan for messages that are in the Message_Deletes table, look for differences that
* we can deal with, and do the work.
*
* @param account
* @param resolver
* @param accountIdArgs
*/
private void processPendingDeletesSynchronous(EmailContent.Account account,
ContentResolver resolver, String[] accountIdArgs) {
Cursor deletes = resolver.query(EmailContent.Message.DELETED_CONTENT_URI,
EmailContent.Message.CONTENT_PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?", accountIdArgs,
EmailContent.MessageColumns.MAILBOX_KEY);
long lastMessageId = -1;
try {
// Defer setting up the store until we know we need to access it
Store remoteStore = null;
// Demand load mailbox (note order-by to reduce thrashing here)
Mailbox mailbox = null;
// loop through messages marked as deleted
while (deletes.moveToNext()) {
boolean deleteFromTrash = false;
EmailContent.Message oldMessage =
EmailContent.getContent(deletes, EmailContent.Message.class);
if (oldMessage != null) {
lastMessageId = oldMessage.mId;
if (mailbox == null || mailbox.mId != oldMessage.mMailboxKey) {
mailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
if (mailbox == null) {
continue; // Mailbox removed. Move to the next message.
}
}
deleteFromTrash = mailbox.mType == Mailbox.TYPE_TRASH;
}
// Load the remote store if it will be needed
if (remoteStore == null && deleteFromTrash) {
remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
}
// Dispatch here for specific change types
if (deleteFromTrash) {
// Move message to trash
processPendingDeleteFromTrash(remoteStore, account, mailbox, oldMessage);
}
// Finally, delete the update
Uri uri = ContentUris.withAppendedId(EmailContent.Message.DELETED_CONTENT_URI,
oldMessage.mId);
resolver.delete(uri, null, null);
}
} catch (MessagingException me) {
// Presumably an error here is an account connection failure, so there is
// no point in continuing through the rest of the pending updates.
if (Email.DEBUG) {
Log.d(Email.LOG_TAG, "Unable to process pending delete for id="
+ lastMessageId + ": " + me);
}
} finally {
deletes.close();
}
}
/**
* Scan for messages that are in Sent, and are in need of upload,
* and send them to the server. "In need of upload" is defined as:
* serverId == null (no UID has been assigned)
* or
* message is in the updated list
*
* Note we also look for messages that are moving from drafts->outbox->sent. They never
* go through "drafts" or "outbox" on the server, so we hang onto these until they can be
* uploaded directly to the Sent folder.
*
* @param account
* @param resolver
* @param accountIdArgs
*/
private void processPendingUploadsSynchronous(EmailContent.Account account,
ContentResolver resolver, String[] accountIdArgs) throws MessagingException {
// Find the Sent folder (since that's all we're uploading for now
Cursor mailboxes = resolver.query(Mailbox.CONTENT_URI, Mailbox.ID_PROJECTION,
MailboxColumns.ACCOUNT_KEY + "=?"
+ " and " + MailboxColumns.TYPE + "=" + Mailbox.TYPE_SENT,
accountIdArgs, null);
long lastMessageId = -1;
try {
// Defer setting up the store until we know we need to access it
Store remoteStore = null;
while (mailboxes.moveToNext()) {
long mailboxId = mailboxes.getLong(Mailbox.ID_PROJECTION_COLUMN);
String[] mailboxKeyArgs = new String[] { Long.toString(mailboxId) };
// Demand load mailbox
Mailbox mailbox = null;
// First handle the "new" messages (serverId == null)
Cursor upsyncs1 = resolver.query(EmailContent.Message.CONTENT_URI,
EmailContent.Message.ID_PROJECTION,
EmailContent.Message.MAILBOX_KEY + "=?"
+ " and (" + EmailContent.Message.SERVER_ID + " is null"
+ " or " + EmailContent.Message.SERVER_ID + "=''" + ")",
mailboxKeyArgs,
null);
try {
while (upsyncs1.moveToNext()) {
// Load the remote store if it will be needed
if (remoteStore == null) {
remoteStore =
Store.getInstance(account.getStoreUri(mContext), mContext, null);
}
// Load the mailbox if it will be needed
if (mailbox == null) {
mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId);
if (mailbox == null) {
continue; // Mailbox removed. Move to the next message.
}
}
// upsync the message
long id = upsyncs1.getLong(EmailContent.Message.ID_PROJECTION_COLUMN);
lastMessageId = id;
processUploadMessage(resolver, remoteStore, account, mailbox, id);
}
} finally {
if (upsyncs1 != null) {
upsyncs1.close();
}
}
// Next, handle any updates (e.g. edited in place, although this shouldn't happen)
Cursor upsyncs2 = resolver.query(EmailContent.Message.UPDATED_CONTENT_URI,
EmailContent.Message.ID_PROJECTION,
EmailContent.MessageColumns.MAILBOX_KEY + "=?", mailboxKeyArgs,
null);
try {
while (upsyncs2.moveToNext()) {
// Load the remote store if it will be needed
if (remoteStore == null) {
remoteStore =
Store.getInstance(account.getStoreUri(mContext), mContext, null);
}
// Load the mailbox if it will be needed
if (mailbox == null) {
mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId);
if (mailbox == null) {
continue; // Mailbox removed. Move to the next message.
}
}
// upsync the message
long id = upsyncs2.getLong(EmailContent.Message.ID_PROJECTION_COLUMN);
lastMessageId = id;
processUploadMessage(resolver, remoteStore, account, mailbox, id);
}
} finally {
if (upsyncs2 != null) {
upsyncs2.close();
}
}
}
} catch (MessagingException me) {
// Presumably an error here is an account connection failure, so there is
// no point in continuing through the rest of the pending updates.
if (Email.DEBUG) {
Log.d(Email.LOG_TAG, "Unable to process pending upsync for id="
+ lastMessageId + ": " + me);
}
} finally {
if (mailboxes != null) {
mailboxes.close();
}
}
}
/**
* Scan for messages that are in the Message_Updates table, look for differences that
* we can deal with, and do the work.
*
* @param account
* @param resolver
* @param accountIdArgs
*/
private void processPendingUpdatesSynchronous(EmailContent.Account account,
ContentResolver resolver, String[] accountIdArgs) {
Cursor updates = resolver.query(EmailContent.Message.UPDATED_CONTENT_URI,
EmailContent.Message.CONTENT_PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?", accountIdArgs,
EmailContent.MessageColumns.MAILBOX_KEY);
long lastMessageId = -1;
try {
// Defer setting up the store until we know we need to access it
Store remoteStore = null;
// Demand load mailbox (note order-by to reduce thrashing here)
Mailbox mailbox = null;
// loop through messages marked as needing updates
while (updates.moveToNext()) {
boolean changeMoveToTrash = false;
boolean changeRead = false;
boolean changeFlagged = false;
boolean changeMailbox = false;
EmailContent.Message oldMessage =
EmailContent.getContent(updates, EmailContent.Message.class);
lastMessageId = oldMessage.mId;
EmailContent.Message newMessage =
EmailContent.Message.restoreMessageWithId(mContext, oldMessage.mId);
if (newMessage != null) {
if (mailbox == null || mailbox.mId != newMessage.mMailboxKey) {
mailbox = Mailbox.restoreMailboxWithId(mContext, newMessage.mMailboxKey);
if (mailbox == null) {
continue; // Mailbox removed. Move to the next message.
}
}
if (oldMessage.mMailboxKey != newMessage.mMailboxKey) {
if (mailbox.mType == Mailbox.TYPE_TRASH) {
changeMoveToTrash = true;
} else {
changeMailbox = true;
}
}
changeRead = oldMessage.mFlagRead != newMessage.mFlagRead;
changeFlagged = oldMessage.mFlagFavorite != newMessage.mFlagFavorite;
}
// Load the remote store if it will be needed
if (remoteStore == null &&
(changeMoveToTrash || changeRead || changeFlagged || changeMailbox)) {
remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
}
// Dispatch here for specific change types
if (changeMoveToTrash) {
// Move message to trash
processPendingMoveToTrash(remoteStore, account, mailbox, oldMessage,
newMessage);
} else if (changeRead || changeFlagged || changeMailbox) {
processPendingDataChange(remoteStore, mailbox, changeRead, changeFlagged,
changeMailbox, oldMessage, newMessage);
}
// Finally, delete the update
Uri uri = ContentUris.withAppendedId(EmailContent.Message.UPDATED_CONTENT_URI,
oldMessage.mId);
resolver.delete(uri, null, null);
}
} catch (MessagingException me) {
// Presumably an error here is an account connection failure, so there is
// no point in continuing through the rest of the pending updates.
if (Email.DEBUG) {
Log.d(Email.LOG_TAG, "Unable to process pending update for id="
+ lastMessageId + ": " + me);
}
} finally {
updates.close();
}
}
/**
* Upsync an entire message. This must also unwind whatever triggered it (either by
* updating the serverId, or by deleting the update record, or it's going to keep happening
* over and over again.
*
* Note: If the message is being uploaded into an unexpected mailbox, we *do not* upload.
* This is to avoid unnecessary uploads into the trash. Although the caller attempts to select
* only the Drafts and Sent folders, this can happen when the update record and the current
* record mismatch. In this case, we let the update record remain, because the filters
* in processPendingUpdatesSynchronous() will pick it up as a move and handle it (or drop it)
* appropriately.
*
* @param resolver
* @param remoteStore
* @param account
* @param mailbox the actual mailbox
* @param messageId
*/
private void processUploadMessage(ContentResolver resolver, Store remoteStore,
EmailContent.Account account, Mailbox mailbox, long messageId)
throws MessagingException {
EmailContent.Message message =
EmailContent.Message.restoreMessageWithId(mContext, messageId);
boolean deleteUpdate = false;
if (message == null) {
deleteUpdate = true;
Log.d(Email.LOG_TAG, "Upsync failed for null message, id=" + messageId);
} else if (mailbox.mType == Mailbox.TYPE_DRAFTS) {
deleteUpdate = false;
Log.d(Email.LOG_TAG, "Upsync skipped for mailbox=drafts, id=" + messageId);
} else if (mailbox.mType == Mailbox.TYPE_OUTBOX) {
deleteUpdate = false;
Log.d(Email.LOG_TAG, "Upsync skipped for mailbox=outbox, id=" + messageId);
} else if (mailbox.mType == Mailbox.TYPE_TRASH) {
deleteUpdate = false;
Log.d(Email.LOG_TAG, "Upsync skipped for mailbox=trash, id=" + messageId);
} else {
Log.d(Email.LOG_TAG, "Upsyc triggered for message id=" + messageId);
deleteUpdate = processPendingAppend(remoteStore, account, mailbox, message);
}
if (deleteUpdate) {
// Finally, delete the update (if any)
Uri uri = ContentUris.withAppendedId(EmailContent.Message.UPDATED_CONTENT_URI, messageId);
resolver.delete(uri, null, null);
}
}
/**
* Upsync changes to read, flagged, or mailbox
*
* @param remoteStore the remote store for this mailbox
* @param mailbox the mailbox the message is stored in
* @param changeRead whether the message's read state has changed
* @param changeFlagged whether the message's flagged state has changed
* @param changeMailbox whether the message's mailbox has changed
* @param oldMessage the message in it's pre-change state
* @param newMessage the current version of the message
*/
private void processPendingDataChange(Store remoteStore, Mailbox mailbox, boolean changeRead,
boolean changeFlagged, boolean changeMailbox, EmailContent.Message oldMessage,
EmailContent.Message newMessage) throws MessagingException {
Mailbox newMailbox = null;;
// 0. No remote update if the message is local-only
if (newMessage.mServerId == null || newMessage.mServerId.equals("")
|| newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX) || (mailbox == null)) {
return;
}
// 0.5 If the mailbox has changed, use the original mailbox for operations
// After any flag changes (which we execute in the original mailbox), we then
// copy the message to the new mailbox
if (changeMailbox) {
newMailbox = mailbox;
mailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
}
// 1. No remote update for DRAFTS or OUTBOX
if (mailbox.mType == Mailbox.TYPE_DRAFTS || mailbox.mType == Mailbox.TYPE_OUTBOX) {
return;
}
// 2. Open the remote store & folder
Folder remoteFolder = remoteStore.getFolder(mailbox.mDisplayName);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(OpenMode.READ_WRITE, null);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
return;
}
// 3. Finally, apply the changes to the message
Message remoteMessage = remoteFolder.getMessage(newMessage.mServerId);
if (remoteMessage == null) {
return;
}
if (Email.DEBUG) {
Log.d(Email.LOG_TAG,
"Update for msg id=" + newMessage.mId
+ " read=" + newMessage.mFlagRead
+ " flagged=" + newMessage.mFlagFavorite
+ " new mailbox=" + newMessage.mMailboxKey);
}
Message[] messages = new Message[] { remoteMessage };
if (changeRead) {
remoteFolder.setFlags(messages, FLAG_LIST_SEEN, newMessage.mFlagRead);
}
if (changeFlagged) {
remoteFolder.setFlags(messages, FLAG_LIST_FLAGGED, newMessage.mFlagFavorite);
}
if (changeMailbox) {
Folder toFolder = remoteStore.getFolder(newMailbox.mDisplayName);
if (!remoteFolder.exists()) {
return;
}
// Copy the message to its new folder
remoteFolder.copyMessages(messages, toFolder, null);
// Delete the message from the remote source folder
remoteMessage.setFlag(Flag.DELETED, true);
remoteFolder.expunge();
// Set the serverId to 0, since we don't know what the new server id will be
ContentValues cv = new ContentValues();
cv.put(EmailContent.Message.SERVER_ID, "0");
mContext.getContentResolver().update(ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, newMessage.mId), cv, null, null);
}
remoteFolder.close(false);
}
/**
* Process a pending trash message command.
*
* @param remoteStore the remote store we're working in
* @param account The account in which we are working
* @param newMailbox The local trash mailbox
* @param oldMessage The message copy that was saved in the updates shadow table
* @param newMessage The message that was moved to the mailbox
*/
private void processPendingMoveToTrash(Store remoteStore,
EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage,
final EmailContent.Message newMessage) throws MessagingException {
// 0. No remote move if the message is local-only
if (newMessage.mServerId == null || newMessage.mServerId.equals("")
|| newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) {
return;
}
// 1. Escape early if we can't find the local mailbox
// TODO smaller projection here
Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
if (oldMailbox == null) {
// can't find old mailbox, it may have been deleted. just return.
return;
}
// 2. We don't support delete-from-trash here
if (oldMailbox.mType == Mailbox.TYPE_TRASH) {
return;
}
// 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return
//
// This sentinel takes the place of the server-side message, and locally "deletes" it
// by inhibiting future sync or display of the message. It will eventually go out of
// scope when it becomes old, or is deleted on the server, and the regular sync code
// will clean it up for us.
if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) {
EmailContent.Message sentinel = new EmailContent.Message();
sentinel.mAccountKey = oldMessage.mAccountKey;
sentinel.mMailboxKey = oldMessage.mMailboxKey;
sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED;
sentinel.mFlagRead = true;
sentinel.mServerId = oldMessage.mServerId;
sentinel.save(mContext);
return;
}
// The rest of this method handles server-side deletion
// 4. Find the remote mailbox (that we deleted from), and open it
Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(OpenMode.READ_WRITE, null);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
remoteFolder.close(false);
return;
}
// 5. Find the remote original message
Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId);
if (remoteMessage == null) {
remoteFolder.close(false);
return;
}
// 6. Find the remote trash folder, and create it if not found
Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName);
if (!remoteTrashFolder.exists()) {
/*
* If the remote trash folder doesn't exist we try to create it.
*/
remoteTrashFolder.create(FolderType.HOLDS_MESSAGES);
}
// 7. Try to copy the message into the remote trash folder
// Note, this entire section will be skipped for POP3 because there's no remote trash
if (remoteTrashFolder.exists()) {
/*
* Because remoteTrashFolder may be new, we need to explicitly open it
*/
remoteTrashFolder.open(OpenMode.READ_WRITE, null);
if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
remoteFolder.close(false);
remoteTrashFolder.close(false);
return;
}
remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder,
new Folder.MessageUpdateCallbacks() {
public void onMessageUidChange(Message message, String newUid) {
// update the UID in the local trash folder, because some stores will
// have to change it when copying to remoteTrashFolder
ContentValues cv = new ContentValues();
cv.put(EmailContent.Message.SERVER_ID, newUid);
mContext.getContentResolver().update(newMessage.getUri(), cv, null, null);
}
/**
* This will be called if the deleted message doesn't exist and can't be
* deleted (e.g. it was already deleted from the server.) In this case,
* attempt to delete the local copy as well.
*/
public void onMessageNotFound(Message message) {
mContext.getContentResolver().delete(newMessage.getUri(), null, null);
}
});
remoteTrashFolder.close(false);
}
// 8. Delete the message from the remote source folder
remoteMessage.setFlag(Flag.DELETED, true);
remoteFolder.expunge();
remoteFolder.close(false);
}
/**
* Process a pending trash message command.
*
* @param remoteStore the remote store we're working in
* @param account The account in which we are working
* @param oldMailbox The local trash mailbox
* @param oldMessage The message that was deleted from the trash
*/
private void processPendingDeleteFromTrash(Store remoteStore,
EmailContent.Account account, Mailbox oldMailbox, EmailContent.Message oldMessage)
throws MessagingException {
// 1. We only support delete-from-trash here
if (oldMailbox.mType != Mailbox.TYPE_TRASH) {
return;
}
// 2. Find the remote trash folder (that we are deleting from), and open it
Folder remoteTrashFolder = remoteStore.getFolder(oldMailbox.mDisplayName);
if (!remoteTrashFolder.exists()) {
return;
}
remoteTrashFolder.open(OpenMode.READ_WRITE, null);
if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
remoteTrashFolder.close(false);
return;
}
// 3. Find the remote original message
Message remoteMessage = remoteTrashFolder.getMessage(oldMessage.mServerId);
if (remoteMessage == null) {
remoteTrashFolder.close(false);
return;
}
// 4. Delete the message from the remote trash folder
remoteMessage.setFlag(Flag.DELETED, true);
remoteTrashFolder.expunge();
remoteTrashFolder.close(false);
}
/**
* Process a pending append message command. This command uploads a local message to the
* server, first checking to be sure that the server message is not newer than
* the local message.
*
* @param remoteStore the remote store we're working in
* @param account The account in which we are working
* @param newMailbox The mailbox we're appending to
* @param message The message we're appending
* @return true if successfully uploaded
*/
private boolean processPendingAppend(Store remoteStore, EmailContent.Account account,
Mailbox newMailbox, EmailContent.Message message)
throws MessagingException {
boolean updateInternalDate = false;
boolean updateMessage = false;
boolean deleteMessage = false;
// 1. Find the remote folder that we're appending to and create and/or open it
Folder remoteFolder = remoteStore.getFolder(newMailbox.mDisplayName);
if (!remoteFolder.exists()) {
if (!remoteFolder.canCreate(FolderType.HOLDS_MESSAGES)) {
// This is POP3, we cannot actually upload. Instead, we'll update the message
// locally with a fake serverId (so we don't keep trying here) and return.
if (message.mServerId == null || message.mServerId.length() == 0) {
message.mServerId = LOCAL_SERVERID_PREFIX + message.mId;
Uri uri =
ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, message.mId);
ContentValues cv = new ContentValues();
cv.put(EmailContent.Message.SERVER_ID, message.mServerId);
mContext.getContentResolver().update(uri, cv, null, null);
}
return true;
}
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
// This is a (hopefully) transient error and we return false to try again later
return false;
}
}
remoteFolder.open(OpenMode.READ_WRITE, null);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
return false;
}
// 2. If possible, load a remote message with the matching UID
Message remoteMessage = null;
if (message.mServerId != null && message.mServerId.length() > 0) {
remoteMessage = remoteFolder.getMessage(message.mServerId);
}
// 3. If a remote message could not be found, upload our local message
if (remoteMessage == null) {
// 3a. Create a legacy message to upload
Message localMessage = LegacyConversions.makeMessage(mContext, message);
// 3b. Upload it
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.appendMessages(new Message[] { localMessage });
// 3b. And record the UID from the server
message.mServerId = localMessage.getUid();
updateInternalDate = true;
updateMessage = true;
} else {
// 4. If the remote message exists we need to determine which copy to keep.
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
Date localDate = new Date(message.mServerTimeStamp);
Date remoteDate = remoteMessage.getInternalDate();
if (remoteDate != null && remoteDate.compareTo(localDate) > 0) {
// 4a. If the remote message is newer than ours we'll just
// delete ours and move on. A sync will get the server message
// if we need to be able to see it.
deleteMessage = true;
} else {
// 4b. Otherwise we'll upload our message and then delete the remote message.
// Create a legacy message to upload
Message localMessage = LegacyConversions.makeMessage(mContext, message);
// 4c. Upload it
fp.clear();
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.appendMessages(new Message[] { localMessage });
// 4d. Record the UID and new internalDate from the server
message.mServerId = localMessage.getUid();
updateInternalDate = true;
updateMessage = true;
// 4e. And delete the old copy of the message from the server
remoteMessage.setFlag(Flag.DELETED, true);
}
}
// 5. If requested, Best-effort to capture new "internaldate" from the server
if (updateInternalDate && message.mServerId != null) {
try {
Message remoteMessage2 = remoteFolder.getMessage(message.mServerId);
if (remoteMessage2 != null) {
FetchProfile fp2 = new FetchProfile();
fp2.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(new Message[] { remoteMessage2 }, fp2, null);
message.mServerTimeStamp = remoteMessage2.getInternalDate().getTime();
updateMessage = true;
}
} catch (MessagingException me) {
// skip it - we can live without this
}
}
// 6. Perform required edits to local copy of message
if (deleteMessage || updateMessage) {
Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, message.mId);
ContentResolver resolver = mContext.getContentResolver();
if (deleteMessage) {
resolver.delete(uri, null, null);
} else if (updateMessage) {
ContentValues cv = new ContentValues();
cv.put(EmailContent.Message.SERVER_ID, message.mServerId);
cv.put(EmailContent.Message.SERVER_TIMESTAMP, message.mServerTimeStamp);
resolver.update(uri, cv, null, null);
}
}
return true;
}
/**
* Finish loading a message that have been partially downloaded.
*
* @param messageId the message to load
* @param listener the callback by which results will be reported
*/
public void loadMessageForView(final long messageId, MessagingListener listener) {
mListeners.loadMessageForViewStarted(messageId);
put("loadMessageForViewRemote", listener, new Runnable() {
public void run() {
try {
// 1. Resample the message, in case it disappeared or synced while
// this command was in queue
EmailContent.Message message =
EmailContent.Message.restoreMessageWithId(mContext, messageId);
if (message == null) {
mListeners.loadMessageForViewFailed(messageId, "Unknown message");
return;
}
if (message.mFlagLoaded == EmailContent.Message.FLAG_LOADED_COMPLETE) {
mListeners.loadMessageForViewFinished(messageId);
return;
}
// 2. Open the remote folder.
// TODO all of these could be narrower projections
// TODO combine with common code in loadAttachment
EmailContent.Account account =
EmailContent.Account.restoreAccountWithId(mContext, message.mAccountKey);
EmailContent.Mailbox mailbox =
EmailContent.Mailbox.restoreMailboxWithId(mContext, message.mMailboxKey);
if (account == null || mailbox == null) {
mListeners.loadMessageForViewFailed(messageId, "null account or mailbox");
return;
}
Store remoteStore =
Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(mailbox.mDisplayName);
remoteFolder.open(OpenMode.READ_WRITE, null);
// 3. Not supported, because IMAP & POP don't use it: structure prefetch
// if (remoteStore.requireStructurePrefetch()) {
// // For remote stores that require it, prefetch the message structure.
// FetchProfile fp = new FetchProfile();
// fp.add(FetchProfile.Item.STRUCTURE);
// localFolder.fetch(new Message[] { message }, fp, null);
//
// ArrayList<Part> viewables = new ArrayList<Part>();
// ArrayList<Part> attachments = new ArrayList<Part>();
// MimeUtility.collectParts(message, viewables, attachments);
// fp.clear();
// for (Part part : viewables) {
// fp.add(part);
// }
//
// remoteFolder.fetch(new Message[] { message }, fp, null);
//
// // Store the updated message locally
// localFolder.updateMessage((LocalMessage)message);
// 4. Set up to download the entire message
Message remoteMessage = remoteFolder.getMessage(message.mServerId);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
// 5. Write to provider
copyOneMessageToProvider(remoteMessage, account, mailbox,
EmailContent.Message.FLAG_LOADED_COMPLETE);
// 6. Notify UI
mListeners.loadMessageForViewFinished(messageId);
} catch (MessagingException me) {
if (Email.LOGD) Log.v(Email.LOG_TAG, "", me);
mListeners.loadMessageForViewFailed(messageId, me.getMessage());
} catch (RuntimeException rte) {
mListeners.loadMessageForViewFailed(messageId, rte.getMessage());
}
}
});
}
/**
* Attempts to load the attachment specified by id from the given account and message.
* @param account
* @param message
* @param part
* @param listener
*/
public void loadAttachment(final long accountId, final long messageId, final long mailboxId,
final long attachmentId, MessagingListener listener) {
mListeners.loadAttachmentStarted(accountId, messageId, attachmentId, true);
put("loadAttachment", listener, new Runnable() {
public void run() {
try {
//1. Check if the attachment is already here and return early in that case
Attachment attachment =
Attachment.restoreAttachmentWithId(mContext, attachmentId);
if (attachment == null) {
mListeners.loadAttachmentFailed(accountId, messageId, attachmentId,
new MessagingException("The attachment is null"));
return;
}
if (Utility.attachmentExists(mContext, attachment)) {
mListeners.loadAttachmentFinished(accountId, messageId, attachmentId);
return;
}
// 2. Open the remote folder.
// TODO all of these could be narrower projections
EmailContent.Account account =
EmailContent.Account.restoreAccountWithId(mContext, accountId);
EmailContent.Mailbox mailbox =
EmailContent.Mailbox.restoreMailboxWithId(mContext, mailboxId);
EmailContent.Message message =
EmailContent.Message.restoreMessageWithId(mContext, messageId);
if (account == null || mailbox == null || message == null) {
mListeners.loadAttachmentFailed(accountId, messageId, attachmentId,
new MessagingException(
"Account, mailbox, message or attachment are null"));
return;
}
Store remoteStore =
Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(mailbox.mDisplayName);
remoteFolder.open(OpenMode.READ_WRITE, null);
// 3. Generate a shell message in which to retrieve the attachment,
// and a shell BodyPart for the attachment. Then glue them together.
Message storeMessage = remoteFolder.createMessage(message.mServerId);
MimeBodyPart storePart = new MimeBodyPart();
storePart.setSize((int)attachment.mSize);
storePart.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA,
attachment.mLocation);
storePart.setHeader(MimeHeader.HEADER_CONTENT_TYPE,
String.format("%s;\n name=\"%s\"",
attachment.mMimeType,
attachment.mFileName));
// TODO is this always true for attachments? I think we dropped the
// true encoding along the way
storePart.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
MimeMultipart multipart = new MimeMultipart();
multipart.setSubType("mixed");
multipart.addBodyPart(storePart);
storeMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed");
storeMessage.setBody(multipart);
// 4. Now ask for the attachment to be fetched
FetchProfile fp = new FetchProfile();
fp.add(storePart);
remoteFolder.fetch(new Message[] { storeMessage }, fp,
mController.new LegacyListener(messageId, attachmentId));
// If we failed to load the attachment, throw an Exception here, so that
// AttachmentDownloadService knows that we failed
if (storePart.getBody() == null) {
throw new MessagingException("Attachment not loaded.");
}
// 5. Save the downloaded file and update the attachment as necessary
LegacyConversions.saveAttachmentBody(mContext, storePart, attachment,
accountId);
// 6. Report success
mListeners.loadAttachmentFinished(accountId, messageId, attachmentId);
}
catch (MessagingException me) {
if (Email.LOGD) Log.v(Email.LOG_TAG, "", me);
mListeners.loadAttachmentFailed(accountId, messageId, attachmentId, me);
} catch (IOException ioe) {
Log.e(Email.LOG_TAG, "Error while storing attachment." + ioe.toString());
}
}});
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessages(final EmailContent.Account account, final long sentFolderId,
MessagingListener listener) {
put("sendPendingMessages", listener, new Runnable() {
public void run() {
sendPendingMessagesSynchronous(account, sentFolderId);
}
});
}
/**
* Attempt to send any messages that are sitting in the Outbox.
*
* @param account
* @param listener
*/
public void sendPendingMessagesSynchronous(final EmailContent.Account account,
long sentFolderId) {
// 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;
}
ContentResolver resolver = mContext.getContentResolver();
Cursor c = resolver.query(EmailContent.Message.CONTENT_URI,
EmailContent.Message.ID_COLUMN_PROJECTION,
EmailContent.Message.MAILBOX_KEY + "=?", new String[] { Long.toString(outboxId) },
null);
try {
// 2. exit early
if (c.getCount() <= 0) {
return;
}
// 3. do one-time setup of the Sender & other stuff
mListeners.sendPendingMessagesStarted(account.mId, -1);
Sender sender = Sender.getInstance(mContext, account.getSenderUri(mContext));
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
boolean requireMoveMessageToSentFolder = remoteStore.requireCopyMessageToSentFolder();
ContentValues moveToSentValues = null;
if (requireMoveMessageToSentFolder) {
moveToSentValues = new ContentValues();
moveToSentValues.put(MessageColumns.MAILBOX_KEY, sentFolderId);
}
// 4. loop through the available messages and send them
while (c.moveToNext()) {
long messageId = -1;
try {
messageId = c.getLong(0);
mListeners.sendPendingMessagesStarted(account.mId, messageId);
// Don't send messages with unloaded attachments
if (Utility.hasUnloadedAttachments(mContext, messageId)) {
if (Email.DEBUG) {
Log.d(Email.LOG_TAG, "Can't send #" + messageId +
"; unloaded attachments");
}
continue;
}
sender.sendMessage(messageId);
} catch (MessagingException me) {
// report error for this message, but keep trying others
mListeners.sendPendingMessagesFailed(account.mId, messageId, me);
continue;
}
// 5. move to sent, or delete
Uri syncedUri =
ContentUris.withAppendedId(EmailContent.Message.SYNCED_CONTENT_URI, messageId);
if (requireMoveMessageToSentFolder) {
// If this is a forwarded message and it has attachments, delete them, as they
// duplicate information found elsewhere (on the server). This saves storage.
EmailContent.Message msg =
EmailContent.Message.restoreMessageWithId(mContext, messageId);
if (msg != null &&
((msg.mFlags & EmailContent.Message.FLAG_TYPE_FORWARD) != 0)) {
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId,
messageId);
}
resolver.update(syncedUri, moveToSentValues, null, null);
} else {
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, messageId);
Uri uri =
ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, messageId);
resolver.delete(uri, null, null);
resolver.delete(syncedUri, null, null);
}
}
// 6. report completion/success
mListeners.sendPendingMessagesCompleted(account.mId);
} catch (MessagingException me) {
mListeners.sendPendingMessagesFailed(account.mId, -1, me);
} finally {
c.close();
}
}
/**
* Checks mail for an account.
* This entry point is for use by the mail checking service only, because it
* gives slightly different callbacks (so the service doesn't get confused by callbacks
* triggered by/for the foreground UI.
*
* TODO clean up the execution model which is unnecessarily threaded due to legacy code
*
* @param accountId the account to check
* @param listener
*/
public void checkMail(final long accountId, final long tag, final MessagingListener listener) {
mListeners.checkMailStarted(mContext, accountId, tag);
// This puts the command on the queue (not synchronous)
listFolders(accountId, null);
// Put this on the queue as well so it follows listFolders
put("checkMail", listener, new Runnable() {
public void run() {
// send any pending outbound messages. note, there is a slight race condition
// here if we somehow don't have a sent folder, but this should never happen
// because the call to sendMessage() would have built one previously.
long inboxId = -1;
EmailContent.Account account =
EmailContent.Account.restoreAccountWithId(mContext, accountId);
if (account != null) {
long sentboxId = Mailbox.findMailboxOfType(mContext, accountId,
Mailbox.TYPE_SENT);
if (sentboxId != Mailbox.NO_MAILBOX) {
sendPendingMessagesSynchronous(account, sentboxId);
}
// find mailbox # for inbox and sync it.
// TODO we already know this in Controller, can we pass it in?
inboxId = Mailbox.findMailboxOfType(mContext, accountId, Mailbox.TYPE_INBOX);
if (inboxId != Mailbox.NO_MAILBOX) {
EmailContent.Mailbox mailbox =
EmailContent.Mailbox.restoreMailboxWithId(mContext, inboxId);
if (mailbox != null) {
synchronizeMailboxSynchronous(account, mailbox);
}
}
}
mListeners.checkMailFinished(mContext, accountId, inboxId, tag);
}
});
}
private static class Command {
public Runnable runnable;
public MessagingListener listener;
public String description;
@Override
public String toString() {
return description;
}
}
}
| true | true | private StoreSynchronizer.SyncResults synchronizeMailboxGeneric(
final EmailContent.Account account, final EmailContent.Mailbox folder)
throws MessagingException {
Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***");
ContentResolver resolver = mContext.getContentResolver();
// 0. We do not ever sync DRAFTS or OUTBOX (down or up)
if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) {
int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null);
return new StoreSynchronizer.SyncResults(totalMessages, 0);
}
// 1. Get the message list from the local store and create an index of the uids
Cursor localUidCursor = null;
HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>();
try {
localUidCursor = resolver.query(
EmailContent.Message.CONTENT_URI,
LocalMessageInfo.PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
},
null);
while (localUidCursor.moveToNext()) {
LocalMessageInfo info = new LocalMessageInfo(localUidCursor);
localMessageMap.put(info.mServerId, info);
}
} finally {
if (localUidCursor != null) {
localUidCursor.close();
}
}
// 1a. Count the unread messages before changing anything
int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?" +
" AND " + MessageColumns.FLAG_READ + "=0",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
});
// 2. Open the remote folder and create the remote folder if necessary
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
|| folder.mType == Mailbox.TYPE_DRAFTS) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return new StoreSynchronizer.SyncResults(0, 0);
}
}
}
// 3, Open the remote folder. This pre-loads certain metadata like message count.
remoteFolder.open(OpenMode.READ_WRITE, null);
// 4. Trash any remote messages that are marked as trashed locally.
// TODO - this comment was here, but no code was here.
// 5. Get the remote message count.
int remoteMessageCount = remoteFolder.getMessageCount();
// 6. Determine the limit # of messages to download
int visibleLimit = folder.mVisibleLimit;
if (visibleLimit <= 0) {
Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
mContext);
visibleLimit = info.mVisibleLimitDefault;
}
// 7. Create a list of messages to download
Message[] remoteMessages = new Message[0];
final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
int newMessageCount = 0;
if (remoteMessageCount > 0) {
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message message : remoteMessages) {
remoteUidMap.put(message.getUid(), message);
}
/*
* Get a list of the messages that are in the remote list but not on the
* local store, or messages that are in the local store but failed to download
* on the last sync. These are the new messages that we will download.
* Note, we also skip syncing messages which are flagged as "deleted message" sentinels,
* because they are locally deleted and we don't need or want the old message from
* the server.
*/
for (Message message : remoteMessages) {
LocalMessageInfo localMessage = localMessageMap.get(message.getUid());
if (localMessage == null) {
newMessageCount++;
}
if (localMessage == null
|| (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)
|| (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_PARTIAL)) {
unsyncedMessages.add(message);
}
}
}
// 8. Download basic info about the new/unloaded messages (if any)
/*
* A list of messages that were downloaded and which did not have the Seen flag set.
* This will serve to indicate the true "new" message count that will be reported to
* the user via notification.
*/
final ArrayList<Message> newMessages = new ArrayList<Message>();
/*
* Fetch the flags and envelope only of the new messages. This is intended to get us
* critical data as fast as possible, and then we'll fill in the details.
*/
if (unsyncedMessages.size() > 0) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
fp.add(FetchProfile.Item.ENVELOPE);
final HashMap<String, LocalMessageInfo> localMapCopy =
new HashMap<String, LocalMessageInfo>(localMessageMap);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
try {
// Determine if the new message was already known (e.g. partial)
// And create or reload the full message info
LocalMessageInfo localMessageInfo =
localMapCopy.get(message.getUid());
EmailContent.Message localMessage = null;
if (localMessageInfo == null) {
localMessage = new EmailContent.Message();
} else {
localMessage = EmailContent.Message.restoreMessageWithId(
mContext, localMessageInfo.mId);
}
if (localMessage != null) {
try {
// Copy the fields that are available into the message
LegacyConversions.updateMessageFields(localMessage,
message, account.mId, folder.mId);
// Commit the message to the local store
saveOrUpdate(localMessage, mContext);
// Track the "new" ness of the downloaded message
if (!message.isSet(Flag.SEEN)) {
newMessages.add(message);
}
} catch (MessagingException me) {
Log.e(Email.LOG_TAG,
"Error while copying downloaded message." + me);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG,
"Error while storing downloaded message." + e.toString());
}
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
}
// 9. Refresh the flags for any messages in the local store that we didn't just download.
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(remoteMessages, fp, null);
boolean remoteSupportsSeen = false;
boolean remoteSupportsFlagged = false;
for (Flag flag : remoteFolder.getPermanentFlags()) {
if (flag == Flag.SEEN) {
remoteSupportsSeen = true;
}
if (flag == Flag.FLAGGED) {
remoteSupportsFlagged = true;
}
}
// Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3)
if (remoteSupportsSeen || remoteSupportsFlagged) {
for (Message remoteMessage : remoteMessages) {
LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid());
if (localMessageInfo == null) {
continue;
}
boolean localSeen = localMessageInfo.mFlagRead;
boolean remoteSeen = remoteMessage.isSet(Flag.SEEN);
boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen));
boolean localFlagged = localMessageInfo.mFlagFavorite;
boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED);
boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged));
if (newSeen || newFlagged) {
Uri uri = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, localMessageInfo.mId);
ContentValues updateValues = new ContentValues();
updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen);
updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged);
resolver.update(uri, updateValues, null, null);
}
}
}
// 10. Compute and store the unread message count.
// -- no longer necessary - Provider uses DB triggers to keep track
// int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
// if (remoteUnreadMessageCount == -1) {
// if (remoteSupportsSeenFlag) {
// /*
// * If remote folder doesn't supported unread message count but supports
// * seen flag, use local folder's unread message count and the size of
// * new messages. This mode is not used for POP3, or IMAP.
// */
//
// remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size();
// } else {
// /*
// * If remote folder doesn't supported unread message count and doesn't
// * support seen flag, use localUnreadCount and newMessageCount which
// * don't rely on remote SEEN flag. This mode is used by POP3.
// */
// remoteUnreadMessageCount = localUnreadCount + newMessageCount;
// }
// } else {
// /*
// * If remote folder supports unread message count, use remoteUnreadMessageCount.
// * This mode is used by IMAP.
// */
// }
// Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId);
// ContentValues updateValues = new ContentValues();
// updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount);
// resolver.update(uri, updateValues, null, null);
// 11. Remove any messages that are in the local store but no longer on the remote store.
HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet());
localUidsToDelete.removeAll(remoteUidMap.keySet());
for (String uidToDelete : localUidsToDelete) {
LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete);
// Delete associated data (attachment files)
// Attachment & Body records are auto-deleted when we delete the Message record
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId);
// Delete the message itself
Uri uriToDelete = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, infoToDelete.mId);
resolver.delete(uriToDelete, null, null);
// Delete extra rows (e.g. synced or deleted)
Uri syncRowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(syncRowToDelete, null, null);
Uri deletERowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(deletERowToDelete, null, null);
}
// 12. Divide the unsynced messages into small & large (by size)
// TODO doing this work here (synchronously) is problematic because it prevents the UI
// from affecting the order (e.g. download a message because the user requested it.) Much
// of this logic should move out to a different sync loop that attempts to update small
// groups of messages at a time, as a background task. However, we can't just return
// (yet) because POP messages don't have an envelope yet....
ArrayList<Message> largeMessages = new ArrayList<Message>();
ArrayList<Message> smallMessages = new ArrayList<Message>();
for (Message message : unsyncedMessages) {
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
}
// 13. Download small messages
// TODO Problems with this implementation. 1. For IMAP, where we get a real envelope,
// this is going to be inefficient and duplicate work we've already done. 2. It's going
// back to the DB for a local message that we already had (and discarded).
// For small messages, we specify "body", which returns everything (incl. attachments)
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
// 14. Download large messages. We ask the server to give us the message structure,
// but not all of the attachments.
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
// POP doesn't support STRUCTURE mode, so we'll just do a partial download
// (hopefully enough to see some/all of the body) and mark the message for
// further download.
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
// TODO a good optimization here would be to make sure that all Stores set
// the proper size after this fetch and compare the before and after size. If
// they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the partially-loaded message and mark it partially loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_PARTIAL);
} else {
// We have a structure to deal with, from which
// we can pull down the parts we want to actually store.
// Build a list of parts we are interested in. Text parts will be downloaded
// right now, attachments will be left for later.
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
// Download the viewables immediately
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
}
// 15. Clean up and report results
remoteFolder.close(false);
// TODO - more
// Original sync code. Using for reference, will delete when done.
if (false) {
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
// localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
// localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// Update the listener with what we've found
// synchronized (mListeners) {
// for (MessagingListener l : mListeners) {
// l.synchronizeMailboxNewMessage(
// account,
// folder,
// localFolder.getMessage(message.getUid()));
// }
// }
}
/*
* Report successful sync
*/
StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults(
remoteFolder.getMessageCount(), newMessages.size());
remoteFolder.close(false);
// localFolder.close(false);
return results;
}
return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size());
}
| private StoreSynchronizer.SyncResults synchronizeMailboxGeneric(
final EmailContent.Account account, final EmailContent.Mailbox folder)
throws MessagingException {
Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***");
ContentResolver resolver = mContext.getContentResolver();
// 0. We do not ever sync DRAFTS or OUTBOX (down or up)
if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) {
int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null);
return new StoreSynchronizer.SyncResults(totalMessages, 0);
}
// 1. Get the message list from the local store and create an index of the uids
Cursor localUidCursor = null;
HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>();
try {
localUidCursor = resolver.query(
EmailContent.Message.CONTENT_URI,
LocalMessageInfo.PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
},
null);
while (localUidCursor.moveToNext()) {
LocalMessageInfo info = new LocalMessageInfo(localUidCursor);
localMessageMap.put(info.mServerId, info);
}
} finally {
if (localUidCursor != null) {
localUidCursor.close();
}
}
// 1a. Count the unread messages before changing anything
int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?" +
" AND " + MessageColumns.FLAG_READ + "=0",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
});
// 2. Open the remote folder and create the remote folder if necessary
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
|| folder.mType == Mailbox.TYPE_DRAFTS) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return new StoreSynchronizer.SyncResults(0, 0);
}
}
}
// 3, Open the remote folder. This pre-loads certain metadata like message count.
remoteFolder.open(OpenMode.READ_WRITE, null);
// 4. Trash any remote messages that are marked as trashed locally.
// TODO - this comment was here, but no code was here.
// 5. Get the remote message count.
int remoteMessageCount = remoteFolder.getMessageCount();
// 6. Determine the limit # of messages to download
int visibleLimit = folder.mVisibleLimit;
if (visibleLimit <= 0) {
Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
mContext);
visibleLimit = info.mVisibleLimitDefault;
}
// 7. Create a list of messages to download
Message[] remoteMessages = new Message[0];
final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
int newMessageCount = 0;
if (remoteMessageCount > 0) {
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message message : remoteMessages) {
remoteUidMap.put(message.getUid(), message);
}
/*
* Get a list of the messages that are in the remote list but not on the
* local store, or messages that are in the local store but failed to download
* on the last sync. These are the new messages that we will download.
* Note, we also skip syncing messages which are flagged as "deleted message" sentinels,
* because they are locally deleted and we don't need or want the old message from
* the server.
*/
for (Message message : remoteMessages) {
LocalMessageInfo localMessage = localMessageMap.get(message.getUid());
if (localMessage == null) {
newMessageCount++;
}
// localMessage == null -> message has never been created (not even headers)
// mFlagLoaded = UNLOADED -> message created, but none of body loaded
// mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded
// mFlagLoaded = COMPLETE -> message body has been completely loaded
// mFlagLoaded = DELETED -> message has been deleted
// Only the first two of these are "unsynced", so let's retrieve them
if (localMessage == null ||
(localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) {
unsyncedMessages.add(message);
}
}
}
// 8. Download basic info about the new/unloaded messages (if any)
/*
* A list of messages that were downloaded and which did not have the Seen flag set.
* This will serve to indicate the true "new" message count that will be reported to
* the user via notification.
*/
final ArrayList<Message> newMessages = new ArrayList<Message>();
/*
* Fetch the flags and envelope only of the new messages. This is intended to get us
* critical data as fast as possible, and then we'll fill in the details.
*/
if (unsyncedMessages.size() > 0) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
fp.add(FetchProfile.Item.ENVELOPE);
final HashMap<String, LocalMessageInfo> localMapCopy =
new HashMap<String, LocalMessageInfo>(localMessageMap);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
try {
// Determine if the new message was already known (e.g. partial)
// And create or reload the full message info
LocalMessageInfo localMessageInfo =
localMapCopy.get(message.getUid());
EmailContent.Message localMessage = null;
if (localMessageInfo == null) {
localMessage = new EmailContent.Message();
} else {
localMessage = EmailContent.Message.restoreMessageWithId(
mContext, localMessageInfo.mId);
}
if (localMessage != null) {
try {
// Copy the fields that are available into the message
LegacyConversions.updateMessageFields(localMessage,
message, account.mId, folder.mId);
// Commit the message to the local store
saveOrUpdate(localMessage, mContext);
// Track the "new" ness of the downloaded message
if (!message.isSet(Flag.SEEN)) {
newMessages.add(message);
}
} catch (MessagingException me) {
Log.e(Email.LOG_TAG,
"Error while copying downloaded message." + me);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG,
"Error while storing downloaded message." + e.toString());
}
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
}
// 9. Refresh the flags for any messages in the local store that we didn't just download.
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(remoteMessages, fp, null);
boolean remoteSupportsSeen = false;
boolean remoteSupportsFlagged = false;
for (Flag flag : remoteFolder.getPermanentFlags()) {
if (flag == Flag.SEEN) {
remoteSupportsSeen = true;
}
if (flag == Flag.FLAGGED) {
remoteSupportsFlagged = true;
}
}
// Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3)
if (remoteSupportsSeen || remoteSupportsFlagged) {
for (Message remoteMessage : remoteMessages) {
LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid());
if (localMessageInfo == null) {
continue;
}
boolean localSeen = localMessageInfo.mFlagRead;
boolean remoteSeen = remoteMessage.isSet(Flag.SEEN);
boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen));
boolean localFlagged = localMessageInfo.mFlagFavorite;
boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED);
boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged));
if (newSeen || newFlagged) {
Uri uri = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, localMessageInfo.mId);
ContentValues updateValues = new ContentValues();
updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen);
updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged);
resolver.update(uri, updateValues, null, null);
}
}
}
// 10. Compute and store the unread message count.
// -- no longer necessary - Provider uses DB triggers to keep track
// int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
// if (remoteUnreadMessageCount == -1) {
// if (remoteSupportsSeenFlag) {
// /*
// * If remote folder doesn't supported unread message count but supports
// * seen flag, use local folder's unread message count and the size of
// * new messages. This mode is not used for POP3, or IMAP.
// */
//
// remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size();
// } else {
// /*
// * If remote folder doesn't supported unread message count and doesn't
// * support seen flag, use localUnreadCount and newMessageCount which
// * don't rely on remote SEEN flag. This mode is used by POP3.
// */
// remoteUnreadMessageCount = localUnreadCount + newMessageCount;
// }
// } else {
// /*
// * If remote folder supports unread message count, use remoteUnreadMessageCount.
// * This mode is used by IMAP.
// */
// }
// Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId);
// ContentValues updateValues = new ContentValues();
// updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount);
// resolver.update(uri, updateValues, null, null);
// 11. Remove any messages that are in the local store but no longer on the remote store.
HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet());
localUidsToDelete.removeAll(remoteUidMap.keySet());
for (String uidToDelete : localUidsToDelete) {
LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete);
// Delete associated data (attachment files)
// Attachment & Body records are auto-deleted when we delete the Message record
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId);
// Delete the message itself
Uri uriToDelete = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, infoToDelete.mId);
resolver.delete(uriToDelete, null, null);
// Delete extra rows (e.g. synced or deleted)
Uri syncRowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(syncRowToDelete, null, null);
Uri deletERowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(deletERowToDelete, null, null);
}
// 12. Divide the unsynced messages into small & large (by size)
// TODO doing this work here (synchronously) is problematic because it prevents the UI
// from affecting the order (e.g. download a message because the user requested it.) Much
// of this logic should move out to a different sync loop that attempts to update small
// groups of messages at a time, as a background task. However, we can't just return
// (yet) because POP messages don't have an envelope yet....
ArrayList<Message> largeMessages = new ArrayList<Message>();
ArrayList<Message> smallMessages = new ArrayList<Message>();
for (Message message : unsyncedMessages) {
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
}
// 13. Download small messages
// TODO Problems with this implementation. 1. For IMAP, where we get a real envelope,
// this is going to be inefficient and duplicate work we've already done. 2. It's going
// back to the DB for a local message that we already had (and discarded).
// For small messages, we specify "body", which returns everything (incl. attachments)
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
// 14. Download large messages. We ask the server to give us the message structure,
// but not all of the attachments.
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
// POP doesn't support STRUCTURE mode, so we'll just do a partial download
// (hopefully enough to see some/all of the body) and mark the message for
// further download.
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
// TODO a good optimization here would be to make sure that all Stores set
// the proper size after this fetch and compare the before and after size. If
// they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the partially-loaded message and mark it partially loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_PARTIAL);
} else {
// We have a structure to deal with, from which
// we can pull down the parts we want to actually store.
// Build a list of parts we are interested in. Text parts will be downloaded
// right now, attachments will be left for later.
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
// Download the viewables immediately
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
}
// 15. Clean up and report results
remoteFolder.close(false);
// TODO - more
// Original sync code. Using for reference, will delete when done.
if (false) {
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
// localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
// localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// Update the listener with what we've found
// synchronized (mListeners) {
// for (MessagingListener l : mListeners) {
// l.synchronizeMailboxNewMessage(
// account,
// folder,
// localFolder.getMessage(message.getUid()));
// }
// }
}
/*
* Report successful sync
*/
StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults(
remoteFolder.getMessageCount(), newMessages.size());
remoteFolder.close(false);
// localFolder.close(false);
return results;
}
return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size());
}
|
diff --git a/n3phele/src/n3phele/service/lifecycle/ProcessLifecycle.java b/n3phele/src/n3phele/service/lifecycle/ProcessLifecycle.java
index 629e128..6aa0ba1 100644
--- a/n3phele/src/n3phele/service/lifecycle/ProcessLifecycle.java
+++ b/n3phele/src/n3phele/service/lifecycle/ProcessLifecycle.java
@@ -1,1112 +1,1113 @@
package n3phele.service.lifecycle;
/**
* (C) Copyright 2010-2013. Nigel Cook. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Licensed under the terms described in LICENSE file that accompanied this code, (the "License"); you may not use this file
* except in compliance with the License.
*
* 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 static com.googlecode.objectify.ObjectifyService.ofy;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import n3phele.service.core.NotFoundException;
import n3phele.service.model.Action;
import n3phele.service.model.ActionState;
import n3phele.service.model.CloudProcess;
import n3phele.service.model.SignalKind;
import n3phele.service.model.core.Helpers;
import n3phele.service.model.core.User;
import n3phele.service.rest.impl.ActionResource;
import n3phele.service.rest.impl.CloudProcessResource;
import n3phele.service.rest.impl.UserResource;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.VoidWork;
import com.googlecode.objectify.Work;
public class ProcessLifecycle {
final private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(ProcessLifecycle.class.getName());
protected ProcessLifecycle() {}
public CloudProcess createProcess(User user, String name, n3phele.service.model.Context context, List<URI> dependency, CloudProcess parent, boolean topLevel, Class<? extends Action> clazz) throws IllegalArgumentException {
Action action;
try {
if(Helpers.isBlankOrNull(name))
name = user.getLastName();
action = clazz.newInstance().create(user.getUri(), name, context);
} catch (InstantiationException e) {
log.log(Level.SEVERE, "Class "+clazz, e);
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
log.log(Level.SEVERE, "Class "+clazz, e);
throw new IllegalArgumentException(e);
}
ActionResource.dao.add(action);
CloudProcess process = new CloudProcess(user.getUri(), name, parent, topLevel, action);
CloudProcessResource.dao.add(process);
action.setProcess(process.getUri());
String contextName = action.getContext().getValue("name");
if(Helpers.isBlankOrNull(contextName)) {
action.getContext().putValue("name", name);
}
ActionResource.dao.update(action);
setDependentOn(process.getUri(), dependency);
return process;
}
/*
* Process execution management
*/
/** Refresh the status of active actions
* @return Map of states of active cloud processes, and count of processes in those states.
*/
public Map<String, Long> periodicScheduler() {
Map<String, Long> counter = new HashMap<String, Long>();
for(CloudProcess process : CloudProcessResource.dao.getNonfinalized()) {
ActionState processState = process.getState();
String active = process.getRunning()!=null?"_Running":"";
String wait = process.getWaitTimeout()!=null?"_Wait":"";
Long count = 0L;
if(counter.containsKey(processState.toString()+active+wait))
count = counter.get(processState.toString()+active+wait);
count = count + 1;
counter.put(processState.toString()+active+wait, count);
log.info("Process "+process.getUri()+" "+processState+" "+process.getRunning());
if(process.getRunning() == null && processState != ActionState.NEWBORN) {
if(process.hasPending() || processState == ActionState.RUNABLE)
schedule(process, false);
}
}
return counter;
}
/** Places a task on to the run queue
* @param process
* @return TRUE if process queued
*/
public boolean schedule(CloudProcess process, final boolean forceWrite) {
final URI processURI = process.getUri();
final Long processId = process.getId();
final Key<CloudProcess> processRoot = process.getRoot();
return CloudProcessResource.dao.transact(new Work<Boolean>() {
@Override
public Boolean run() {
log.info(">>>>>>>>>>Schedule "+processURI);
boolean result = false;
boolean dirty = forceWrite;
CloudProcess process = CloudProcessResource.dao.load(processRoot, processId);
if(process.getRunning() == null && !process.isFinalized()) {
if(process.getWaitTimeout() != null) {
Date now = new Date();
if(process.hasPendingAssertions() || now.after(process.getWaitTimeout())) {
process.setWaitTimeout(null);
dirty = true;
}
}
if(process.getState().equals(ActionState.RUNABLE) && !process.isPendingCall()
&& !(process.isPendingCancel() || process.isPendingDump())
&& process.hasPendingAssertions() || process.getWaitTimeout() == null ) {
dirty = true;
log.info("===========>Pending call of "+processURI);
process.setPendingCall(true);
}
if(process.hasPending()) {
Date stamp = new Date();
log.info("Queued "+processURI+" "+stamp);
process.setRunning(stamp);
QueueFactory.getDefaultQueue().add(ofy().getTxn(),
TaskOptions.Builder.withPayload(new Schedule(processURI, process.getRunning())));
result = true;
dirty = true;
}
}
if(dirty)
CloudProcessResource.dao.update(process);
log.info("<<<<<<<<Schedule "+processURI);
return result;
}});
}
private static class Schedule implements DeferredTask {
private static final long serialVersionUID = 1L;
final private URI process;
final private Date stamp;
public Schedule(URI process, Date stamp) {
this.process = process;
this.stamp = stamp;
}
@Override
public void run(){
try {
boolean redispatch = true;
while(redispatch) {
CloudProcessResource.dao.clear();
redispatch = mgr().dispatch(process, stamp);
}
} catch (Exception e) {
log.log(Level.SEVERE, "Dispatch exception", e);
mgr().dump(process);
}
}
}
/** Dispatches execution to a task's entry points
* @param processId
* @return true if additional dispatch requested
*/
private boolean dispatch(final URI processId, final Date stamp) {
NextStep dispatchCode = CloudProcessResource.dao.transact(new Work<NextStep>() {
public NextStep run() {
log.info(">>>>>>>>>Dispatch "+processId);
CloudProcess process = CloudProcessResource.dao.load(processId);
if(process.isFinalized()) {
log.warning("Processing called on process "+processId+" finalized="+process.isFinalized()+" state="+process.getState());
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.nothing);
}
if(!process.getRunning().equals(stamp)) {
log.severe("Processing stamp is "+process.getRunning()+" expected "+stamp);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.nothing);
}
if(process.isPendingCancel() || process.isPendingDump()) {
process.setState(ActionState.CANCELLED);
CloudProcessResource.dao.update(process);
if(process.isPendingCancel()) {
process.setPendingCancel(false);
process.setPendingDump(false);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.cancel);
} else {
process.setPendingCancel(false);
process.setPendingDump(false);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.dump);
}
} else if(process.isPendingInit()) {
process.setPendingInit(false);
process.setStart(new Date());
CloudProcessResource.dao.update(process);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.init);
} else if(process.hasPendingAssertions()) {
ArrayList<String> assertions = new ArrayList<String>(process.getPendingAssertion().size());
assertions.addAll(process.getPendingAssertion());
process.getPendingAssertion().clear();
+ process.setPendingCall(true);
CloudProcessResource.dao.update(process);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.assertion, assertions);
} else if(process.isPendingCall()) {
process.setPendingCall(false);
CloudProcessResource.dao.update(process);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.call);
}
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.nothing);
} });
CloudProcess process = CloudProcessResource.dao.load(processId);
Action task = null;
try {
task = ActionResource.dao.load(process.getAction());
} catch (Exception e) {
log.log(Level.SEVERE, "Failed to access task "+process.getAction(), e);
toFailed(process);
return false;
}
log.info("Dispatch "+dispatchCode+": process "+process.getName()+" "+process.getUri()+" task "+task.getUri());
boolean error = false;
switch(dispatchCode.todo){
case assertion:
for(String assertion : dispatchCode.assertion) {
try {
int index = assertion.indexOf(":");
SignalKind kind = SignalKind.valueOf(assertion.substring(0,index));
task.signal(kind, assertion.substring(index+1));
} catch (Exception e) {
log.log(Level.WARNING, "Assertion "+ assertion + " exception for process "+process.getUri()+" task "+task.getUri(), e);
}
}
writeOnChange(task);
return endOfTimeSlice(process);
case init:
try {
task.init();
} catch (Exception e) {
log.log(Level.WARNING, "Init exception for process "+process.getUri()+" task "+task.getUri(), e);
error = true;
}
writeOnChange(task);
if(error) {
toFailed(process);
} else {
return endOfTimeSlice(process);
}
break;
case call:
boolean complete = false;
try {
complete = task.call();
} catch (WaitForSignalRequest e) {
toWait(process, e.getTimeout());
} catch (Exception e) {
log.log(Level.WARNING, "Call exception for process "+process.getUri()+" task "+task.getUri(), e);
error = true;
}
writeOnChange(task);
if(error) {
toFailed(process);
break;
} else if(complete) {
toComplete(process);
} else {
return endOfTimeSlice(process);
}
break;
case cancel:
try {
task.cancel();
} catch (Exception e) {
log.log(Level.WARNING, "Cancel exception for process "+process.getUri()+" task "+task.getUri(), e);
}
writeOnChange(task);
toCancelled(process);
break;
case dump:
try {
task.dump();
} catch (Exception e) {
log.log(Level.WARNING, "Dump exception for process "+process.getUri()+" task "+task.getUri(), e);
}
writeOnChange(task);
toCancelled(process);
break;
case nothing:
default:
log.severe("******Nothing to do for "+process.getName()+":"+process.toString());
// Likely concurrency bug. Process gets dispatched twice.
break;
}
return false;
}
/* -------------------------------------------------------------------------------------------------
* The following routines manage the lifecycle changes associated with the transaction of a process
* to a particular state.
* ------------------------------------------------------------------------------------------------
*/
/** Moves a process to the "complete" state, signifying error free completion of processing
* @param process
*/
private void toComplete(final CloudProcess process) {
final Long processId = process.getId();
final Key<CloudProcess> processRoot = process.getRoot();
log.info("Complete "+process.getName()+":"+process.getUri());
giveChildrenToGrandparent(process);
final List<String> dependents = CloudProcessResource.dao.transact(new Work<List<String>>() {
@Override
public List<String> run() {
log.info(">>>>>>>>>toComplete "+processId);
CloudProcess targetProcess = CloudProcessResource.dao.load(processRoot, processId);
logExecutionTime(targetProcess);
targetProcess.setState(ActionState.COMPLETE);
targetProcess.setComplete(new Date());
targetProcess.setRunning(null);
targetProcess.setFinalized(true);
List<String> result = new ArrayList<String>();
result.add(Helpers.URItoString(targetProcess.getParent()));
if(targetProcess.getDependencyFor() != null) {
result.addAll(targetProcess.getDependencyFor());
}
CloudProcessResource.dao.update(targetProcess);
log.info("<<<<<<<<toComplete "+processId);
return result;
}
});
URI parentURI = Helpers.stringToURI(dependents.get(0));
if(parentURI != null) {
CloudProcess parent;
try {
parent = CloudProcessResource.dao.load(parentURI);
signal(parent, SignalKind.Ok, process.getUri().toString());
} catch (NotFoundException e) {
log.severe("Unknown parent "+ process);
} catch (Exception e) {
log.log(Level.SEVERE, "Signal failure to "+parentURI+" "+process, e);
}
}
if(dependents != null && dependents.size() > 1) {
for(String dependent : dependents.subList(1, dependents.size())) {
signalDependentProcessIsComplete(process, URI.create(dependent));
}
}
}
/** Signals to a process that its dependency has now successfully completed
* @param process that completed successfully
* @param depender process awaiting dependency completion
*/
private void signalDependentProcessIsComplete(CloudProcess process, final URI depender ) {
final URI processUri = process.getUri();
CloudProcessResource.dao.transact(new VoidWork(){
@Override
public void vrun() {
log.info(">>>>>>>>>signalDependentProcessIsComplete "+processUri);
String hasFinalized = processUri.toString();
CloudProcess dprocess = CloudProcessResource.dao.load(depender);
if(dprocess.getDependentOn() != null && dprocess.getDependentOn().size() > 0) {
boolean found = dprocess.getDependentOn().remove(hasFinalized);
if(found) {
if(dprocess.getDependentOn().size() == 0 && dprocess.getState() != ActionState.NEWBORN && !dprocess.isFinalized()) {
if(dprocess.getState() == ActionState.INIT) {
dprocess.setPendingInit(true);
}
dprocess.setState(ActionState.RUNABLE);
schedule(dprocess, true);
}
} else {
if(dprocess.getState() == ActionState.NEWBORN){
log.warning("**HANDLED RACE CONDITION** Dependency "+hasFinalized+" not found in "+dprocess.getUri());
} else {
log.severe("Dependency "+hasFinalized+" not found in "+dprocess.getUri());
}
}
}
log.info("<<<<<<<<signalDependentProcessIsComplete "+processUri);
}});
}
/** Blocks process execution block until successful completion of dependent process
* @param process the process to block awaiting successful completion
* @param dependent the process that when complete unblocks execution of process
* @return true if the dependency causes the process to block
* @throws IllegalArgumentException
*/
public boolean addDependentOn(final CloudProcess process, CloudProcess dependent) throws IllegalArgumentException {
return setDependentOn(process.getUri(), Arrays.asList(dependent.getUri()));
}
/** Adds a set of dependency such that process runs dependent on the successful execution of dependentOnList members
* @param process
* @param dependentOnList
* @return TRUE if dependency causes process execution to block
* @throws IllegalArgumentException if the dependency is non-existent or has terminated abnormally
*/
public boolean setDependentOn(final URI process, List<URI> dependentOnList) {
if(dependentOnList == null || dependentOnList.isEmpty()) return false;
boolean result = false;
int chunkSize = 4;
for(int i = 0; i < dependentOnList.size(); i += chunkSize) {
int lim = (i + chunkSize) < dependentOnList.size()? i+ chunkSize : dependentOnList.size();
boolean chunkResult = setListOfDependentOn(process, dependentOnList.subList(i, lim));
result = result || chunkResult;
}
if(result)
CloudProcessResource.dao.transact(new VoidWork(){
@Override
public void vrun() {
CloudProcess targetProcess = CloudProcessResource.dao.load(process);
if(!targetProcess.isFinalized()) {
if(targetProcess.getDependentOn() != null && targetProcess.getDependentOn().size() > 0 &&
targetProcess.getRunning()==null &&
targetProcess.getState().equals(ActionState.RUNABLE)) {
targetProcess.setState(ActionState.BLOCKED);
targetProcess.setWaitTimeout(null);
CloudProcessResource.dao.update(targetProcess);
}
}
}
});
return result;
}
/** Adds a set of dependency such that process runs dependent on the successful execution of dependentOnList members
* @param processUri
* @param dependentOnList
* @return TRUE if dependency causes process execution to block
* @throws IllegalArgumentException if the dependency is non-existent or has terminated abnormally
*/
private boolean setListOfDependentOn(final URI processUri, final List<URI> dependentOnList) {
return CloudProcessResource.dao.transact(new Work<Boolean>(){
@Override
public Boolean run() {
log.info(">>>>>>>>>setListOfDependentOn "+processUri);
boolean willBlock = false;
CloudProcess depender = CloudProcessResource.dao.load(processUri);
if(depender.isFinalized()) {
log.warning("Cannot add dependencies to finalized process "+processUri+" state "+depender.getState());
throw new IllegalArgumentException("Cannot add dependencies to finalized process "+processUri+" state "+depender.getState());
}
for(URI dependentOn : dependentOnList) {
CloudProcess dependency;
try {
dependency = CloudProcessResource.dao.load(dependentOn);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Dependency does exist "+dependentOn,e);
}
if(dependency.isFinalized()) {
if(dependency.getState().equals(ActionState.COMPLETE)) {
log.warning(dependentOn+" already finalized, removing dependency constraint from "+processUri);
} else {
throw new IllegalArgumentException("Process "+processUri+" has a dependency on "+dependentOn+" which is "+dependency.getState());
}
} else {
if(!depender.getDependentOn().contains(dependency.getUri().toString())) {
dependency.getDependencyFor().add(depender.getUri().toString());
depender.getDependentOn().add(dependency.getUri().toString());
CloudProcessResource.dao.update(dependency);
willBlock = true;
} else {
log.severe(dependentOn+" already in list for "+processUri);
}
}
}
CloudProcessResource.dao.update(depender);
log.info("<<<<<<<<setListOfDependentsOn "+processUri);
return willBlock;
}});
}
/** Set process to having terminated with processing failure. The process parent is notified of
* the failure.
* @param process
*/
private void toFailed(CloudProcess process) {
final Long processId = process.getId();
final Key<CloudProcess> processRoot = process.getRoot();
giveChildrenToGrandparent(process);
List<String> dependents = CloudProcessResource.dao.transact(new Work<List<String>>() {
@Override
public List<String> run() {
log.info(">>>>>>>>>toFailed "+processId);
CloudProcess targetProcess = CloudProcessResource.dao.load(processRoot, processId);
List<String> result = null;
if(!targetProcess.isFinalized()) {
logExecutionTime(targetProcess);
targetProcess.setState(ActionState.FAILED);
targetProcess.setComplete(new Date());
targetProcess.setRunning(null);
targetProcess.setFinalized(true);
result = new ArrayList<String>();
result.add(Helpers.URItoString(targetProcess.getParent()));
if(targetProcess.getDependencyFor() != null) {
result.addAll(targetProcess.getDependencyFor());
}
CloudProcessResource.dao.update(targetProcess);
} else {
log.warning("Failed process "+targetProcess.getUri()+" is finalized");
}
log.info("<<<<<<<<toFailed "+processId);
return result;
}});
URI parentURI = Helpers.stringToURI(dependents.get(0));
if(parentURI != null) {
CloudProcess parent;
try {
parent = CloudProcessResource.dao.load(parentURI);
signal(parent, SignalKind.Failed, process.getUri().toString());
} catch (NotFoundException e) {
log.severe("Unknown parent "+ process);
} catch (Exception e) {
log.log(Level.SEVERE, "Signal failure to "+parentURI+" "+process, e);
}
}
if(dependents != null && dependents.size() > 1) {
for(String dependent : dependents.subList(1, dependents.size())) {
CloudProcess dprocess = CloudProcessResource.dao.load(URI.create(dependent));
if(!dprocess.isFinalized()) {
toCancelled(dprocess);
}
}
}
}
private void giveChildrenToGrandparent(final CloudProcess process) {
URI uri = process.getParent();
CloudProcess grandParent=null;
while(uri != null) {
grandParent = CloudProcessResource.dao.load(uri);
if(!grandParent.isFinalized()) break;
uri = grandParent.getParent();
}
final URI grandParentURI = uri;
/*
*
*/
boolean moreToDo = true;
while(moreToDo) {
moreToDo = CloudProcessResource.dao.transact(new Work<Boolean>(){
@Override
public Boolean run() {
log.info(">>>>>>>>>giveChildToGrandparent "+grandParentURI);
boolean goAgain = false;
CloudProcess grandParent = null;
if(grandParentURI != null) {
grandParent = CloudProcessResource.dao.load(grandParentURI);
if(grandParent.isFinalized()) {
log.warning("Grandparent "+grandParent.getUri()+" is finalized");
throw new IllegalArgumentException("Grandparent "+grandParent.getUri()+" is finalized");
}
}
List<CloudProcess> children = getNonfinalizedChildren(process);
boolean parentUpdate = false;
int chunk = 4;
for(CloudProcess childProcess : children) {
if(chunk-- < 1) {
goAgain = true;
break;
}
if(grandParent != null) {
childProcess.setParent(grandParentURI);
CloudProcessResource.dao.update(childProcess);
final String typedAssertion = SignalKind.Adoption+":"+childProcess.getUri().toString();
if(!grandParent.getPendingAssertion().contains(typedAssertion)) {
grandParent.getPendingAssertion().add(typedAssertion);
parentUpdate = true;
}
} else {
childProcess.setPendingCancel(true);
childProcess.setParent(null);
schedule(childProcess, true);
}
}
if(parentUpdate) {
CloudProcessResource.dao.update(grandParent);
}
log.info("<<<<<<<<giveChildToGrandparent "+grandParentURI);
return goAgain;
}});
}
if(grandParentURI != null)
schedule(grandParent, false);
}
/** Set process to the wait state
*
* @param process
*/
private void toWait(CloudProcess process, final Date timeout) {
final Long processId = process.getId();
final Key<CloudProcess> processRoot = process.getRoot();
CloudProcessResource.dao.transact(new VoidWork() {
@Override
public void vrun() {
log.info(">>>>>>>>>toWait "+processId);
CloudProcess targetProcess = CloudProcessResource.dao.load(processRoot, processId);
if(!targetProcess.isFinalized()) {
targetProcess.setWaitTimeout(timeout);
CloudProcessResource.dao.update(targetProcess);
} else {
log.warning("Wait process "+targetProcess.getUri()+" is finalized");
}
log.info("<<<<<<<<toWait "+processId);
}});
}
/** Re-evaluate process state at normal end of execution.
* @param process
* @return true if redispatch requested
*/
private boolean endOfTimeSlice(CloudProcess process) {
final Long processId = process.getId();
final Key<CloudProcess> processRoot = process.getRoot();
boolean redispatch = CloudProcessResource.dao.transact(new Work<Boolean>() {
@Override
public Boolean run() {
log.info(">>>>>>>>>endOfTimeSlice "+processId);
boolean redispatch = false;
CloudProcess targetProcess = CloudProcessResource.dao.load(processRoot, processId);
if(!targetProcess.isFinalized()) {
if(targetProcess.getState() == ActionState.RUNABLE && targetProcess.hasPending()) {
targetProcess.setWaitTimeout(null);
long now = new Date().getTime();
if(targetProcess.getRunning().getTime()+(60*1000) < now) {
// process has run too long .. re queue
logExecutionTime(targetProcess);
targetProcess.setRunning(null);
log.warning("Re-queue process "+targetProcess.getId());
schedule(targetProcess, true);
} else {
log.info("Re-dispatch process "+targetProcess);
redispatch = true;
}
} else {
logExecutionTime(targetProcess);
targetProcess.setRunning(null);
if(targetProcess.getDependentOn() != null && !targetProcess.getDependentOn().isEmpty()) {
targetProcess.setState(ActionState.BLOCKED);
targetProcess.setWaitTimeout(null);
}
CloudProcessResource.dao.update(targetProcess);
}
}
log.info("<<<<<<<<endOfTimeSlice "+processId+(redispatch?" -- redispatch":""));
return redispatch;
}});
return redispatch;
}
/** Move process to cancelled state.
* The process parent is notified of the cancellation.
* @param process
*/
private void toCancelled(CloudProcess process) {
final Map<URI, Set<String>>notifications = new HashMap<URI, Set<String>>();
final Set<String> priorDependents = new HashSet<String>();
canceller(process, notifications, priorDependents);
if(!notifications.isEmpty()) {
for(Entry<URI, Set<String>> notification : notifications.entrySet()) {
addSignalList(notification.getKey(), SignalKind.Cancel, notification.getValue());
}
}
}
private void canceller(CloudProcess process, final Map<URI, Set<String>>notifications, final Set<String> priorDependents) {
final Long processId = process.getId();
final Key<CloudProcess> processRoot = process.getRoot();
Set<String> dependents = CloudProcessResource.dao.transact(new Work<Set<String>>() {
@Override
public Set<String> run() {
log.info(">>>>>>>>>toCancelled "+processId);
CloudProcess targetProcess = CloudProcessResource.dao.load(processRoot, processId);
Set<String> result = null;
if(!targetProcess.isFinalized()) {
if(targetProcess.getState().equals(ActionState.BLOCKED)){
targetProcess.setPendingCancel(true);
schedule(targetProcess, true);
} else {
logExecutionTime(targetProcess);
targetProcess.setState(ActionState.CANCELLED);
targetProcess.setComplete(new Date());
if(targetProcess.getStart() == null) {
targetProcess.setStart(targetProcess.getComplete());
}
targetProcess.setRunning(null);
targetProcess.setFinalized(true);
if(targetProcess.getParent() != null) {
try {
Set<String> notifyList = notifications.get(targetProcess.getParent());
if(notifyList == null) {
notifyList = new HashSet<String>();
notifications.put(targetProcess.getParent(), notifyList);
}
notifyList.add(targetProcess.getUri().toString());
} catch (Exception e) {
log.log(Level.SEVERE, "Signal failure "+targetProcess, e);
}
}
if(targetProcess.getDependencyFor() != null) {
result = new HashSet<String>();
for(String target : targetProcess.getDependencyFor()) {
if(!priorDependents.contains(target)) {
result.add(target);
}
}
}
CloudProcessResource.dao.update(targetProcess);
}
} else {
log.warning("Cancelled process "+targetProcess.getUri()+" is finalized");
}
log.info("<<<<<<<<toCancelled "+processId);
return result;
}});
if(dependents != null && !dependents.isEmpty()) {
for(String dependent : dependents) {
CloudProcess dprocess;
try {
dprocess = CloudProcessResource.dao.load(URI.create(dependent));
if(!dprocess.isFinalized()) {
canceller(dprocess, notifications, priorDependents);
}
} catch (NotFoundException e) {
log.severe("Process "+dependent+" not found");
}
}
}
}
public CloudProcess spawn(URI owner, String name, n3phele.service.model.Context context,
List<URI> dependency, URI parentURI, String className) throws IllegalArgumentException, NotFoundException, ClassNotFoundException {
String canonicalClassName = "n3phele.service.actions."+className+"Action";
User user;
CloudProcess parent = null;
try {
user = UserResource.dao.load(owner);
} catch (NotFoundException e) {
log.warning("Cant find owner "+owner);
throw e;
}
try {
if(parentURI != null)
parent = CloudProcessResource.dao.load(parentURI);
} catch (NotFoundException e) {
log.warning("Cant find parent "+parentURI);
throw e;
}
CloudProcess process = this.createProcess(user,
name, context, dependency, parent, false,
Class.forName(canonicalClassName).asSubclass(Action.class));
return process;
}
/** cancel running an existing process.
* Causes the existing process to stop current processing and to close and free any resources that the
* process is currently using.
*
*/
public void cancel(CloudProcess process) {
log.info("cancel "+process.getUri());
final Long processId = process.getId();
final Key<CloudProcess> groupId = process.getRoot();
CloudProcessResource.dao.transact(new VoidWork() {
@Override
public void vrun() {
log.info(">>>>>>>>>cancel "+processId);
CloudProcess targetProcess = CloudProcessResource.dao.load(groupId, processId);
if(!targetProcess.isFinalized()) {
targetProcess.setPendingCancel(true);
schedule(targetProcess, true);
} else {
log.severe("Cancel on finalized process "+targetProcess.getUri());
}
log.info("<<<<<<<<cancel "+processId);
}});
}
/** cancel running an existing process.
* Causes the existing process to stop current processing and to close and free any resources that the
* process is currently using.
*
*/
public void cancel(URI processId) throws NotFoundException {
CloudProcess process = CloudProcessResource.dao.load(processId);
cancel(process);
}
public void init(CloudProcess process) {
log.info("init "+process.getUri()+" "+process.getName());
final Long processId = process.getId();
final Key<CloudProcess> processRoot = process.getRoot();
CloudProcessResource.dao.transact(new VoidWork() {
@Override
public void vrun() {
log.info(">>>>>>>>>init "+processId);
CloudProcess targetProcess = CloudProcessResource.dao.load(processRoot, processId);
if(!targetProcess.isFinalized() && targetProcess.getState() == ActionState.NEWBORN) {
if(targetProcess.getDependentOn() != null && targetProcess.getDependentOn().size() != 0) {
targetProcess.setState(ActionState.INIT);
CloudProcessResource.dao.update(targetProcess);
} else {
targetProcess.setState(ActionState.RUNABLE);
targetProcess.setPendingInit(true);
targetProcess.setPendingCall(true);
/*
* NB: There is an assumption that:
* 1. The objectify get operation will fetch the modified process object
* in the schedule transaction
* 2. The pendingInit will cause schedule to write the CloudProcess object
*/
schedule(targetProcess, true);
}
} else {
log.severe("Init on finalized or non-newborn process "+targetProcess.getUri()+" "+targetProcess.getState());
}
log.info("<<<<<<<<init "+processId);
}});
}
/** Dump a running process, which causes the process to be stopped current processing and
* to save diagnostic information that
* can be later reviews.
*
*/
public CloudProcess dump(CloudProcess process) {
final Long processId = process.getId();
final Key<CloudProcess> processRoot = process.getRoot();
log.info("dump "+process.getUri());
return CloudProcessResource.dao.transact(new Work<CloudProcess>() {
@Override
public CloudProcess run() {
log.info(">>>>>>>>>dump "+processId);
CloudProcess targetProcess = CloudProcessResource.dao.load(processRoot, processId);
if(!targetProcess.isFinalized()) {
targetProcess.setPendingDump(true);
schedule(targetProcess, true);
} else {
log.severe("Dump on finalized process "+targetProcess.getUri());
}
log.info("<<<<<<<<dump "+processId);
return targetProcess;
}});
}
/** Dump a running process, which causes the process to be stopped current processing and
* to save diagnostic information that
* can be later reviews.
*
*/
public CloudProcess dump(URI processId) throws NotFoundException {
CloudProcess process = CloudProcessResource.dao.load(processId);
return dump(process);
}
/**
* @param jobAction
* @throws WaitForSignalRequest
*/
public void waitForSignal() throws WaitForSignalRequest {
throw new WaitForSignalRequest();
}
public static class WaitForSignalRequest extends Exception {
private static final long serialVersionUID = 1L;
private final Date timeout;
public WaitForSignalRequest() {
this(Calendar.HOUR, 1);
}
public WaitForSignalRequest(int unit, int count) {
Calendar alarm = Calendar.getInstance();
alarm.add(unit, count);
timeout = alarm.getTime();
}
public Date getTimeout() {
return this.timeout;
}
}
/** Signals a process with an assertion.
* @param process
* @param kind
* @param assertion
*/
public void signal(CloudProcess process, SignalKind kind, String assertion) {
this.signal(process.getUri(), kind, assertion);
}
/** Signals a process with an assertion.
* @param cloudProcessURI
* @param kind
* @param assertion
*/
public void signal(final URI cloudProcessURI, final SignalKind kind, final String assertion) {
addSignalList(cloudProcessURI, kind, Arrays.asList(assertion));
}
/** Signals a process with an assertion.
* @param cloudProcessURI
* @param kind
* @param assertion
*/
public void addSignalList(final URI cloudProcessURI, final SignalKind kind, final Collection<String> assertions) {
log.info("signal <"+kind+":"+assertions+"> to "+cloudProcessURI);
CloudProcessResource.dao.transact(new VoidWork() {
@Override
public void vrun() {
log.info(">>>>>>>>>signalList "+cloudProcessURI);
CloudProcess p = CloudProcessResource.dao.load(cloudProcessURI);
if(!p.isFinalized()) {
boolean added = false;
if(!assertions.isEmpty()) {
for(String assertion : assertions) {
if(!p.getPendingAssertion().contains(kind+":"+assertion)) {
p.getPendingAssertion().add(kind+":"+assertion);
added = true;
}
}
if(added) {
if(p.getState() == ActionState.RUNABLE) {
schedule(p, true);
} else {
CloudProcessResource.dao.update(p);
}
}
}
} else {
log.severe("Signal <"+kind+":"+assertions+"> on finalized process "+p.getUri());
}
log.info("<<<<<<<<signalList "+cloudProcessURI);
}});
}
/** Signals a process parent with an assertion.
* @param cloudProcessURI
* @param kind
* @param assertion
*/
public void signalParent(final URI childProcessURI, final SignalKind kind, final String assertion) {
log.info("signal <"+kind+":"+assertion+"> to parent of "+childProcessURI);
CloudProcessResource.dao.transact(new VoidWork() {
@Override
public void vrun() {
log.info(">>>>>>>>>signalParent "+childProcessURI);
CloudProcess child = CloudProcessResource.dao.load(childProcessURI);
if(child.getParent() != null) {
log.info("signal <"+kind+":"+assertion+"> to "+child.getParent());
CloudProcess p = CloudProcessResource.dao.load(child.getParent());
if(!p.isFinalized()) {
if(!p.getPendingAssertion().contains(kind+":"+assertion)) {
p.getPendingAssertion().add(kind+":"+assertion);
if(p.getState() == ActionState.RUNABLE) {
schedule(p, true);
} else {
CloudProcessResource.dao.update(p);
}
}
} else {
log.warning("Signal <"+kind+":"+assertion+"> on finalized process "+p.getUri());
}
} else {
log.info("signal <"+kind+":"+assertion+"> "+childProcessURI+" has no parent");
}
log.info("<<<<<<<<signalParent "+childProcessURI);
}});
}
/*
* Helpers
* =======
*/
private enum DoNext {
nothing,
cancel,
dump,
init,
assertion,
call
}
private static class NextStep {
public List<String> assertion;
public DoNext todo;
public NextStep(DoNext todo, List<String> assertion) {
this.todo = todo;
this.assertion = assertion;
}
public NextStep(DoNext todo) {
this.todo = todo;
}
public String toString() {
if(todo == DoNext.assertion) {
return todo+"<"+assertion+">";
} else {
return ""+todo;
}
}
}
private void logExecutionTime(CloudProcess process) {
Date started = process.getRunning();
if(started != null) {
Date now = new Date();
Long duration = now.getTime() - started.getTime();
log.info(process.getName()+" "+process.getUri()+" executed "+duration+" milliseconds");
}
}
private boolean writeOnChange(final Action action) {
boolean result = ActionResource.dao.transact(new Work<Boolean>() {
@Override
public Boolean run() {
log.info(">>>>>>>>>writeOnChange "+action.getUri());
Action db = ActionResource.dao.load(action.getUri());
if(!db.equals(action)) {
ActionResource.dao.update(action);
return true;
}
return false;
}});
log.info("Action "+action.getName()+" "+action.getUri()+" write "+result);
log.info("<<<<<<<<writeOnChange "+action.getUri());
return result;
}
private List<CloudProcess> getNonfinalizedChildren(CloudProcess process) {
Key<CloudProcess> root = process.getRoot();
if(root == null) {
root = Key.create(process);
}
return ofy().load().type(CloudProcess.class).ancestor(root)
.filter("parent", process.getUri().toString())
.filter("finalized", false).list();
}
private final static ProcessLifecycle processLifecycle = new ProcessLifecycle();
public static ProcessLifecycle mgr() {
return processLifecycle;
}
}
| true | true | private boolean dispatch(final URI processId, final Date stamp) {
NextStep dispatchCode = CloudProcessResource.dao.transact(new Work<NextStep>() {
public NextStep run() {
log.info(">>>>>>>>>Dispatch "+processId);
CloudProcess process = CloudProcessResource.dao.load(processId);
if(process.isFinalized()) {
log.warning("Processing called on process "+processId+" finalized="+process.isFinalized()+" state="+process.getState());
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.nothing);
}
if(!process.getRunning().equals(stamp)) {
log.severe("Processing stamp is "+process.getRunning()+" expected "+stamp);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.nothing);
}
if(process.isPendingCancel() || process.isPendingDump()) {
process.setState(ActionState.CANCELLED);
CloudProcessResource.dao.update(process);
if(process.isPendingCancel()) {
process.setPendingCancel(false);
process.setPendingDump(false);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.cancel);
} else {
process.setPendingCancel(false);
process.setPendingDump(false);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.dump);
}
} else if(process.isPendingInit()) {
process.setPendingInit(false);
process.setStart(new Date());
CloudProcessResource.dao.update(process);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.init);
} else if(process.hasPendingAssertions()) {
ArrayList<String> assertions = new ArrayList<String>(process.getPendingAssertion().size());
assertions.addAll(process.getPendingAssertion());
process.getPendingAssertion().clear();
CloudProcessResource.dao.update(process);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.assertion, assertions);
} else if(process.isPendingCall()) {
process.setPendingCall(false);
CloudProcessResource.dao.update(process);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.call);
}
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.nothing);
} });
CloudProcess process = CloudProcessResource.dao.load(processId);
Action task = null;
try {
task = ActionResource.dao.load(process.getAction());
} catch (Exception e) {
log.log(Level.SEVERE, "Failed to access task "+process.getAction(), e);
toFailed(process);
return false;
}
log.info("Dispatch "+dispatchCode+": process "+process.getName()+" "+process.getUri()+" task "+task.getUri());
boolean error = false;
switch(dispatchCode.todo){
case assertion:
for(String assertion : dispatchCode.assertion) {
try {
int index = assertion.indexOf(":");
SignalKind kind = SignalKind.valueOf(assertion.substring(0,index));
task.signal(kind, assertion.substring(index+1));
} catch (Exception e) {
log.log(Level.WARNING, "Assertion "+ assertion + " exception for process "+process.getUri()+" task "+task.getUri(), e);
}
}
writeOnChange(task);
return endOfTimeSlice(process);
case init:
try {
task.init();
} catch (Exception e) {
log.log(Level.WARNING, "Init exception for process "+process.getUri()+" task "+task.getUri(), e);
error = true;
}
writeOnChange(task);
if(error) {
toFailed(process);
} else {
return endOfTimeSlice(process);
}
break;
case call:
boolean complete = false;
try {
complete = task.call();
} catch (WaitForSignalRequest e) {
toWait(process, e.getTimeout());
} catch (Exception e) {
log.log(Level.WARNING, "Call exception for process "+process.getUri()+" task "+task.getUri(), e);
error = true;
}
writeOnChange(task);
if(error) {
toFailed(process);
break;
} else if(complete) {
toComplete(process);
} else {
return endOfTimeSlice(process);
}
break;
case cancel:
try {
task.cancel();
} catch (Exception e) {
log.log(Level.WARNING, "Cancel exception for process "+process.getUri()+" task "+task.getUri(), e);
}
writeOnChange(task);
toCancelled(process);
break;
case dump:
try {
task.dump();
} catch (Exception e) {
log.log(Level.WARNING, "Dump exception for process "+process.getUri()+" task "+task.getUri(), e);
}
writeOnChange(task);
toCancelled(process);
break;
case nothing:
default:
log.severe("******Nothing to do for "+process.getName()+":"+process.toString());
// Likely concurrency bug. Process gets dispatched twice.
break;
}
return false;
}
| private boolean dispatch(final URI processId, final Date stamp) {
NextStep dispatchCode = CloudProcessResource.dao.transact(new Work<NextStep>() {
public NextStep run() {
log.info(">>>>>>>>>Dispatch "+processId);
CloudProcess process = CloudProcessResource.dao.load(processId);
if(process.isFinalized()) {
log.warning("Processing called on process "+processId+" finalized="+process.isFinalized()+" state="+process.getState());
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.nothing);
}
if(!process.getRunning().equals(stamp)) {
log.severe("Processing stamp is "+process.getRunning()+" expected "+stamp);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.nothing);
}
if(process.isPendingCancel() || process.isPendingDump()) {
process.setState(ActionState.CANCELLED);
CloudProcessResource.dao.update(process);
if(process.isPendingCancel()) {
process.setPendingCancel(false);
process.setPendingDump(false);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.cancel);
} else {
process.setPendingCancel(false);
process.setPendingDump(false);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.dump);
}
} else if(process.isPendingInit()) {
process.setPendingInit(false);
process.setStart(new Date());
CloudProcessResource.dao.update(process);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.init);
} else if(process.hasPendingAssertions()) {
ArrayList<String> assertions = new ArrayList<String>(process.getPendingAssertion().size());
assertions.addAll(process.getPendingAssertion());
process.getPendingAssertion().clear();
process.setPendingCall(true);
CloudProcessResource.dao.update(process);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.assertion, assertions);
} else if(process.isPendingCall()) {
process.setPendingCall(false);
CloudProcessResource.dao.update(process);
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.call);
}
log.info("<<<<<<<<Dispatch "+processId);
return new NextStep(DoNext.nothing);
} });
CloudProcess process = CloudProcessResource.dao.load(processId);
Action task = null;
try {
task = ActionResource.dao.load(process.getAction());
} catch (Exception e) {
log.log(Level.SEVERE, "Failed to access task "+process.getAction(), e);
toFailed(process);
return false;
}
log.info("Dispatch "+dispatchCode+": process "+process.getName()+" "+process.getUri()+" task "+task.getUri());
boolean error = false;
switch(dispatchCode.todo){
case assertion:
for(String assertion : dispatchCode.assertion) {
try {
int index = assertion.indexOf(":");
SignalKind kind = SignalKind.valueOf(assertion.substring(0,index));
task.signal(kind, assertion.substring(index+1));
} catch (Exception e) {
log.log(Level.WARNING, "Assertion "+ assertion + " exception for process "+process.getUri()+" task "+task.getUri(), e);
}
}
writeOnChange(task);
return endOfTimeSlice(process);
case init:
try {
task.init();
} catch (Exception e) {
log.log(Level.WARNING, "Init exception for process "+process.getUri()+" task "+task.getUri(), e);
error = true;
}
writeOnChange(task);
if(error) {
toFailed(process);
} else {
return endOfTimeSlice(process);
}
break;
case call:
boolean complete = false;
try {
complete = task.call();
} catch (WaitForSignalRequest e) {
toWait(process, e.getTimeout());
} catch (Exception e) {
log.log(Level.WARNING, "Call exception for process "+process.getUri()+" task "+task.getUri(), e);
error = true;
}
writeOnChange(task);
if(error) {
toFailed(process);
break;
} else if(complete) {
toComplete(process);
} else {
return endOfTimeSlice(process);
}
break;
case cancel:
try {
task.cancel();
} catch (Exception e) {
log.log(Level.WARNING, "Cancel exception for process "+process.getUri()+" task "+task.getUri(), e);
}
writeOnChange(task);
toCancelled(process);
break;
case dump:
try {
task.dump();
} catch (Exception e) {
log.log(Level.WARNING, "Dump exception for process "+process.getUri()+" task "+task.getUri(), e);
}
writeOnChange(task);
toCancelled(process);
break;
case nothing:
default:
log.severe("******Nothing to do for "+process.getName()+":"+process.toString());
// Likely concurrency bug. Process gets dispatched twice.
break;
}
return false;
}
|
diff --git a/ui/plugins/eu.esdihumboldt.hale.ui/src/eu/esdihumboldt/hale/ui/io/source/FileSourceFileFieldEditor.java b/ui/plugins/eu.esdihumboldt.hale.ui/src/eu/esdihumboldt/hale/ui/io/source/FileSourceFileFieldEditor.java
index 93c730a03..6485765fc 100644
--- a/ui/plugins/eu.esdihumboldt.hale.ui/src/eu/esdihumboldt/hale/ui/io/source/FileSourceFileFieldEditor.java
+++ b/ui/plugins/eu.esdihumboldt.hale.ui/src/eu/esdihumboldt/hale/ui/io/source/FileSourceFileFieldEditor.java
@@ -1,179 +1,179 @@
/*
* Copyright (c) 2013 Data Harmonisation Panel
*
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution. If not, see <http://www.gnu.org/licenses/>.
*
* Contributors:
* Data Harmonisation Panel <http://www.dhpanel.eu>
*/
package eu.esdihumboldt.hale.ui.io.source;
import java.io.File;
import java.net.URI;
import org.eclipse.jface.preference.FileFieldEditor;
import org.eclipse.swt.widgets.Composite;
import eu.esdihumboldt.hale.ui.io.util.OpenFileFieldEditor;
import eu.esdihumboldt.util.io.IOUtils;
/**
* A {@link OpenFileFieldEditor} with support for relative URIs with regard to
* the current project's location.
*
* @author Kai Schwierczek
*/
public class FileSourceFileFieldEditor extends OpenFileFieldEditor {
private final URI projectURI;
private boolean useRelative;
/**
* Default constructor.
*/
public FileSourceFileFieldEditor() {
this(null);
}
/**
* Constructor with the specified project URI. Can be used in conjunction
* with {@link #setUseRelativeIfPossible(boolean)}.
*
* @param projectURI the project URI to use
*/
public FileSourceFileFieldEditor(URI projectURI) {
super();
this.projectURI = projectURI;
}
/**
* @see FileFieldEditor#FileFieldEditor(String, String, Composite)
* @see #FileSourceFileFieldEditor(URI)
*/
public FileSourceFileFieldEditor(String name, String labelText, Composite parent, URI projectURI) {
super(name, labelText, parent);
this.projectURI = projectURI;
}
/**
* @see FileFieldEditor#FileFieldEditor(String, String, boolean, int,
* Composite)
* @see #FileSourceFileFieldEditor(URI)
*/
public FileSourceFileFieldEditor(String name, String labelText, int validationStrategy,
Composite parent, URI projectURI) {
super(name, labelText, false, validationStrategy, parent);
this.projectURI = projectURI;
}
/**
* Sets the editor to allow relative values. The projectURI has to be
* supplied during construction to support this feature.
*
* @param useRelative the new value
*/
public void setUseRelativeIfPossible(boolean useRelative) {
if (this.useRelative && !useRelative) {
File f = new File(getTextControl().getText());
f = resolve(f);
if (f != null)
getTextControl().setText(f.getAbsolutePath());
this.useRelative = false;
}
else if (!this.useRelative && useRelative && projectURI != null) {
this.useRelative = true;
File f = new File(getTextControl().getText());
URI absoluteSelected = f.toURI();
URI relativeSelected = IOUtils.getRelativePath(absoluteSelected, projectURI);
if (!relativeSelected.isAbsolute())
f = new File(relativeSelected.toString());
getTextControl().setText(f.getPath());
}
}
/**
* @see FileFieldEditor#changePressed()
*/
@Override
protected String changePressed() {
File f = new File(getTextControl().getText());
f = resolve(f);
File d = getFile(f);
if (d == null) {
return null;
}
if (useRelative) {
d = d.getAbsoluteFile();
URI absoluteSelected = d.toURI();
URI relativeSelected = IOUtils.getRelativePath(absoluteSelected, projectURI);
if (!relativeSelected.isAbsolute())
d = new File(relativeSelected.toString());
}
return d.getPath();
}
@Override
protected boolean checkState() {
String msg = null;
String path = getTextControl().getText();
if (path != null) {
path = path.trim();
}
else {
path = "";//$NON-NLS-1$
}
if (path.length() == 0) {
if (!isEmptyStringAllowed()) {
msg = getErrorMessage();
}
}
else {
File file = resolve(new File(path));
- if (!file.isFile()) {
+ if (file == null || !file.isFile()) {
msg = getErrorMessage();
}
}
if (msg != null) { // error
showErrorMessage(msg);
return false;
}
if (doCheckState()) { // OK!
clearErrorMessage();
return true;
}
msg = getErrorMessage(); // subclass might have changed it in the
// #doCheckState()
if (msg != null) {
showErrorMessage(msg);
}
return false;
}
private File resolve(File f) {
// first find absolute
File resolved;
if (f.isAbsolute())
resolved = f;
else if (useRelative)
resolved = new File(projectURI.resolve(IOUtils.relativeFileToURI(f)));
else
resolved = null;
// then check existence
if (resolved != null && resolved.exists())
return resolved;
else
return null;
}
}
| true | true | protected boolean checkState() {
String msg = null;
String path = getTextControl().getText();
if (path != null) {
path = path.trim();
}
else {
path = "";//$NON-NLS-1$
}
if (path.length() == 0) {
if (!isEmptyStringAllowed()) {
msg = getErrorMessage();
}
}
else {
File file = resolve(new File(path));
if (!file.isFile()) {
msg = getErrorMessage();
}
}
if (msg != null) { // error
showErrorMessage(msg);
return false;
}
if (doCheckState()) { // OK!
clearErrorMessage();
return true;
}
msg = getErrorMessage(); // subclass might have changed it in the
// #doCheckState()
if (msg != null) {
showErrorMessage(msg);
}
return false;
}
| protected boolean checkState() {
String msg = null;
String path = getTextControl().getText();
if (path != null) {
path = path.trim();
}
else {
path = "";//$NON-NLS-1$
}
if (path.length() == 0) {
if (!isEmptyStringAllowed()) {
msg = getErrorMessage();
}
}
else {
File file = resolve(new File(path));
if (file == null || !file.isFile()) {
msg = getErrorMessage();
}
}
if (msg != null) { // error
showErrorMessage(msg);
return false;
}
if (doCheckState()) { // OK!
clearErrorMessage();
return true;
}
msg = getErrorMessage(); // subclass might have changed it in the
// #doCheckState()
if (msg != null) {
showErrorMessage(msg);
}
return false;
}
|
diff --git a/modules/world/avatarbase/src/classes/org/jdesktop/wonderland/modules/avatarbase/client/jme/cellrenderer/GestureHUD.java b/modules/world/avatarbase/src/classes/org/jdesktop/wonderland/modules/avatarbase/client/jme/cellrenderer/GestureHUD.java
index 6bf99afdf..898b297a8 100644
--- a/modules/world/avatarbase/src/classes/org/jdesktop/wonderland/modules/avatarbase/client/jme/cellrenderer/GestureHUD.java
+++ b/modules/world/avatarbase/src/classes/org/jdesktop/wonderland/modules/avatarbase/client/jme/cellrenderer/GestureHUD.java
@@ -1,197 +1,198 @@
/**
* Project Wonderland
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied
* this code.
*/
package org.jdesktop.wonderland.modules.avatarbase.client.jme.cellrenderer;
import imi.character.CharacterEyes;
import imi.character.avatar.AvatarContext.TriggerNames;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import org.jdesktop.wonderland.client.hud.HUD;
import org.jdesktop.wonderland.client.hud.HUDButton;
import org.jdesktop.wonderland.client.hud.HUDManagerFactory;
/**
* A HUD display for avatar gestures
*
* @author nsimpson
*/
public class GestureHUD {
private static final Logger logger = Logger.getLogger(GestureHUD.class.getName());
private static final ResourceBundle bundle = ResourceBundle.getBundle("org/jdesktop/wonderland/modules/avatarbase/client/resources/Bundle");
private boolean visible = false;
private boolean showingGestures = true;
private Map<String, String> gestureMap = new HashMap();
private Map<String, HUDButton> buttonMap = new HashMap();
private HUDButton showGesturesButton;
private HUD mainHUD;
// map gestures to column, row locations on gesture HUD
private String[][] gestures = {
{"Answer Cell", "0", "1"},
{"Sit", "0", "2"},
/*{"Take Damage", "0", "3"},*/
{"Public Speaking", "1", "0"},
{"Bow", "1", "1"},
{"Shake Hands", "1", "2"},
{"Cheer", "2", "0"},
{"Clap", "2", "1"},
{"Laugh", "2", "2"},
{"Wave", "3", "2"},
{"Raise Hand", "3", "1"},
{"Follow", "3", "0"},
/*{"Left Wink", "4", "0"},*/
{"Wink", "4", "0"},
{"No", "4", "1"},
{"Yes", "4", "2"}};
private int leftMargin = 20;
private int bottomMargin = 10;
private int rowHeight = 30;
private int columnWidth = 100;
public GestureHUD() {
setAvatarCharacter(null);
}
public void setVisible(final boolean visible) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (GestureHUD.this.visible == visible) {
return;
}
if (showGesturesButton == null) {
showGesturesButton = mainHUD.createButton(bundle.getString("HideGestures"));
showGesturesButton.setDecoratable(false);
showGesturesButton.setLocation(leftMargin, bottomMargin);
showGesturesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
showingGestures = (showGesturesButton.getLabel().equals(bundle.getString("HideGestures"))) ? false : true;
showGesturesButton.setLabel(showingGestures ? bundle.getString("HideGestures") : bundle.getString("ShowGestures"));
showGestureButtons(showingGestures);
}
});
mainHUD.addComponent(showGesturesButton);
}
GestureHUD.this.visible = visible;
showGesturesButton.setVisible(visible);
showGestureButtons(visible && showingGestures);
}
});
}
public void showGestureButtons(boolean show) {
for (String gesture : buttonMap.keySet()) {
HUDButton button = buttonMap.get(gesture);
button.setVisible(show);
}
}
public boolean isVisible() {
return visible;
}
public void setAvatarCharacter(final WlAvatarCharacter avatar) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (mainHUD == null) {
mainHUD = HUDManagerFactory.getHUDManager().getHUD("main");
}
// remove existing gesture buttons
for (String name : buttonMap.keySet()) {
HUDButton button = buttonMap.get(name);
mainHUD.removeComponent(button);
}
buttonMap.clear();
gestureMap.clear();
// If we don't have an avatar, then just return
if (avatar == null) {
return;
}
// Otherwise, figure out which gestures are supported. We want to
// remove the "Male_" or "Female_" for now.
for (String action : avatar.getAnimationNames()) {
String name = action;
if (action.startsWith("Male_") == true) {
name = name.substring(5);
} else if (action.startsWith("Female_") == true) {
name = name.substring(7);
}
// add to a map of user-friendly names to avatar animations
// e.g., "Shake Hands" -> "Male_ShakeHands"
gestureMap.put(bundle.getString(name), action);
}
// Add the left and right wink
//gestureMap.put("Left Wink", "LeftWink");
gestureMap.put("Wink", "RightWink");
gestureMap.put("Sit", "Sit");
// Create HUD buttons for each of the actions
for (String name : gestureMap.keySet()) {
int row = 0;
int column = 0;
// find the button row, column position for this gesture
for (String[] gesture : gestures) {
if (gesture[0].equals(name)) {
column = Integer.valueOf(gesture[1]);
row = Integer.valueOf(gesture[2]);
HUDButton button = mainHUD.createButton(name);
button.setDecoratable(false);
+ button.setPreferredTransparency(0.2f);
button.setLocation(leftMargin + column * columnWidth, bottomMargin + row * rowHeight);
mainHUD.addComponent(button);
buttonMap.put(name, button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String action = gestureMap.get(event.getActionCommand());
logger.info("playing animation: " + event.getActionCommand());
if (action.equals("Sit") == true) {
avatar.triggerActionStart(TriggerNames.SitOnGround);
} else if (action.equals("RightWink") == true) {
CharacterEyes eyes = avatar.getEyes();
eyes.wink(false);
// } else if (action.equals("RightWink") == true) {
// CharacterEyes eyes = avatar.getEyes();
// eyes.wink(true);
} else {
avatar.playAnimation(action);
}
}
});
break;
}
}
}
setVisible(true);
}
});
}
}
| true | true | public void setAvatarCharacter(final WlAvatarCharacter avatar) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (mainHUD == null) {
mainHUD = HUDManagerFactory.getHUDManager().getHUD("main");
}
// remove existing gesture buttons
for (String name : buttonMap.keySet()) {
HUDButton button = buttonMap.get(name);
mainHUD.removeComponent(button);
}
buttonMap.clear();
gestureMap.clear();
// If we don't have an avatar, then just return
if (avatar == null) {
return;
}
// Otherwise, figure out which gestures are supported. We want to
// remove the "Male_" or "Female_" for now.
for (String action : avatar.getAnimationNames()) {
String name = action;
if (action.startsWith("Male_") == true) {
name = name.substring(5);
} else if (action.startsWith("Female_") == true) {
name = name.substring(7);
}
// add to a map of user-friendly names to avatar animations
// e.g., "Shake Hands" -> "Male_ShakeHands"
gestureMap.put(bundle.getString(name), action);
}
// Add the left and right wink
//gestureMap.put("Left Wink", "LeftWink");
gestureMap.put("Wink", "RightWink");
gestureMap.put("Sit", "Sit");
// Create HUD buttons for each of the actions
for (String name : gestureMap.keySet()) {
int row = 0;
int column = 0;
// find the button row, column position for this gesture
for (String[] gesture : gestures) {
if (gesture[0].equals(name)) {
column = Integer.valueOf(gesture[1]);
row = Integer.valueOf(gesture[2]);
HUDButton button = mainHUD.createButton(name);
button.setDecoratable(false);
button.setLocation(leftMargin + column * columnWidth, bottomMargin + row * rowHeight);
mainHUD.addComponent(button);
buttonMap.put(name, button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String action = gestureMap.get(event.getActionCommand());
logger.info("playing animation: " + event.getActionCommand());
if (action.equals("Sit") == true) {
avatar.triggerActionStart(TriggerNames.SitOnGround);
} else if (action.equals("RightWink") == true) {
CharacterEyes eyes = avatar.getEyes();
eyes.wink(false);
// } else if (action.equals("RightWink") == true) {
// CharacterEyes eyes = avatar.getEyes();
// eyes.wink(true);
} else {
avatar.playAnimation(action);
}
}
});
break;
}
}
}
setVisible(true);
}
});
}
| public void setAvatarCharacter(final WlAvatarCharacter avatar) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (mainHUD == null) {
mainHUD = HUDManagerFactory.getHUDManager().getHUD("main");
}
// remove existing gesture buttons
for (String name : buttonMap.keySet()) {
HUDButton button = buttonMap.get(name);
mainHUD.removeComponent(button);
}
buttonMap.clear();
gestureMap.clear();
// If we don't have an avatar, then just return
if (avatar == null) {
return;
}
// Otherwise, figure out which gestures are supported. We want to
// remove the "Male_" or "Female_" for now.
for (String action : avatar.getAnimationNames()) {
String name = action;
if (action.startsWith("Male_") == true) {
name = name.substring(5);
} else if (action.startsWith("Female_") == true) {
name = name.substring(7);
}
// add to a map of user-friendly names to avatar animations
// e.g., "Shake Hands" -> "Male_ShakeHands"
gestureMap.put(bundle.getString(name), action);
}
// Add the left and right wink
//gestureMap.put("Left Wink", "LeftWink");
gestureMap.put("Wink", "RightWink");
gestureMap.put("Sit", "Sit");
// Create HUD buttons for each of the actions
for (String name : gestureMap.keySet()) {
int row = 0;
int column = 0;
// find the button row, column position for this gesture
for (String[] gesture : gestures) {
if (gesture[0].equals(name)) {
column = Integer.valueOf(gesture[1]);
row = Integer.valueOf(gesture[2]);
HUDButton button = mainHUD.createButton(name);
button.setDecoratable(false);
button.setPreferredTransparency(0.2f);
button.setLocation(leftMargin + column * columnWidth, bottomMargin + row * rowHeight);
mainHUD.addComponent(button);
buttonMap.put(name, button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String action = gestureMap.get(event.getActionCommand());
logger.info("playing animation: " + event.getActionCommand());
if (action.equals("Sit") == true) {
avatar.triggerActionStart(TriggerNames.SitOnGround);
} else if (action.equals("RightWink") == true) {
CharacterEyes eyes = avatar.getEyes();
eyes.wink(false);
// } else if (action.equals("RightWink") == true) {
// CharacterEyes eyes = avatar.getEyes();
// eyes.wink(true);
} else {
avatar.playAnimation(action);
}
}
});
break;
}
}
}
setVisible(true);
}
});
}
|
diff --git a/SlidingLayerSample/src/com/slidinglayer/SlidingLayer.java b/SlidingLayerSample/src/com/slidinglayer/SlidingLayer.java
index 70b60d6..6cfe5c6 100644
--- a/SlidingLayerSample/src/com/slidinglayer/SlidingLayer.java
+++ b/SlidingLayerSample/src/com/slidinglayer/SlidingLayer.java
@@ -1,877 +1,877 @@
/*
* SlidingLayer.java
*
* Copyright (C) 2013 6 Wunderkinder GmbH.
*
* @author Jose L Ugia - @Jl_Ugia
* @author Antonio Consuegra - @aconsuegra
* @author Cesar Valiente - @CesarValiente
* @version 2.0
*
* 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.slidinglayer;
import java.lang.reflect.Method;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v4.view.ViewConfigurationCompat;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.view.Display;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.Scroller;
import com.slidinglayer.util.CommonUtils;
import com.slidinglayersample.R;
public class SlidingLayer extends FrameLayout {
// TODO Document
/**
* Default value for the position of the layer. STICK_TO_AUTO shall inspect the container and choose a stick
* mode depending on the position of the layour (ie.: layout is positioned on the right = STICK_TO_RIGHT).
*/
public static final int STICK_TO_AUTO = 0;
/**
* Special value for the position of the layer. STICK_TO_RIGHT means that the view shall be attached to the
* right side of the screen, and come from there into the viewable area.
*/
public static final int STICK_TO_RIGHT = -1;
/**
* Special value for the position of the layer. STICK_TO_LEFT means that the view shall be attached to the left
* side of the screen, and come from there into the viewable area.
*/
public static final int STICK_TO_LEFT = -2;
/**
* Special value for the position of the layer. STICK_TO_MIDDLE means that the view will stay attached trying to
* be in the middle of the screen and allowing dismissing both to right and left side.
*/
public static final int STICK_TO_MIDDLE = -3;
private static final int MAX_SCROLLING_DURATION = 600; // in ms
private static final int MIN_DISTANCE_FOR_FLING = 25; // in dip
private static final Interpolator sMenuInterpolator = new Interpolator() {
@Override
public float getInterpolation(float t) {
t -= 1.0f;
return (float) Math.pow(t, 5) + 1.0f;
}
};
private Scroller mScroller;
private int mShadowWidth;
private Drawable mShadowDrawable;
private boolean mDrawingCacheEnabled;
private int mScreenSide = STICK_TO_AUTO;
private boolean closeOnTapEnabled = true;
private boolean mEnabled = true;
private boolean mSlidingFromShadowEnabled = true;
private boolean mIsDragging;
private boolean mIsUnableToDrag;
private int mTouchSlop;
private float mLastX = -1;
private float mLastY = -1;
private float mInitialX = -1;
protected int mActivePointerId = INVALID_POINTER;
/**
* Sentinel value for no current active pointer. Used by {@link #mActivePointerId}.
*/
private static final int INVALID_POINTER = -1;
private boolean mIsOpen;
private boolean mScrolling;
private OnInteractListener mOnInteractListener;
protected VelocityTracker mVelocityTracker;
private int mMinimumVelocity;
protected int mMaximumVelocity;
private int mFlingDistance;
private boolean mLastTouchAllowed = false;
public SlidingLayer(Context context) {
this(context, null);
}
public SlidingLayer(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingLayer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Style
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SlidingLayer);
// Set the side of the screen
setStickTo(ta.getInt(R.styleable.SlidingLayer_stickTo, STICK_TO_AUTO));
// Sets the shadow drawable
int shadowRes = ta.getResourceId(R.styleable.SlidingLayer_shadowDrawable, -1);
if (shadowRes != -1) {
setShadowDrawable(shadowRes);
}
// Sets the shadow width
setShadowWidth((int) ta.getDimension(R.styleable.SlidingLayer_shadowWidth, 0));
// Sets the ability to close the layer by tapping in any empty space
closeOnTapEnabled = ta.getBoolean(R.styleable.SlidingLayer_closeOnTapEnabled, true);
ta.recycle();
init();
}
private void init() {
setWillNotDraw(false);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
setFocusable(true);
final Context context = getContext();
mScroller = new Scroller(context, sMenuInterpolator);
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
final float density = context.getResources().getDisplayMetrics().density;
mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);
}
public interface OnInteractListener {
public void onOpen();
public void onClose();
public void onOpened();
public void onClosed();
}
public boolean isOpened() {
return mIsOpen;
}
public void openLayer(boolean smoothAnim) {
openLayer(smoothAnim, false);
}
private void openLayer(boolean smoothAnim, boolean forceOpen) {
switchLayer(true, smoothAnim, forceOpen, 0);
}
public void closeLayer(boolean smoothAnim) {
closeLayer(smoothAnim, false);
}
private void closeLayer(boolean smoothAnim, boolean forceClose) {
switchLayer(false, smoothAnim, forceClose, 0);
}
private void switchLayer(boolean open, boolean smoothAnim, boolean forceSwitch) {
switchLayer(open, smoothAnim, forceSwitch, 0);
}
private void switchLayer(boolean open, boolean smoothAnim, boolean forceSwitch, int velocity) {
if (!forceSwitch && open == mIsOpen) {
setDrawingCacheEnabled(false);
return;
}
if (open) {
if (mOnInteractListener != null) {
mOnInteractListener.onOpen();
}
} else {
if (mOnInteractListener != null) {
mOnInteractListener.onClose();
}
}
mIsOpen = open;
final int destX = getDestScrollX(velocity);
if (smoothAnim) {
smoothScrollTo(destX, 0, velocity);
} else {
completeScroll();
scrollTo(destX, 0);
}
}
/**
* Sets the listener to be invoked after a switch change {@link OnInteractListener}.
*
* @param listener
* Listener to set
*/
public void setOnInteractListener(OnInteractListener listener) {
mOnInteractListener = listener;
}
/**
* Sets the shadow of the width which will be included within the view by using padding since it's on the left
* of the view in this case
*
* @param shadowWidth
* Desired width of the shadow
* @see #getShadowWidth()
* @see #setShadowDrawable(Drawable)
* @see #setShadowDrawable(int)
*/
public void setShadowWidth(int shadowWidth) {
mShadowWidth = shadowWidth;
invalidate(getLeft(), getTop(), getRight(), getBottom());
}
/**
* Sets the shadow width by the value of a resource.
*
* @param resId
* The dimension resource id to be set as the shadow width.
*/
public void setShadowWidthRes(int resId) {
setShadowWidth((int) getResources().getDimension(resId));
}
/**
* Return the current with of the shadow.
*
* @return The size of the shadow in pixels
*/
public int getShadowWidth() {
return mShadowWidth;
}
/**
* Sets a drawable that will be used to create the shadow for the layer.
*
* @param d
* Drawable append as a shadow
*/
public void setShadowDrawable(Drawable d) {
mShadowDrawable = d;
refreshDrawableState();
setWillNotDraw(false);
invalidate(getLeft(), getTop(), getRight(), getBottom());
}
/**
* Sets a drawable resource that will be used to create the shadow for the layer.
*
* @param resId
* Resource ID of a drawable
*/
public void setShadowDrawable(int resId) {
setShadowDrawable(getContext().getResources().getDrawable(resId));
}
@Override
protected boolean verifyDrawable(Drawable who) {
return super.verifyDrawable(who) || who == mShadowDrawable;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
final Drawable d = mShadowDrawable;
if (d != null && d.isStateful()) {
d.setState(getDrawableState());
}
}
public boolean isSlidingEnabled() {
return mEnabled;
}
public void setSlidingEnabled(boolean _enabled) {
mEnabled = _enabled;
}
public boolean isSlidingFromShadowEnabled() {
return mSlidingFromShadowEnabled;
}
public void setSlidingFromShadowEnabled(boolean _slidingShadow) {
mSlidingFromShadowEnabled = _slidingShadow;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (!mEnabled) {
return false;
}
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
mIsDragging = false;
mIsUnableToDrag = false;
mActivePointerId = INVALID_POINTER;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
return false;
}
if (action != MotionEvent.ACTION_DOWN) {
if (mIsDragging) {
return true;
} else if (mIsUnableToDrag) {
return false;
}
}
switch (action) {
case MotionEvent.ACTION_MOVE:
final int activePointerId = mActivePointerId;
if (activePointerId == INVALID_POINTER) {
break;
}
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId);
if (pointerIndex == -1) {
mActivePointerId = INVALID_POINTER;
break;
}
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float dx = x - mLastX;
final float xDiff = Math.abs(dx);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = Math.abs(y - mLastY);
if (xDiff > mTouchSlop && xDiff > yDiff && allowDraging(dx)) {
mIsDragging = true;
mLastX = x;
setDrawingCacheEnabled(true);
} else if (yDiff > mTouchSlop) {
mIsUnableToDrag = true;
}
break;
case MotionEvent.ACTION_DOWN:
mActivePointerId = ev.getAction()
& (Build.VERSION.SDK_INT >= 8 ? MotionEvent.ACTION_POINTER_INDEX_MASK
: MotionEvent.ACTION_POINTER_INDEX_MASK);
mLastX = mInitialX = MotionEventCompat.getX(ev, mActivePointerId);
mLastY = MotionEventCompat.getY(ev, mActivePointerId);
if (allowSlidingFromHere(ev)) {
mIsDragging = false;
mIsUnableToDrag = false;
// If nobody else got the focus we use it to close the layer
return super.onInterceptTouchEvent(ev);
} else {
mIsUnableToDrag = true;
}
break;
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
if (!mIsDragging) {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
}
return mIsDragging;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!mEnabled || !mIsDragging && !mLastTouchAllowed && !allowSlidingFromHere(ev)) {
return false;
}
final int action = ev.getAction();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL
|| action == MotionEvent.ACTION_OUTSIDE) {
mLastTouchAllowed = false;
} else {
mLastTouchAllowed = true;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
completeScroll();
// Remember where the motion event started
mLastX = mInitialX = ev.getX();
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
break;
case MotionEvent.ACTION_MOVE:
if (!mIsDragging) {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (pointerIndex == -1) {
mActivePointerId = INVALID_POINTER;
break;
}
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float xDiff = Math.abs(x - mLastX);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = Math.abs(y - mLastY);
if (xDiff > mTouchSlop && xDiff > yDiff) {
mIsDragging = true;
mLastX = x;
setDrawingCacheEnabled(true);
}
}
if (mIsDragging) {
// Scroll to follow the motion event
final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (activePointerIndex == -1) {
mActivePointerId = INVALID_POINTER;
break;
}
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final float deltaX = mLastX - x;
mLastX = x;
float oldScrollX = getScrollX();
float scrollX = oldScrollX + deltaX;
final float leftBound = mScreenSide < STICK_TO_RIGHT ? getWidth() : 0;
final float rightBound = mScreenSide == STICK_TO_LEFT ? 0 : -getWidth();
if (scrollX > leftBound) {
scrollX = leftBound;
} else if (scrollX < rightBound) {
scrollX = rightBound;
}
// Keep the precision
mLastX += scrollX - (int) scrollX;
scrollTo((int) scrollX, getScrollY());
}
break;
case MotionEvent.ACTION_UP:
if (mIsDragging) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(velocityTracker, mActivePointerId);
final int scrollX = getScrollX();
final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final int totalDelta = (int) (x - mInitialX);
boolean nextStateOpened = determineNextStateOpened(mIsOpen, scrollX, initialVelocity, totalDelta);
switchLayer(nextStateOpened, true, true, initialVelocity);
mActivePointerId = INVALID_POINTER;
endDrag();
} else if (mIsOpen && closeOnTapEnabled) {
closeLayer(true);
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsDragging) {
switchLayer(mIsOpen, true, true);
mActivePointerId = INVALID_POINTER;
endDrag();
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
final float x = MotionEventCompat.getX(ev, index);
mLastX = x;
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
- mLastY = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
+ mLastX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
break;
}
if (mActivePointerId == INVALID_POINTER) {
mLastTouchAllowed = false;
}
return true;
}
private boolean allowSlidingFromHere(MotionEvent ev) {
return mIsOpen /* && allowSlidingFromShadow || ev.getX() > mShadowWidth */;
}
private boolean allowDraging(float dx) {
return mIsOpen && dx > 0;
}
private boolean determineNextStateOpened(boolean currentState, float swipeOffset, int velocity, int deltaX) {
boolean targetState;
if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) {
targetState = mScreenSide == STICK_TO_RIGHT && velocity <= 0 || mScreenSide == STICK_TO_LEFT
&& velocity > 0;
} else {
int w = getWidth();
if (mScreenSide == STICK_TO_RIGHT) {
targetState = swipeOffset > -w / 2;
} else if (mScreenSide == STICK_TO_LEFT) {
targetState = swipeOffset < w / 2;
} else if (mScreenSide == STICK_TO_MIDDLE) {
targetState = Math.abs(swipeOffset) < w / 2;
} else {
targetState = true;
}
}
return targetState;
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x
* the number of pixels to scroll by on the X axis
* @param y
* the number of pixels to scroll by on the Y axis
*/
void smoothScrollTo(int x, int y) {
smoothScrollTo(x, y, 0);
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x
* the number of pixels to scroll by on the X axis
* @param y
* the number of pixels to scroll by on the Y axis
* @param velocity
* the velocity associated with a fling, if applicable. (0 otherwise)
*/
void smoothScrollTo(int x, int y, int velocity) {
if (getChildCount() == 0) {
setDrawingCacheEnabled(false);
return;
}
int sx = getScrollX();
int sy = getScrollY();
int dx = x - sx;
int dy = y - sy;
if (dx == 0 && dy == 0) {
completeScroll();
if (mIsOpen) {
if (mOnInteractListener != null) {
mOnInteractListener.onOpened();
}
} else {
if (mOnInteractListener != null) {
mOnInteractListener.onClosed();
}
}
return;
}
setDrawingCacheEnabled(true);
mScrolling = true;
final int width = getWidth();
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);
final float distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration(distanceRatio);
int duration = 0;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
duration = MAX_SCROLLING_DURATION;
}
duration = Math.min(duration, MAX_SCROLLING_DURATION);
mScroller.startScroll(sx, sy, dx, dy, duration);
invalidate();
}
// We want the duration of the page snap animation to be influenced by the distance that
// the screen has to travel, however, we don't want this duration to be effected in a
// purely linear fashion. Instead, we use this method to moderate the effect that the distance
// of travel has on the overall snap duration.
float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * Math.PI / 2.0f;
return FloatMath.sin(f);
}
private void endDrag() {
mIsDragging = false;
mIsUnableToDrag = false;
mLastTouchAllowed = false;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
@Override
public void setDrawingCacheEnabled(boolean enabled) {
if (mDrawingCacheEnabled != enabled) {
super.setDrawingCacheEnabled(enabled);
mDrawingCacheEnabled = enabled;
final int l = getChildCount();
for (int i = 0; i < l; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.setDrawingCacheEnabled(enabled);
}
}
}
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastX = MotionEventCompat.getX(ev, newPointerIndex);
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
}
}
private void completeScroll() {
boolean needPopulate = mScrolling;
if (needPopulate) {
// Done with scroll, no longer want to cache view drawing.
setDrawingCacheEnabled(false);
mScroller.abortAnimation();
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
}
if (mIsOpen) {
if (mOnInteractListener != null) {
mOnInteractListener.onOpened();
}
} else {
if (mOnInteractListener != null) {
mOnInteractListener.onClosed();
}
}
}
mScrolling = false;
}
public void setStickTo(int screenSide) {
mScreenSide = screenSide;
closeLayer(false, true);
}
public void setCloseOnTapEnabled(boolean _closeOnTapEnabled) {
closeOnTapEnabled = _closeOnTapEnabled;
}
@SuppressWarnings("deprecation")
private int getScreenSideAuto(int newLeft, int newRight) {
int newScreenSide;
if (mScreenSide == STICK_TO_AUTO) {
int screenWidth;
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
try {
Class<?> cls = Display.class;
Class<?>[] parameterTypes = { Point.class };
Point parameter = new Point();
Method method = cls.getMethod("getSize", parameterTypes);
method.invoke(display, parameter);
screenWidth = parameter.x;
} catch (Exception e) {
screenWidth = display.getWidth();
}
boolean boundToLeftBorder = newLeft == 0;
boolean boundToRightBorder = newRight == screenWidth;
if (boundToLeftBorder == boundToRightBorder && getLayoutParams().width == LayoutParams.MATCH_PARENT) {
newScreenSide = STICK_TO_MIDDLE;
} else if (boundToLeftBorder) {
newScreenSide = STICK_TO_LEFT;
} else {
newScreenSide = STICK_TO_RIGHT;
}
} else {
newScreenSide = mScreenSide;
}
return newScreenSide;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = getDefaultSize(0, widthMeasureSpec);
int height = getDefaultSize(0, heightMeasureSpec);
setMeasuredDimension(width, height);
super.onMeasure(getChildMeasureSpec(widthMeasureSpec, 0, width),
getChildMeasureSpec(heightMeasureSpec, 0, height));
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Make sure scroll position is set correctly.
if (w != oldw) {
completeScroll();
scrollTo(getDestScrollX(), getScrollY());
}
}
// FIXME Draw with lefts and rights instead of paddings
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int screenSide = mScreenSide;
if (mScreenSide == STICK_TO_AUTO) {
screenSide = getScreenSideAuto(left, right);
}
if (screenSide != mScreenSide) {
setStickTo(screenSide);
if (mScreenSide == STICK_TO_RIGHT) {
setPadding(getPaddingLeft() + mShadowWidth, getPaddingTop(), getPaddingRight(), getPaddingBottom());
} else if (mScreenSide == STICK_TO_LEFT) {
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight() + mShadowWidth, getPaddingBottom());
} else if (mScreenSide == STICK_TO_MIDDLE) {
setPadding(getPaddingLeft() + mShadowWidth, getPaddingTop(), getPaddingRight() + mShadowWidth,
getPaddingBottom());
}
}
super.onLayout(changed, left, top, right, bottom);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
private int getDestScrollX() {
return getDestScrollX(0);
}
private int getDestScrollX(int velocity) {
if (mIsOpen) {
return 0;
} else {
if (mScreenSide == STICK_TO_RIGHT) {
return -getWidth();
} else if (mScreenSide == STICK_TO_LEFT) {
return getWidth();
} else {
if (velocity == 0) {
return CommonUtils.getNextRandomBoolean() ? -getWidth() : getWidth();
} else {
return velocity > 0 ? -getWidth() : getWidth();
}
}
}
}
public int getContentLeft() {
return getLeft() + getPaddingLeft();
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
// Draw the margin drawable if needed.
if (mShadowWidth > 0 && mShadowDrawable != null) {
if (mScreenSide != STICK_TO_LEFT) {
mShadowDrawable.setBounds(0, 0, mShadowWidth, getHeight());
}
if (mScreenSide < STICK_TO_RIGHT) {
mShadowDrawable.setBounds(getWidth() - mShadowWidth, 0, getWidth(), getHeight());
}
mShadowDrawable.draw(canvas);
}
}
@Override
public void computeScroll() {
if (!mScroller.isFinished()) {
if (mScroller.computeScrollOffset()) {
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
}
// Keep on drawing until the animation has finished. Just re-draw the necessary part
invalidate(getLeft() + oldX, getTop(), getRight(), getBottom());
return;
}
}
// Done with scroll, clean up state.
completeScroll();
}
}
| true | true | public boolean onTouchEvent(MotionEvent ev) {
if (!mEnabled || !mIsDragging && !mLastTouchAllowed && !allowSlidingFromHere(ev)) {
return false;
}
final int action = ev.getAction();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL
|| action == MotionEvent.ACTION_OUTSIDE) {
mLastTouchAllowed = false;
} else {
mLastTouchAllowed = true;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
completeScroll();
// Remember where the motion event started
mLastX = mInitialX = ev.getX();
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
break;
case MotionEvent.ACTION_MOVE:
if (!mIsDragging) {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (pointerIndex == -1) {
mActivePointerId = INVALID_POINTER;
break;
}
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float xDiff = Math.abs(x - mLastX);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = Math.abs(y - mLastY);
if (xDiff > mTouchSlop && xDiff > yDiff) {
mIsDragging = true;
mLastX = x;
setDrawingCacheEnabled(true);
}
}
if (mIsDragging) {
// Scroll to follow the motion event
final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (activePointerIndex == -1) {
mActivePointerId = INVALID_POINTER;
break;
}
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final float deltaX = mLastX - x;
mLastX = x;
float oldScrollX = getScrollX();
float scrollX = oldScrollX + deltaX;
final float leftBound = mScreenSide < STICK_TO_RIGHT ? getWidth() : 0;
final float rightBound = mScreenSide == STICK_TO_LEFT ? 0 : -getWidth();
if (scrollX > leftBound) {
scrollX = leftBound;
} else if (scrollX < rightBound) {
scrollX = rightBound;
}
// Keep the precision
mLastX += scrollX - (int) scrollX;
scrollTo((int) scrollX, getScrollY());
}
break;
case MotionEvent.ACTION_UP:
if (mIsDragging) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(velocityTracker, mActivePointerId);
final int scrollX = getScrollX();
final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final int totalDelta = (int) (x - mInitialX);
boolean nextStateOpened = determineNextStateOpened(mIsOpen, scrollX, initialVelocity, totalDelta);
switchLayer(nextStateOpened, true, true, initialVelocity);
mActivePointerId = INVALID_POINTER;
endDrag();
} else if (mIsOpen && closeOnTapEnabled) {
closeLayer(true);
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsDragging) {
switchLayer(mIsOpen, true, true);
mActivePointerId = INVALID_POINTER;
endDrag();
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
final float x = MotionEventCompat.getX(ev, index);
mLastX = x;
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
mLastY = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
break;
}
if (mActivePointerId == INVALID_POINTER) {
mLastTouchAllowed = false;
}
return true;
}
| public boolean onTouchEvent(MotionEvent ev) {
if (!mEnabled || !mIsDragging && !mLastTouchAllowed && !allowSlidingFromHere(ev)) {
return false;
}
final int action = ev.getAction();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL
|| action == MotionEvent.ACTION_OUTSIDE) {
mLastTouchAllowed = false;
} else {
mLastTouchAllowed = true;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
completeScroll();
// Remember where the motion event started
mLastX = mInitialX = ev.getX();
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
break;
case MotionEvent.ACTION_MOVE:
if (!mIsDragging) {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (pointerIndex == -1) {
mActivePointerId = INVALID_POINTER;
break;
}
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float xDiff = Math.abs(x - mLastX);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = Math.abs(y - mLastY);
if (xDiff > mTouchSlop && xDiff > yDiff) {
mIsDragging = true;
mLastX = x;
setDrawingCacheEnabled(true);
}
}
if (mIsDragging) {
// Scroll to follow the motion event
final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (activePointerIndex == -1) {
mActivePointerId = INVALID_POINTER;
break;
}
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final float deltaX = mLastX - x;
mLastX = x;
float oldScrollX = getScrollX();
float scrollX = oldScrollX + deltaX;
final float leftBound = mScreenSide < STICK_TO_RIGHT ? getWidth() : 0;
final float rightBound = mScreenSide == STICK_TO_LEFT ? 0 : -getWidth();
if (scrollX > leftBound) {
scrollX = leftBound;
} else if (scrollX < rightBound) {
scrollX = rightBound;
}
// Keep the precision
mLastX += scrollX - (int) scrollX;
scrollTo((int) scrollX, getScrollY());
}
break;
case MotionEvent.ACTION_UP:
if (mIsDragging) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(velocityTracker, mActivePointerId);
final int scrollX = getScrollX();
final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final int totalDelta = (int) (x - mInitialX);
boolean nextStateOpened = determineNextStateOpened(mIsOpen, scrollX, initialVelocity, totalDelta);
switchLayer(nextStateOpened, true, true, initialVelocity);
mActivePointerId = INVALID_POINTER;
endDrag();
} else if (mIsOpen && closeOnTapEnabled) {
closeLayer(true);
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsDragging) {
switchLayer(mIsOpen, true, true);
mActivePointerId = INVALID_POINTER;
endDrag();
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
final float x = MotionEventCompat.getX(ev, index);
mLastX = x;
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
mLastX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
break;
}
if (mActivePointerId == INVALID_POINTER) {
mLastTouchAllowed = false;
}
return true;
}
|
diff --git a/src/main/java/at/molindo/esi4j/rebuild/BulkIndexHelper.java b/src/main/java/at/molindo/esi4j/rebuild/BulkIndexHelper.java
index 5187743..9e2e6cf 100644
--- a/src/main/java/at/molindo/esi4j/rebuild/BulkIndexHelper.java
+++ b/src/main/java/at/molindo/esi4j/rebuild/BulkIndexHelper.java
@@ -1,175 +1,176 @@
/**
* Copyright 2010 Molindo GmbH
*
* 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 at.molindo.esi4j.rebuild;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ListenableActionFuture;
import org.elasticsearch.action.bulk.BulkItemResponse;
import at.molindo.esi4j.action.BulkResponseWrapper;
import at.molindo.esi4j.core.Esi4JIndex;
/**
* helper class that helps awaiting completion of submitted bulk index tasks
*/
public class BulkIndexHelper {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BulkIndexHelper.class);
private static final int DEFAULT_MAX_RUNNING = 10;
private final Esi4JIndex _index;
private final ReentrantLock _lock = new ReentrantLock();
private final Condition _allCompleted = _lock.newCondition();
private final Condition _nextCompleted = _lock.newCondition();
private int _maxRunning = DEFAULT_MAX_RUNNING;
private int _running = 0;
private int _indexed = 0;
private int _failed = 0;
public BulkIndexHelper(Esi4JIndex index) {
if (index == null) {
throw new NullPointerException("index");
}
_index = index;
}
/**
* bulk index all objects in list
*
* @see Esi4JIndex#bulkIndex(Iterable)
*/
public void bulkIndex(List<?> list) {
final int listSize = list.size();
ListenableActionFuture<BulkResponseWrapper> future = _index.bulkIndex(list);
_lock.lock();
try {
while (_running >= _maxRunning) {
try {
_nextCompleted.await();
} catch (InterruptedException e) {
throw new RuntimeException("waiting interrupted", e);
}
}
_running++;
} finally {
_lock.unlock();
}
// might execute immediately
future.addListener(new ActionListener<BulkResponseWrapper>() {
@Override
public void onResponse(BulkResponseWrapper response) {
int indexed = 0;
int failed = 0;
BulkItemResponse[] items = response.getBulkResponse().items();
for (int i = 0; i < items.length; i++) {
if (items[i].failed()) {
failed++;
} else {
indexed++;
}
}
end(indexed, failed);
}
@Override
public void onFailure(Throwable e) {
log.warn("failed to bulk index", e);
end(0, listSize);
}
private void end(int indexed, int failed) {
_lock.lock();
try {
_failed += failed;
_indexed += indexed;
+ _nextCompleted.signal();
if (--_running == 0) {
_allCompleted.signal();
}
} finally {
_lock.unlock();
}
}
});
}
/**
* await termination of all running batch index tasks
*/
public void await() throws InterruptedException {
_lock.lock();
try {
while (_running > 0) {
_allCompleted.await();
}
} finally {
_lock.unlock();
}
}
/**
* @return number of indexed objects
*/
public int getIndexed() {
_lock.lock();
try {
return _indexed;
} finally {
_lock.unlock();
}
}
/**
* @return number of failed objects
*/
public int getFailed() {
_lock.lock();
try {
return _failed;
} finally {
_lock.unlock();
}
}
public int getMaxRunning() {
return _maxRunning;
}
public BulkIndexHelper setMaxRunning(int maxRunning) {
if (maxRunning <= 0) {
throw new IllegalArgumentException("maxRunning must be > 0, was " + maxRunning);
}
_maxRunning = maxRunning;
return this;
}
}
| true | true | public void bulkIndex(List<?> list) {
final int listSize = list.size();
ListenableActionFuture<BulkResponseWrapper> future = _index.bulkIndex(list);
_lock.lock();
try {
while (_running >= _maxRunning) {
try {
_nextCompleted.await();
} catch (InterruptedException e) {
throw new RuntimeException("waiting interrupted", e);
}
}
_running++;
} finally {
_lock.unlock();
}
// might execute immediately
future.addListener(new ActionListener<BulkResponseWrapper>() {
@Override
public void onResponse(BulkResponseWrapper response) {
int indexed = 0;
int failed = 0;
BulkItemResponse[] items = response.getBulkResponse().items();
for (int i = 0; i < items.length; i++) {
if (items[i].failed()) {
failed++;
} else {
indexed++;
}
}
end(indexed, failed);
}
@Override
public void onFailure(Throwable e) {
log.warn("failed to bulk index", e);
end(0, listSize);
}
private void end(int indexed, int failed) {
_lock.lock();
try {
_failed += failed;
_indexed += indexed;
if (--_running == 0) {
_allCompleted.signal();
}
} finally {
_lock.unlock();
}
}
});
}
| public void bulkIndex(List<?> list) {
final int listSize = list.size();
ListenableActionFuture<BulkResponseWrapper> future = _index.bulkIndex(list);
_lock.lock();
try {
while (_running >= _maxRunning) {
try {
_nextCompleted.await();
} catch (InterruptedException e) {
throw new RuntimeException("waiting interrupted", e);
}
}
_running++;
} finally {
_lock.unlock();
}
// might execute immediately
future.addListener(new ActionListener<BulkResponseWrapper>() {
@Override
public void onResponse(BulkResponseWrapper response) {
int indexed = 0;
int failed = 0;
BulkItemResponse[] items = response.getBulkResponse().items();
for (int i = 0; i < items.length; i++) {
if (items[i].failed()) {
failed++;
} else {
indexed++;
}
}
end(indexed, failed);
}
@Override
public void onFailure(Throwable e) {
log.warn("failed to bulk index", e);
end(0, listSize);
}
private void end(int indexed, int failed) {
_lock.lock();
try {
_failed += failed;
_indexed += indexed;
_nextCompleted.signal();
if (--_running == 0) {
_allCompleted.signal();
}
} finally {
_lock.unlock();
}
}
});
}
|
diff --git a/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/BasicCommands/GameManagementCommands.java b/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/BasicCommands/GameManagementCommands.java
index f8a682e..1702374 100644
--- a/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/BasicCommands/GameManagementCommands.java
+++ b/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/BasicCommands/GameManagementCommands.java
@@ -1,168 +1,169 @@
/*
* The MIT License
*
* Copyright 2013 Manuel Gauto.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.mgenterprises.java.bukkit.gmcfps.Core.BasicCommands;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.mgenterprises.java.bukkit.gmcfps.Core.GameManagement.Game;
import org.mgenterprises.java.bukkit.gmcfps.Core.GameManagement.GameManager;
import org.mgenterprises.java.bukkit.gmcfps.Core.Teams.Team;
import org.mgenterprises.java.bukkit.gmcfps.Core.Weapons.Implementations.BasicRocketLauncher;
import org.mgenterprises.java.bukkit.gmcfps.Core.Weapons.Implementations.BasicSMG;
import org.mgenterprises.java.bukkit.gmcfps.Core.Weapons.Implementations.BasicShotgun;
import org.mgenterprises.java.bukkit.gmcfps.Core.Weapons.Implementations.BasicSniper;
import org.mgenterprises.java.bukkit.gmcfps.Core.Weapons.Implementations.Twa16GodWeapon;
/**
*
* @author Manuel Gauto
*/
public class GameManagementCommands implements CommandExecutor {
private GameManager gameManager;
private HashMap<String, Game> editing = new HashMap<String, Game>();
private HashMap<String, String> editingTeam = new HashMap<String, String>();
public GameManagementCommands(GameManager gameManager) {
this.gameManager = gameManager;
}
@Override
public boolean onCommand(CommandSender cs, Command cmnd, String string, String[] args) {
if (string.equalsIgnoreCase(Commands.JOIN.toString())) {
return processJoinCommand(cs, args);
} else if (string.equalsIgnoreCase(Commands.LEAVE.toString())) {
return processLeaveCommand(cs, args);
} else if (string.equalsIgnoreCase(Commands.GAME.toString())) {
return processWizard(cs, args);
}
return false;
}
private boolean processJoinCommand(CommandSender cs, String[] args) {
if (cs instanceof Player) {
if (((Player) cs).hasPermission("gfps.join") || ((Player) cs).isOp()) {
if (args.length >= 1) {
Player p = (Player) cs;
Game g = gameManager.getGameByName(args[0]);
if (g == null) {
p.sendRawMessage(ChatColor.BLUE + "Please enter a valid game name!");
} else {
if (g.registerPlayer(p)) {
p.sendRawMessage(ChatColor.BLUE + "You have joined: " + g.getName());
} else {
p.sendRawMessage(ChatColor.BLUE + g.getName() + " is full!");
}
return true;
}
}
return false;
} else {
cs.sendMessage(ChatColor.RED + "You do not have permission to do that!");
return true;
}
} else {
cs.sendMessage(ChatColor.BLUE + "Command must be executed by a player");
return true;
}
}
private boolean processLeaveCommand(CommandSender cs, String[] args) {
if (cs instanceof Player) {
if (((Player) cs).hasPermission("gfps.leave") || ((Player) cs).isOp()) {
Player p = (Player) cs;
Game g = gameManager.getGameByName(args[0]);
if (g == null) {
p.sendRawMessage(ChatColor.BLUE + "Please enter a valid game name!");
} else {
g.unregisterPlayer(p);
p.sendRawMessage(ChatColor.BLUE + "You have left your game!");
}
}
}
return true;
}
private boolean processWizard(CommandSender cs, String[] args) {
Player p = (Player) cs;
if (!p.hasPermission("gfps.create") && !p.isOp()) {
+ p.sendRawMessage(ChatColor.RED+"You do not have permission");
return true;
}
if (args.length > 2 && args[0].equals("create")) {
Game newGame = new Game(gameManager.getPluginReference(), args[1]);
this.editing.put(p.getName(), newGame);
p.sendRawMessage(ChatColor.AQUA + "Game " + newGame.getName() + " was Created!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + " Set the lobby as the location you are at with " + ChatColor.GREEN + "/game setlobby");
}
if (args[0].equals("setlobby")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getSpawnManager().setLobby(p.getLocation());
p.sendRawMessage(ChatColor.AQUA + "Game lobby set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Decide if the game will be free for all using " + ChatColor.GREEN + "/game setffa [true/false]");
}
if (args.length > 2 && args[0].equals("setffa")) {
Game newGame = this.editing.get(p.getName());
if (args[1].contains("t")) {
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.BLUE + "TRUE");
newGame.getFPSCore().getTeamManager().setFreeForAll(true);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
return true;
}
newGame.getFPSCore().getTeamManager().setFreeForAll(false);
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.RED + "FALSE");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
}
if (args.length > 2 && args[0].equals("addteam")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getTeamManager().registerTeam(new Team(args[1]));
p.sendRawMessage(ChatColor.AQUA + "Team " + args[1] + " was Added!");
this.editingTeam.put(p.getName(), args[1]);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Set the team spawn with " + ChatColor.GREEN + "/game setspawn");
}
if (args[0].equals("setspawn")) {
Game newGame = this.editing.get(p.getName());
Team edit = newGame.getFPSCore().getTeamManager().getTeam(this.editingTeam.get(p.getName()));
edit.setSpawn(p.getLocation());
this.editingTeam.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + "Team spawn set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add more teams or finish the game with " + ChatColor.GREEN + "/game done");
}
if (args[0].equals("done")) {
Game g = this.editing.get(p.getName());
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSMG(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSniper(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicRocketLauncher(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicShotgun(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new Twa16GodWeapon(g.getFPSCore().getWeaponManager()));
this.editing.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + g.getName()+" completed!");
}
return true;
}
}
| true | true | private boolean processWizard(CommandSender cs, String[] args) {
Player p = (Player) cs;
if (!p.hasPermission("gfps.create") && !p.isOp()) {
return true;
}
if (args.length > 2 && args[0].equals("create")) {
Game newGame = new Game(gameManager.getPluginReference(), args[1]);
this.editing.put(p.getName(), newGame);
p.sendRawMessage(ChatColor.AQUA + "Game " + newGame.getName() + " was Created!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + " Set the lobby as the location you are at with " + ChatColor.GREEN + "/game setlobby");
}
if (args[0].equals("setlobby")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getSpawnManager().setLobby(p.getLocation());
p.sendRawMessage(ChatColor.AQUA + "Game lobby set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Decide if the game will be free for all using " + ChatColor.GREEN + "/game setffa [true/false]");
}
if (args.length > 2 && args[0].equals("setffa")) {
Game newGame = this.editing.get(p.getName());
if (args[1].contains("t")) {
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.BLUE + "TRUE");
newGame.getFPSCore().getTeamManager().setFreeForAll(true);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
return true;
}
newGame.getFPSCore().getTeamManager().setFreeForAll(false);
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.RED + "FALSE");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
}
if (args.length > 2 && args[0].equals("addteam")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getTeamManager().registerTeam(new Team(args[1]));
p.sendRawMessage(ChatColor.AQUA + "Team " + args[1] + " was Added!");
this.editingTeam.put(p.getName(), args[1]);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Set the team spawn with " + ChatColor.GREEN + "/game setspawn");
}
if (args[0].equals("setspawn")) {
Game newGame = this.editing.get(p.getName());
Team edit = newGame.getFPSCore().getTeamManager().getTeam(this.editingTeam.get(p.getName()));
edit.setSpawn(p.getLocation());
this.editingTeam.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + "Team spawn set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add more teams or finish the game with " + ChatColor.GREEN + "/game done");
}
if (args[0].equals("done")) {
Game g = this.editing.get(p.getName());
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSMG(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSniper(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicRocketLauncher(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicShotgun(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new Twa16GodWeapon(g.getFPSCore().getWeaponManager()));
this.editing.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + g.getName()+" completed!");
}
return true;
}
| private boolean processWizard(CommandSender cs, String[] args) {
Player p = (Player) cs;
if (!p.hasPermission("gfps.create") && !p.isOp()) {
p.sendRawMessage(ChatColor.RED+"You do not have permission");
return true;
}
if (args.length > 2 && args[0].equals("create")) {
Game newGame = new Game(gameManager.getPluginReference(), args[1]);
this.editing.put(p.getName(), newGame);
p.sendRawMessage(ChatColor.AQUA + "Game " + newGame.getName() + " was Created!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + " Set the lobby as the location you are at with " + ChatColor.GREEN + "/game setlobby");
}
if (args[0].equals("setlobby")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getSpawnManager().setLobby(p.getLocation());
p.sendRawMessage(ChatColor.AQUA + "Game lobby set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Decide if the game will be free for all using " + ChatColor.GREEN + "/game setffa [true/false]");
}
if (args.length > 2 && args[0].equals("setffa")) {
Game newGame = this.editing.get(p.getName());
if (args[1].contains("t")) {
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.BLUE + "TRUE");
newGame.getFPSCore().getTeamManager().setFreeForAll(true);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
return true;
}
newGame.getFPSCore().getTeamManager().setFreeForAll(false);
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.RED + "FALSE");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
}
if (args.length > 2 && args[0].equals("addteam")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getTeamManager().registerTeam(new Team(args[1]));
p.sendRawMessage(ChatColor.AQUA + "Team " + args[1] + " was Added!");
this.editingTeam.put(p.getName(), args[1]);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Set the team spawn with " + ChatColor.GREEN + "/game setspawn");
}
if (args[0].equals("setspawn")) {
Game newGame = this.editing.get(p.getName());
Team edit = newGame.getFPSCore().getTeamManager().getTeam(this.editingTeam.get(p.getName()));
edit.setSpawn(p.getLocation());
this.editingTeam.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + "Team spawn set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add more teams or finish the game with " + ChatColor.GREEN + "/game done");
}
if (args[0].equals("done")) {
Game g = this.editing.get(p.getName());
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSMG(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSniper(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicRocketLauncher(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicShotgun(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new Twa16GodWeapon(g.getFPSCore().getWeaponManager()));
this.editing.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + g.getName()+" completed!");
}
return true;
}
|
diff --git a/rwiki-tool/tool/src/java/uk/ac/cam/caret/sakai/rwiki/tool/service/impl/CommandServiceImpl.java b/rwiki-tool/tool/src/java/uk/ac/cam/caret/sakai/rwiki/tool/service/impl/CommandServiceImpl.java
index 4177627e..5534acb0 100644
--- a/rwiki-tool/tool/src/java/uk/ac/cam/caret/sakai/rwiki/tool/service/impl/CommandServiceImpl.java
+++ b/rwiki-tool/tool/src/java/uk/ac/cam/caret/sakai/rwiki/tool/service/impl/CommandServiceImpl.java
@@ -1,218 +1,218 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package uk.ac.cam.caret.sakai.rwiki.tool.service.impl;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import uk.ac.cam.caret.sakai.rwiki.service.exception.PermissionException;
import uk.ac.cam.caret.sakai.rwiki.service.api.RWikiObjectService;
import uk.ac.cam.caret.sakai.rwiki.tool.api.CommandService;
import uk.ac.cam.caret.sakai.rwiki.tool.api.HttpCommand;
import uk.ac.cam.caret.sakai.rwiki.tool.command.Dispatcher;
import uk.ac.cam.caret.sakai.rwiki.tool.RequestScopeSuperBean;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.event.api.NotificationService;
/**
* Implementation of RWikiCommandService, that is initialised with a map of
* commands and a default command
*
* @author andrew
*/
public class CommandServiceImpl implements CommandService
{
private static Log log = LogFactory.getLog(CommandServiceImpl.class);
private Map commandMap;
private String template = "/WEB-INF/command-pages/{0}.jsp";
private String permissionPath = "/WEB-INF/command-pages/permission.jsp";
private boolean trackReads = false;
private EventTrackingService eventTrackingService = null;
private class WrappedCommand implements HttpCommand
{
private HttpCommand command;
public WrappedCommand(HttpCommand command)
{
this.command = command;
}
public void execute(Dispatcher dispatcher, HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
try
{
command.execute(dispatcher,request, response);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
private class DefaultCommand implements HttpCommand
{
private String action;
public DefaultCommand(String action)
{
this.action = action;
log.debug("Created command " + action);
}
public void execute(Dispatcher dispatcher,HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
String actionPath = MessageFormat.format(template,
new Object[] { action });
try
{
dispatcher.dispatch(actionPath, request, response);
if ( trackReads && "view".equals(action) ) {
RequestScopeSuperBean rssb = RequestScopeSuperBean.getInstance();
String ref = rssb.getCurrentRWikiObjectReference();
eventTrackingService.post(eventTrackingService.newEvent(
- RWikiObjectService.EVENT_RESOURCE_READ, ref, true,
- NotificationService.PREF_IMMEDIATE));
+ RWikiObjectService.EVENT_RESOURCE_READ, ref, false,
+ NotificationService.NOTI_NONE));
}
}
catch (ServletException e)
{
if (e.getRootCause() instanceof PermissionException)
{
dispatcher.dispatch(permissionPath, request, response);
}
else
{
throw new RuntimeException(e);
}
}
catch (PermissionException e)
{
dispatcher.dispatch(permissionPath, request, response);
}
}
}
public void init()
{
trackReads = ServerConfigurationService.getBoolean("wiki.trackreads", false);
for (Iterator it = commandMap.keySet().iterator(); it.hasNext();)
{
String commandName = (String) it.next();
HttpCommand toWrap = (HttpCommand) commandMap.get(commandName);
commandMap.put(commandName, new WrappedCommand(toWrap));
}
}
/*
* (non-Javadoc)
*
* @see uk.ac.cam.caret.sakai.rwiki.service.api.RWikiCommandService#getCommand(java.lang.String)
*/
public HttpCommand getCommand(String commandName)
{
HttpCommand command = (HttpCommand) commandMap.get(commandName);
if (command == null)
{
return new DefaultCommand(commandName);
}
return command;
}
public Map getCommandMap()
{
return commandMap;
}
public void setCommandMap(Map commandMap)
{
this.commandMap = commandMap;
}
public String getDefaultActionPathTemplate()
{
return template;
}
public void setDefaultActionPathTemplate(String template)
{
this.template = template;
}
public String getPermissionPath()
{
return permissionPath;
}
public void setPermissionPath(String permissionPath)
{
this.permissionPath = permissionPath;
}
public boolean getTrackReads()
{
return trackReads;
}
public void setTrackReads(boolean trackReads)
{
this.trackReads = trackReads;
}
public EventTrackingService getEventTrackingService()
{
return eventTrackingService;
}
public void setEventTrackingService(EventTrackingService eventTrackingService)
{
this.eventTrackingService = eventTrackingService;
}
}
| true | true | public void execute(Dispatcher dispatcher,HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
String actionPath = MessageFormat.format(template,
new Object[] { action });
try
{
dispatcher.dispatch(actionPath, request, response);
if ( trackReads && "view".equals(action) ) {
RequestScopeSuperBean rssb = RequestScopeSuperBean.getInstance();
String ref = rssb.getCurrentRWikiObjectReference();
eventTrackingService.post(eventTrackingService.newEvent(
RWikiObjectService.EVENT_RESOURCE_READ, ref, true,
NotificationService.PREF_IMMEDIATE));
}
}
catch (ServletException e)
{
if (e.getRootCause() instanceof PermissionException)
{
dispatcher.dispatch(permissionPath, request, response);
}
else
{
throw new RuntimeException(e);
}
}
catch (PermissionException e)
{
dispatcher.dispatch(permissionPath, request, response);
}
}
| public void execute(Dispatcher dispatcher,HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
String actionPath = MessageFormat.format(template,
new Object[] { action });
try
{
dispatcher.dispatch(actionPath, request, response);
if ( trackReads && "view".equals(action) ) {
RequestScopeSuperBean rssb = RequestScopeSuperBean.getInstance();
String ref = rssb.getCurrentRWikiObjectReference();
eventTrackingService.post(eventTrackingService.newEvent(
RWikiObjectService.EVENT_RESOURCE_READ, ref, false,
NotificationService.NOTI_NONE));
}
}
catch (ServletException e)
{
if (e.getRootCause() instanceof PermissionException)
{
dispatcher.dispatch(permissionPath, request, response);
}
else
{
throw new RuntimeException(e);
}
}
catch (PermissionException e)
{
dispatcher.dispatch(permissionPath, request, response);
}
}
|
diff --git a/src/autosaveworld/commands/CommandsHandler.java b/src/autosaveworld/commands/CommandsHandler.java
index 3c4577e..e9e1d97 100644
--- a/src/autosaveworld/commands/CommandsHandler.java
+++ b/src/autosaveworld/commands/CommandsHandler.java
@@ -1,233 +1,233 @@
/**
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package autosaveworld.commands;
import java.io.File;
import java.text.DecimalFormat;
import java.util.Arrays;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import autosaveworld.config.AutoSaveConfig;
import autosaveworld.config.AutoSaveConfigMSG;
import autosaveworld.config.LocaleChanger;
import autosaveworld.core.AutoSaveWorld;
public class CommandsHandler implements CommandExecutor {
private AutoSaveWorld plugin = null;
private AutoSaveConfig config;
private AutoSaveConfigMSG configmsg;
private LocaleChanger localeChanger;
public CommandsHandler(AutoSaveWorld plugin, AutoSaveConfig config,
AutoSaveConfigMSG configmsg, LocaleChanger localeChanger) {
this.plugin = plugin;
this.config = config;
this.configmsg = configmsg;
this.localeChanger = localeChanger;
};
private PermissionCheck permCheck = new PermissionCheck();
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
String commandName = command.getName().toLowerCase();
//check permissions
if (!permCheck.isAllowed(sender, commandName, args, config.commandonlyfromconsole)) {
plugin.sendMessage(sender, configmsg.messageInsufficientPermissions);
return true;
}
// now handle commands
if (commandName.equalsIgnoreCase("autosave")) {
//"autosave" command handler
plugin.saveThread.startsave();
return true;
} else if (commandName.equalsIgnoreCase("autobackup")) {
//"autobackup" command handler
plugin.backupThread6.startbackup();
return true;
} else if (commandName.equalsIgnoreCase("autopurge")) {
//"autopurge" command handler
plugin.purgeThread.startpurge();
return true;
} else if (commandName.equalsIgnoreCase("autosaveworld")) {
//"autosaveworld" command handler
if (args.length == 1 && args[0].equalsIgnoreCase("help")) {
// help
plugin.sendMessage(sender, "&f/asw help&7 - &3Shows this help");
plugin.sendMessage(sender, "&f/asw pmanager load {pluginname}&7 - &3Loads plugin {pluginname}");
plugin.sendMessage(sender, "&f/asw pmanager unload {pluginname}&7 - &3Unloads plugin {pluginname}");
plugin.sendMessage(sender, "&f/asw pmanager reload {pluginname}&7 - &3Reloads(unloads and then loads) plugin {pluginname}");
plugin.sendMessage(sender, "&f/asw save&7 - &3Saves all worlds and players");
plugin.sendMessage(sender, "&f/save&7 - &3Same as /asw save");
plugin.sendMessage(sender, "&f/asw backup&7 - &3Backups worlds defined in config.yml (* - all worlds) and plugins (if enabled in config)");
plugin.sendMessage(sender, "&f/backup&7 - &3Same as /asw backup");
plugin.sendMessage(sender, "&f/asw purge&7 - &3Purges plugins info from inactive players");
plugin.sendMessage(sender, "&f/purge&7 - &3Same as /asw purge");
plugin.sendMessage(sender, "&f/asw restart&7 - &3Restarts server");
plugin.sendMessage(sender, "&f/asw regenworld {world}&7 - &3Regenerates world");
plugin.sendMessage(sender, "&f/asw reload&7 - &3Reload all configs)");
plugin.sendMessage(sender, "&f/asw reloadconfig&7 - &3Reload plugin config (config.yml)");
plugin.sendMessage(sender, "&f/asw reloadmsg&7 - &3Reload message config (configmsg.yml)");
plugin.sendMessage(sender, "&f/asw locale&7 - &3Show current messages locale");
plugin.sendMessage(sender, "&f/asw locale available&7 - &3Show available messages locales");
plugin.sendMessage(sender, "&f/asw locale load {locale}&7 - &3Set meesages locale to one of the available locales");
plugin.sendMessage(sender, "&f/asw info&7 - &3Shows some info");
plugin.sendMessage(sender, "&f/asw version&7 - &3Shows plugin version");
return true;
} else if (args.length >= 3 && args[0].equalsIgnoreCase("pmanager")) {
String[] nameArray = Arrays.copyOfRange(args, 2, args.length);
StringBuilder sb = new StringBuilder(50);
for (String namearg : nameArray)
{
sb.append(namearg);
sb.append(" ");
}
sb.deleteCharAt(sb.length()-1);
plugin.pmanager.handlePluginManagerCommand(sender, args[1], sb.toString());
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("forcegc")) {
plugin.sendMessage(sender, "&9Forcing GC");
System.gc();
System.gc();
plugin.sendMessage(sender, "&9GC probably finished");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("serverstatus")) {
DecimalFormat df = new DecimalFormat("0.00");
//processor (if available)
try {
com.sun.management.OperatingSystemMXBean systemBean = (com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean();
double cpuusage = systemBean.getProcessCpuLoad()*100;
if (cpuusage > 0) {
sender.sendMessage(ChatColor.GOLD+"Cpu usage: "+ChatColor.RED+df.format(cpuusage)+"%");
} else {
sender.sendMessage(ChatColor.GOLD+"Cpu usage: "+ChatColor.RED+"not available");
}
} catch (Exception e) {}
//memory
Runtime runtime = Runtime.getRuntime();
long maxmemmb = runtime.maxMemory()/1024/1024;
long freememmb = (runtime.maxMemory()-(runtime.totalMemory()-runtime.freeMemory()))/1024/1024;
sender.sendMessage(ChatColor.GOLD+"Memory usage: "+ChatColor.RED+df.format((maxmemmb-freememmb)*100/maxmemmb)+"% "+ChatColor.DARK_AQUA+"("+ChatColor.DARK_GREEN+(maxmemmb-freememmb)+"/"+maxmemmb+" MB"+ChatColor.DARK_AQUA+")"+ChatColor.RESET);
//hard drive
File file = new File(".");
long maxspacegb = file.getTotalSpace()/1024/1024/1024;
long freespacegb = file.getFreeSpace()/1024/1024/1024;
sender.sendMessage(ChatColor.GOLD+"Disk usage: "+ChatColor.RED+df.format((maxspacegb-freespacegb)*100/maxspacegb)+"% "+ChatColor.DARK_AQUA+"("+ChatColor.DARK_GREEN+(maxspacegb-freespacegb)+"/"+maxspacegb+" GB"+ChatColor.DARK_AQUA+")"+ChatColor.RESET);
return true;
- } else if (args.length == 1 && args[0].equalsIgnoreCase("save")) {
+ } else if (args.length == 1 && args[0].equalsIgnoreCase("save")) {
//save
plugin.saveThread.startsave();
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("backup")) {
//backup
plugin.backupThread6.startbackup();
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("purge")) {
//purge
plugin.purgeThread.startpurge();
return true;
} else if ((args.length == 1 && args[0].equalsIgnoreCase("restart"))) {
//restart
plugin.autorestartThread.startrestart(false);
return true;
} else if ((args.length == 2 && args[0].equalsIgnoreCase("regenworld"))) {
//regen world
if (Bukkit.getPluginManager().getPlugin("WorldEdit") == null) {
plugin.sendMessage(sender, "[AutoSaveWorld] You need WorldEdit installed to do that");
return true;
}
if (Bukkit.getWorld(args[1]) == null) {
plugin.sendMessage(sender, "[AutoSaveWorld] This world doesn't exist");
return true;
}
if (plugin.worldregenInProcess) {
plugin.sendMessage(sender, "[AutoSaveWorld] Please wait before previous world regeneration is finished");
return true;
}
plugin.worldregencopyThread.startworldregen(args[1]);
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
//reload
config.load();
configmsg.loadmsg();
plugin.sendMessage(sender, "[AutoSaveWorld] All configurations reloaded");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("reloadconfig")) {
//reload config
config.load();
plugin.sendMessage(sender,"[AutoSaveWorld] Main configuration reloaded");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("reloadmsg")) {
//reload messages
configmsg.loadmsg();
plugin.sendMessage(sender, "[AutoSaveWorld] Messages file reloaded");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("version")) {
//version
plugin.sendMessage(sender, plugin.getDescription().getName()+ " " + plugin.getDescription().getVersion());
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("info")) {
//info
plugin.sendMessage(sender,"&9======AutoSaveWorld Info & Status======");
if (config.saveEnabled) {
plugin.sendMessage(sender, "&2AutoSave is active");
plugin.sendMessage(sender, "&2Last save time: " + plugin.LastSave);
} else {
plugin.sendMessage(sender, "&2AutoSave is inactive");
}
if (config.backupEnabled) {
plugin.sendMessage(sender, "&2AutoBackup is active");
plugin.sendMessage(sender, "&2Last backup time: " + plugin.LastBackup);
} else {
plugin.sendMessage(sender, "&2AutoBackup is inactive");
}
plugin.sendMessage(sender,"&9====================================");
return true;
} else if ((args.length >= 1 && args[0].equalsIgnoreCase("locale"))) {
//locale loader
if (args.length == 2 && args[1].equalsIgnoreCase("available")) {
plugin.sendMessage(sender, "Available locales: "+ localeChanger.getAvailableLocales());
return true;
} else if (args.length == 2 && args[1].equalsIgnoreCase("load")) {
plugin.sendMessage(sender,"You should specify a locale to load (get available locales using /asw locale available command)");
return true;
} else if (args.length == 3 && args[1].equalsIgnoreCase("load")) {
if (localeChanger.getAvailableLocales().contains(args[2])) {
plugin.sendMessage(sender, "Loading locale " + args[2]);
localeChanger.loadLocale(args[2]);
plugin.sendMessage(sender, "Loaded locale " + args[2]);
return true;
} else {
plugin.sendMessage(sender, "Locale " + args[2] + " is not available");
return true;
}
}
}
return false;
}
return false;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
String commandName = command.getName().toLowerCase();
//check permissions
if (!permCheck.isAllowed(sender, commandName, args, config.commandonlyfromconsole)) {
plugin.sendMessage(sender, configmsg.messageInsufficientPermissions);
return true;
}
// now handle commands
if (commandName.equalsIgnoreCase("autosave")) {
//"autosave" command handler
plugin.saveThread.startsave();
return true;
} else if (commandName.equalsIgnoreCase("autobackup")) {
//"autobackup" command handler
plugin.backupThread6.startbackup();
return true;
} else if (commandName.equalsIgnoreCase("autopurge")) {
//"autopurge" command handler
plugin.purgeThread.startpurge();
return true;
} else if (commandName.equalsIgnoreCase("autosaveworld")) {
//"autosaveworld" command handler
if (args.length == 1 && args[0].equalsIgnoreCase("help")) {
// help
plugin.sendMessage(sender, "&f/asw help&7 - &3Shows this help");
plugin.sendMessage(sender, "&f/asw pmanager load {pluginname}&7 - &3Loads plugin {pluginname}");
plugin.sendMessage(sender, "&f/asw pmanager unload {pluginname}&7 - &3Unloads plugin {pluginname}");
plugin.sendMessage(sender, "&f/asw pmanager reload {pluginname}&7 - &3Reloads(unloads and then loads) plugin {pluginname}");
plugin.sendMessage(sender, "&f/asw save&7 - &3Saves all worlds and players");
plugin.sendMessage(sender, "&f/save&7 - &3Same as /asw save");
plugin.sendMessage(sender, "&f/asw backup&7 - &3Backups worlds defined in config.yml (* - all worlds) and plugins (if enabled in config)");
plugin.sendMessage(sender, "&f/backup&7 - &3Same as /asw backup");
plugin.sendMessage(sender, "&f/asw purge&7 - &3Purges plugins info from inactive players");
plugin.sendMessage(sender, "&f/purge&7 - &3Same as /asw purge");
plugin.sendMessage(sender, "&f/asw restart&7 - &3Restarts server");
plugin.sendMessage(sender, "&f/asw regenworld {world}&7 - &3Regenerates world");
plugin.sendMessage(sender, "&f/asw reload&7 - &3Reload all configs)");
plugin.sendMessage(sender, "&f/asw reloadconfig&7 - &3Reload plugin config (config.yml)");
plugin.sendMessage(sender, "&f/asw reloadmsg&7 - &3Reload message config (configmsg.yml)");
plugin.sendMessage(sender, "&f/asw locale&7 - &3Show current messages locale");
plugin.sendMessage(sender, "&f/asw locale available&7 - &3Show available messages locales");
plugin.sendMessage(sender, "&f/asw locale load {locale}&7 - &3Set meesages locale to one of the available locales");
plugin.sendMessage(sender, "&f/asw info&7 - &3Shows some info");
plugin.sendMessage(sender, "&f/asw version&7 - &3Shows plugin version");
return true;
} else if (args.length >= 3 && args[0].equalsIgnoreCase("pmanager")) {
String[] nameArray = Arrays.copyOfRange(args, 2, args.length);
StringBuilder sb = new StringBuilder(50);
for (String namearg : nameArray)
{
sb.append(namearg);
sb.append(" ");
}
sb.deleteCharAt(sb.length()-1);
plugin.pmanager.handlePluginManagerCommand(sender, args[1], sb.toString());
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("forcegc")) {
plugin.sendMessage(sender, "&9Forcing GC");
System.gc();
System.gc();
plugin.sendMessage(sender, "&9GC probably finished");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("serverstatus")) {
DecimalFormat df = new DecimalFormat("0.00");
//processor (if available)
try {
com.sun.management.OperatingSystemMXBean systemBean = (com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean();
double cpuusage = systemBean.getProcessCpuLoad()*100;
if (cpuusage > 0) {
sender.sendMessage(ChatColor.GOLD+"Cpu usage: "+ChatColor.RED+df.format(cpuusage)+"%");
} else {
sender.sendMessage(ChatColor.GOLD+"Cpu usage: "+ChatColor.RED+"not available");
}
} catch (Exception e) {}
//memory
Runtime runtime = Runtime.getRuntime();
long maxmemmb = runtime.maxMemory()/1024/1024;
long freememmb = (runtime.maxMemory()-(runtime.totalMemory()-runtime.freeMemory()))/1024/1024;
sender.sendMessage(ChatColor.GOLD+"Memory usage: "+ChatColor.RED+df.format((maxmemmb-freememmb)*100/maxmemmb)+"% "+ChatColor.DARK_AQUA+"("+ChatColor.DARK_GREEN+(maxmemmb-freememmb)+"/"+maxmemmb+" MB"+ChatColor.DARK_AQUA+")"+ChatColor.RESET);
//hard drive
File file = new File(".");
long maxspacegb = file.getTotalSpace()/1024/1024/1024;
long freespacegb = file.getFreeSpace()/1024/1024/1024;
sender.sendMessage(ChatColor.GOLD+"Disk usage: "+ChatColor.RED+df.format((maxspacegb-freespacegb)*100/maxspacegb)+"% "+ChatColor.DARK_AQUA+"("+ChatColor.DARK_GREEN+(maxspacegb-freespacegb)+"/"+maxspacegb+" GB"+ChatColor.DARK_AQUA+")"+ChatColor.RESET);
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("save")) {
//save
plugin.saveThread.startsave();
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("backup")) {
//backup
plugin.backupThread6.startbackup();
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("purge")) {
//purge
plugin.purgeThread.startpurge();
return true;
} else if ((args.length == 1 && args[0].equalsIgnoreCase("restart"))) {
//restart
plugin.autorestartThread.startrestart(false);
return true;
} else if ((args.length == 2 && args[0].equalsIgnoreCase("regenworld"))) {
//regen world
if (Bukkit.getPluginManager().getPlugin("WorldEdit") == null) {
plugin.sendMessage(sender, "[AutoSaveWorld] You need WorldEdit installed to do that");
return true;
}
if (Bukkit.getWorld(args[1]) == null) {
plugin.sendMessage(sender, "[AutoSaveWorld] This world doesn't exist");
return true;
}
if (plugin.worldregenInProcess) {
plugin.sendMessage(sender, "[AutoSaveWorld] Please wait before previous world regeneration is finished");
return true;
}
plugin.worldregencopyThread.startworldregen(args[1]);
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
//reload
config.load();
configmsg.loadmsg();
plugin.sendMessage(sender, "[AutoSaveWorld] All configurations reloaded");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("reloadconfig")) {
//reload config
config.load();
plugin.sendMessage(sender,"[AutoSaveWorld] Main configuration reloaded");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("reloadmsg")) {
//reload messages
configmsg.loadmsg();
plugin.sendMessage(sender, "[AutoSaveWorld] Messages file reloaded");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("version")) {
//version
plugin.sendMessage(sender, plugin.getDescription().getName()+ " " + plugin.getDescription().getVersion());
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("info")) {
//info
plugin.sendMessage(sender,"&9======AutoSaveWorld Info & Status======");
if (config.saveEnabled) {
plugin.sendMessage(sender, "&2AutoSave is active");
plugin.sendMessage(sender, "&2Last save time: " + plugin.LastSave);
} else {
plugin.sendMessage(sender, "&2AutoSave is inactive");
}
if (config.backupEnabled) {
plugin.sendMessage(sender, "&2AutoBackup is active");
plugin.sendMessage(sender, "&2Last backup time: " + plugin.LastBackup);
} else {
plugin.sendMessage(sender, "&2AutoBackup is inactive");
}
plugin.sendMessage(sender,"&9====================================");
return true;
} else if ((args.length >= 1 && args[0].equalsIgnoreCase("locale"))) {
//locale loader
if (args.length == 2 && args[1].equalsIgnoreCase("available")) {
plugin.sendMessage(sender, "Available locales: "+ localeChanger.getAvailableLocales());
return true;
} else if (args.length == 2 && args[1].equalsIgnoreCase("load")) {
plugin.sendMessage(sender,"You should specify a locale to load (get available locales using /asw locale available command)");
return true;
} else if (args.length == 3 && args[1].equalsIgnoreCase("load")) {
if (localeChanger.getAvailableLocales().contains(args[2])) {
plugin.sendMessage(sender, "Loading locale " + args[2]);
localeChanger.loadLocale(args[2]);
plugin.sendMessage(sender, "Loaded locale " + args[2]);
return true;
} else {
plugin.sendMessage(sender, "Locale " + args[2] + " is not available");
return true;
}
}
}
return false;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
String commandName = command.getName().toLowerCase();
//check permissions
if (!permCheck.isAllowed(sender, commandName, args, config.commandonlyfromconsole)) {
plugin.sendMessage(sender, configmsg.messageInsufficientPermissions);
return true;
}
// now handle commands
if (commandName.equalsIgnoreCase("autosave")) {
//"autosave" command handler
plugin.saveThread.startsave();
return true;
} else if (commandName.equalsIgnoreCase("autobackup")) {
//"autobackup" command handler
plugin.backupThread6.startbackup();
return true;
} else if (commandName.equalsIgnoreCase("autopurge")) {
//"autopurge" command handler
plugin.purgeThread.startpurge();
return true;
} else if (commandName.equalsIgnoreCase("autosaveworld")) {
//"autosaveworld" command handler
if (args.length == 1 && args[0].equalsIgnoreCase("help")) {
// help
plugin.sendMessage(sender, "&f/asw help&7 - &3Shows this help");
plugin.sendMessage(sender, "&f/asw pmanager load {pluginname}&7 - &3Loads plugin {pluginname}");
plugin.sendMessage(sender, "&f/asw pmanager unload {pluginname}&7 - &3Unloads plugin {pluginname}");
plugin.sendMessage(sender, "&f/asw pmanager reload {pluginname}&7 - &3Reloads(unloads and then loads) plugin {pluginname}");
plugin.sendMessage(sender, "&f/asw save&7 - &3Saves all worlds and players");
plugin.sendMessage(sender, "&f/save&7 - &3Same as /asw save");
plugin.sendMessage(sender, "&f/asw backup&7 - &3Backups worlds defined in config.yml (* - all worlds) and plugins (if enabled in config)");
plugin.sendMessage(sender, "&f/backup&7 - &3Same as /asw backup");
plugin.sendMessage(sender, "&f/asw purge&7 - &3Purges plugins info from inactive players");
plugin.sendMessage(sender, "&f/purge&7 - &3Same as /asw purge");
plugin.sendMessage(sender, "&f/asw restart&7 - &3Restarts server");
plugin.sendMessage(sender, "&f/asw regenworld {world}&7 - &3Regenerates world");
plugin.sendMessage(sender, "&f/asw reload&7 - &3Reload all configs)");
plugin.sendMessage(sender, "&f/asw reloadconfig&7 - &3Reload plugin config (config.yml)");
plugin.sendMessage(sender, "&f/asw reloadmsg&7 - &3Reload message config (configmsg.yml)");
plugin.sendMessage(sender, "&f/asw locale&7 - &3Show current messages locale");
plugin.sendMessage(sender, "&f/asw locale available&7 - &3Show available messages locales");
plugin.sendMessage(sender, "&f/asw locale load {locale}&7 - &3Set meesages locale to one of the available locales");
plugin.sendMessage(sender, "&f/asw info&7 - &3Shows some info");
plugin.sendMessage(sender, "&f/asw version&7 - &3Shows plugin version");
return true;
} else if (args.length >= 3 && args[0].equalsIgnoreCase("pmanager")) {
String[] nameArray = Arrays.copyOfRange(args, 2, args.length);
StringBuilder sb = new StringBuilder(50);
for (String namearg : nameArray)
{
sb.append(namearg);
sb.append(" ");
}
sb.deleteCharAt(sb.length()-1);
plugin.pmanager.handlePluginManagerCommand(sender, args[1], sb.toString());
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("forcegc")) {
plugin.sendMessage(sender, "&9Forcing GC");
System.gc();
System.gc();
plugin.sendMessage(sender, "&9GC probably finished");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("serverstatus")) {
DecimalFormat df = new DecimalFormat("0.00");
//processor (if available)
try {
com.sun.management.OperatingSystemMXBean systemBean = (com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean();
double cpuusage = systemBean.getProcessCpuLoad()*100;
if (cpuusage > 0) {
sender.sendMessage(ChatColor.GOLD+"Cpu usage: "+ChatColor.RED+df.format(cpuusage)+"%");
} else {
sender.sendMessage(ChatColor.GOLD+"Cpu usage: "+ChatColor.RED+"not available");
}
} catch (Exception e) {}
//memory
Runtime runtime = Runtime.getRuntime();
long maxmemmb = runtime.maxMemory()/1024/1024;
long freememmb = (runtime.maxMemory()-(runtime.totalMemory()-runtime.freeMemory()))/1024/1024;
sender.sendMessage(ChatColor.GOLD+"Memory usage: "+ChatColor.RED+df.format((maxmemmb-freememmb)*100/maxmemmb)+"% "+ChatColor.DARK_AQUA+"("+ChatColor.DARK_GREEN+(maxmemmb-freememmb)+"/"+maxmemmb+" MB"+ChatColor.DARK_AQUA+")"+ChatColor.RESET);
//hard drive
File file = new File(".");
long maxspacegb = file.getTotalSpace()/1024/1024/1024;
long freespacegb = file.getFreeSpace()/1024/1024/1024;
sender.sendMessage(ChatColor.GOLD+"Disk usage: "+ChatColor.RED+df.format((maxspacegb-freespacegb)*100/maxspacegb)+"% "+ChatColor.DARK_AQUA+"("+ChatColor.DARK_GREEN+(maxspacegb-freespacegb)+"/"+maxspacegb+" GB"+ChatColor.DARK_AQUA+")"+ChatColor.RESET);
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("save")) {
//save
plugin.saveThread.startsave();
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("backup")) {
//backup
plugin.backupThread6.startbackup();
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("purge")) {
//purge
plugin.purgeThread.startpurge();
return true;
} else if ((args.length == 1 && args[0].equalsIgnoreCase("restart"))) {
//restart
plugin.autorestartThread.startrestart(false);
return true;
} else if ((args.length == 2 && args[0].equalsIgnoreCase("regenworld"))) {
//regen world
if (Bukkit.getPluginManager().getPlugin("WorldEdit") == null) {
plugin.sendMessage(sender, "[AutoSaveWorld] You need WorldEdit installed to do that");
return true;
}
if (Bukkit.getWorld(args[1]) == null) {
plugin.sendMessage(sender, "[AutoSaveWorld] This world doesn't exist");
return true;
}
if (plugin.worldregenInProcess) {
plugin.sendMessage(sender, "[AutoSaveWorld] Please wait before previous world regeneration is finished");
return true;
}
plugin.worldregencopyThread.startworldregen(args[1]);
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
//reload
config.load();
configmsg.loadmsg();
plugin.sendMessage(sender, "[AutoSaveWorld] All configurations reloaded");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("reloadconfig")) {
//reload config
config.load();
plugin.sendMessage(sender,"[AutoSaveWorld] Main configuration reloaded");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("reloadmsg")) {
//reload messages
configmsg.loadmsg();
plugin.sendMessage(sender, "[AutoSaveWorld] Messages file reloaded");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("version")) {
//version
plugin.sendMessage(sender, plugin.getDescription().getName()+ " " + plugin.getDescription().getVersion());
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("info")) {
//info
plugin.sendMessage(sender,"&9======AutoSaveWorld Info & Status======");
if (config.saveEnabled) {
plugin.sendMessage(sender, "&2AutoSave is active");
plugin.sendMessage(sender, "&2Last save time: " + plugin.LastSave);
} else {
plugin.sendMessage(sender, "&2AutoSave is inactive");
}
if (config.backupEnabled) {
plugin.sendMessage(sender, "&2AutoBackup is active");
plugin.sendMessage(sender, "&2Last backup time: " + plugin.LastBackup);
} else {
plugin.sendMessage(sender, "&2AutoBackup is inactive");
}
plugin.sendMessage(sender,"&9====================================");
return true;
} else if ((args.length >= 1 && args[0].equalsIgnoreCase("locale"))) {
//locale loader
if (args.length == 2 && args[1].equalsIgnoreCase("available")) {
plugin.sendMessage(sender, "Available locales: "+ localeChanger.getAvailableLocales());
return true;
} else if (args.length == 2 && args[1].equalsIgnoreCase("load")) {
plugin.sendMessage(sender,"You should specify a locale to load (get available locales using /asw locale available command)");
return true;
} else if (args.length == 3 && args[1].equalsIgnoreCase("load")) {
if (localeChanger.getAvailableLocales().contains(args[2])) {
plugin.sendMessage(sender, "Loading locale " + args[2]);
localeChanger.loadLocale(args[2]);
plugin.sendMessage(sender, "Loaded locale " + args[2]);
return true;
} else {
plugin.sendMessage(sender, "Locale " + args[2] + " is not available");
return true;
}
}
}
return false;
}
return false;
}
|
diff --git a/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/util/rasterize/GDALRasterize.java b/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/util/rasterize/GDALRasterize.java
index a78f300..0f321d5 100644
--- a/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/util/rasterize/GDALRasterize.java
+++ b/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/util/rasterize/GDALRasterize.java
@@ -1,249 +1,250 @@
/*
* GeoBatch - Open Source geospatial batch processing system
* https://github.com/nfms4redd/nfms-geobatch
* Copyright (C) 2007-2008-2009 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* GPLv3 + Classpath exception
*
* 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 it.geosolutions.geobatch.unredd.script.util.rasterize;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import it.geosolutions.geobatch.task.TaskExecutor;
import it.geosolutions.geobatch.task.TaskExecutorConfiguration;
//FreeMarker
import it.geosolutions.geobatch.actions.freemarker.*;
import it.geosolutions.geobatch.flow.event.action.ActionException;
import it.geosolutions.geobatch.unredd.script.model.PostGisConfig;
import it.geosolutions.geobatch.unredd.script.model.RasterizeConfig;
import it.geosolutions.geobatch.unredd.script.util.PostGISUtils;
import it.geosolutions.geobatch.unredd.script.util.SingleFileActionExecutor;
import it.geosolutions.unredd.geostore.model.UNREDDLayer;
import it.geosolutions.unredd.geostore.model.UNREDDLayerUpdate;
import it.geosolutions.unredd.geostore.model.UNREDDLayerUpdate.Attributes;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GDALRasterize {
private static final Logger LOGGER = LoggerFactory.getLogger(GDALRasterize.class);
private RasterizeConfig rasterizeConfig;
private File configDir;
private File tempDir;
public GDALRasterize(
RasterizeConfig config,
File configDir, File tempDir) {
super();
this.rasterizeConfig = config;
this.configDir = configDir;
this.tempDir = tempDir;
}
private File freemarker(Map<String, Object> fmRoot) throws ActionException, IllegalAccessException, IOException {
// FREEMARKER -> GDALRASTERIZE
// ----------------------- FreeMarker ----------------
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("-------------------- FreeMarker - rasterize ----------------");
}
// relative to the working dir
FreeMarkerConfiguration fmc = new FreeMarkerConfiguration("unredd_freemarker", "unredd_freemarker", "unredd_freemarker");
fmc.setConfigDir(configDir);
fmc.setRoot(fmRoot);
// relative to the working dir
fmc.setInput(rasterizeConfig.getFreeMarkerTemplate());
fmc.setOutput(tempDir.getAbsolutePath());
// SIMULATE THE EventObject on the queue
final File file = File.createTempFile("fm_", ".xml", tempDir);
FreeMarkerAction fma = new FreeMarkerAction(fmc);
fma.setTempDir(tempDir);
File outFile = SingleFileActionExecutor.execute(fma, file);
if(outFile == null)
throw new ActionException(fma, "No output events from freemarker Action");
return outFile;
}
private File taskExecutor(File inputFile, File errorFile) throws IOException, ActionException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("--------------------- TaskExecutor - rasterization ----------------");
}
final TaskExecutorConfiguration teConfig = new TaskExecutorConfiguration("gdal_rasterize_id", "UNREDD_rasterize", "gdal_rasterize");
// final EventObject ev;
// ev = (EventObject) queue.peek();
// String filename = ev.getSource().toString();
if(LOGGER.isDebugEnabled())
LOGGER.debug("Input file: " + inputFile);
teConfig.setDefaultScript(inputFile.getAbsolutePath());
teConfig.setErrorFile(errorFile.getAbsolutePath());
teConfig.setExecutable(rasterizeConfig.getExecutable());
if(LOGGER.isDebugEnabled())
LOGGER.debug("gdal_rasterize executable file: " + rasterizeConfig.getExecutable());
teConfig.setFailIgnored(false);
// teConfig.setOutput(getOutput());
// teConfig.setOutputName(getOutputName());
// teConfig.setServiceID(getServiceID());
teConfig.setTimeOut(120000l);
// teConfig.setVariables(getVariables());
teConfig.setConfigDir(configDir);
teConfig.setXsl(rasterizeConfig.getTaskExecutorXslFileName());
TaskExecutor tea = new TaskExecutor(teConfig);
// tea.setRunningContext(tempDir.getAbsolutePath());
tea.setTempDir(tempDir);
+ tea.setConfigDir(configDir);
File outFile = SingleFileActionExecutor.execute(tea, inputFile);
// taskexec just returns the input file
if ( errorFile.length() != 0) {
// error file is NOT empty
throw new ActionException(tea, "Error in gdal_rasterize; check the error file " + errorFile.getAbsolutePath() + " for more information");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Rasterization successfully performed");
}
return outFile;
}
public File run(UNREDDLayer layer, UNREDDLayerUpdate layerUpdate, PostGisConfig pgConfig) throws ActionException, IllegalAccessException, IOException {
LOGGER.info("Rasterizing from postgis");
// params to inject into the ROOT datadir for FreeMarker
final Map<String, Object> fmRoot = buildFreemarkerMap(layer, layerUpdate);
// create the where option
String year = layerUpdate.getAttribute(Attributes.YEAR);
String month = layerUpdate.getAttribute(Attributes.MONTH);
String where = PostGISUtils.YEARATTRIBUTENAME+"="+year;
if (month!=null)
where += " and " + PostGISUtils.MONTHATTRIBUTENAME+"="+month;
fmRoot.put("WHERE", where);
fmRoot.put("LAYERNAME", pgConfig.getSchema() + "." + layerUpdate.getAttribute(Attributes.LAYER));
fmRoot.put("SRC", pgConfig.buildOGRString());
// run it
return run(fmRoot);
}
/**
* Rasterize a shapefile.
* Main rasterization params are read from the UNREDDLayer attribs.
*
* @return the raster file
*
*/
public File run(UNREDDLayer layer, UNREDDLayerUpdate layerUpdate, File shapefile) throws ActionException, IllegalAccessException, IOException {
LOGGER.info("Rasterizing from shapefile");
// params to inject into the ROOT datadir for FreeMarker
final Map<String, Object> fmRoot = buildFreemarkerMap(layer, layerUpdate);
// create the where option
// String year = layerUpdate.getAttribute(Attributes.YEAR);
// String month = layerUpdate.getAttribute(Attributes.MONTH);
//
// String where = PostGISUtils.YEARATTRIBUTENAME+"="+year;
// if (month!=null)
// where += " and " + PostGISUtils.MONTHATTRIBUTENAME+"="+month;
// fmRoot.put("WHERE", where);
fmRoot.put("LAYERNAME", FilenameUtils.getBaseName(shapefile.getAbsolutePath()));
fmRoot.put("SRC", shapefile.getAbsolutePath());
// run it
return run(fmRoot);
}
protected File run(Map<String, Object> fmRoot) throws ActionException, IllegalAccessException, IOException {
File tifFile = File.createTempFile("rst_out_", ".tif", tempDir);
fmRoot.put("OUTPUTFILENAME", tifFile.getAbsolutePath());
LOGGER.info("Creating command line for gdal_rasterize");
File freemarked = freemarker(fmRoot);
File errorFile = File.createTempFile("rst_err_", ".xml", tempDir);
LOGGER.info("Performing rasterization into " + tifFile);
taskExecutor(freemarked, errorFile);
LOGGER.info("Rasterization completed into " + tifFile.getName());
return tifFile;
}
protected Map<String, Object> buildFreemarkerMap(UNREDDLayer layer, UNREDDLayerUpdate layerUpdate)
{
Map<String, Object> ret = new HashMap<String, Object>();
ret.put("LAYERNAME", layerUpdate.getAttribute(Attributes.LAYER));
// ret.put("SRC", options.getSrc());
// ret.put("LAYERNAME", options.getLayer());
ret.put("ATTRIBUTENAME", layer.getAttribute(UNREDDLayer.Attributes.RASTERATTRIBNAME));
// ret.put("OUTPUTFILENAME", outputFile.getAbsolutePath());
ret.put("WIDTH", layer.getAttribute(UNREDDLayer.Attributes.RASTERPIXELWIDTH));
ret.put("HEIGHT", layer.getAttribute(UNREDDLayer.Attributes.RASTERPIXELHEIGHT));
ret.put("RX0", layer.getAttribute(UNREDDLayer.Attributes.RASTERX0));
ret.put("RX1", layer.getAttribute(UNREDDLayer.Attributes.RASTERX1));
ret.put("RY0", layer.getAttribute(UNREDDLayer.Attributes.RASTERY0));
ret.put("RY1", layer.getAttribute(UNREDDLayer.Attributes.RASTERY1));
ret.put("NODATA", layer.getAttribute(UNREDDLayer.Attributes.RASTERNODATA));
ret.put("OF", "GTiff");
ret.put("TILED", "TILED=YES");
ret.put("TILEH", "BLOCKYSIZE="+256); // TODO
ret.put("TILEW", "BLOCKXSIZE="+256); // TODO
ret.put("ASRS", "EPSG:4326"); // TODO
// ret.put("WHERE", options.getWhere());
String dataType = layer.getAttribute(UNREDDLayer.Attributes.RASTERDATATYPE);
if(dataType == null) {
dataType = "Int16";
LOGGER.warn("Datatype not specified for layer " + layer + ". Default " + dataType + " will be used.");
}
ret.put("OT", dataType);
return ret;
}
}
| true | true | private File taskExecutor(File inputFile, File errorFile) throws IOException, ActionException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("--------------------- TaskExecutor - rasterization ----------------");
}
final TaskExecutorConfiguration teConfig = new TaskExecutorConfiguration("gdal_rasterize_id", "UNREDD_rasterize", "gdal_rasterize");
// final EventObject ev;
// ev = (EventObject) queue.peek();
// String filename = ev.getSource().toString();
if(LOGGER.isDebugEnabled())
LOGGER.debug("Input file: " + inputFile);
teConfig.setDefaultScript(inputFile.getAbsolutePath());
teConfig.setErrorFile(errorFile.getAbsolutePath());
teConfig.setExecutable(rasterizeConfig.getExecutable());
if(LOGGER.isDebugEnabled())
LOGGER.debug("gdal_rasterize executable file: " + rasterizeConfig.getExecutable());
teConfig.setFailIgnored(false);
// teConfig.setOutput(getOutput());
// teConfig.setOutputName(getOutputName());
// teConfig.setServiceID(getServiceID());
teConfig.setTimeOut(120000l);
// teConfig.setVariables(getVariables());
teConfig.setConfigDir(configDir);
teConfig.setXsl(rasterizeConfig.getTaskExecutorXslFileName());
TaskExecutor tea = new TaskExecutor(teConfig);
// tea.setRunningContext(tempDir.getAbsolutePath());
tea.setTempDir(tempDir);
File outFile = SingleFileActionExecutor.execute(tea, inputFile);
// taskexec just returns the input file
if ( errorFile.length() != 0) {
// error file is NOT empty
throw new ActionException(tea, "Error in gdal_rasterize; check the error file " + errorFile.getAbsolutePath() + " for more information");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Rasterization successfully performed");
}
return outFile;
}
| private File taskExecutor(File inputFile, File errorFile) throws IOException, ActionException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("--------------------- TaskExecutor - rasterization ----------------");
}
final TaskExecutorConfiguration teConfig = new TaskExecutorConfiguration("gdal_rasterize_id", "UNREDD_rasterize", "gdal_rasterize");
// final EventObject ev;
// ev = (EventObject) queue.peek();
// String filename = ev.getSource().toString();
if(LOGGER.isDebugEnabled())
LOGGER.debug("Input file: " + inputFile);
teConfig.setDefaultScript(inputFile.getAbsolutePath());
teConfig.setErrorFile(errorFile.getAbsolutePath());
teConfig.setExecutable(rasterizeConfig.getExecutable());
if(LOGGER.isDebugEnabled())
LOGGER.debug("gdal_rasterize executable file: " + rasterizeConfig.getExecutable());
teConfig.setFailIgnored(false);
// teConfig.setOutput(getOutput());
// teConfig.setOutputName(getOutputName());
// teConfig.setServiceID(getServiceID());
teConfig.setTimeOut(120000l);
// teConfig.setVariables(getVariables());
teConfig.setConfigDir(configDir);
teConfig.setXsl(rasterizeConfig.getTaskExecutorXslFileName());
TaskExecutor tea = new TaskExecutor(teConfig);
// tea.setRunningContext(tempDir.getAbsolutePath());
tea.setTempDir(tempDir);
tea.setConfigDir(configDir);
File outFile = SingleFileActionExecutor.execute(tea, inputFile);
// taskexec just returns the input file
if ( errorFile.length() != 0) {
// error file is NOT empty
throw new ActionException(tea, "Error in gdal_rasterize; check the error file " + errorFile.getAbsolutePath() + " for more information");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Rasterization successfully performed");
}
return outFile;
}
|
diff --git a/anglewyrm/src/ColoniesMain.java b/anglewyrm/src/ColoniesMain.java
index 6c7422c..2415604 100644
--- a/anglewyrm/src/ColoniesMain.java
+++ b/anglewyrm/src/ColoniesMain.java
@@ -1,124 +1,125 @@
package colonies.anglewyrm.src;
import java.util.ArrayList;
import java.util.List;
import colonies.vector67.src.BlockColoniesChest;
import colonies.vector67.src.TileEntityColoniesChest;
import net.minecraft.src.BiomeGenBase;
import net.minecraft.src.Block;
import net.minecraft.src.BlockContainer;
import net.minecraft.src.CreativeTabs;
import net.minecraft.src.EnumCreatureType;
import net.minecraft.src.Item;
import net.minecraft.src.ItemStack;
import net.minecraft.src.Material;
import net.minecraft.src.ModLoader;
import net.minecraft.src.SoundManager;
import net.minecraftforge.common.MinecraftForge;
import colonies.lohikaarme.src.ItemMeasuringTape;
import colonies.vector67.src.BlockColoniesChest;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PostInit;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
@Mod(modid = "Colonies", name = "Colonies", version = "7 Dec 2012")
@NetworkMod(
channels = { "Colonies" },
clientSideRequired = true,
serverSideRequired = false,
packetHandler = PacketHandler.class )
public class ColoniesMain
{
public static Block test;
public static Item MeasuringTape;
public static Block chestBlock;
public static Block townHall;
public static List<TownHall> townsList;
@Instance
public static ColoniesMain instance;
@SidedProxy(clientSide = "colonies.anglewyrm.src.ClientProxy", serverSide = "colonies.anglewyrm.src.ServerProxy")
public static ServerProxy proxy;
@PreInit
public void preInit(FMLPreInitializationEvent event)
{
System.out.println("Initializing Colonies");
ConfigFile.load();
MinecraftForge.EVENT_BUS.register(new ColoniesSoundManager());
}
@Init
public void init(FMLInitializationEvent evt)
{
registerColoniesStuff(); // at bottom of this file for legibility
}
@PostInit
public void postInit(FMLPostInitializationEvent evt)
{
// TODO: Add Post-Initialization code such as mod hooks
}
public String Version(){
return "Pre-Alpha, Revision 3";
}
// Register Colonies stuff with Minecraft Forge
private void registerColoniesStuff()
{
// List of towns
// TODO: find a way to save/load this data structure
townsList = new ArrayList<TownHall>();
// Chest block
chestBlock = new BlockColoniesChest(ConfigFile.parseInt("DefaultChestID"));
LanguageRegistry.addName(chestBlock, "Colonies Chest");
GameRegistry.registerBlock(chestBlock);
GameRegistry.registerTileEntity(TileEntityColoniesChest.class, "Colonies Chest TileEntity");
LanguageRegistry.instance().addStringLocalization("Colonies Chest TileEntity" + ".name", "en_US", "Colonies Chest TileEntity");
proxy.registerTileEntitySpecialRenderer(TileEntityColoniesChest.class);
// Town Hall
townHall = new TownHall(ConfigFile.parseInt("TownHallID"),townsList);
LanguageRegistry.addName(townHall, "Town Hall");
GameRegistry.registerBlock(townHall);
// Measuring tape
MeasuringTape = new ItemMeasuringTape(ConfigFile.parseInt("MeasuringTape")).setItemName("Measuring Tape");
LanguageRegistry.addName(MeasuringTape,"Measuring Tape");
GameRegistry.addRecipe(new ItemStack(MeasuringTape),"II",Character.valueOf('I'),Item.ingotIron);
// Test block
test = (TestBlock) new TestBlock(ConfigFile.parseInt("TestBlockID"), 3, Material.ground)
.setBlockName("test").setHardness(0.75f).setCreativeTab(CreativeTabs.tabBlock);
MinecraftForge.setBlockHarvestLevel(test, "shovel", 0);
LanguageRegistry.addName(test, "Test Block");
GameRegistry.registerBlock(test);
// Citizens
EntityRegistry.registerGlobalEntityID(EntityCitizen.class, "Citizen", ModLoader.getUniqueEntityId(), 0xCCCCFF, 0xFF4444);
EntityRegistry.addSpawn(EntityCitizen.class, 10, 2, 4, EnumCreatureType.monster,
BiomeGenBase.beach, BiomeGenBase.extremeHills,BiomeGenBase.extremeHillsEdge, BiomeGenBase.forest,
BiomeGenBase.forestHills, BiomeGenBase.jungle, BiomeGenBase.jungleHills, BiomeGenBase.mushroomIsland,
BiomeGenBase.mushroomIslandShore, BiomeGenBase.ocean, BiomeGenBase.plains, BiomeGenBase.river, BiomeGenBase.swampland);
+ LanguageRegistry.instance().addStringLocalization("entity.Citizen.name", "en_US", "Default Citizen");
proxy.registerRenderInformation();
}
}
| true | true | private void registerColoniesStuff()
{
// List of towns
// TODO: find a way to save/load this data structure
townsList = new ArrayList<TownHall>();
// Chest block
chestBlock = new BlockColoniesChest(ConfigFile.parseInt("DefaultChestID"));
LanguageRegistry.addName(chestBlock, "Colonies Chest");
GameRegistry.registerBlock(chestBlock);
GameRegistry.registerTileEntity(TileEntityColoniesChest.class, "Colonies Chest TileEntity");
LanguageRegistry.instance().addStringLocalization("Colonies Chest TileEntity" + ".name", "en_US", "Colonies Chest TileEntity");
proxy.registerTileEntitySpecialRenderer(TileEntityColoniesChest.class);
// Town Hall
townHall = new TownHall(ConfigFile.parseInt("TownHallID"),townsList);
LanguageRegistry.addName(townHall, "Town Hall");
GameRegistry.registerBlock(townHall);
// Measuring tape
MeasuringTape = new ItemMeasuringTape(ConfigFile.parseInt("MeasuringTape")).setItemName("Measuring Tape");
LanguageRegistry.addName(MeasuringTape,"Measuring Tape");
GameRegistry.addRecipe(new ItemStack(MeasuringTape),"II",Character.valueOf('I'),Item.ingotIron);
// Test block
test = (TestBlock) new TestBlock(ConfigFile.parseInt("TestBlockID"), 3, Material.ground)
.setBlockName("test").setHardness(0.75f).setCreativeTab(CreativeTabs.tabBlock);
MinecraftForge.setBlockHarvestLevel(test, "shovel", 0);
LanguageRegistry.addName(test, "Test Block");
GameRegistry.registerBlock(test);
// Citizens
EntityRegistry.registerGlobalEntityID(EntityCitizen.class, "Citizen", ModLoader.getUniqueEntityId(), 0xCCCCFF, 0xFF4444);
EntityRegistry.addSpawn(EntityCitizen.class, 10, 2, 4, EnumCreatureType.monster,
BiomeGenBase.beach, BiomeGenBase.extremeHills,BiomeGenBase.extremeHillsEdge, BiomeGenBase.forest,
BiomeGenBase.forestHills, BiomeGenBase.jungle, BiomeGenBase.jungleHills, BiomeGenBase.mushroomIsland,
BiomeGenBase.mushroomIslandShore, BiomeGenBase.ocean, BiomeGenBase.plains, BiomeGenBase.river, BiomeGenBase.swampland);
proxy.registerRenderInformation();
}
| private void registerColoniesStuff()
{
// List of towns
// TODO: find a way to save/load this data structure
townsList = new ArrayList<TownHall>();
// Chest block
chestBlock = new BlockColoniesChest(ConfigFile.parseInt("DefaultChestID"));
LanguageRegistry.addName(chestBlock, "Colonies Chest");
GameRegistry.registerBlock(chestBlock);
GameRegistry.registerTileEntity(TileEntityColoniesChest.class, "Colonies Chest TileEntity");
LanguageRegistry.instance().addStringLocalization("Colonies Chest TileEntity" + ".name", "en_US", "Colonies Chest TileEntity");
proxy.registerTileEntitySpecialRenderer(TileEntityColoniesChest.class);
// Town Hall
townHall = new TownHall(ConfigFile.parseInt("TownHallID"),townsList);
LanguageRegistry.addName(townHall, "Town Hall");
GameRegistry.registerBlock(townHall);
// Measuring tape
MeasuringTape = new ItemMeasuringTape(ConfigFile.parseInt("MeasuringTape")).setItemName("Measuring Tape");
LanguageRegistry.addName(MeasuringTape,"Measuring Tape");
GameRegistry.addRecipe(new ItemStack(MeasuringTape),"II",Character.valueOf('I'),Item.ingotIron);
// Test block
test = (TestBlock) new TestBlock(ConfigFile.parseInt("TestBlockID"), 3, Material.ground)
.setBlockName("test").setHardness(0.75f).setCreativeTab(CreativeTabs.tabBlock);
MinecraftForge.setBlockHarvestLevel(test, "shovel", 0);
LanguageRegistry.addName(test, "Test Block");
GameRegistry.registerBlock(test);
// Citizens
EntityRegistry.registerGlobalEntityID(EntityCitizen.class, "Citizen", ModLoader.getUniqueEntityId(), 0xCCCCFF, 0xFF4444);
EntityRegistry.addSpawn(EntityCitizen.class, 10, 2, 4, EnumCreatureType.monster,
BiomeGenBase.beach, BiomeGenBase.extremeHills,BiomeGenBase.extremeHillsEdge, BiomeGenBase.forest,
BiomeGenBase.forestHills, BiomeGenBase.jungle, BiomeGenBase.jungleHills, BiomeGenBase.mushroomIsland,
BiomeGenBase.mushroomIslandShore, BiomeGenBase.ocean, BiomeGenBase.plains, BiomeGenBase.river, BiomeGenBase.swampland);
LanguageRegistry.instance().addStringLocalization("entity.Citizen.name", "en_US", "Default Citizen");
proxy.registerRenderInformation();
}
|
diff --git a/src/com/diycomputerscience/minesweepercore/RandomBoardInitializer.java b/src/com/diycomputerscience/minesweepercore/RandomBoardInitializer.java
index c0935d1..ad4cf36 100644
--- a/src/com/diycomputerscience/minesweepercore/RandomBoardInitializer.java
+++ b/src/com/diycomputerscience/minesweepercore/RandomBoardInitializer.java
@@ -1,44 +1,44 @@
package com.diycomputerscience.minesweepercore;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandomBoardInitializer implements Initializer {
private Random mineCountRand = new Random();
private Random specificMineRand = new Random();
@Override
public Point[] mines() {
List<Point> points = new ArrayList<Point>();
for(int row=0; row<Board.MAX_ROWS; row++) {
int minesssCount = mineCountRand.nextInt(Board.MAX_COLS/2);
points.addAll(getRandonMinesForRow(row, minesssCount));
}
Point pointsArr[] = new Point[points.size()];
return points.toArray(pointsArr);
}
private int getMineCountForThisRow() {
return specificMineRand.nextInt(Board.MAX_COLS-1);
}
private List<Point> getRandonMinesForRow(int row, int mines) {
List<Point> points = new ArrayList<Point>();
- for(int j=0; j<mines; j++) {
- int col = getMineCountForThisRow();
+ for(int j=0; j<mines; j++) {
boolean addedMine = false;
while(!addedMine) {
+ int col = getMineCountForThisRow();
Point mine = new Point(row, col);
if(!points.contains(mine)) {
points.add(mine);
addedMine = true;
}
}
}
return points;
}
}
| false | true | private List<Point> getRandonMinesForRow(int row, int mines) {
List<Point> points = new ArrayList<Point>();
for(int j=0; j<mines; j++) {
int col = getMineCountForThisRow();
boolean addedMine = false;
while(!addedMine) {
Point mine = new Point(row, col);
if(!points.contains(mine)) {
points.add(mine);
addedMine = true;
}
}
}
return points;
}
| private List<Point> getRandonMinesForRow(int row, int mines) {
List<Point> points = new ArrayList<Point>();
for(int j=0; j<mines; j++) {
boolean addedMine = false;
while(!addedMine) {
int col = getMineCountForThisRow();
Point mine = new Point(row, col);
if(!points.contains(mine)) {
points.add(mine);
addedMine = true;
}
}
}
return points;
}
|
diff --git a/Portal_DB-portlet/docroot/WEB-INF/src/org/goodreturn/story/portlet/StoryValidator.java b/Portal_DB-portlet/docroot/WEB-INF/src/org/goodreturn/story/portlet/StoryValidator.java
index aa9fe13..15916ec 100644
--- a/Portal_DB-portlet/docroot/WEB-INF/src/org/goodreturn/story/portlet/StoryValidator.java
+++ b/Portal_DB-portlet/docroot/WEB-INF/src/org/goodreturn/story/portlet/StoryValidator.java
@@ -1,13 +1,13 @@
package org.goodreturn.story.portlet;
import java.util.List;
import org.goodreturn.model.Story;
public class StoryValidator {
- public static boolean validateStory(Story finalStory, List errors) {
+ public static boolean validateStory(Story story, List errors) {
return false;
}
}
| true | true | public static boolean validateStory(Story finalStory, List errors) {
return false;
}
| public static boolean validateStory(Story story, List errors) {
return false;
}
|
diff --git a/HW3/SetupUI.java b/HW3/SetupUI.java
index 2e24d34..8770fca 100644
--- a/HW3/SetupUI.java
+++ b/HW3/SetupUI.java
@@ -1,156 +1,155 @@
import java.util.List;
import java.util.LinkedList;
import java.util.Scanner;
/**
* Provides the saffolding to get the game up and running. Prompts
* the user for the word length and max attempts. Creates a new Logic
* and GameUI instance when the user is ready to play.
*
* The API will be generic so that this game can be run from the console
* or with a swing pane.
*
* @author Josh Gillham
* @version 9-23-12
*/
public class SetupUI extends SetupBase {
/** Holds the default dictionary file. Should in the root of the project folder. */
static public final String DICTIONARY_FILE= "smalldictionary.txt";
/**
* Initializes the dictionary. Creates a new instance of SetupUI.
*
* @arg args command line arguments - not used.
*/
static public void main( String[] args ){
SetupUI setup= null;
try{
setup= new SetupUI();
} catch( java.io.FileNotFoundException e ) {
e.printStackTrace();
System.exit( 1 );
}
setup.inputSetupGame();
Logic game= setup.getGame( );
setup.startGame( game );
while( game.getGameState() == Logic.Statis.STARTED ){
game.rotateTurn();
}
}
/** Holds a copy of the player name. */
private String name= null;
/** Holds the word length. */
private int wordLength= 0;
/** Holds the maximum guesses. */
private int maxAttempts= 0;
/**
* Brings up the user interface.
*
* @throws FileNotFoundException when dictionary could not be loaded.
*/
public SetupUI( ) throws java.io.FileNotFoundException {
super.addManager( "Default" );
}
public Logic getGame() {
Logic game= super.getGame( wordLength );
game.setMaxAttempts( maxAttempts );
return game;
}
/**
* Launches the Game UI.
*
* @return the newly create GameUI.
*/
public GameUI startGame( Logic game ) {
GameUI UI= new GameUI( game );
game.setGameEventsHandler(UI);
return UI;
}
/**
* Walk through the setup steps with the user.
*
* @return a new game logic.
*/
public void inputSetupGame() {
Scanner userInput= new Scanner(System.in);
// Get their name
int tries= 0;
String name= null;
while( name == null && tries++ < 3 )
name= inputPlayerName( userInput );
// The player doesn't want to play?
if( name == null )
System.exit( 1 );
// Add him to the first team.
super.addPlayer( name );
// Get the word length
tries= 0;
- int wordLength= 0;
while( wordLength == 0 && tries++ < 3 )
wordLength= inputGameWordLength( userInput );
// Get the maximum allowed guesses.
tries= 0;
while( maxAttempts == 0 && tries++ < 3 )
maxAttempts= inputMaxAttempts( userInput );
}
/**
* Listens for the player's name and throws out bad input.
*
* @arg inputScanner gets the next input
*
* @return the name
* @return null if the input was bad.
*/
public String inputPlayerName( Scanner inputScanner ) {
System.out.println( "Enter your name:" );
try{
String name= inputScanner.next();
if( name.isEmpty() )
return null;
return name;
}catch( Exception e) {
return null;
}
}
/**
* Listens for the game word length.
*
* @arg inputScanner gets the next input.
*
* @return the word length.
*/
public int inputGameWordLength( Scanner inputScanner ) {
System.out.println( "Whats the word length:" );
int wordLength= inputScanner.nextInt();
if( !Dictionary.checkWordLength( wordLength ) ) {
System.out.println( "Please enter a length between " + Dictionary.MIN_WORDLENGTH + " and " + Dictionary.LARGEST_WORD + "." );
return 0;
}
return wordLength;
}
/**
* Listens for the game word length.
*
* @arg inputScanner gets the next input.
*
* @return the word length.
*/
public int inputMaxAttempts( Scanner inputScanner ) {
System.out.println( "Whats is the max tries to win the game?" );
int attempts= inputScanner.nextInt();
return attempts;
}
}
| true | true | public void inputSetupGame() {
Scanner userInput= new Scanner(System.in);
// Get their name
int tries= 0;
String name= null;
while( name == null && tries++ < 3 )
name= inputPlayerName( userInput );
// The player doesn't want to play?
if( name == null )
System.exit( 1 );
// Add him to the first team.
super.addPlayer( name );
// Get the word length
tries= 0;
int wordLength= 0;
while( wordLength == 0 && tries++ < 3 )
wordLength= inputGameWordLength( userInput );
// Get the maximum allowed guesses.
tries= 0;
while( maxAttempts == 0 && tries++ < 3 )
maxAttempts= inputMaxAttempts( userInput );
}
| public void inputSetupGame() {
Scanner userInput= new Scanner(System.in);
// Get their name
int tries= 0;
String name= null;
while( name == null && tries++ < 3 )
name= inputPlayerName( userInput );
// The player doesn't want to play?
if( name == null )
System.exit( 1 );
// Add him to the first team.
super.addPlayer( name );
// Get the word length
tries= 0;
while( wordLength == 0 && tries++ < 3 )
wordLength= inputGameWordLength( userInput );
// Get the maximum allowed guesses.
tries= 0;
while( maxAttempts == 0 && tries++ < 3 )
maxAttempts= inputMaxAttempts( userInput );
}
|
diff --git a/Tetris/src/net/foxycorndog/tetris/board/Board.java b/Tetris/src/net/foxycorndog/tetris/board/Board.java
index 875e839..44a6b52 100644
--- a/Tetris/src/net/foxycorndog/tetris/board/Board.java
+++ b/Tetris/src/net/foxycorndog/tetris/board/Board.java
@@ -1,655 +1,658 @@
package net.foxycorndog.tetris.board;
import java.io.IOException;
import java.util.ArrayList;
import net.foxycorndog.jfoxylib.Frame;
import net.foxycorndog.jfoxylib.components.Button;
import net.foxycorndog.jfoxylib.events.ButtonEvent;
import net.foxycorndog.jfoxylib.events.ButtonListener;
import net.foxycorndog.jfoxylib.events.KeyEvent;
import net.foxycorndog.jfoxylib.events.KeyListener;
import net.foxycorndog.jfoxylib.font.Font;
import net.foxycorndog.jfoxylib.input.Keyboard;
import net.foxycorndog.jfoxylib.network.Client;
import net.foxycorndog.jfoxylib.network.Network;
import net.foxycorndog.jfoxylib.network.Packet;
import net.foxycorndog.jfoxylib.network.Server;
import net.foxycorndog.jfoxylib.opengl.GL;
import net.foxycorndog.tetris.Tetris;
import net.foxycorndog.tetris.event.BoardEvent;
import net.foxycorndog.tetris.event.BoardListener;
import net.foxycorndog.tetris.multiplayer.GamePacket;
/**
* Class that holds the information for the Pieces in the Tetris game, as well
* as demonstrating the interactions of the Pieces.
*
* @author Jeremiah Blackburn
* @author Braden Steffaniak
* @since May 6, 2013 at 3:31:08 PM
* @since v0.1
* @version May 6, 2013 at 3:31:08 PM
* @version v0.1
*/
public class Board extends AbstractBoard
{
private boolean lost;
private boolean gameStarted;
private int ticks;
private int lastSpeedTick;
private float speedChangeAmount;
private float speedChangeFactor;
private long pressStartTime;
private Piece currentPiece;
private KeyListener keyListener;
private Network network;
private Client client;
private Server server;
private Tetris tetris;
private ArrayList<BoardListener> events;
/**
* Instantiate the image for the Board as well as other instantiations.
*
* @param width
* The number of horizontal grid spaces the Board will contain.
* @param height
* The number of vertical grid spaces the Board will contain.
* @param gridSpaceSize
* The size (in pixels) that each space on the Board will take
* up. eg: passing 10 would create 10x10 grid spaces across the
* board.
*/
public Board(int width, int height, int gridSpaceSize, final Tetris tetris)
{
super(width, height, gridSpaceSize);
this.tetris = tetris;
events = new ArrayList<BoardListener>();
pressStartTime = Long.MAX_VALUE;
keyListener = new KeyListener()
{
public void keyPressed(KeyEvent event)
{
if (event.getKeyCode() == Keyboard.KEY_LEFT)
{
movePiece(currentPiece, -1, 0);
pressStartTime = System.currentTimeMillis();
}
if (event.getKeyCode() == Keyboard.KEY_RIGHT)
{
movePiece(currentPiece, 1, 0);
pressStartTime = System.currentTimeMillis();
}
if (event.getKeyCode() == Keyboard.KEY_UP)
{
currentPiece.rotateClockwise();
}
if (event.getKeyCode() == Keyboard.KEY_DOWN)
{
setTicksPerSecond(getTicksPerSecond() * 4);
}
}
public void keyReleased(KeyEvent event)
{
if (event.getKeyCode() == Keyboard.KEY_DOWN)
{
setTicksPerSecond(getTicksPerSecond() / 4);
}
if (event.getKeyCode() == Keyboard.KEY_LEFT)
{
if (!Keyboard.isKeyDown(Keyboard.KEY_RIGHT))
{
pressStartTime = Long.MAX_VALUE;
}
}
if (event.getKeyCode() == Keyboard.KEY_RIGHT)
{
if (!Keyboard.isKeyDown(Keyboard.KEY_LEFT))
{
pressStartTime = Long.MAX_VALUE;
}
}
}
public void keyTyped(KeyEvent event)
{
}
public void keyDown(KeyEvent event)
{
}
};
Keyboard.addKeyListener(keyListener);
//setTicksPerSecond(8f);
speedChangeFactor = 1.8f;
speedChangeAmount = 0.5f;
lastSpeedTick = 10;
addListener(new BoardListener()
{
public void onPieceMove(BoardEvent event)
{
}
public void onLineCompleted(BoardEvent event)
{
if (network != null)
{
GamePacket packet = new GamePacket(event.getLines(), GamePacket.LINES_COMPLETED);
network.sendPacket(packet);
}
}
public void onGameLost(BoardEvent event)
{
GamePacket packet = new GamePacket(null, GamePacket.GAME_LOST);
- network.sendPacket(packet);
+ if (network != null)
+ {
+ network.sendPacket(packet);
+ }
}
});
}
/**
* @see net.foxycorndog.tetris.board.AbstractBoard#tick()
*
* Moves a piece down
* one space after half a second until the piece hits the bottom of the
* board or another piece on the board.
*/
public void tick()
{
if (server != null)
{
if (server.isConnected() && !gameStarted)
{
newGame();
gameStarted = true;
}
else
{
}
}
if (!lost && gameStarted)
{
if (ticks >= lastSpeedTick * speedChangeFactor)
{
lastSpeedTick = ticks;
setTicksPerSecond(getTicksPerSecond() + speedChangeAmount);
}
if (System.currentTimeMillis() - pressStartTime >= 200)
{
if (Keyboard.isKeyDown(Keyboard.KEY_LEFT))
{
movePiece(currentPiece, -1, 0);
}
if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT))
{
movePiece(currentPiece, 1, 0);
}
}
boolean moved = movePiece(currentPiece, 0, -1);
if (!moved)
{
currentPiece.kill();
clearRows();
currentPiece = tetris.getSidebar().getNextPiece().getNextPiece();
tetris.getSidebar().getNextPiece().generateNextPiece();
addPieceToCenter();
if (currentPiece.yallHitTheBottomBaby())
{
Keyboard.removeKeyListener(keyListener);
lost = true;
for (BoardListener listener : events)
{
listener.onGameLost(null);
}
quitGame();
Tetris.SOUND_LIBRARY.playSound("lose.wav");
}
else
{
Tetris.SOUND_LIBRARY.playSound("pop.wav");
}
}
ticks++;
}
}
/**
* Quit the game and stop the music.
*/
public void quitGame()
{
Tetris.SOUND_LIBRARY.stopSound("music.wav");
if (network != null)
{
network.close();
}
}
/**
* Move the specified Piece the specified amount.
*
* @param piece The Piece to move.
* @param dx The amount of squares to move it horizontally.
* @param dy The amount of squares to move it vertically.
* @return Whether it moved successfully or not.
*/
private boolean movePiece(Piece piece, int dx, int dy)
{
boolean moved = piece.move(dx, dy);
if (moved)
{
BoardEvent event = new BoardEvent(piece.getX(), piece.getY(), piece, 0);
for (BoardListener listener : events)
{
listener.onPieceMove(event);
}
}
return moved;
}
/**
* Sets lost to l.
*/
public void setLost(boolean l)
{
lost = l;
}
/**
* @return lost. Lost is either true or false. If lost is true, the piece is
* still able to move.
*/
public boolean hasLost()
{
return lost;
}
/**
* Coordinates use the Cartesian system.
*
* @see net.foxycorndog.tetris.board.AbstractBoard#isValid(int, int)
*
* checks to see it the coordinate (x,y) is valid for the piece to
* move to.
*/
public boolean isValid(int x, int y)
{
return (x >= 0 && x < getWidth()) && (y >= 0 && y < getHeight());
}
/**
* Coordinates use the Cartesian system.
*
* @see net.foxycorndog.tetris.board.AbstractBoard#isValid(int, int) checks
* to see it the coordinate (x,y) is valid for the piece to move to.
*/
public boolean isValid(Location loc)
{
return isValid(loc.getX(), loc.getY());
}
/**
* Looks at one row of the board at a time and checks each location in that
* row to see if it has a square. If all of the locations in the row have a
* square the squares are deleted.
*/
public void clearRows()
{
// if (true)return;
int counter = 0;
int r = 0;
int lines = 0;
while (r < getHeight())
{
counter = 0;
for (int c = 0; c < getWidth(); c++)
{
if (getPieces(new Location(c, r)).length > 0)
{
counter++;
}
if (counter == getWidth())
{
for (int dRow = 0; dRow < getWidth(); dRow++)
{
Location l = new Location(dRow, r);
Piece pieces[] = getPieces(l);
pieces[0].deleteSquare(l);
}
moveSquares(0, r, getWidth(), getHeight(), 0, -1);
lines++;
}
}
if (counter < getWidth())
{
r++;
}
}
if (lines > 0)
{
BoardEvent event = new BoardEvent(0, r, null, lines);
for (BoardListener listener : events)
{
listener.onLineCompleted(event);
}
Tetris.SOUND_LIBRARY.playSound("lineremoved.wav");
}
}
/**
* Adds a BoardListener to the ArrayList events.
*
* @param b
*/
public void addListener(BoardListener b)
{
events.add(b);
}
/**
* @see net.foxycorndog.tetris.board.AbstractBoard#newGame()
*/
public void newGame()
{
gameStarted = true;
// int ind = (int)(Math.random() * getWidth());
//
// ArrayList<Location> shape = new ArrayList<Location>();
//
//// ind = 0;
//
// int i = 0;
// while (i < getWidth())
// {
// if (i != ind)
// {
// shape.add(new Location(i, 0));
// }
//
// i++;
// }
//
// currentPiece = new Piece(shape, new Color(100, 100, 100));
currentPiece = Piece.getRandomPiece();
// currentPiece = new Piece(2);
addPieceToCenter();
Tetris.SOUND_LIBRARY.playSound("pop.wav");
Tetris.SOUND_LIBRARY.loopSound("music.wav");
// setTicksPerSecond(4);
setTicksPerSecond(4);
}
public void addPieceToCenter()
{
addPiece(currentPiece, getWidth() / 2 - Math.round(currentPiece.getWidth() / 2), getHeight() - currentPiece.getHeight());
}
/**
* @see net.foxycorndog.tetris.board.AbstractBoard#addPiece(net.foxycorndog.tetris.board.Piece,
* int, int)
*/
public void addPiece(Piece piece, int x, int y)
{
piece.setBoard(this);
piece.setLocation(x, y);
getPieces().add(piece);
}
/**
* Moves all of the squares within the given rectangle specifications
* the specified amount.
*
* @param x The horizontal start of the bounds of the rectangle of the
* squares to move.
* @param y The vertical start of the bounds of the rectangle of the
* squares to move.
* @param width The width of the bounds of the rectangle of the
* squares to move.
* @param height The height of the bounds of the rectangles of the
* squares to move.
* @param dx The horizontal amount to move the squares.
* @param dy The vertical amount to move the squares.
*/
private void moveSquares(int x, int y, int width, int height, int dx, int dy)
{
x = x < 0 ? 0 : x;
y = y < 0 ? 0 : y;
x = x >= getWidth() ? getWidth() - 1 : x;
y = y >= getHeight() ? getHeight() - 1 : y;
width = width > getWidth() ? getWidth() : width;
height = height > getHeight() ? getHeight() : height;
ArrayList<Piece> ps = new ArrayList<Piece>();
ArrayList<Location> locs = new ArrayList<Location>();
for (int y2 = y; y2 < height; y2++)
{
for (int x2 = x; x2 < width; x2++)
{
Location l = new Location(x2, y2);
Piece pieces[] = getPieces(l);
if (pieces.length > 0)
{
locs.add(l);
ps.add(pieces[0]);
// pieces[0].moveSquare(l, new Location(dx, dy));
}
}
}
for (int i = 0; i < ps.size(); i++)
{
Location loc = locs.get(i);
ps.get(i).moveSquare(loc, new Location(dx, dy));
}
}
/**
* Adds the specified number of straight lines to the bottom of the
* Board. The straight lines are full of squares, except for one
* spot.
*/
public void addStraightLines(int numLines)
{
moveSquares(0, 0, getWidth(), getHeight(), 0, numLines);
for (int n = 0; n < numLines; n++)
{
int ind = (int)(Math.random() * getWidth());
ArrayList<Location> shape = new ArrayList<Location>();
// ind = 0;
int i = 0;
while (i < getWidth())
{
if (i != ind)
{
shape.add(new Location(i, 0));
}
i++;
}
Piece newPiece = new Piece(shape, new Color(100, 100, 100));
addPiece(newPiece, 0, n);
}
}
/**
* Connect the Board game to the Client.
*
* @param ip The IP of the Server to connect to.
* @param port The port of the Server to connect to.
*/
public void connectClient(String ip, int port)
{
client = new Client(ip, port)
{
public void onReceivedPacket(Packet packet)
{
tetris.addPacketToQueue(packet);
}
};
setClient(client);
new Thread()
{
public void run()
{
client.connect();
newGame();
}
}.start();
}
/**
* Set the Client that the Board should use.
*
* @param client The Client to use.
*/
public void setClient(Client client)
{
network = client;
if (client.isConnected())
{
newGame();
}
}
/**
* Create a server for Clients to connect to.
*
* @param port The port to create the Server on.
*/
public void createServer(int port)
{
gameStarted = false;
server = new Server(port)
{
public void onReceivedPacket(Packet packet)
{
tetris.addPacketToQueue(packet);
}
};
network = server;
new Thread()
{
public void run()
{
server.create();
// server.sendPacket(new Packet(null, 33));
}
}.start();
}
/**
* Render the back Button.
*
* @see net.foxycorndog.tetris.board.AbstractBoard#render()
*/
public void render()
{
if (server != null)
{
if (server.isConnected())
{
}
else
{
GL.setColor(0, 0, 0, 1);
Tetris.getFont().render("Waiting for\nconnection.", 0, 0, 2, 1, Font.CENTER, Font.CENTER, null);
GL.setColor(1, 1, 1, 1);
Tetris.getFont().render("Waiting for\nconnection.", 2, 2, 2, 1, Font.CENTER, Font.CENTER, null);
GL.setColor(0.5f, 0.5f, 0.5f, 1);
}
}
super.render();
GL.pushMatrix();
{
GL.scale(0.75f, 0.75f, 1);
}
GL.popMatrix();
}
}
| true | true | public Board(int width, int height, int gridSpaceSize, final Tetris tetris)
{
super(width, height, gridSpaceSize);
this.tetris = tetris;
events = new ArrayList<BoardListener>();
pressStartTime = Long.MAX_VALUE;
keyListener = new KeyListener()
{
public void keyPressed(KeyEvent event)
{
if (event.getKeyCode() == Keyboard.KEY_LEFT)
{
movePiece(currentPiece, -1, 0);
pressStartTime = System.currentTimeMillis();
}
if (event.getKeyCode() == Keyboard.KEY_RIGHT)
{
movePiece(currentPiece, 1, 0);
pressStartTime = System.currentTimeMillis();
}
if (event.getKeyCode() == Keyboard.KEY_UP)
{
currentPiece.rotateClockwise();
}
if (event.getKeyCode() == Keyboard.KEY_DOWN)
{
setTicksPerSecond(getTicksPerSecond() * 4);
}
}
public void keyReleased(KeyEvent event)
{
if (event.getKeyCode() == Keyboard.KEY_DOWN)
{
setTicksPerSecond(getTicksPerSecond() / 4);
}
if (event.getKeyCode() == Keyboard.KEY_LEFT)
{
if (!Keyboard.isKeyDown(Keyboard.KEY_RIGHT))
{
pressStartTime = Long.MAX_VALUE;
}
}
if (event.getKeyCode() == Keyboard.KEY_RIGHT)
{
if (!Keyboard.isKeyDown(Keyboard.KEY_LEFT))
{
pressStartTime = Long.MAX_VALUE;
}
}
}
public void keyTyped(KeyEvent event)
{
}
public void keyDown(KeyEvent event)
{
}
};
Keyboard.addKeyListener(keyListener);
//setTicksPerSecond(8f);
speedChangeFactor = 1.8f;
speedChangeAmount = 0.5f;
lastSpeedTick = 10;
addListener(new BoardListener()
{
public void onPieceMove(BoardEvent event)
{
}
public void onLineCompleted(BoardEvent event)
{
if (network != null)
{
GamePacket packet = new GamePacket(event.getLines(), GamePacket.LINES_COMPLETED);
network.sendPacket(packet);
}
}
public void onGameLost(BoardEvent event)
{
GamePacket packet = new GamePacket(null, GamePacket.GAME_LOST);
network.sendPacket(packet);
}
});
}
| public Board(int width, int height, int gridSpaceSize, final Tetris tetris)
{
super(width, height, gridSpaceSize);
this.tetris = tetris;
events = new ArrayList<BoardListener>();
pressStartTime = Long.MAX_VALUE;
keyListener = new KeyListener()
{
public void keyPressed(KeyEvent event)
{
if (event.getKeyCode() == Keyboard.KEY_LEFT)
{
movePiece(currentPiece, -1, 0);
pressStartTime = System.currentTimeMillis();
}
if (event.getKeyCode() == Keyboard.KEY_RIGHT)
{
movePiece(currentPiece, 1, 0);
pressStartTime = System.currentTimeMillis();
}
if (event.getKeyCode() == Keyboard.KEY_UP)
{
currentPiece.rotateClockwise();
}
if (event.getKeyCode() == Keyboard.KEY_DOWN)
{
setTicksPerSecond(getTicksPerSecond() * 4);
}
}
public void keyReleased(KeyEvent event)
{
if (event.getKeyCode() == Keyboard.KEY_DOWN)
{
setTicksPerSecond(getTicksPerSecond() / 4);
}
if (event.getKeyCode() == Keyboard.KEY_LEFT)
{
if (!Keyboard.isKeyDown(Keyboard.KEY_RIGHT))
{
pressStartTime = Long.MAX_VALUE;
}
}
if (event.getKeyCode() == Keyboard.KEY_RIGHT)
{
if (!Keyboard.isKeyDown(Keyboard.KEY_LEFT))
{
pressStartTime = Long.MAX_VALUE;
}
}
}
public void keyTyped(KeyEvent event)
{
}
public void keyDown(KeyEvent event)
{
}
};
Keyboard.addKeyListener(keyListener);
//setTicksPerSecond(8f);
speedChangeFactor = 1.8f;
speedChangeAmount = 0.5f;
lastSpeedTick = 10;
addListener(new BoardListener()
{
public void onPieceMove(BoardEvent event)
{
}
public void onLineCompleted(BoardEvent event)
{
if (network != null)
{
GamePacket packet = new GamePacket(event.getLines(), GamePacket.LINES_COMPLETED);
network.sendPacket(packet);
}
}
public void onGameLost(BoardEvent event)
{
GamePacket packet = new GamePacket(null, GamePacket.GAME_LOST);
if (network != null)
{
network.sendPacket(packet);
}
}
});
}
|
diff --git a/src/game/ChoiceStorage.java b/src/game/ChoiceStorage.java
index 8d43b7d..6b17f39 100644
--- a/src/game/ChoiceStorage.java
+++ b/src/game/ChoiceStorage.java
@@ -1,620 +1,620 @@
package game;
import java.util.ArrayList;
public class ChoiceStorage {
private int currentChoice = -1;
private ArrayList<Choice> choices = new ArrayList<Choice>();
/**
* Builds a new instance of ChoiceStorages
*/
public ChoiceStorage(Person p) {
// Choice1
final Requirements hr1[] = { new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0) };
final String[] hc1Story = new String[] {
"You leave the object alone! \nBad call on your part you have missed out on a very valuble childhood experience. \nYou should explore more in coming ages.",
"You are clearly going to grow up to be very self concious and closed off.\nYour choice to not only miss out on a very important experience but to also cry leaves everyone concerned about your outgoingness.",
"GREAT! You have just found the object you will call BaBa for the rest of your life. \nYou are showing not only the first signs of motion but also outgoingness and bravery to grab an unknown object.\nWhen you grab the object you hear beads rattle and you vigoursly shake.\nYour parents walk in and smile.",
"Your attempts to do something are amusing and you start to giggle.\n Your parents walk in and smile. You have just found a great skill in life...Being a goof.",
"Great! You have just found the object you will call MeMe for the rest of your life. \nYou are showing the first signs of motion and your ability to start shaking the object shows intelligence and gives you a new passion...Weightlifting" };
final Outcome[] houtcomeLineC1 = new Outcome[] { new Outcome(true, 0, 0, 0, 0, -3, 0),
new Outcome(true, 0, -2, 0, 0, -4, 0), new Outcome(true, 0, 0, 2, 0, 3, 0),
new Outcome(true, 5, 0, 0, 0, 2, 0), new Outcome(true, 0, 0, 6, 0, 2, 0) };
final Choice hc1 = new Choice(
"When you are born you see an object in the distance what do you do? \n1. Leave the object alone \n2.Leave the object and cry \n3. Crawl over to the object and grab it \n4.Flail misserably\5.Crawl over to the object and shake it up and down.",
hc1Story, hr1, houtcomeLineC1, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice2
final String[] hc2Story = new String[] {
"Your confidence and charisma have impressed your peers. \nYou are immensily successful and have just found some bros for life! \nYou will surely reap the benefits of being one of the cool kids later in life...Keep it up.",
"Ohhhh so your one of THOSE kids...",
"Your dedication to academia is quite apparant.\nKeep it up so your life can go further",
"Your leadership has united this band of misfits! \nThese are some friends you will keep forever", "",
"", "", "", "", "",
"Your peers think your statement is ingenuine and your not bro enough. 'Leave GDI'. You have failed" };
final Outcome[] houtcomeLineC2 = new Outcome[] { new Outcome(true, 3, 0, 0, 2, 6, 0),
new Outcome(true, 2, -5, 0, 0, 0, 0), new Outcome(true, 0, 6, 0, 0, -2, 0),
new Outcome(true, 4, 0, 0, 0, 2, 0), null, null, null, null, null, null,
new Outcome(true, -1, 0, 0, 0, -2, 0) };
final Requirements hr2[] = { new Requirements(2, 0, 0, 0, 5), new Requirements(-1, -1, -1, -1, -1),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Choice hc2 = new Choice(
"You are now away from being in the isolated haven now known as 'Home' and you are entering a new place your parents call 'School'. \nWhen you enter this weird place you see kids like yourself running around. \nConfused by everything happening what do you do? \n1.Approach some of the boys that are playing blocks with eachother and say 'What up bros' .\n2.Sit in the corner and sniff and eat glue \n3.Go pick up a book and start looking at pictures. \n4.Approach one of the kids that are playing by themselves.",
hc2Story, hr2, houtcomeLineC2, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice3
final String[] hc3Story = new String[] {
"Your dedication to academia is apparaent. \nYour teacher loves you and you feel your brain growing",
"You and your bros go outside hit on some ladies and P some Ls. \nYou kids are clearly the kings of the castle keep it up",
"You again.....",
"You guys play some tag and hide and go seek keep growing with your peers." };
final Outcome[] outcomeLineC3 = new Outcome[] { new Outcome(true, 3, 0, 0, 0, 9, 0),
new Outcome(true, 2, -5, 0, 0, 0, 0), new Outcome(true, 0, 5, 0, 0, -2, 0),
new Outcome(true, 4, 0, 0, 0, 2, 0), null, null, null, null, null, null,
new Outcome(true, -3, 0, 0, 0, -2, 0) };
final Requirements hr3[] = { new Requirements(4, 0, 0, 0, 11), new Requirements(-1, -1, -1, -1, -1),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Choice hc3 = new Choice(
"Your teacher says 'Recess' and all the kids go outside what do you do? \n1.Stay indoors and read. \n2.Go outside with your bros and kick it. \n3.Stay indoors and sniff glue. \n4.Go outside and play with random kids.",
hc3Story, hr3, outcomeLineC3, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice4
final String[] hc4Story = new String[] {
"Your pretty much the Cleaver family. \nYou have family dinners and movie nights on the weekend, your parents grant you a ton of responsility and push you to new heights",
"Wow your personality is really showing now... needless to say your life is pretty boring",
"Your parents hate you but the kids respect you. You snek out on the reg with the rest of your boys teepeing and smoking tea. You and your boys are the talk of the town, boys want to be you and girls want their nap mat next to yours. lets just hope your parents wont retaliate that much.",
"Good choice bro. Your birthdays are filled with Vinard Vines boxes and Brookes Brothers bags. Your country club lifestyle has made you the talk of the school. THe boys want to be you and the girls want their nap mat next to you. May your croakies hang with pride...",
"",
"",
"",
"",
"",
"",
"",
"",
"HAHA you think YOU could be a rebel?? Your parents laugh and joke about your 'phases' and the kids around school think your more of a tool than you already are.",
"Although your intentions shape what you will strive for in your life...your family's wealth is no where near that level." };
// boolean alive, int charisma, int intelligence, int strength, int
// wealth,
// int confidence, int age)
final Outcome[] houtcomeLineC4 = new Outcome[] { new Outcome(true, 5, 1, 0, 0, 2, 0),
new Outcome(true, -2, 5, -1, 0, -2, 0), new Outcome(true, 3, -2, 0, -1, 5, 0),
new Outcome(true, 3, 0, 0, 2, 6, 0), null, null, null, null, null, null, null, null,
new Outcome(true, 0, 0, 0, 0, -5, 0), new Outcome(true, 2, 0, 0, 0, 1, 0) };
// int charisma, int intelligence, int strength, int wealth, int
// confidence
final Requirements hr4[] = { new Requirements(0, 0, 0, 0, 0), new Requirements(-1, -1, -1, -1, -1),
new Requirements(0, 0, 0, 0, 5), new Requirements(0, 0, 0, 5, 0), };
final Choice hc4 = new Choice(
"You have come of age to choose what your family life will be like. \n1.Be a happy content boy that always does what their parents say. \n2.Stay in your room and study and obey your parents whenever. \n3.Your a rebel...Enough said. \n4.You follow in the excessive and bourgeois lifestyle of your parents",
hc4Story, hr4, houtcomeLineC4, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice5
final String[] hc5Story = new String[] {
"As you approach the shorts you can hear your destiny calling...Your choice is the generic.",
"As you approach the shorts you can hear your destiny calling...Your one of the cool kids.",
"As you approach the shorts you can hear your destiny calling...You are a prep master, born to join a frat.",
"As you approach the shorts you can hear your destiny calling...You are an artsy hipster.",
"As you approach the shorts you can hear your destiny calling...You are a happy hippie." };
// boolean alive, int charisma, int intelligence, int strength, int
// wealth,
// int confidence, int age)
final Outcome[] houtcomeLineC5 = new Outcome[] { new Outcome(true, 3, 2, 0, 0, 2, 1),
new Outcome(true, 3, 0, 0, 0, 5, 0), new Outcome(true, 3, 0, 0, 1, 5, 0),
new Outcome(true, 4, 3, 0, 0, 0, 0), new Outcome(true, 6, 0, 0, 0, 0, 0) };
final Requirements hr5[] = { new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Choice hc5 = new Choice(
- "Now here is the BIG decision...\nYour parents have finally have decided to let you choose your pants...\n(Be Careful and wise this pretty much determines the game).\n1.Choose cargo shorts.\n2.Choose jeans.\n3.Choose Nantucket Reds\4.Cordaroy Overalls.\n5.Tie Die Shorts.",
+ "Now here is the BIG decision...\nYour parents have finally have decided to let you choose your pants...\n(Be Careful and wise this pretty much determines the game).\n1.Choose cargo shorts.\n2.Choose jeans.\n3.Choose Nantucket Reds\n4.Cordaroy Overalls.\n5.Tie Die Shorts.",
hc5Story, hr5, houtcomeLineC5, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// ///////// Constructs the Prompts ///////////
final String pt1 = "Welcome to your first day of highschool! Today you get to decide how you want to act.\n1: Become a sports jock.\n2: Hang with the popular crowd.\n3: Study for your classes.\n4: Do nothing";
final String pt2 = "You get invited to a party. Everyone seems to be having fun. Drugs and alcohol are present.\n1: Get drunk and go crazy\n2: Drive your drunk friend home\n3: Socialize\n4: Stare at your phone";
final String pt3 = "It is the day before finals. The year is almost over and summer is within your reach. Do you: \n1: Spend your time studying for your tests.\n2: Hang out with your friends and cram the morning of the test.\n3: Don't study and try to cheat off of someone else.\n4: Just kinda chill.";
final String pt4 = "It is senior year and about time you made up your mind about College. Let's apply! \n1: You apply to schools with Division A Lax teams. \n2: You apply to law school. \n3: You apply to the best engineering schools in the country. \n4: You decide maybe college isn't your thing.";
final String pt5 = "It's time to find a full-time job. \n1: Get a job. \n2: Go back to live at your parents' house.";
// ///////// Constructs the outcome string arrays ///////////
final String[] sl1 = {
"You get recruited by the Lax team because of your sick Lax skills. Lax.",
"You meet some new friends. Everyone seems to want to sit next to you at lunch.",
"You hit the books. Your grades stay steady and the teachers seem to enjoy your participation in class.",
"You just kinda coast along. Nobody seems to know a whole lot about you.", null, "You win", null, null,
null, null, "The bros stare at you blankly. You really thought you could lax with them?",
"It's obvious to them that you aren't that cool.",
"You lose concentration while trying to study. Maybe you have ADHD?", "Error 808: you suck." };
final String[] sl2 = {
"You wake up on a park bench in the next town over wearing a traffic cone as hat.",
"The next day, your friend thanks you profusely for your wise actions of the previous night.",
"You meet a girl named Maria and hit it off.",
"You stay in the corner and keep to yourself. No one seems to notice your presence.",
null,
null,
null,
null,
null,
null,
"You take one drink and throw up. You're not exactly the life of the party,",
"Your friend says he doesn't need any help. He gets in his car and crashes it into a tree almost immediately.",
"You can't talk over the music. You don't end up meeting anyone", "Error 808: you suck." };
final String[] sl3 = {
"After hours of studying you feel ready for your tests. You do well on all of them.",
"You don't do awesome on your tests, but you feel as though your friends appreciate your carefree style.",
"You do well on your tests: maybe a little too well. Nobody has proof of anything, but you lose the trust of those around you.",
"You do pretty average, although your not even sure your teachers know your name.", null, null, null,
null, null, null, "You fall asleep while studying. You don't do great on your tests",
"You fail your tests, and your friends think you should spend more time on your academics",
"You get caught! You get a zero on all of your tests", "Error 808: you suck." };
final String[] sl4 = { "You make it in to Lax U. Congratulations!",
"You make it in to Lawyer U. Congratulations!", "You make it in to Engineering U. Congratulations!",
"You take a job at McDoodles to make an income. Congratulations?", null, null, null, null, null, null,
"Your lax skills aren't quite up to snuff. You get rejected.",
"You aren't a great public speaker. You get rejected.",
"You aren't that great at math and science. You get rejected.", "Error 808: you suck." };
final String[] sl5 = { "Welcome to adulthood.", "Your parents aren't very happy about this.", null, null, null,
null, null, null, null, null, "You aren't qualified enough.", "Error 808: you suck." };
// ///////// Constructs outcomes and outcome arrays ///////////
final Outcome o1 = new Outcome(true, 2, -1, 5, 0, 5, 0);
final Outcome o2 = new Outcome(true, 5, -1, 0, 2, 5, 0);
final Outcome o3 = new Outcome(true, -1, 5, 0, 5, 2, 0);
final Outcome o4 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome owin = new Outcome(true, 100, 100, 100, 100, 100, 0);
final Outcome o1a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o2a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o3a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o4a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol1 = { o1, o2, o3, o4, null, owin, null, null, null, null, o1a, o2a, o3a, o4a };
final Outcome o5 = new Outcome(true, 7, -4, 4, -2, 7, 0);
final Outcome o6 = new Outcome(true, 3, 5, 0, 0, 4, 0);
final Outcome o7 = new Outcome(true, 6, 0, 0, -1, 7, 0);
final Outcome o8 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome o5a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o6a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o7a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o8a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol2 = { o5, o6, o7, o8, null, null, null, null, null, null, o5a, o6a, o7a, o8a };
final Outcome o9 = new Outcome(true, 0, 6, 0, 3, 3, 0);
final Outcome o10 = new Outcome(true, 6, 0, 3, 0, 3, 0);
final Outcome o11 = new Outcome(true, -2, 8, 0, -2, 8, 0);
final Outcome o12 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome o9a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o10a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o11a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o12a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol3 = { o9, o10, o11, o12, null, null, null, null, null, null, o9a, o10a, o11a, o12a };
final Outcome o13 = new Outcome(true, 2, -1, 5, 0, 5, 0);
final Outcome o14 = new Outcome(true, 5, -1, 0, 2, 5, 0);
final Outcome o15 = new Outcome(true, -1, 5, 0, 5, 2, 0);
final Outcome o16 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome o13a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o14a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o15a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o16a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol4 = { o13, o14, o15, o16, null, null, null, null, null, null, o13a, o14a, o15a, o16a };
final Outcome o17 = new Outcome(true, 2, 2, 2, 2, 2, 5);
final Outcome o18 = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome o17a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o18a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome[] ol5 = { o17, o18, null, null, null, null, null, null, null, null, o17a, o18a };
// ///////// Constructs requirements and requirement arrays ///////////
final Requirements r1 = new Requirements(2, 0, 2, 0, 2);
final Requirements r2 = new Requirements(2, 0, 0, 2, 2);
final Requirements r3 = new Requirements(1, 3, 0, 1, 1);
final Requirements r4 = new Requirements(0, 0, 0, 0, 0);
final Requirements rwin = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra1 = { r1, r2, r3, r4, null, rwin };
final Requirements r5 = new Requirements(6, 0, 0, 0, 6);
final Requirements r6 = new Requirements(2, 6, 2, 0, 2);
final Requirements r7 = new Requirements(6, 0, 0, 0, 6);
final Requirements r8 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra2 = { r5, r6, r7, r8 };
final Requirements r9 = new Requirements(0, 3, 0, 0, 0);
final Requirements r10 = new Requirements(1, 0, 0, 1, 1);
final Requirements r11 = new Requirements(0, 3, 0, 0, 3);
final Requirements r12 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra3 = { r9, r10, r11, r12 };
final Requirements r13 = new Requirements(0, 0, 10, 5, 5);
final Requirements r14 = new Requirements(10, 0, 0, 5, 5);
final Requirements r15 = new Requirements(0, 10, 0, 5, 5);
final Requirements r16 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra4 = { r13, r14, r15, r16 };
final Requirements r17 = new Requirements(2, 2, 2, 2, 2);
final Requirements r18 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra5 = { r17, r18, };
// ///////// Constructs the choices ///////////
Choice c1 = new Choice(pt1, sl1, ra1, ol1, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c2 = new Choice(pt2, sl2, ra2, ol2, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c3 = new Choice(pt3, sl3, ra3, ol3, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c4 = new Choice(pt4, sl4, ra4, ol4, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c5 = new Choice(pt5, sl5, ra5, ol5, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] A1Story = {
"You become a McDoodles worker",
"You become a mechanic",
"You become a sports star",
"You become an engineer",
"You become a CEO",
"You become a politician",
"DO NOT READ! in three days you will be kissed by the love of your life, but if you do not repost this to 5 other videos, you will be murdered in two days by a pack of wild puffins!",
null, null, null, "You fail to become a McDoodles worker. You may wish to reevaluate your life.",
"You fail to become a mechanic. Perhaps a lower-skill job would be better for you.",
"You fail to become a sports star. Try to get stronger.",
"You fail to become an engineer. You should work at McDoodles instead.", "You fail to become a CEO.",
"You fail to become a politician. You're not good enough at wooing voters." };
final Outcome[] A1Outcomes = { new Outcome(true, 0, 0, 0, 5, 1, 0), new Outcome(true, 0, 1, 1, 10, 3, 0),
new Outcome(true, 5, 0, 10, 20, 10, 0), new Outcome(true, 0, 15, 0, 15, 10, 0),
new Outcome(true, 5, 10, 0, 25, 7, 0), new Outcome(true, 10, 7, 0, 15, 10, 0),
new Outcome(true, 100, 100, 100, -100, 100, 100), null, null, null, null,
new Outcome(true, 0, 0, 0, 0, -20, 0), new Outcome(true, 0, 0, 0, 0, -10, 0),
new Outcome(true, 0, 0, 0, 0, -10, 0), new Outcome(true, 0, 0, 0, 0, -10, 0),
new Outcome(true, 0, 0, 0, 0, -10, 0), new Outcome(true, 0, 0, 0, 0, -10, 0)
};
Requirements[] A1reqs = { new Requirements(1, 1, 1, 1, 1), new Requirements(3, 20, 15, 5, 5),
new Requirements(20, 5, 30, 20, 10), new Requirements(10, 30, 5, 15, 10),
new Requirements(30, 20, 5, 10, 10), new Requirements(20, 30, 5, 20, 15),
new Requirements(0, 0, 0, 0, 0) };
Choice choiceA1 = new Choice(
"You decide to get a job. The choices are \n1: 'McDoodles worker'\n2: 'Mechanic'\n3: 'Sports Star'\n4: 'Engineer'\n5: 'CEO'\n6: or 'Politician'",
A1Story, A1reqs, A1Outcomes, p, 2, 0, 0, 0, 0, 0);
final String A2printText = "You are bored at home. You decide to do something. You can\n1: read a book\n2: work out, or \n3:go to a party";
final String[] A2Story = { "You decide to read a book. You are now more intelligent",
"You decide to work out. You are now stronger", "You decide to go to a party. Charisma goes up", null,
null, null, null, null, null, null, "You managed to fail at reading. Are you even literate?",
"You failed to work out. frynotsureifweakorstupid.jpg",
"You failed to go to a party. I've given up hope." };
final Requirements[] A2Reqs = { new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0) };
final Outcome[] A2Outcomes = { new Outcome(true, 0, 10, 0, 0, 0, 0), new Outcome(true, 0, 0, 10, 0, 0, 0),
new Outcome(true, 10, 0, 0, 0, 0, 0), null, null, null, null, null, null, null,
new Outcome(true, -5, -5, -5, -5, -5, 0), new Outcome(true, -5, -5, -5, -5, -5, 0),
new Outcome(true, -5, -5, -5, -5, -5, 0) };
Choice choiceA2 = new Choice(A2printText, A2Story, A2Reqs, A2Outcomes, p, 2, 0, 0, 0, 0, 0);
final String A3printText = "You are very lonely. Would you like to try to get married? (1 yes, 2 no)";
final String[] A3Story = {
"Congratulations! You managed to convince someone to spend their entire life with you! You are now married.",
"You decided that married life is not for you.",
"If this text is displayed, something is horribly wrong",
"Seriously, if you can see this, they're coming", "I'm not kidding. You'd better run",
"Seriously, RUN!", "Well clearly you're not listening to me",
"I'm going to sit tight while they eat you", "and I'm not going to feel any regret",
"Well, I guess this is a lost cause, bye",
"You failed to convince somebody to marry you. You must be ugly, poor, or both",
"How did you possibly fail at not getting married?! I'm ashamed of you."
};
final Requirements[] A3reqs = { new Requirements(30, 20, 15, 20, 25), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Outcome[] A3Outcomes = { new Outcome(true, 10, 0, 0, -10, 10, 0), new Outcome(true, 0, 0, 0, 0, 0, 0),
null, null, null, null, null, null, null, null, new Outcome(true, -5, 0, 0, 0, -20, 0),
new Outcome(true, -10, -10, -10, -10, -40, 0), };
Choice choiceA3 = new Choice(A3printText, A3Story, A3reqs, A3Outcomes, p, 3, 0, 0, 0, 0, 0);
final String A4printText = "You really hate people. You're so angry you consider becoming a serial killer. Would you like to become a serial killer?";
final String[] A4Story = {
"You succeed at becoming a serial killer, you monster",
"I suppose you don't have the killer instinct",
null,
null,
null,
null,
null,
null,
null,
null,
"At the house of your first hit, you are discovered, and the police are called. You are shot by the police and die.",
"I'm not sure how, but you managed to fail at not becoming a serial killer. I'm going to kill you because of your sheer incompetence. Self-control isn't even an attribute in this game!" };
final Outcome[] A4Outcomes = { new Outcome(true, 5, 10, 10, -5, 10, 0), new Outcome(true, 0, 0, 0, 0, 0, 0),
null, null, null, null, null, null, null, null, new Outcome(false, -100, -100, -100, -100, -100, 0),
new Outcome(false, -1000, -1000, -1000, -1000, -1000, 0)
};
final Requirements[] A4reqs = { new Requirements(40, 30, 20, 20, 0), new Requirements(0, 0, 0, 0, 0) };
Choice choiceA4 = new Choice(A4printText, A4Story, A4reqs, A4Outcomes, p, 3, 30, 0, 0, 0, 0);
final String A5PrintText = "Kids? (yes/maybe/no)";
final String[] A5Story = {
"You've had a baby! prepare for the next 18 years well",
"Maybe? Well, I suppose I'll choose for you and give you a baby, you seem qualified enough. Your reluctance will not, however, go unpunished",
"I suppose having a kid isn't for everybody", null, null, null, null, null, null, null,
"You didn't manage to have a baby. You aren't very good at this, are you?",
"Maybe? You seem horribly unqualified to have a kid, so I'll spare the baby and not let you have one",
"You failed (somehow) at not having a kid, so you'll get one anyway" };
final Requirements[] A5Reqs = { new Requirements(5, 0, 5, 0, 0), new Requirements(5, 15, 10, 20, 0),
new Requirements(0, 0, 0, 0, 0) };
final Outcome[] A5Outcomes = { new Outcome(true, 5, 5, 5, -20, 5, 1), new Outcome(true, 5, 5, 5, -30, -10, 1),
new Outcome(true, 0, 0, 0, 0, 0, 1), null, null, null, null, null, null, null,
new Outcome(true, 0, 0, 0, -5, -15, 1), new Outcome(true, 0, 0, 0, 0, 0, 1),
new Outcome(true, -5, -5, -5, -40, -5, 1) };
Choice choiceA5 = new Choice(A5PrintText, A5Story, A5Reqs, A5Outcomes, p, 3, 0, 0, 0, 0, 0);
final String wpt1 = "After what has been an eternity of work and focus, it's time to retire. As you know, you're getting older. What will you focus on after retirement?\n1. Invest in stocks\n2. Expand your wisdom\n3. Go after younger women\n4. Relax and do what you want";
final String wpt2 = "You sit at your house and you realize there is yard work to be done outside, but due to your age, you're not sure if it would be best to do it yourself. What do you do?\n1. Hire gardener\n2. Take advantage of 'slave labor' by paying the neighborhood kid 1 cent per weed he picks\n3. Go out and try to do it yourself\n4. Put off the yard work ";
final String wpt3 = "Time to update your will. Who do you leave your most prized possesions and fortunes to?\n1. Your family\n2. Your mistress\n3. Charity\n4. Dedicate your net worth to maintaining your legacy.";
final String wpt4 = "Your family wants you to move into a nursing home. How do you respond?\n1. Move into the nursing home\n2. Move to a tropical island paradise \n3. Refuse to move into the nursing home and stay in your house\n4. Force your family to let you stay with them";
final String wpt5 = "Your doctor tells you that you are on the verge of death. What is the last thing you decide to do before you die?\n1. Go on the vacation of a lifetime\n2. Climb Mount Everest\n3. Solidify your legacy\n4. Relax and wait to die in peace with the Wu Wei wisdom you have gained through a lifetime of experience";
final String[] wsl1 = { "You succesfully invest in stocks. You make bank.",
"You successfully expand your wisdom. You are now a wise old man.",
"You successfully go after younger women. Even in your later days, you can sure still pull.",
"You decide to relax and do nothing. Wu Wei.", null, null, null, null, null, null,
"You fail investing in stocks, and lose a substantial amount of your money.",
"You fail to expand your wisdom. Seems like your intelligence will not make great gains.",
"You fail to get any younger women. Maybe your pickup lines threw them off.",
"You cannot relax. Maybe you should try meditation." };
final Outcome[] wo1 = { new Outcome(true, 2, 2, 0, 20, 10, 0), new Outcome(true, 2, 20, 0, 2, 10, 0),
new Outcome(true, 20, 0, 5, 5, 20, 0), new Outcome(true, 20, 0, 20, 0, 20, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr1 = { new Requirements(0, 15, 0, 15, 15), new Requirements(0, 15, 0, 5, 15),
new Requirements(15, 5, 15, 15, 20), new Requirements(0, 0, 15, 0, 20), };
Choice wc1 = new Choice(wpt1, wsl1, wr1, wo1, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl2 = {
"You hire a gardener, and he takes care of your yard problem. Smart move.",
"You exploitative old man. Way to take advantage of the youth. Nonetheless, the yard work is done.",
"You go outside and get the yard work done. Your health is impressive at your age.",
"You put off the yard work. The yard work remains unfinished, but at least you don't have to spend money.",
null,
null,
null,
null,
null,
null,
"You can't hire a good gardenenr, and thus your yard remains unkempt",
"You can't seem to hire a young man to do your yard work. Maybe they are afraid of you.",
"Why did you try that? You know your health isn't what it used to be. The yard work is not ever finished.",
"You put off the yard work. The yard work remains unfinished, but at least you don't have to spend money." };
final Outcome[] wo2 = { new Outcome(true, 0, 5, 10, -1, 10, 0), new Outcome(true, 10, 15, 10, 5, 15, 0),
new Outcome(true, 5, 5, 0, 10, 20, 0), new Outcome(true, 0, 0, 10, 10, 0, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr2 = { new Requirements(5, 0, 0, 15, 10), new Requirements(10, 10, 0, 10, 20),
new Requirements(0, 0, 35, 0, 25), new Requirements(0, 0, 0, 0, 15), };
Choice wc2 = new Choice(wpt2, wsl2, wr2, wo2, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl3 = {
"You leave your most important possesions to your family. You are quite the family man.",
"You leave your estate to your mistress. If your wife outlives you, you can only imagine what she would say.",
"You leave your fortune to charity. You are quite the philanthropist.",
"You set up a fund to create giant statues and public services in your name. You shall be remembered forever.",
null,
null,
null,
null,
null,
null,
"Your ego prevents you from leaving your possesions to your family. You should feel ashamed.",
"You fail to leave your estate to your mistress, and are caught by your wife. You get divorced.",
"You wouldn't really do that? Let's be honest. Better keep all that money away from those money grabbing idiots.",
"Come on? We both know you wouldn't do that. That's not in your capacity." };
final Outcome[] wo3 = { new Outcome(true, 10, 0, 0, 10, 0, 0), new Outcome(true, 5, 0, 0, 0, 15, 0),
new Outcome(true, 15, 0, 0, 15, 0, 0), new Outcome(true, 15, 0, 0, 5, 20, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr3 = { new Requirements(10, 15, 0, 0, 10), new Requirements(25, 0, 0, 0, 25),
new Requirements(15, 0, 0, 5, 10), new Requirements(30, 0, 0, 30, 30), };
Choice wc3 = new Choice(wpt3, wsl3, wr3, wo3, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl4 = {
"You move into the nursing home without complaint. You agree with your family that it is best.",
"You offer a better idea and buy a remote island tropical paradise. Sounds nice.",
"You successfully stay in your home by putting your family off.",
"You come up with an idea that makes your family wish they never even suggested you move in to the nursing home. You move into your younger family's home tomorrow.",
null,
null,
null,
null,
null,
null,
"You can't move into the nursing home. Even though you want it, you know it just won't work.",
"Really? Since when could you afford a tropical island home?",
"You fail to stay in your home, and your family is insistent. You are forced to go to the nursing home.",
"Your family does not let that happen, and you are not insistent enough. You go to the nursing home." };
final Outcome[] wo4 = { new Outcome(true, 10, 0, 0, 10, 5, 0), new Outcome(true, 10, 0, 5, 0, 20, 0),
new Outcome(true, 10, 0, 0, 10, 10, 0), new Outcome(true, 10, 0, 0, 15, 10, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr4 = { new Requirements(0, 0, 0, 0, 0), new Requirements(10, 0, 20, 40, 25),
new Requirements(10, 10, 15, 15, 15), new Requirements(15, 15, 10, 0, 20), };
Choice wc4 = new Choice(wpt4, wsl4, wr4, wo4, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl5 = {
"You go on the vacation of your dreams. You die in peace, sleeping on the beach.",
"You begin to climb Mount Everest, and as you reach your arms into the sky at the top of the mountain, you die in complete ecstacy.",
"You succesfully solidify your legacy. Your dead body is coated in gold and made into a statue at the center of your home town.",
"You die without desire in your mind, and with wisdom in your mind. Peace eternalizes you, and you are reincarnated.",
null,
null,
null,
null,
null,
null,
"You can't afford the tropical island vacation, and you die in a hospital from a heart attack.",
"Your health is definitely not up for that, and you die a painful and slow death of an unusual disease you catch traveling to the mountain.",
"You fail to solidify your legacy, and die as an unknown man with little money and few friends.",
"You have not embraced Wu Wei, and you die a life of eternal suffering and dispair." };
final Outcome[] wo5 = { new Outcome(false, 20, 0, 15, 15, 30, 0), new Outcome(false, 20, 0, 25, 0, 25, 0),
new Outcome(false, 45, 0, 0, 0, 45, 0), new Outcome(false, 30, 70, 0, 0, 25, 0), null, null, null,
null, null, null, new Outcome(false, -1, -1, -1, -1, -1, 0), new Outcome(false, -1, -1, -1, -1, -1, 0),
new Outcome(false, -1, -1, -1, -1, -1, 0), new Outcome(false, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr5 = { new Requirements(20, 0, 30, 30, 30), new Requirements(15, 0, 40, 20, 30),
new Requirements(40, 0, 0, 30, 35), new Requirements(15, 40, 0, 0, 0), };
Choice wc5 = new Choice(wpt5, wsl5, wr5, wo5, p, p.getAge(), 0, 0, 0, 0, 0);
choices.add(hc1);
choices.add(hc2);
choices.add(hc3);
choices.add(hc4);
choices.add(hc5);
choices.add(c1);
choices.add(c2);
choices.add(c3);
choices.add(c4);
choices.add(c5);
choices.add(choiceA1);
choices.add(choiceA2);
choices.add(choiceA3);
choices.add(choiceA4);
choices.add(choiceA5);
choices.add(wc1);
choices.add(wc2);
choices.add(wc3);
choices.add(wc4);
choices.add(wc5);
}
/**
* returns a boolean that is true if the person's attributes satisfy all of
* the requirements for the choice c
*
* @param p
* @param c
* @return whether or not the person p is qualified for choice c
*/
private boolean isQualified(Person p, Choice c) {
if (!(p.getCharisma() >= c.getCharismaReq())) {
return false;
} else if (!(p.getConfidence() >= c.getConfindenceReq())) {
return false;
} else if (!(p.getIntelligence() >= c.getIntelligenceReq())) {
return false;
} else if (!(p.getStrength() >= c.getStrengthReq())) {
return false;
} else if (!(p.getWealth() >= c.getWealthReq())) {
return false;
}
return true;
}
/**
* @param p
* A person object
*
* @return A choice that the person is qualified for
*/
/**
* @param p
* @return
*/
public Choice getNextChoice(Person p) {
Choice selectedChoice = choices.get(++currentChoice);
boolean qualified = false;
while (!qualified) {
if (this.isQualified(p, selectedChoice)) {
qualified = true;
} else {
selectedChoice = choices.get(currentChoice + 1);
}
}
return selectedChoice;
}
}
| true | true | public ChoiceStorage(Person p) {
// Choice1
final Requirements hr1[] = { new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0) };
final String[] hc1Story = new String[] {
"You leave the object alone! \nBad call on your part you have missed out on a very valuble childhood experience. \nYou should explore more in coming ages.",
"You are clearly going to grow up to be very self concious and closed off.\nYour choice to not only miss out on a very important experience but to also cry leaves everyone concerned about your outgoingness.",
"GREAT! You have just found the object you will call BaBa for the rest of your life. \nYou are showing not only the first signs of motion but also outgoingness and bravery to grab an unknown object.\nWhen you grab the object you hear beads rattle and you vigoursly shake.\nYour parents walk in and smile.",
"Your attempts to do something are amusing and you start to giggle.\n Your parents walk in and smile. You have just found a great skill in life...Being a goof.",
"Great! You have just found the object you will call MeMe for the rest of your life. \nYou are showing the first signs of motion and your ability to start shaking the object shows intelligence and gives you a new passion...Weightlifting" };
final Outcome[] houtcomeLineC1 = new Outcome[] { new Outcome(true, 0, 0, 0, 0, -3, 0),
new Outcome(true, 0, -2, 0, 0, -4, 0), new Outcome(true, 0, 0, 2, 0, 3, 0),
new Outcome(true, 5, 0, 0, 0, 2, 0), new Outcome(true, 0, 0, 6, 0, 2, 0) };
final Choice hc1 = new Choice(
"When you are born you see an object in the distance what do you do? \n1. Leave the object alone \n2.Leave the object and cry \n3. Crawl over to the object and grab it \n4.Flail misserably\5.Crawl over to the object and shake it up and down.",
hc1Story, hr1, houtcomeLineC1, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice2
final String[] hc2Story = new String[] {
"Your confidence and charisma have impressed your peers. \nYou are immensily successful and have just found some bros for life! \nYou will surely reap the benefits of being one of the cool kids later in life...Keep it up.",
"Ohhhh so your one of THOSE kids...",
"Your dedication to academia is quite apparant.\nKeep it up so your life can go further",
"Your leadership has united this band of misfits! \nThese are some friends you will keep forever", "",
"", "", "", "", "",
"Your peers think your statement is ingenuine and your not bro enough. 'Leave GDI'. You have failed" };
final Outcome[] houtcomeLineC2 = new Outcome[] { new Outcome(true, 3, 0, 0, 2, 6, 0),
new Outcome(true, 2, -5, 0, 0, 0, 0), new Outcome(true, 0, 6, 0, 0, -2, 0),
new Outcome(true, 4, 0, 0, 0, 2, 0), null, null, null, null, null, null,
new Outcome(true, -1, 0, 0, 0, -2, 0) };
final Requirements hr2[] = { new Requirements(2, 0, 0, 0, 5), new Requirements(-1, -1, -1, -1, -1),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Choice hc2 = new Choice(
"You are now away from being in the isolated haven now known as 'Home' and you are entering a new place your parents call 'School'. \nWhen you enter this weird place you see kids like yourself running around. \nConfused by everything happening what do you do? \n1.Approach some of the boys that are playing blocks with eachother and say 'What up bros' .\n2.Sit in the corner and sniff and eat glue \n3.Go pick up a book and start looking at pictures. \n4.Approach one of the kids that are playing by themselves.",
hc2Story, hr2, houtcomeLineC2, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice3
final String[] hc3Story = new String[] {
"Your dedication to academia is apparaent. \nYour teacher loves you and you feel your brain growing",
"You and your bros go outside hit on some ladies and P some Ls. \nYou kids are clearly the kings of the castle keep it up",
"You again.....",
"You guys play some tag and hide and go seek keep growing with your peers." };
final Outcome[] outcomeLineC3 = new Outcome[] { new Outcome(true, 3, 0, 0, 0, 9, 0),
new Outcome(true, 2, -5, 0, 0, 0, 0), new Outcome(true, 0, 5, 0, 0, -2, 0),
new Outcome(true, 4, 0, 0, 0, 2, 0), null, null, null, null, null, null,
new Outcome(true, -3, 0, 0, 0, -2, 0) };
final Requirements hr3[] = { new Requirements(4, 0, 0, 0, 11), new Requirements(-1, -1, -1, -1, -1),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Choice hc3 = new Choice(
"Your teacher says 'Recess' and all the kids go outside what do you do? \n1.Stay indoors and read. \n2.Go outside with your bros and kick it. \n3.Stay indoors and sniff glue. \n4.Go outside and play with random kids.",
hc3Story, hr3, outcomeLineC3, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice4
final String[] hc4Story = new String[] {
"Your pretty much the Cleaver family. \nYou have family dinners and movie nights on the weekend, your parents grant you a ton of responsility and push you to new heights",
"Wow your personality is really showing now... needless to say your life is pretty boring",
"Your parents hate you but the kids respect you. You snek out on the reg with the rest of your boys teepeing and smoking tea. You and your boys are the talk of the town, boys want to be you and girls want their nap mat next to yours. lets just hope your parents wont retaliate that much.",
"Good choice bro. Your birthdays are filled with Vinard Vines boxes and Brookes Brothers bags. Your country club lifestyle has made you the talk of the school. THe boys want to be you and the girls want their nap mat next to you. May your croakies hang with pride...",
"",
"",
"",
"",
"",
"",
"",
"",
"HAHA you think YOU could be a rebel?? Your parents laugh and joke about your 'phases' and the kids around school think your more of a tool than you already are.",
"Although your intentions shape what you will strive for in your life...your family's wealth is no where near that level." };
// boolean alive, int charisma, int intelligence, int strength, int
// wealth,
// int confidence, int age)
final Outcome[] houtcomeLineC4 = new Outcome[] { new Outcome(true, 5, 1, 0, 0, 2, 0),
new Outcome(true, -2, 5, -1, 0, -2, 0), new Outcome(true, 3, -2, 0, -1, 5, 0),
new Outcome(true, 3, 0, 0, 2, 6, 0), null, null, null, null, null, null, null, null,
new Outcome(true, 0, 0, 0, 0, -5, 0), new Outcome(true, 2, 0, 0, 0, 1, 0) };
// int charisma, int intelligence, int strength, int wealth, int
// confidence
final Requirements hr4[] = { new Requirements(0, 0, 0, 0, 0), new Requirements(-1, -1, -1, -1, -1),
new Requirements(0, 0, 0, 0, 5), new Requirements(0, 0, 0, 5, 0), };
final Choice hc4 = new Choice(
"You have come of age to choose what your family life will be like. \n1.Be a happy content boy that always does what their parents say. \n2.Stay in your room and study and obey your parents whenever. \n3.Your a rebel...Enough said. \n4.You follow in the excessive and bourgeois lifestyle of your parents",
hc4Story, hr4, houtcomeLineC4, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice5
final String[] hc5Story = new String[] {
"As you approach the shorts you can hear your destiny calling...Your choice is the generic.",
"As you approach the shorts you can hear your destiny calling...Your one of the cool kids.",
"As you approach the shorts you can hear your destiny calling...You are a prep master, born to join a frat.",
"As you approach the shorts you can hear your destiny calling...You are an artsy hipster.",
"As you approach the shorts you can hear your destiny calling...You are a happy hippie." };
// boolean alive, int charisma, int intelligence, int strength, int
// wealth,
// int confidence, int age)
final Outcome[] houtcomeLineC5 = new Outcome[] { new Outcome(true, 3, 2, 0, 0, 2, 1),
new Outcome(true, 3, 0, 0, 0, 5, 0), new Outcome(true, 3, 0, 0, 1, 5, 0),
new Outcome(true, 4, 3, 0, 0, 0, 0), new Outcome(true, 6, 0, 0, 0, 0, 0) };
final Requirements hr5[] = { new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Choice hc5 = new Choice(
"Now here is the BIG decision...\nYour parents have finally have decided to let you choose your pants...\n(Be Careful and wise this pretty much determines the game).\n1.Choose cargo shorts.\n2.Choose jeans.\n3.Choose Nantucket Reds\4.Cordaroy Overalls.\n5.Tie Die Shorts.",
hc5Story, hr5, houtcomeLineC5, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// ///////// Constructs the Prompts ///////////
final String pt1 = "Welcome to your first day of highschool! Today you get to decide how you want to act.\n1: Become a sports jock.\n2: Hang with the popular crowd.\n3: Study for your classes.\n4: Do nothing";
final String pt2 = "You get invited to a party. Everyone seems to be having fun. Drugs and alcohol are present.\n1: Get drunk and go crazy\n2: Drive your drunk friend home\n3: Socialize\n4: Stare at your phone";
final String pt3 = "It is the day before finals. The year is almost over and summer is within your reach. Do you: \n1: Spend your time studying for your tests.\n2: Hang out with your friends and cram the morning of the test.\n3: Don't study and try to cheat off of someone else.\n4: Just kinda chill.";
final String pt4 = "It is senior year and about time you made up your mind about College. Let's apply! \n1: You apply to schools with Division A Lax teams. \n2: You apply to law school. \n3: You apply to the best engineering schools in the country. \n4: You decide maybe college isn't your thing.";
final String pt5 = "It's time to find a full-time job. \n1: Get a job. \n2: Go back to live at your parents' house.";
// ///////// Constructs the outcome string arrays ///////////
final String[] sl1 = {
"You get recruited by the Lax team because of your sick Lax skills. Lax.",
"You meet some new friends. Everyone seems to want to sit next to you at lunch.",
"You hit the books. Your grades stay steady and the teachers seem to enjoy your participation in class.",
"You just kinda coast along. Nobody seems to know a whole lot about you.", null, "You win", null, null,
null, null, "The bros stare at you blankly. You really thought you could lax with them?",
"It's obvious to them that you aren't that cool.",
"You lose concentration while trying to study. Maybe you have ADHD?", "Error 808: you suck." };
final String[] sl2 = {
"You wake up on a park bench in the next town over wearing a traffic cone as hat.",
"The next day, your friend thanks you profusely for your wise actions of the previous night.",
"You meet a girl named Maria and hit it off.",
"You stay in the corner and keep to yourself. No one seems to notice your presence.",
null,
null,
null,
null,
null,
null,
"You take one drink and throw up. You're not exactly the life of the party,",
"Your friend says he doesn't need any help. He gets in his car and crashes it into a tree almost immediately.",
"You can't talk over the music. You don't end up meeting anyone", "Error 808: you suck." };
final String[] sl3 = {
"After hours of studying you feel ready for your tests. You do well on all of them.",
"You don't do awesome on your tests, but you feel as though your friends appreciate your carefree style.",
"You do well on your tests: maybe a little too well. Nobody has proof of anything, but you lose the trust of those around you.",
"You do pretty average, although your not even sure your teachers know your name.", null, null, null,
null, null, null, "You fall asleep while studying. You don't do great on your tests",
"You fail your tests, and your friends think you should spend more time on your academics",
"You get caught! You get a zero on all of your tests", "Error 808: you suck." };
final String[] sl4 = { "You make it in to Lax U. Congratulations!",
"You make it in to Lawyer U. Congratulations!", "You make it in to Engineering U. Congratulations!",
"You take a job at McDoodles to make an income. Congratulations?", null, null, null, null, null, null,
"Your lax skills aren't quite up to snuff. You get rejected.",
"You aren't a great public speaker. You get rejected.",
"You aren't that great at math and science. You get rejected.", "Error 808: you suck." };
final String[] sl5 = { "Welcome to adulthood.", "Your parents aren't very happy about this.", null, null, null,
null, null, null, null, null, "You aren't qualified enough.", "Error 808: you suck." };
// ///////// Constructs outcomes and outcome arrays ///////////
final Outcome o1 = new Outcome(true, 2, -1, 5, 0, 5, 0);
final Outcome o2 = new Outcome(true, 5, -1, 0, 2, 5, 0);
final Outcome o3 = new Outcome(true, -1, 5, 0, 5, 2, 0);
final Outcome o4 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome owin = new Outcome(true, 100, 100, 100, 100, 100, 0);
final Outcome o1a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o2a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o3a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o4a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol1 = { o1, o2, o3, o4, null, owin, null, null, null, null, o1a, o2a, o3a, o4a };
final Outcome o5 = new Outcome(true, 7, -4, 4, -2, 7, 0);
final Outcome o6 = new Outcome(true, 3, 5, 0, 0, 4, 0);
final Outcome o7 = new Outcome(true, 6, 0, 0, -1, 7, 0);
final Outcome o8 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome o5a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o6a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o7a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o8a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol2 = { o5, o6, o7, o8, null, null, null, null, null, null, o5a, o6a, o7a, o8a };
final Outcome o9 = new Outcome(true, 0, 6, 0, 3, 3, 0);
final Outcome o10 = new Outcome(true, 6, 0, 3, 0, 3, 0);
final Outcome o11 = new Outcome(true, -2, 8, 0, -2, 8, 0);
final Outcome o12 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome o9a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o10a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o11a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o12a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol3 = { o9, o10, o11, o12, null, null, null, null, null, null, o9a, o10a, o11a, o12a };
final Outcome o13 = new Outcome(true, 2, -1, 5, 0, 5, 0);
final Outcome o14 = new Outcome(true, 5, -1, 0, 2, 5, 0);
final Outcome o15 = new Outcome(true, -1, 5, 0, 5, 2, 0);
final Outcome o16 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome o13a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o14a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o15a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o16a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol4 = { o13, o14, o15, o16, null, null, null, null, null, null, o13a, o14a, o15a, o16a };
final Outcome o17 = new Outcome(true, 2, 2, 2, 2, 2, 5);
final Outcome o18 = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome o17a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o18a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome[] ol5 = { o17, o18, null, null, null, null, null, null, null, null, o17a, o18a };
// ///////// Constructs requirements and requirement arrays ///////////
final Requirements r1 = new Requirements(2, 0, 2, 0, 2);
final Requirements r2 = new Requirements(2, 0, 0, 2, 2);
final Requirements r3 = new Requirements(1, 3, 0, 1, 1);
final Requirements r4 = new Requirements(0, 0, 0, 0, 0);
final Requirements rwin = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra1 = { r1, r2, r3, r4, null, rwin };
final Requirements r5 = new Requirements(6, 0, 0, 0, 6);
final Requirements r6 = new Requirements(2, 6, 2, 0, 2);
final Requirements r7 = new Requirements(6, 0, 0, 0, 6);
final Requirements r8 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra2 = { r5, r6, r7, r8 };
final Requirements r9 = new Requirements(0, 3, 0, 0, 0);
final Requirements r10 = new Requirements(1, 0, 0, 1, 1);
final Requirements r11 = new Requirements(0, 3, 0, 0, 3);
final Requirements r12 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra3 = { r9, r10, r11, r12 };
final Requirements r13 = new Requirements(0, 0, 10, 5, 5);
final Requirements r14 = new Requirements(10, 0, 0, 5, 5);
final Requirements r15 = new Requirements(0, 10, 0, 5, 5);
final Requirements r16 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra4 = { r13, r14, r15, r16 };
final Requirements r17 = new Requirements(2, 2, 2, 2, 2);
final Requirements r18 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra5 = { r17, r18, };
// ///////// Constructs the choices ///////////
Choice c1 = new Choice(pt1, sl1, ra1, ol1, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c2 = new Choice(pt2, sl2, ra2, ol2, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c3 = new Choice(pt3, sl3, ra3, ol3, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c4 = new Choice(pt4, sl4, ra4, ol4, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c5 = new Choice(pt5, sl5, ra5, ol5, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] A1Story = {
"You become a McDoodles worker",
"You become a mechanic",
"You become a sports star",
"You become an engineer",
"You become a CEO",
"You become a politician",
"DO NOT READ! in three days you will be kissed by the love of your life, but if you do not repost this to 5 other videos, you will be murdered in two days by a pack of wild puffins!",
null, null, null, "You fail to become a McDoodles worker. You may wish to reevaluate your life.",
"You fail to become a mechanic. Perhaps a lower-skill job would be better for you.",
"You fail to become a sports star. Try to get stronger.",
"You fail to become an engineer. You should work at McDoodles instead.", "You fail to become a CEO.",
"You fail to become a politician. You're not good enough at wooing voters." };
final Outcome[] A1Outcomes = { new Outcome(true, 0, 0, 0, 5, 1, 0), new Outcome(true, 0, 1, 1, 10, 3, 0),
new Outcome(true, 5, 0, 10, 20, 10, 0), new Outcome(true, 0, 15, 0, 15, 10, 0),
new Outcome(true, 5, 10, 0, 25, 7, 0), new Outcome(true, 10, 7, 0, 15, 10, 0),
new Outcome(true, 100, 100, 100, -100, 100, 100), null, null, null, null,
new Outcome(true, 0, 0, 0, 0, -20, 0), new Outcome(true, 0, 0, 0, 0, -10, 0),
new Outcome(true, 0, 0, 0, 0, -10, 0), new Outcome(true, 0, 0, 0, 0, -10, 0),
new Outcome(true, 0, 0, 0, 0, -10, 0), new Outcome(true, 0, 0, 0, 0, -10, 0)
};
Requirements[] A1reqs = { new Requirements(1, 1, 1, 1, 1), new Requirements(3, 20, 15, 5, 5),
new Requirements(20, 5, 30, 20, 10), new Requirements(10, 30, 5, 15, 10),
new Requirements(30, 20, 5, 10, 10), new Requirements(20, 30, 5, 20, 15),
new Requirements(0, 0, 0, 0, 0) };
Choice choiceA1 = new Choice(
"You decide to get a job. The choices are \n1: 'McDoodles worker'\n2: 'Mechanic'\n3: 'Sports Star'\n4: 'Engineer'\n5: 'CEO'\n6: or 'Politician'",
A1Story, A1reqs, A1Outcomes, p, 2, 0, 0, 0, 0, 0);
final String A2printText = "You are bored at home. You decide to do something. You can\n1: read a book\n2: work out, or \n3:go to a party";
final String[] A2Story = { "You decide to read a book. You are now more intelligent",
"You decide to work out. You are now stronger", "You decide to go to a party. Charisma goes up", null,
null, null, null, null, null, null, "You managed to fail at reading. Are you even literate?",
"You failed to work out. frynotsureifweakorstupid.jpg",
"You failed to go to a party. I've given up hope." };
final Requirements[] A2Reqs = { new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0) };
final Outcome[] A2Outcomes = { new Outcome(true, 0, 10, 0, 0, 0, 0), new Outcome(true, 0, 0, 10, 0, 0, 0),
new Outcome(true, 10, 0, 0, 0, 0, 0), null, null, null, null, null, null, null,
new Outcome(true, -5, -5, -5, -5, -5, 0), new Outcome(true, -5, -5, -5, -5, -5, 0),
new Outcome(true, -5, -5, -5, -5, -5, 0) };
Choice choiceA2 = new Choice(A2printText, A2Story, A2Reqs, A2Outcomes, p, 2, 0, 0, 0, 0, 0);
final String A3printText = "You are very lonely. Would you like to try to get married? (1 yes, 2 no)";
final String[] A3Story = {
"Congratulations! You managed to convince someone to spend their entire life with you! You are now married.",
"You decided that married life is not for you.",
"If this text is displayed, something is horribly wrong",
"Seriously, if you can see this, they're coming", "I'm not kidding. You'd better run",
"Seriously, RUN!", "Well clearly you're not listening to me",
"I'm going to sit tight while they eat you", "and I'm not going to feel any regret",
"Well, I guess this is a lost cause, bye",
"You failed to convince somebody to marry you. You must be ugly, poor, or both",
"How did you possibly fail at not getting married?! I'm ashamed of you."
};
final Requirements[] A3reqs = { new Requirements(30, 20, 15, 20, 25), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Outcome[] A3Outcomes = { new Outcome(true, 10, 0, 0, -10, 10, 0), new Outcome(true, 0, 0, 0, 0, 0, 0),
null, null, null, null, null, null, null, null, new Outcome(true, -5, 0, 0, 0, -20, 0),
new Outcome(true, -10, -10, -10, -10, -40, 0), };
Choice choiceA3 = new Choice(A3printText, A3Story, A3reqs, A3Outcomes, p, 3, 0, 0, 0, 0, 0);
final String A4printText = "You really hate people. You're so angry you consider becoming a serial killer. Would you like to become a serial killer?";
final String[] A4Story = {
"You succeed at becoming a serial killer, you monster",
"I suppose you don't have the killer instinct",
null,
null,
null,
null,
null,
null,
null,
null,
"At the house of your first hit, you are discovered, and the police are called. You are shot by the police and die.",
"I'm not sure how, but you managed to fail at not becoming a serial killer. I'm going to kill you because of your sheer incompetence. Self-control isn't even an attribute in this game!" };
final Outcome[] A4Outcomes = { new Outcome(true, 5, 10, 10, -5, 10, 0), new Outcome(true, 0, 0, 0, 0, 0, 0),
null, null, null, null, null, null, null, null, new Outcome(false, -100, -100, -100, -100, -100, 0),
new Outcome(false, -1000, -1000, -1000, -1000, -1000, 0)
};
final Requirements[] A4reqs = { new Requirements(40, 30, 20, 20, 0), new Requirements(0, 0, 0, 0, 0) };
Choice choiceA4 = new Choice(A4printText, A4Story, A4reqs, A4Outcomes, p, 3, 30, 0, 0, 0, 0);
final String A5PrintText = "Kids? (yes/maybe/no)";
final String[] A5Story = {
"You've had a baby! prepare for the next 18 years well",
"Maybe? Well, I suppose I'll choose for you and give you a baby, you seem qualified enough. Your reluctance will not, however, go unpunished",
"I suppose having a kid isn't for everybody", null, null, null, null, null, null, null,
"You didn't manage to have a baby. You aren't very good at this, are you?",
"Maybe? You seem horribly unqualified to have a kid, so I'll spare the baby and not let you have one",
"You failed (somehow) at not having a kid, so you'll get one anyway" };
final Requirements[] A5Reqs = { new Requirements(5, 0, 5, 0, 0), new Requirements(5, 15, 10, 20, 0),
new Requirements(0, 0, 0, 0, 0) };
final Outcome[] A5Outcomes = { new Outcome(true, 5, 5, 5, -20, 5, 1), new Outcome(true, 5, 5, 5, -30, -10, 1),
new Outcome(true, 0, 0, 0, 0, 0, 1), null, null, null, null, null, null, null,
new Outcome(true, 0, 0, 0, -5, -15, 1), new Outcome(true, 0, 0, 0, 0, 0, 1),
new Outcome(true, -5, -5, -5, -40, -5, 1) };
Choice choiceA5 = new Choice(A5PrintText, A5Story, A5Reqs, A5Outcomes, p, 3, 0, 0, 0, 0, 0);
final String wpt1 = "After what has been an eternity of work and focus, it's time to retire. As you know, you're getting older. What will you focus on after retirement?\n1. Invest in stocks\n2. Expand your wisdom\n3. Go after younger women\n4. Relax and do what you want";
final String wpt2 = "You sit at your house and you realize there is yard work to be done outside, but due to your age, you're not sure if it would be best to do it yourself. What do you do?\n1. Hire gardener\n2. Take advantage of 'slave labor' by paying the neighborhood kid 1 cent per weed he picks\n3. Go out and try to do it yourself\n4. Put off the yard work ";
final String wpt3 = "Time to update your will. Who do you leave your most prized possesions and fortunes to?\n1. Your family\n2. Your mistress\n3. Charity\n4. Dedicate your net worth to maintaining your legacy.";
final String wpt4 = "Your family wants you to move into a nursing home. How do you respond?\n1. Move into the nursing home\n2. Move to a tropical island paradise \n3. Refuse to move into the nursing home and stay in your house\n4. Force your family to let you stay with them";
final String wpt5 = "Your doctor tells you that you are on the verge of death. What is the last thing you decide to do before you die?\n1. Go on the vacation of a lifetime\n2. Climb Mount Everest\n3. Solidify your legacy\n4. Relax and wait to die in peace with the Wu Wei wisdom you have gained through a lifetime of experience";
final String[] wsl1 = { "You succesfully invest in stocks. You make bank.",
"You successfully expand your wisdom. You are now a wise old man.",
"You successfully go after younger women. Even in your later days, you can sure still pull.",
"You decide to relax and do nothing. Wu Wei.", null, null, null, null, null, null,
"You fail investing in stocks, and lose a substantial amount of your money.",
"You fail to expand your wisdom. Seems like your intelligence will not make great gains.",
"You fail to get any younger women. Maybe your pickup lines threw them off.",
"You cannot relax. Maybe you should try meditation." };
final Outcome[] wo1 = { new Outcome(true, 2, 2, 0, 20, 10, 0), new Outcome(true, 2, 20, 0, 2, 10, 0),
new Outcome(true, 20, 0, 5, 5, 20, 0), new Outcome(true, 20, 0, 20, 0, 20, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr1 = { new Requirements(0, 15, 0, 15, 15), new Requirements(0, 15, 0, 5, 15),
new Requirements(15, 5, 15, 15, 20), new Requirements(0, 0, 15, 0, 20), };
Choice wc1 = new Choice(wpt1, wsl1, wr1, wo1, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl2 = {
"You hire a gardener, and he takes care of your yard problem. Smart move.",
"You exploitative old man. Way to take advantage of the youth. Nonetheless, the yard work is done.",
"You go outside and get the yard work done. Your health is impressive at your age.",
"You put off the yard work. The yard work remains unfinished, but at least you don't have to spend money.",
null,
null,
null,
null,
null,
null,
"You can't hire a good gardenenr, and thus your yard remains unkempt",
"You can't seem to hire a young man to do your yard work. Maybe they are afraid of you.",
"Why did you try that? You know your health isn't what it used to be. The yard work is not ever finished.",
"You put off the yard work. The yard work remains unfinished, but at least you don't have to spend money." };
final Outcome[] wo2 = { new Outcome(true, 0, 5, 10, -1, 10, 0), new Outcome(true, 10, 15, 10, 5, 15, 0),
new Outcome(true, 5, 5, 0, 10, 20, 0), new Outcome(true, 0, 0, 10, 10, 0, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr2 = { new Requirements(5, 0, 0, 15, 10), new Requirements(10, 10, 0, 10, 20),
new Requirements(0, 0, 35, 0, 25), new Requirements(0, 0, 0, 0, 15), };
Choice wc2 = new Choice(wpt2, wsl2, wr2, wo2, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl3 = {
"You leave your most important possesions to your family. You are quite the family man.",
"You leave your estate to your mistress. If your wife outlives you, you can only imagine what she would say.",
"You leave your fortune to charity. You are quite the philanthropist.",
"You set up a fund to create giant statues and public services in your name. You shall be remembered forever.",
null,
null,
null,
null,
null,
null,
"Your ego prevents you from leaving your possesions to your family. You should feel ashamed.",
"You fail to leave your estate to your mistress, and are caught by your wife. You get divorced.",
"You wouldn't really do that? Let's be honest. Better keep all that money away from those money grabbing idiots.",
"Come on? We both know you wouldn't do that. That's not in your capacity." };
final Outcome[] wo3 = { new Outcome(true, 10, 0, 0, 10, 0, 0), new Outcome(true, 5, 0, 0, 0, 15, 0),
new Outcome(true, 15, 0, 0, 15, 0, 0), new Outcome(true, 15, 0, 0, 5, 20, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr3 = { new Requirements(10, 15, 0, 0, 10), new Requirements(25, 0, 0, 0, 25),
new Requirements(15, 0, 0, 5, 10), new Requirements(30, 0, 0, 30, 30), };
Choice wc3 = new Choice(wpt3, wsl3, wr3, wo3, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl4 = {
"You move into the nursing home without complaint. You agree with your family that it is best.",
"You offer a better idea and buy a remote island tropical paradise. Sounds nice.",
"You successfully stay in your home by putting your family off.",
"You come up with an idea that makes your family wish they never even suggested you move in to the nursing home. You move into your younger family's home tomorrow.",
null,
null,
null,
null,
null,
null,
"You can't move into the nursing home. Even though you want it, you know it just won't work.",
"Really? Since when could you afford a tropical island home?",
"You fail to stay in your home, and your family is insistent. You are forced to go to the nursing home.",
"Your family does not let that happen, and you are not insistent enough. You go to the nursing home." };
final Outcome[] wo4 = { new Outcome(true, 10, 0, 0, 10, 5, 0), new Outcome(true, 10, 0, 5, 0, 20, 0),
new Outcome(true, 10, 0, 0, 10, 10, 0), new Outcome(true, 10, 0, 0, 15, 10, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr4 = { new Requirements(0, 0, 0, 0, 0), new Requirements(10, 0, 20, 40, 25),
new Requirements(10, 10, 15, 15, 15), new Requirements(15, 15, 10, 0, 20), };
Choice wc4 = new Choice(wpt4, wsl4, wr4, wo4, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl5 = {
"You go on the vacation of your dreams. You die in peace, sleeping on the beach.",
"You begin to climb Mount Everest, and as you reach your arms into the sky at the top of the mountain, you die in complete ecstacy.",
"You succesfully solidify your legacy. Your dead body is coated in gold and made into a statue at the center of your home town.",
"You die without desire in your mind, and with wisdom in your mind. Peace eternalizes you, and you are reincarnated.",
null,
null,
null,
null,
null,
null,
"You can't afford the tropical island vacation, and you die in a hospital from a heart attack.",
"Your health is definitely not up for that, and you die a painful and slow death of an unusual disease you catch traveling to the mountain.",
"You fail to solidify your legacy, and die as an unknown man with little money and few friends.",
"You have not embraced Wu Wei, and you die a life of eternal suffering and dispair." };
final Outcome[] wo5 = { new Outcome(false, 20, 0, 15, 15, 30, 0), new Outcome(false, 20, 0, 25, 0, 25, 0),
new Outcome(false, 45, 0, 0, 0, 45, 0), new Outcome(false, 30, 70, 0, 0, 25, 0), null, null, null,
null, null, null, new Outcome(false, -1, -1, -1, -1, -1, 0), new Outcome(false, -1, -1, -1, -1, -1, 0),
new Outcome(false, -1, -1, -1, -1, -1, 0), new Outcome(false, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr5 = { new Requirements(20, 0, 30, 30, 30), new Requirements(15, 0, 40, 20, 30),
new Requirements(40, 0, 0, 30, 35), new Requirements(15, 40, 0, 0, 0), };
Choice wc5 = new Choice(wpt5, wsl5, wr5, wo5, p, p.getAge(), 0, 0, 0, 0, 0);
choices.add(hc1);
choices.add(hc2);
choices.add(hc3);
choices.add(hc4);
choices.add(hc5);
choices.add(c1);
choices.add(c2);
choices.add(c3);
choices.add(c4);
choices.add(c5);
choices.add(choiceA1);
choices.add(choiceA2);
choices.add(choiceA3);
choices.add(choiceA4);
choices.add(choiceA5);
choices.add(wc1);
choices.add(wc2);
choices.add(wc3);
choices.add(wc4);
choices.add(wc5);
}
| public ChoiceStorage(Person p) {
// Choice1
final Requirements hr1[] = { new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0) };
final String[] hc1Story = new String[] {
"You leave the object alone! \nBad call on your part you have missed out on a very valuble childhood experience. \nYou should explore more in coming ages.",
"You are clearly going to grow up to be very self concious and closed off.\nYour choice to not only miss out on a very important experience but to also cry leaves everyone concerned about your outgoingness.",
"GREAT! You have just found the object you will call BaBa for the rest of your life. \nYou are showing not only the first signs of motion but also outgoingness and bravery to grab an unknown object.\nWhen you grab the object you hear beads rattle and you vigoursly shake.\nYour parents walk in and smile.",
"Your attempts to do something are amusing and you start to giggle.\n Your parents walk in and smile. You have just found a great skill in life...Being a goof.",
"Great! You have just found the object you will call MeMe for the rest of your life. \nYou are showing the first signs of motion and your ability to start shaking the object shows intelligence and gives you a new passion...Weightlifting" };
final Outcome[] houtcomeLineC1 = new Outcome[] { new Outcome(true, 0, 0, 0, 0, -3, 0),
new Outcome(true, 0, -2, 0, 0, -4, 0), new Outcome(true, 0, 0, 2, 0, 3, 0),
new Outcome(true, 5, 0, 0, 0, 2, 0), new Outcome(true, 0, 0, 6, 0, 2, 0) };
final Choice hc1 = new Choice(
"When you are born you see an object in the distance what do you do? \n1. Leave the object alone \n2.Leave the object and cry \n3. Crawl over to the object and grab it \n4.Flail misserably\5.Crawl over to the object and shake it up and down.",
hc1Story, hr1, houtcomeLineC1, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice2
final String[] hc2Story = new String[] {
"Your confidence and charisma have impressed your peers. \nYou are immensily successful and have just found some bros for life! \nYou will surely reap the benefits of being one of the cool kids later in life...Keep it up.",
"Ohhhh so your one of THOSE kids...",
"Your dedication to academia is quite apparant.\nKeep it up so your life can go further",
"Your leadership has united this band of misfits! \nThese are some friends you will keep forever", "",
"", "", "", "", "",
"Your peers think your statement is ingenuine and your not bro enough. 'Leave GDI'. You have failed" };
final Outcome[] houtcomeLineC2 = new Outcome[] { new Outcome(true, 3, 0, 0, 2, 6, 0),
new Outcome(true, 2, -5, 0, 0, 0, 0), new Outcome(true, 0, 6, 0, 0, -2, 0),
new Outcome(true, 4, 0, 0, 0, 2, 0), null, null, null, null, null, null,
new Outcome(true, -1, 0, 0, 0, -2, 0) };
final Requirements hr2[] = { new Requirements(2, 0, 0, 0, 5), new Requirements(-1, -1, -1, -1, -1),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Choice hc2 = new Choice(
"You are now away from being in the isolated haven now known as 'Home' and you are entering a new place your parents call 'School'. \nWhen you enter this weird place you see kids like yourself running around. \nConfused by everything happening what do you do? \n1.Approach some of the boys that are playing blocks with eachother and say 'What up bros' .\n2.Sit in the corner and sniff and eat glue \n3.Go pick up a book and start looking at pictures. \n4.Approach one of the kids that are playing by themselves.",
hc2Story, hr2, houtcomeLineC2, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice3
final String[] hc3Story = new String[] {
"Your dedication to academia is apparaent. \nYour teacher loves you and you feel your brain growing",
"You and your bros go outside hit on some ladies and P some Ls. \nYou kids are clearly the kings of the castle keep it up",
"You again.....",
"You guys play some tag and hide and go seek keep growing with your peers." };
final Outcome[] outcomeLineC3 = new Outcome[] { new Outcome(true, 3, 0, 0, 0, 9, 0),
new Outcome(true, 2, -5, 0, 0, 0, 0), new Outcome(true, 0, 5, 0, 0, -2, 0),
new Outcome(true, 4, 0, 0, 0, 2, 0), null, null, null, null, null, null,
new Outcome(true, -3, 0, 0, 0, -2, 0) };
final Requirements hr3[] = { new Requirements(4, 0, 0, 0, 11), new Requirements(-1, -1, -1, -1, -1),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Choice hc3 = new Choice(
"Your teacher says 'Recess' and all the kids go outside what do you do? \n1.Stay indoors and read. \n2.Go outside with your bros and kick it. \n3.Stay indoors and sniff glue. \n4.Go outside and play with random kids.",
hc3Story, hr3, outcomeLineC3, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice4
final String[] hc4Story = new String[] {
"Your pretty much the Cleaver family. \nYou have family dinners and movie nights on the weekend, your parents grant you a ton of responsility and push you to new heights",
"Wow your personality is really showing now... needless to say your life is pretty boring",
"Your parents hate you but the kids respect you. You snek out on the reg with the rest of your boys teepeing and smoking tea. You and your boys are the talk of the town, boys want to be you and girls want their nap mat next to yours. lets just hope your parents wont retaliate that much.",
"Good choice bro. Your birthdays are filled with Vinard Vines boxes and Brookes Brothers bags. Your country club lifestyle has made you the talk of the school. THe boys want to be you and the girls want their nap mat next to you. May your croakies hang with pride...",
"",
"",
"",
"",
"",
"",
"",
"",
"HAHA you think YOU could be a rebel?? Your parents laugh and joke about your 'phases' and the kids around school think your more of a tool than you already are.",
"Although your intentions shape what you will strive for in your life...your family's wealth is no where near that level." };
// boolean alive, int charisma, int intelligence, int strength, int
// wealth,
// int confidence, int age)
final Outcome[] houtcomeLineC4 = new Outcome[] { new Outcome(true, 5, 1, 0, 0, 2, 0),
new Outcome(true, -2, 5, -1, 0, -2, 0), new Outcome(true, 3, -2, 0, -1, 5, 0),
new Outcome(true, 3, 0, 0, 2, 6, 0), null, null, null, null, null, null, null, null,
new Outcome(true, 0, 0, 0, 0, -5, 0), new Outcome(true, 2, 0, 0, 0, 1, 0) };
// int charisma, int intelligence, int strength, int wealth, int
// confidence
final Requirements hr4[] = { new Requirements(0, 0, 0, 0, 0), new Requirements(-1, -1, -1, -1, -1),
new Requirements(0, 0, 0, 0, 5), new Requirements(0, 0, 0, 5, 0), };
final Choice hc4 = new Choice(
"You have come of age to choose what your family life will be like. \n1.Be a happy content boy that always does what their parents say. \n2.Stay in your room and study and obey your parents whenever. \n3.Your a rebel...Enough said. \n4.You follow in the excessive and bourgeois lifestyle of your parents",
hc4Story, hr4, houtcomeLineC4, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// Choice5
final String[] hc5Story = new String[] {
"As you approach the shorts you can hear your destiny calling...Your choice is the generic.",
"As you approach the shorts you can hear your destiny calling...Your one of the cool kids.",
"As you approach the shorts you can hear your destiny calling...You are a prep master, born to join a frat.",
"As you approach the shorts you can hear your destiny calling...You are an artsy hipster.",
"As you approach the shorts you can hear your destiny calling...You are a happy hippie." };
// boolean alive, int charisma, int intelligence, int strength, int
// wealth,
// int confidence, int age)
final Outcome[] houtcomeLineC5 = new Outcome[] { new Outcome(true, 3, 2, 0, 0, 2, 1),
new Outcome(true, 3, 0, 0, 0, 5, 0), new Outcome(true, 3, 0, 0, 1, 5, 0),
new Outcome(true, 4, 3, 0, 0, 0, 0), new Outcome(true, 6, 0, 0, 0, 0, 0) };
final Requirements hr5[] = { new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Choice hc5 = new Choice(
"Now here is the BIG decision...\nYour parents have finally have decided to let you choose your pants...\n(Be Careful and wise this pretty much determines the game).\n1.Choose cargo shorts.\n2.Choose jeans.\n3.Choose Nantucket Reds\n4.Cordaroy Overalls.\n5.Tie Die Shorts.",
hc5Story, hr5, houtcomeLineC5, p, p.getAge(), p.getCharisma(), p.getIntelligence(), p.getStrength(), p
.getWealth(), p.getConfidence());
// ///////// Constructs the Prompts ///////////
final String pt1 = "Welcome to your first day of highschool! Today you get to decide how you want to act.\n1: Become a sports jock.\n2: Hang with the popular crowd.\n3: Study for your classes.\n4: Do nothing";
final String pt2 = "You get invited to a party. Everyone seems to be having fun. Drugs and alcohol are present.\n1: Get drunk and go crazy\n2: Drive your drunk friend home\n3: Socialize\n4: Stare at your phone";
final String pt3 = "It is the day before finals. The year is almost over and summer is within your reach. Do you: \n1: Spend your time studying for your tests.\n2: Hang out with your friends and cram the morning of the test.\n3: Don't study and try to cheat off of someone else.\n4: Just kinda chill.";
final String pt4 = "It is senior year and about time you made up your mind about College. Let's apply! \n1: You apply to schools with Division A Lax teams. \n2: You apply to law school. \n3: You apply to the best engineering schools in the country. \n4: You decide maybe college isn't your thing.";
final String pt5 = "It's time to find a full-time job. \n1: Get a job. \n2: Go back to live at your parents' house.";
// ///////// Constructs the outcome string arrays ///////////
final String[] sl1 = {
"You get recruited by the Lax team because of your sick Lax skills. Lax.",
"You meet some new friends. Everyone seems to want to sit next to you at lunch.",
"You hit the books. Your grades stay steady and the teachers seem to enjoy your participation in class.",
"You just kinda coast along. Nobody seems to know a whole lot about you.", null, "You win", null, null,
null, null, "The bros stare at you blankly. You really thought you could lax with them?",
"It's obvious to them that you aren't that cool.",
"You lose concentration while trying to study. Maybe you have ADHD?", "Error 808: you suck." };
final String[] sl2 = {
"You wake up on a park bench in the next town over wearing a traffic cone as hat.",
"The next day, your friend thanks you profusely for your wise actions of the previous night.",
"You meet a girl named Maria and hit it off.",
"You stay in the corner and keep to yourself. No one seems to notice your presence.",
null,
null,
null,
null,
null,
null,
"You take one drink and throw up. You're not exactly the life of the party,",
"Your friend says he doesn't need any help. He gets in his car and crashes it into a tree almost immediately.",
"You can't talk over the music. You don't end up meeting anyone", "Error 808: you suck." };
final String[] sl3 = {
"After hours of studying you feel ready for your tests. You do well on all of them.",
"You don't do awesome on your tests, but you feel as though your friends appreciate your carefree style.",
"You do well on your tests: maybe a little too well. Nobody has proof of anything, but you lose the trust of those around you.",
"You do pretty average, although your not even sure your teachers know your name.", null, null, null,
null, null, null, "You fall asleep while studying. You don't do great on your tests",
"You fail your tests, and your friends think you should spend more time on your academics",
"You get caught! You get a zero on all of your tests", "Error 808: you suck." };
final String[] sl4 = { "You make it in to Lax U. Congratulations!",
"You make it in to Lawyer U. Congratulations!", "You make it in to Engineering U. Congratulations!",
"You take a job at McDoodles to make an income. Congratulations?", null, null, null, null, null, null,
"Your lax skills aren't quite up to snuff. You get rejected.",
"You aren't a great public speaker. You get rejected.",
"You aren't that great at math and science. You get rejected.", "Error 808: you suck." };
final String[] sl5 = { "Welcome to adulthood.", "Your parents aren't very happy about this.", null, null, null,
null, null, null, null, null, "You aren't qualified enough.", "Error 808: you suck." };
// ///////// Constructs outcomes and outcome arrays ///////////
final Outcome o1 = new Outcome(true, 2, -1, 5, 0, 5, 0);
final Outcome o2 = new Outcome(true, 5, -1, 0, 2, 5, 0);
final Outcome o3 = new Outcome(true, -1, 5, 0, 5, 2, 0);
final Outcome o4 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome owin = new Outcome(true, 100, 100, 100, 100, 100, 0);
final Outcome o1a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o2a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o3a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o4a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol1 = { o1, o2, o3, o4, null, owin, null, null, null, null, o1a, o2a, o3a, o4a };
final Outcome o5 = new Outcome(true, 7, -4, 4, -2, 7, 0);
final Outcome o6 = new Outcome(true, 3, 5, 0, 0, 4, 0);
final Outcome o7 = new Outcome(true, 6, 0, 0, -1, 7, 0);
final Outcome o8 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome o5a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o6a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o7a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o8a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol2 = { o5, o6, o7, o8, null, null, null, null, null, null, o5a, o6a, o7a, o8a };
final Outcome o9 = new Outcome(true, 0, 6, 0, 3, 3, 0);
final Outcome o10 = new Outcome(true, 6, 0, 3, 0, 3, 0);
final Outcome o11 = new Outcome(true, -2, 8, 0, -2, 8, 0);
final Outcome o12 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome o9a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o10a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o11a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o12a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol3 = { o9, o10, o11, o12, null, null, null, null, null, null, o9a, o10a, o11a, o12a };
final Outcome o13 = new Outcome(true, 2, -1, 5, 0, 5, 0);
final Outcome o14 = new Outcome(true, 5, -1, 0, 2, 5, 0);
final Outcome o15 = new Outcome(true, -1, 5, 0, 5, 2, 0);
final Outcome o16 = new Outcome(true, 2, 2, 2, 2, 2, 0);
final Outcome o13a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o14a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o15a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o16a = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome[] ol4 = { o13, o14, o15, o16, null, null, null, null, null, null, o13a, o14a, o15a, o16a };
final Outcome o17 = new Outcome(true, 2, 2, 2, 2, 2, 5);
final Outcome o18 = new Outcome(true, 0, 0, 0, 0, 0, 0);
final Outcome o17a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome o18a = new Outcome(true, -1, -1, -1, -1, -1, 0);
final Outcome[] ol5 = { o17, o18, null, null, null, null, null, null, null, null, o17a, o18a };
// ///////// Constructs requirements and requirement arrays ///////////
final Requirements r1 = new Requirements(2, 0, 2, 0, 2);
final Requirements r2 = new Requirements(2, 0, 0, 2, 2);
final Requirements r3 = new Requirements(1, 3, 0, 1, 1);
final Requirements r4 = new Requirements(0, 0, 0, 0, 0);
final Requirements rwin = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra1 = { r1, r2, r3, r4, null, rwin };
final Requirements r5 = new Requirements(6, 0, 0, 0, 6);
final Requirements r6 = new Requirements(2, 6, 2, 0, 2);
final Requirements r7 = new Requirements(6, 0, 0, 0, 6);
final Requirements r8 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra2 = { r5, r6, r7, r8 };
final Requirements r9 = new Requirements(0, 3, 0, 0, 0);
final Requirements r10 = new Requirements(1, 0, 0, 1, 1);
final Requirements r11 = new Requirements(0, 3, 0, 0, 3);
final Requirements r12 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra3 = { r9, r10, r11, r12 };
final Requirements r13 = new Requirements(0, 0, 10, 5, 5);
final Requirements r14 = new Requirements(10, 0, 0, 5, 5);
final Requirements r15 = new Requirements(0, 10, 0, 5, 5);
final Requirements r16 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra4 = { r13, r14, r15, r16 };
final Requirements r17 = new Requirements(2, 2, 2, 2, 2);
final Requirements r18 = new Requirements(0, 0, 0, 0, 0);
final Requirements[] ra5 = { r17, r18, };
// ///////// Constructs the choices ///////////
Choice c1 = new Choice(pt1, sl1, ra1, ol1, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c2 = new Choice(pt2, sl2, ra2, ol2, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c3 = new Choice(pt3, sl3, ra3, ol3, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c4 = new Choice(pt4, sl4, ra4, ol4, p, p.getAge(), 0, 0, 0, 0, 0);
Choice c5 = new Choice(pt5, sl5, ra5, ol5, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] A1Story = {
"You become a McDoodles worker",
"You become a mechanic",
"You become a sports star",
"You become an engineer",
"You become a CEO",
"You become a politician",
"DO NOT READ! in three days you will be kissed by the love of your life, but if you do not repost this to 5 other videos, you will be murdered in two days by a pack of wild puffins!",
null, null, null, "You fail to become a McDoodles worker. You may wish to reevaluate your life.",
"You fail to become a mechanic. Perhaps a lower-skill job would be better for you.",
"You fail to become a sports star. Try to get stronger.",
"You fail to become an engineer. You should work at McDoodles instead.", "You fail to become a CEO.",
"You fail to become a politician. You're not good enough at wooing voters." };
final Outcome[] A1Outcomes = { new Outcome(true, 0, 0, 0, 5, 1, 0), new Outcome(true, 0, 1, 1, 10, 3, 0),
new Outcome(true, 5, 0, 10, 20, 10, 0), new Outcome(true, 0, 15, 0, 15, 10, 0),
new Outcome(true, 5, 10, 0, 25, 7, 0), new Outcome(true, 10, 7, 0, 15, 10, 0),
new Outcome(true, 100, 100, 100, -100, 100, 100), null, null, null, null,
new Outcome(true, 0, 0, 0, 0, -20, 0), new Outcome(true, 0, 0, 0, 0, -10, 0),
new Outcome(true, 0, 0, 0, 0, -10, 0), new Outcome(true, 0, 0, 0, 0, -10, 0),
new Outcome(true, 0, 0, 0, 0, -10, 0), new Outcome(true, 0, 0, 0, 0, -10, 0)
};
Requirements[] A1reqs = { new Requirements(1, 1, 1, 1, 1), new Requirements(3, 20, 15, 5, 5),
new Requirements(20, 5, 30, 20, 10), new Requirements(10, 30, 5, 15, 10),
new Requirements(30, 20, 5, 10, 10), new Requirements(20, 30, 5, 20, 15),
new Requirements(0, 0, 0, 0, 0) };
Choice choiceA1 = new Choice(
"You decide to get a job. The choices are \n1: 'McDoodles worker'\n2: 'Mechanic'\n3: 'Sports Star'\n4: 'Engineer'\n5: 'CEO'\n6: or 'Politician'",
A1Story, A1reqs, A1Outcomes, p, 2, 0, 0, 0, 0, 0);
final String A2printText = "You are bored at home. You decide to do something. You can\n1: read a book\n2: work out, or \n3:go to a party";
final String[] A2Story = { "You decide to read a book. You are now more intelligent",
"You decide to work out. You are now stronger", "You decide to go to a party. Charisma goes up", null,
null, null, null, null, null, null, "You managed to fail at reading. Are you even literate?",
"You failed to work out. frynotsureifweakorstupid.jpg",
"You failed to go to a party. I've given up hope." };
final Requirements[] A2Reqs = { new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0) };
final Outcome[] A2Outcomes = { new Outcome(true, 0, 10, 0, 0, 0, 0), new Outcome(true, 0, 0, 10, 0, 0, 0),
new Outcome(true, 10, 0, 0, 0, 0, 0), null, null, null, null, null, null, null,
new Outcome(true, -5, -5, -5, -5, -5, 0), new Outcome(true, -5, -5, -5, -5, -5, 0),
new Outcome(true, -5, -5, -5, -5, -5, 0) };
Choice choiceA2 = new Choice(A2printText, A2Story, A2Reqs, A2Outcomes, p, 2, 0, 0, 0, 0, 0);
final String A3printText = "You are very lonely. Would you like to try to get married? (1 yes, 2 no)";
final String[] A3Story = {
"Congratulations! You managed to convince someone to spend their entire life with you! You are now married.",
"You decided that married life is not for you.",
"If this text is displayed, something is horribly wrong",
"Seriously, if you can see this, they're coming", "I'm not kidding. You'd better run",
"Seriously, RUN!", "Well clearly you're not listening to me",
"I'm going to sit tight while they eat you", "and I'm not going to feel any regret",
"Well, I guess this is a lost cause, bye",
"You failed to convince somebody to marry you. You must be ugly, poor, or both",
"How did you possibly fail at not getting married?! I'm ashamed of you."
};
final Requirements[] A3reqs = { new Requirements(30, 20, 15, 20, 25), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0),
new Requirements(0, 0, 0, 0, 0), new Requirements(0, 0, 0, 0, 0), };
final Outcome[] A3Outcomes = { new Outcome(true, 10, 0, 0, -10, 10, 0), new Outcome(true, 0, 0, 0, 0, 0, 0),
null, null, null, null, null, null, null, null, new Outcome(true, -5, 0, 0, 0, -20, 0),
new Outcome(true, -10, -10, -10, -10, -40, 0), };
Choice choiceA3 = new Choice(A3printText, A3Story, A3reqs, A3Outcomes, p, 3, 0, 0, 0, 0, 0);
final String A4printText = "You really hate people. You're so angry you consider becoming a serial killer. Would you like to become a serial killer?";
final String[] A4Story = {
"You succeed at becoming a serial killer, you monster",
"I suppose you don't have the killer instinct",
null,
null,
null,
null,
null,
null,
null,
null,
"At the house of your first hit, you are discovered, and the police are called. You are shot by the police and die.",
"I'm not sure how, but you managed to fail at not becoming a serial killer. I'm going to kill you because of your sheer incompetence. Self-control isn't even an attribute in this game!" };
final Outcome[] A4Outcomes = { new Outcome(true, 5, 10, 10, -5, 10, 0), new Outcome(true, 0, 0, 0, 0, 0, 0),
null, null, null, null, null, null, null, null, new Outcome(false, -100, -100, -100, -100, -100, 0),
new Outcome(false, -1000, -1000, -1000, -1000, -1000, 0)
};
final Requirements[] A4reqs = { new Requirements(40, 30, 20, 20, 0), new Requirements(0, 0, 0, 0, 0) };
Choice choiceA4 = new Choice(A4printText, A4Story, A4reqs, A4Outcomes, p, 3, 30, 0, 0, 0, 0);
final String A5PrintText = "Kids? (yes/maybe/no)";
final String[] A5Story = {
"You've had a baby! prepare for the next 18 years well",
"Maybe? Well, I suppose I'll choose for you and give you a baby, you seem qualified enough. Your reluctance will not, however, go unpunished",
"I suppose having a kid isn't for everybody", null, null, null, null, null, null, null,
"You didn't manage to have a baby. You aren't very good at this, are you?",
"Maybe? You seem horribly unqualified to have a kid, so I'll spare the baby and not let you have one",
"You failed (somehow) at not having a kid, so you'll get one anyway" };
final Requirements[] A5Reqs = { new Requirements(5, 0, 5, 0, 0), new Requirements(5, 15, 10, 20, 0),
new Requirements(0, 0, 0, 0, 0) };
final Outcome[] A5Outcomes = { new Outcome(true, 5, 5, 5, -20, 5, 1), new Outcome(true, 5, 5, 5, -30, -10, 1),
new Outcome(true, 0, 0, 0, 0, 0, 1), null, null, null, null, null, null, null,
new Outcome(true, 0, 0, 0, -5, -15, 1), new Outcome(true, 0, 0, 0, 0, 0, 1),
new Outcome(true, -5, -5, -5, -40, -5, 1) };
Choice choiceA5 = new Choice(A5PrintText, A5Story, A5Reqs, A5Outcomes, p, 3, 0, 0, 0, 0, 0);
final String wpt1 = "After what has been an eternity of work and focus, it's time to retire. As you know, you're getting older. What will you focus on after retirement?\n1. Invest in stocks\n2. Expand your wisdom\n3. Go after younger women\n4. Relax and do what you want";
final String wpt2 = "You sit at your house and you realize there is yard work to be done outside, but due to your age, you're not sure if it would be best to do it yourself. What do you do?\n1. Hire gardener\n2. Take advantage of 'slave labor' by paying the neighborhood kid 1 cent per weed he picks\n3. Go out and try to do it yourself\n4. Put off the yard work ";
final String wpt3 = "Time to update your will. Who do you leave your most prized possesions and fortunes to?\n1. Your family\n2. Your mistress\n3. Charity\n4. Dedicate your net worth to maintaining your legacy.";
final String wpt4 = "Your family wants you to move into a nursing home. How do you respond?\n1. Move into the nursing home\n2. Move to a tropical island paradise \n3. Refuse to move into the nursing home and stay in your house\n4. Force your family to let you stay with them";
final String wpt5 = "Your doctor tells you that you are on the verge of death. What is the last thing you decide to do before you die?\n1. Go on the vacation of a lifetime\n2. Climb Mount Everest\n3. Solidify your legacy\n4. Relax and wait to die in peace with the Wu Wei wisdom you have gained through a lifetime of experience";
final String[] wsl1 = { "You succesfully invest in stocks. You make bank.",
"You successfully expand your wisdom. You are now a wise old man.",
"You successfully go after younger women. Even in your later days, you can sure still pull.",
"You decide to relax and do nothing. Wu Wei.", null, null, null, null, null, null,
"You fail investing in stocks, and lose a substantial amount of your money.",
"You fail to expand your wisdom. Seems like your intelligence will not make great gains.",
"You fail to get any younger women. Maybe your pickup lines threw them off.",
"You cannot relax. Maybe you should try meditation." };
final Outcome[] wo1 = { new Outcome(true, 2, 2, 0, 20, 10, 0), new Outcome(true, 2, 20, 0, 2, 10, 0),
new Outcome(true, 20, 0, 5, 5, 20, 0), new Outcome(true, 20, 0, 20, 0, 20, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr1 = { new Requirements(0, 15, 0, 15, 15), new Requirements(0, 15, 0, 5, 15),
new Requirements(15, 5, 15, 15, 20), new Requirements(0, 0, 15, 0, 20), };
Choice wc1 = new Choice(wpt1, wsl1, wr1, wo1, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl2 = {
"You hire a gardener, and he takes care of your yard problem. Smart move.",
"You exploitative old man. Way to take advantage of the youth. Nonetheless, the yard work is done.",
"You go outside and get the yard work done. Your health is impressive at your age.",
"You put off the yard work. The yard work remains unfinished, but at least you don't have to spend money.",
null,
null,
null,
null,
null,
null,
"You can't hire a good gardenenr, and thus your yard remains unkempt",
"You can't seem to hire a young man to do your yard work. Maybe they are afraid of you.",
"Why did you try that? You know your health isn't what it used to be. The yard work is not ever finished.",
"You put off the yard work. The yard work remains unfinished, but at least you don't have to spend money." };
final Outcome[] wo2 = { new Outcome(true, 0, 5, 10, -1, 10, 0), new Outcome(true, 10, 15, 10, 5, 15, 0),
new Outcome(true, 5, 5, 0, 10, 20, 0), new Outcome(true, 0, 0, 10, 10, 0, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr2 = { new Requirements(5, 0, 0, 15, 10), new Requirements(10, 10, 0, 10, 20),
new Requirements(0, 0, 35, 0, 25), new Requirements(0, 0, 0, 0, 15), };
Choice wc2 = new Choice(wpt2, wsl2, wr2, wo2, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl3 = {
"You leave your most important possesions to your family. You are quite the family man.",
"You leave your estate to your mistress. If your wife outlives you, you can only imagine what she would say.",
"You leave your fortune to charity. You are quite the philanthropist.",
"You set up a fund to create giant statues and public services in your name. You shall be remembered forever.",
null,
null,
null,
null,
null,
null,
"Your ego prevents you from leaving your possesions to your family. You should feel ashamed.",
"You fail to leave your estate to your mistress, and are caught by your wife. You get divorced.",
"You wouldn't really do that? Let's be honest. Better keep all that money away from those money grabbing idiots.",
"Come on? We both know you wouldn't do that. That's not in your capacity." };
final Outcome[] wo3 = { new Outcome(true, 10, 0, 0, 10, 0, 0), new Outcome(true, 5, 0, 0, 0, 15, 0),
new Outcome(true, 15, 0, 0, 15, 0, 0), new Outcome(true, 15, 0, 0, 5, 20, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr3 = { new Requirements(10, 15, 0, 0, 10), new Requirements(25, 0, 0, 0, 25),
new Requirements(15, 0, 0, 5, 10), new Requirements(30, 0, 0, 30, 30), };
Choice wc3 = new Choice(wpt3, wsl3, wr3, wo3, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl4 = {
"You move into the nursing home without complaint. You agree with your family that it is best.",
"You offer a better idea and buy a remote island tropical paradise. Sounds nice.",
"You successfully stay in your home by putting your family off.",
"You come up with an idea that makes your family wish they never even suggested you move in to the nursing home. You move into your younger family's home tomorrow.",
null,
null,
null,
null,
null,
null,
"You can't move into the nursing home. Even though you want it, you know it just won't work.",
"Really? Since when could you afford a tropical island home?",
"You fail to stay in your home, and your family is insistent. You are forced to go to the nursing home.",
"Your family does not let that happen, and you are not insistent enough. You go to the nursing home." };
final Outcome[] wo4 = { new Outcome(true, 10, 0, 0, 10, 5, 0), new Outcome(true, 10, 0, 5, 0, 20, 0),
new Outcome(true, 10, 0, 0, 10, 10, 0), new Outcome(true, 10, 0, 0, 15, 10, 0), null, null, null, null,
null, null, new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
new Outcome(true, -1, -1, -1, -1, -1, 0), new Outcome(true, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr4 = { new Requirements(0, 0, 0, 0, 0), new Requirements(10, 0, 20, 40, 25),
new Requirements(10, 10, 15, 15, 15), new Requirements(15, 15, 10, 0, 20), };
Choice wc4 = new Choice(wpt4, wsl4, wr4, wo4, p, p.getAge(), 0, 0, 0, 0, 0);
final String[] wsl5 = {
"You go on the vacation of your dreams. You die in peace, sleeping on the beach.",
"You begin to climb Mount Everest, and as you reach your arms into the sky at the top of the mountain, you die in complete ecstacy.",
"You succesfully solidify your legacy. Your dead body is coated in gold and made into a statue at the center of your home town.",
"You die without desire in your mind, and with wisdom in your mind. Peace eternalizes you, and you are reincarnated.",
null,
null,
null,
null,
null,
null,
"You can't afford the tropical island vacation, and you die in a hospital from a heart attack.",
"Your health is definitely not up for that, and you die a painful and slow death of an unusual disease you catch traveling to the mountain.",
"You fail to solidify your legacy, and die as an unknown man with little money and few friends.",
"You have not embraced Wu Wei, and you die a life of eternal suffering and dispair." };
final Outcome[] wo5 = { new Outcome(false, 20, 0, 15, 15, 30, 0), new Outcome(false, 20, 0, 25, 0, 25, 0),
new Outcome(false, 45, 0, 0, 0, 45, 0), new Outcome(false, 30, 70, 0, 0, 25, 0), null, null, null,
null, null, null, new Outcome(false, -1, -1, -1, -1, -1, 0), new Outcome(false, -1, -1, -1, -1, -1, 0),
new Outcome(false, -1, -1, -1, -1, -1, 0), new Outcome(false, -1, -1, -1, -1, -1, 0),
};
final Requirements[] wr5 = { new Requirements(20, 0, 30, 30, 30), new Requirements(15, 0, 40, 20, 30),
new Requirements(40, 0, 0, 30, 35), new Requirements(15, 40, 0, 0, 0), };
Choice wc5 = new Choice(wpt5, wsl5, wr5, wo5, p, p.getAge(), 0, 0, 0, 0, 0);
choices.add(hc1);
choices.add(hc2);
choices.add(hc3);
choices.add(hc4);
choices.add(hc5);
choices.add(c1);
choices.add(c2);
choices.add(c3);
choices.add(c4);
choices.add(c5);
choices.add(choiceA1);
choices.add(choiceA2);
choices.add(choiceA3);
choices.add(choiceA4);
choices.add(choiceA5);
choices.add(wc1);
choices.add(wc2);
choices.add(wc3);
choices.add(wc4);
choices.add(wc5);
}
|
diff --git a/strategoxt-java-backend/java/runtime/org/strategoxt/lang/compat/report_failure_compat_1_0.java b/strategoxt-java-backend/java/runtime/org/strategoxt/lang/compat/report_failure_compat_1_0.java
index ba863fcaa..8ba14d14a 100644
--- a/strategoxt-java-backend/java/runtime/org/strategoxt/lang/compat/report_failure_compat_1_0.java
+++ b/strategoxt-java-backend/java/runtime/org/strategoxt/lang/compat/report_failure_compat_1_0.java
@@ -1,93 +1,95 @@
package org.strategoxt.lang.compat;
import static org.spoofax.interpreter.core.Tools.*;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.strategoxt.lang.Context;
import org.strategoxt.lang.StrategoErrorExit;
import org.strategoxt.lang.StrategoExit;
import org.strategoxt.lang.Strategy;
import org.strategoxt.stratego_lib.log_0_2;
import org.strategoxt.stratego_lib.report_failure_1_0;
/**
* Overrides report-failure(s) to throw a proper StrategoErrorExit exception
* (used for with clause failures).
*
* @author Lennart Kats <lennart add lclnet.nl>
*/
public class report_failure_compat_1_0 extends report_failure_1_0 {
private static volatile boolean isInited;
private final report_failure_1_0 proceed = instance;
private final LogIntercept logIntercept = new LogIntercept();
public static void init() {
if (!isInited) {
report_failure_1_0.instance = new report_failure_compat_1_0();
isInited = true;
}
}
@Override
public IStrategoTerm invoke(Context context, IStrategoTerm current, Strategy s) {
synchronized (this) {
String[] trace = context.getTrace();
try {
logIntercept.proceed = log_0_2.instance;
logIntercept.enabled = true;
log_0_2.instance = logIntercept;
return proceed.invoke(context, current, s);
+ } catch (StrategoErrorExit e) {
+ throw new StrategoErrorExit(e.getMessage(), e.getTerm(), e);
} catch (StrategoExit e) {
IStrategoTerm message = logIntercept.lastMessage.get();
IStrategoTerm term = logIntercept.lastTerm.get();
context.setTrace(trace);
if (message != null && isTermString(message)) {
throw new StrategoErrorExit(asJavaString(message), term);
} else {
throw new StrategoExit(e);
}
} finally {
log_0_2.instance = logIntercept.proceed;
logIntercept.enabled = false;
}
}
}
/**
* Intercepts logging messages.
*/
private class LogIntercept extends log_0_2 {
log_0_2 proceed;
ThreadLocal<IStrategoTerm> lastTerm = new ThreadLocal<IStrategoTerm>();
ThreadLocal<IStrategoTerm> lastMessage = new ThreadLocal<IStrategoTerm>();
boolean enabled;
@Override
public IStrategoTerm invoke(Context context, IStrategoTerm current, IStrategoTerm level, IStrategoTerm message) {
if (enabled) {
synchronized (report_failure_compat_1_0.this) {
if (enabled) {
lastTerm.set(current);
lastMessage.set(message);
}
}
}
return proceed.invoke(context, current, level, message);
}
}
}
| true | true | public IStrategoTerm invoke(Context context, IStrategoTerm current, Strategy s) {
synchronized (this) {
String[] trace = context.getTrace();
try {
logIntercept.proceed = log_0_2.instance;
logIntercept.enabled = true;
log_0_2.instance = logIntercept;
return proceed.invoke(context, current, s);
} catch (StrategoExit e) {
IStrategoTerm message = logIntercept.lastMessage.get();
IStrategoTerm term = logIntercept.lastTerm.get();
context.setTrace(trace);
if (message != null && isTermString(message)) {
throw new StrategoErrorExit(asJavaString(message), term);
} else {
throw new StrategoExit(e);
}
} finally {
log_0_2.instance = logIntercept.proceed;
logIntercept.enabled = false;
}
}
}
| public IStrategoTerm invoke(Context context, IStrategoTerm current, Strategy s) {
synchronized (this) {
String[] trace = context.getTrace();
try {
logIntercept.proceed = log_0_2.instance;
logIntercept.enabled = true;
log_0_2.instance = logIntercept;
return proceed.invoke(context, current, s);
} catch (StrategoErrorExit e) {
throw new StrategoErrorExit(e.getMessage(), e.getTerm(), e);
} catch (StrategoExit e) {
IStrategoTerm message = logIntercept.lastMessage.get();
IStrategoTerm term = logIntercept.lastTerm.get();
context.setTrace(trace);
if (message != null && isTermString(message)) {
throw new StrategoErrorExit(asJavaString(message), term);
} else {
throw new StrategoExit(e);
}
} finally {
log_0_2.instance = logIntercept.proceed;
logIntercept.enabled = false;
}
}
}
|
diff --git a/javafxdoc/src/com/sun/tools/javafxdoc/Start.java b/javafxdoc/src/com/sun/tools/javafxdoc/Start.java
index d2119faf8..07158bccc 100644
--- a/javafxdoc/src/com/sun/tools/javafxdoc/Start.java
+++ b/javafxdoc/src/com/sun/tools/javafxdoc/Start.java
@@ -1,485 +1,490 @@
/*
* Copyright 2008-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code 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 code 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 in the LICENSE file that
* accompanied this code).
*
* 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.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafxdoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.main.CommandLine;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Options;
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javafx.code.JavafxFlags.*;
/**
* Main program of Javadoc.
* Previously named "Main".
*
* @since 1.2
* @author Robert Field
* @author Neal Gafter (rewrite)
*/
class Start {
/** Context for this invocation. */
private final Context context;
/**
* Name of the program
*/
private final String defaultDocletClassName;
private static final String javafxdocName = "javafxdoc";
private static final String standardDocletClassName =
"com.sun.tools.xmldoclet.XMLDoclet";
private ListBuffer<String[]> options = new ListBuffer<String[]>();
private ModifierFilter showAccess = null;
private long defaultFilter = PUBLIC | PROTECTED | PUBLIC_READ | PUBLIC_INIT;
private Messager messager;
String docLocale = "";
boolean breakiterator = false;
boolean quiet = false;
String encoding = null;
private DocletInvoker docletInvoker;
/* Treat warnings as errors. */
private boolean rejectWarnings = false;
Start(String programName,
PrintWriter errWriter,
PrintWriter warnWriter,
PrintWriter noticeWriter,
String defaultDocletClassName) {
context = new Context();
messager = new Messager(context, programName, errWriter, warnWriter, noticeWriter);
this.defaultDocletClassName = defaultDocletClassName;
}
Start(String programName, String defaultDocletClassName) {
context = new Context();
messager = new Messager(context, programName);
this.defaultDocletClassName = defaultDocletClassName;
}
Start(String programName) {
this(programName, standardDocletClassName);
}
Start() {
this(javafxdocName);
}
/**
* Usage
*/
private void usage() {
messager.notice("main.usage");
// let doclet print usage information (does nothing on error)
if (docletInvoker != null) {
docletInvoker.optionLength("-help");
}
}
/**
* Exit
*/
private void exit() {
messager.exit();
}
private static final String versionRBName =
"com.sun.tools.javafxdoc.resources.version";
private static ResourceBundle versionRB;
private static String version(String key) {
if (versionRB == null) {
try {
versionRB = ResourceBundle.getBundle(versionRBName);
} catch (MissingResourceException e) {
return "Error:" + e.getMessage() + " " +
System.getProperty("java.version");
}
}
try {
return versionRB.getString(key);
} catch (MissingResourceException e) {
return "Error:" + e.getMessage() + " " +
System.getProperty("java.version");
}
}
private void version(boolean fullversion) {
// TODO: for now send it to err.
System.err.print(javafxdocName + " ");
if (fullversion) {
System.err.println("full version \"" + version("full") + "\"");
} else {
System.err.println(version("release"));
}
}
/**
* Main program - external wrapper
*/
int begin(String argv[]) {
boolean failed = false;
try {
failed = !parseAndExecute(argv);
} catch(Messager.ExitJavadoc exc) {
// ignore, we just exit this way
} catch (OutOfMemoryError ee) {
messager.error("main.out.of.memory");
failed = true;
} catch (Error ee) {
ee.printStackTrace();
messager.error("main.fatal.error");
failed = true;
} catch (Exception ee) {
ee.printStackTrace();
messager.error("main.fatal.exception");
failed = true;
} finally {
messager.exitNotice();
messager.flush();
}
failed |= messager.nerrors() > 0;
failed |= rejectWarnings && messager.nwarnings() > 0;
return failed ? 1 : 0;
}
private void addToList(ListBuffer<String> list, String str){
StringTokenizer st = new StringTokenizer(str, ":");
String current;
while(st.hasMoreTokens()){
current = st.nextToken();
list.append(current);
}
}
/**
* Main program - internal
*/
private boolean parseAndExecute(String argv[]) throws IOException {
long tm = System.currentTimeMillis();
ListBuffer<String> javaNames = new ListBuffer<String>();
// Preprocess @file arguments
try {
argv = CommandLine.parse(argv);
} catch (FileNotFoundException e) {
messager.error("main.cant.read", e.getMessage());
exit();
} catch (IOException e) {
e.printStackTrace();
exit();
}
setDocletInvoker(argv);
ListBuffer<String> subPackages = new ListBuffer<String>();
ListBuffer<String> excludedPackages = new ListBuffer<String>();
Options compOpts = Options.instance(context);
boolean docClasses = false;
+ boolean versionOption = false;
// Parse arguments
for (int i = 0 ; i < argv.length ; i++) {
String arg = argv[i];
if (arg.equals("-subpackages")) {
oneArg(argv, i++);
addToList(subPackages, argv[i]);
} else if (arg.equals("-exclude")){
oneArg(argv, i++);
addToList(excludedPackages, argv[i]);
} else if (arg.equals("-verbose")) {
setOption(arg);
compOpts.put("-verbose", "");
} else if (arg.equals("-encoding")) {
oneArg(argv, i++);
encoding = argv[i];
compOpts.put("-encoding", argv[i]);
} else if (arg.equals("-breakiterator")) {
breakiterator = true;
setOption("-breakiterator");
} else if (arg.equals("-quiet")) {
quiet = true;
setOption("-quiet");
} else if (arg.equals("-help")) {
usage();
exit();
} else if (arg.equals("-Xclasses")) {
setOption(arg);
docClasses = true;
} else if (arg.equals("-Xwerror")) {
setOption(arg);
rejectWarnings = true;
} else if (arg.equals("-private")) {
setOption(arg);
setFilter(ModifierFilter.ALL_ACCESS);
} else if (arg.equals("-package")) {
setOption(arg);
setFilter(PUBLIC | PROTECTED | PUBLIC_READ | PUBLIC_INIT | PACKAGE_ACCESS );
} else if (arg.equals("-protected")) {
setOption(arg);
setFilter(PUBLIC | PROTECTED | PUBLIC_READ | PUBLIC_INIT );
} else if (arg.equals("-public")) {
setOption(arg);
setFilter(PUBLIC | PUBLIC_READ | PUBLIC_INIT);
} else if (arg.equals("-source")) {
oneArg(argv, i++);
if (compOpts.get("-source") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-source", argv[i]);
} else if (arg.equals("-prompt")) {
compOpts.put("-prompt", "-prompt");
messager.promptOnError = true;
} else if (arg.equals("-sourcepath")) {
oneArg(argv, i++);
if (compOpts.get("-sourcepath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-sourcepath", argv[i]);
} else if (arg.equals("-classpath")) {
oneArg(argv, i++);
if (compOpts.get("-classpath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-classpath", argv[i]);
} else if (arg.equals("-sysclasspath")) {
oneArg(argv, i++);
if (compOpts.get("-bootclasspath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-bootclasspath", argv[i]);
} else if (arg.equals("-bootclasspath")) {
oneArg(argv, i++);
if (compOpts.get("-bootclasspath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-bootclasspath", argv[i]);
} else if (arg.equals("-extdirs")) {
oneArg(argv, i++);
if (compOpts.get("-extdirs") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-extdirs", argv[i]);
} else if (arg.equals("-overview")) {
oneArg(argv, i++);
} else if (arg.equals("-doclet")) {
i++; // handled in setDocletInvoker
} else if (arg.equals("-docletpath")) {
i++; // handled in setDocletInvoker
} else if (arg.equals("-locale")) {
if (i != 0)
usageError("main.locale_first");
oneArg(argv, i++);
docLocale = argv[i];
} else if (arg.startsWith("-XD")) {
String s = arg.substring("-XD".length());
int eq = s.indexOf('=');
String key = (eq < 0) ? s : s.substring(0, eq);
String value = (eq < 0) ? s : s.substring(eq+1);
compOpts.put(key, value);
} else if (arg.startsWith("-version")) {
+ versionOption = true;
version(false);
- exit();
} else if (arg.startsWith("-fullversion")) {
+ versionOption = true;
version(true);
- exit();
}
// call doclet for its options
// other arg starts with - is invalid
else if ( arg.startsWith("-") ) {
int optionLength;
optionLength = docletInvoker.optionLength(arg);
if (optionLength < 0) {
// error already displayed
exit();
} else if (optionLength == 0) {
// option not found
usageError("main.invalid_flag", arg);
} else {
// doclet added option
if ((i + optionLength) > argv.length) {
usageError("main.requires_argument", arg);
}
ListBuffer<String> args = new ListBuffer<String>();
for (int j = 0; j < optionLength-1; ++j) {
args.append(argv[++i]);
}
setOption(arg, args.toList());
}
} else {
javaNames.append(arg);
}
}
if (javaNames.isEmpty() && subPackages.isEmpty()) {
- usageError("main.No_packages_or_classes_specified");
+ if (versionOption) {
+ exit();
+ } else {
+ usageError("main.No_packages_or_classes_specified");
+ }
}
if (!docletInvoker.validOptions(options.toList())) {
// error message already displayed
exit();
}
JavafxdocTool comp = JavafxdocTool.make0(context);
if (comp == null) return false;
if (showAccess == null) {
setFilter(defaultFilter);
}
LanguageVersion languageVersion = docletInvoker.languageVersion();
RootDocImpl root = comp.getRootDocImpl(
docLocale, encoding, showAccess,
javaNames.toList(), options.toList(), breakiterator,
subPackages.toList(), excludedPackages.toList(),
docClasses,
// legacy?
languageVersion == null || languageVersion == LanguageVersion.JAVA_1_1, quiet);
// pass off control to the doclet
boolean ok = root != null;
if (ok) ok = docletInvoker.start(root);
// We're done.
if (compOpts.get("-verbose") != null) {
tm = System.currentTimeMillis() - tm;
messager.notice("main.done_in", Long.toString(tm));
}
return ok;
}
private void setDocletInvoker(String[] argv) {
String docletClassName = null;
String docletPath = null;
// Parse doclet specifying arguments
for (int i = 0 ; i < argv.length ; i++) {
String arg = argv[i];
if (arg.equals("-doclet")) {
oneArg(argv, i++);
if (docletClassName != null) {
usageError("main.more_than_one_doclet_specified_0_and_1",
docletClassName, argv[i]);
}
docletClassName = argv[i];
} else if (arg.equals("-docletpath")) {
oneArg(argv, i++);
if (docletPath == null) {
docletPath = argv[i];
} else {
docletPath += File.pathSeparator + argv[i];
}
}
}
if (docletClassName == null) {
docletClassName = defaultDocletClassName;
}
// attempt to find doclet
docletInvoker = new DocletInvoker(messager,
docletClassName, docletPath);
}
private void setFilter(long filterBits) {
if (showAccess != null) {
messager.error("main.incompatible.access.flags");
usage();
exit();
}
showAccess = new ModifierFilter(filterBits);
}
/**
* Set one arg option.
* Error and exit if one argument is not provided.
*/
private void oneArg(String[] args, int index) {
if ((index + 1) < args.length) {
setOption(args[index], args[index+1]);
} else {
usageError("main.requires_argument", args[index]);
}
}
private void usageError(String key, Object... args) {
messager.error(key, args);
usage();
exit();
}
/**
* indicate an option with no arguments was given.
*/
private void setOption(String opt) {
String[] option = { opt };
options.append(option);
}
/**
* indicate an option with one argument was given.
*/
private void setOption(String opt, String argument) {
String[] option = { opt, argument };
options.append(option);
}
/**
* indicate an option with the specified list of arguments was given.
*/
private void setOption(String opt, List<String> arguments) {
String[] args = new String[arguments.length() + 1];
int k = 0;
args[k++] = opt;
for (List<String> i = arguments; i.nonEmpty(); i=i.tail) {
args[k++] = i.head;
}
options = options.append(args);
}
}
| false | true | private boolean parseAndExecute(String argv[]) throws IOException {
long tm = System.currentTimeMillis();
ListBuffer<String> javaNames = new ListBuffer<String>();
// Preprocess @file arguments
try {
argv = CommandLine.parse(argv);
} catch (FileNotFoundException e) {
messager.error("main.cant.read", e.getMessage());
exit();
} catch (IOException e) {
e.printStackTrace();
exit();
}
setDocletInvoker(argv);
ListBuffer<String> subPackages = new ListBuffer<String>();
ListBuffer<String> excludedPackages = new ListBuffer<String>();
Options compOpts = Options.instance(context);
boolean docClasses = false;
// Parse arguments
for (int i = 0 ; i < argv.length ; i++) {
String arg = argv[i];
if (arg.equals("-subpackages")) {
oneArg(argv, i++);
addToList(subPackages, argv[i]);
} else if (arg.equals("-exclude")){
oneArg(argv, i++);
addToList(excludedPackages, argv[i]);
} else if (arg.equals("-verbose")) {
setOption(arg);
compOpts.put("-verbose", "");
} else if (arg.equals("-encoding")) {
oneArg(argv, i++);
encoding = argv[i];
compOpts.put("-encoding", argv[i]);
} else if (arg.equals("-breakiterator")) {
breakiterator = true;
setOption("-breakiterator");
} else if (arg.equals("-quiet")) {
quiet = true;
setOption("-quiet");
} else if (arg.equals("-help")) {
usage();
exit();
} else if (arg.equals("-Xclasses")) {
setOption(arg);
docClasses = true;
} else if (arg.equals("-Xwerror")) {
setOption(arg);
rejectWarnings = true;
} else if (arg.equals("-private")) {
setOption(arg);
setFilter(ModifierFilter.ALL_ACCESS);
} else if (arg.equals("-package")) {
setOption(arg);
setFilter(PUBLIC | PROTECTED | PUBLIC_READ | PUBLIC_INIT | PACKAGE_ACCESS );
} else if (arg.equals("-protected")) {
setOption(arg);
setFilter(PUBLIC | PROTECTED | PUBLIC_READ | PUBLIC_INIT );
} else if (arg.equals("-public")) {
setOption(arg);
setFilter(PUBLIC | PUBLIC_READ | PUBLIC_INIT);
} else if (arg.equals("-source")) {
oneArg(argv, i++);
if (compOpts.get("-source") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-source", argv[i]);
} else if (arg.equals("-prompt")) {
compOpts.put("-prompt", "-prompt");
messager.promptOnError = true;
} else if (arg.equals("-sourcepath")) {
oneArg(argv, i++);
if (compOpts.get("-sourcepath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-sourcepath", argv[i]);
} else if (arg.equals("-classpath")) {
oneArg(argv, i++);
if (compOpts.get("-classpath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-classpath", argv[i]);
} else if (arg.equals("-sysclasspath")) {
oneArg(argv, i++);
if (compOpts.get("-bootclasspath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-bootclasspath", argv[i]);
} else if (arg.equals("-bootclasspath")) {
oneArg(argv, i++);
if (compOpts.get("-bootclasspath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-bootclasspath", argv[i]);
} else if (arg.equals("-extdirs")) {
oneArg(argv, i++);
if (compOpts.get("-extdirs") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-extdirs", argv[i]);
} else if (arg.equals("-overview")) {
oneArg(argv, i++);
} else if (arg.equals("-doclet")) {
i++; // handled in setDocletInvoker
} else if (arg.equals("-docletpath")) {
i++; // handled in setDocletInvoker
} else if (arg.equals("-locale")) {
if (i != 0)
usageError("main.locale_first");
oneArg(argv, i++);
docLocale = argv[i];
} else if (arg.startsWith("-XD")) {
String s = arg.substring("-XD".length());
int eq = s.indexOf('=');
String key = (eq < 0) ? s : s.substring(0, eq);
String value = (eq < 0) ? s : s.substring(eq+1);
compOpts.put(key, value);
} else if (arg.startsWith("-version")) {
version(false);
exit();
} else if (arg.startsWith("-fullversion")) {
version(true);
exit();
}
// call doclet for its options
// other arg starts with - is invalid
else if ( arg.startsWith("-") ) {
int optionLength;
optionLength = docletInvoker.optionLength(arg);
if (optionLength < 0) {
// error already displayed
exit();
} else if (optionLength == 0) {
// option not found
usageError("main.invalid_flag", arg);
} else {
// doclet added option
if ((i + optionLength) > argv.length) {
usageError("main.requires_argument", arg);
}
ListBuffer<String> args = new ListBuffer<String>();
for (int j = 0; j < optionLength-1; ++j) {
args.append(argv[++i]);
}
setOption(arg, args.toList());
}
} else {
javaNames.append(arg);
}
}
if (javaNames.isEmpty() && subPackages.isEmpty()) {
usageError("main.No_packages_or_classes_specified");
}
if (!docletInvoker.validOptions(options.toList())) {
// error message already displayed
exit();
}
JavafxdocTool comp = JavafxdocTool.make0(context);
if (comp == null) return false;
if (showAccess == null) {
setFilter(defaultFilter);
}
LanguageVersion languageVersion = docletInvoker.languageVersion();
RootDocImpl root = comp.getRootDocImpl(
docLocale, encoding, showAccess,
javaNames.toList(), options.toList(), breakiterator,
subPackages.toList(), excludedPackages.toList(),
docClasses,
// legacy?
languageVersion == null || languageVersion == LanguageVersion.JAVA_1_1, quiet);
// pass off control to the doclet
boolean ok = root != null;
if (ok) ok = docletInvoker.start(root);
// We're done.
if (compOpts.get("-verbose") != null) {
tm = System.currentTimeMillis() - tm;
messager.notice("main.done_in", Long.toString(tm));
}
return ok;
}
| private boolean parseAndExecute(String argv[]) throws IOException {
long tm = System.currentTimeMillis();
ListBuffer<String> javaNames = new ListBuffer<String>();
// Preprocess @file arguments
try {
argv = CommandLine.parse(argv);
} catch (FileNotFoundException e) {
messager.error("main.cant.read", e.getMessage());
exit();
} catch (IOException e) {
e.printStackTrace();
exit();
}
setDocletInvoker(argv);
ListBuffer<String> subPackages = new ListBuffer<String>();
ListBuffer<String> excludedPackages = new ListBuffer<String>();
Options compOpts = Options.instance(context);
boolean docClasses = false;
boolean versionOption = false;
// Parse arguments
for (int i = 0 ; i < argv.length ; i++) {
String arg = argv[i];
if (arg.equals("-subpackages")) {
oneArg(argv, i++);
addToList(subPackages, argv[i]);
} else if (arg.equals("-exclude")){
oneArg(argv, i++);
addToList(excludedPackages, argv[i]);
} else if (arg.equals("-verbose")) {
setOption(arg);
compOpts.put("-verbose", "");
} else if (arg.equals("-encoding")) {
oneArg(argv, i++);
encoding = argv[i];
compOpts.put("-encoding", argv[i]);
} else if (arg.equals("-breakiterator")) {
breakiterator = true;
setOption("-breakiterator");
} else if (arg.equals("-quiet")) {
quiet = true;
setOption("-quiet");
} else if (arg.equals("-help")) {
usage();
exit();
} else if (arg.equals("-Xclasses")) {
setOption(arg);
docClasses = true;
} else if (arg.equals("-Xwerror")) {
setOption(arg);
rejectWarnings = true;
} else if (arg.equals("-private")) {
setOption(arg);
setFilter(ModifierFilter.ALL_ACCESS);
} else if (arg.equals("-package")) {
setOption(arg);
setFilter(PUBLIC | PROTECTED | PUBLIC_READ | PUBLIC_INIT | PACKAGE_ACCESS );
} else if (arg.equals("-protected")) {
setOption(arg);
setFilter(PUBLIC | PROTECTED | PUBLIC_READ | PUBLIC_INIT );
} else if (arg.equals("-public")) {
setOption(arg);
setFilter(PUBLIC | PUBLIC_READ | PUBLIC_INIT);
} else if (arg.equals("-source")) {
oneArg(argv, i++);
if (compOpts.get("-source") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-source", argv[i]);
} else if (arg.equals("-prompt")) {
compOpts.put("-prompt", "-prompt");
messager.promptOnError = true;
} else if (arg.equals("-sourcepath")) {
oneArg(argv, i++);
if (compOpts.get("-sourcepath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-sourcepath", argv[i]);
} else if (arg.equals("-classpath")) {
oneArg(argv, i++);
if (compOpts.get("-classpath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-classpath", argv[i]);
} else if (arg.equals("-sysclasspath")) {
oneArg(argv, i++);
if (compOpts.get("-bootclasspath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-bootclasspath", argv[i]);
} else if (arg.equals("-bootclasspath")) {
oneArg(argv, i++);
if (compOpts.get("-bootclasspath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-bootclasspath", argv[i]);
} else if (arg.equals("-extdirs")) {
oneArg(argv, i++);
if (compOpts.get("-extdirs") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-extdirs", argv[i]);
} else if (arg.equals("-overview")) {
oneArg(argv, i++);
} else if (arg.equals("-doclet")) {
i++; // handled in setDocletInvoker
} else if (arg.equals("-docletpath")) {
i++; // handled in setDocletInvoker
} else if (arg.equals("-locale")) {
if (i != 0)
usageError("main.locale_first");
oneArg(argv, i++);
docLocale = argv[i];
} else if (arg.startsWith("-XD")) {
String s = arg.substring("-XD".length());
int eq = s.indexOf('=');
String key = (eq < 0) ? s : s.substring(0, eq);
String value = (eq < 0) ? s : s.substring(eq+1);
compOpts.put(key, value);
} else if (arg.startsWith("-version")) {
versionOption = true;
version(false);
} else if (arg.startsWith("-fullversion")) {
versionOption = true;
version(true);
}
// call doclet for its options
// other arg starts with - is invalid
else if ( arg.startsWith("-") ) {
int optionLength;
optionLength = docletInvoker.optionLength(arg);
if (optionLength < 0) {
// error already displayed
exit();
} else if (optionLength == 0) {
// option not found
usageError("main.invalid_flag", arg);
} else {
// doclet added option
if ((i + optionLength) > argv.length) {
usageError("main.requires_argument", arg);
}
ListBuffer<String> args = new ListBuffer<String>();
for (int j = 0; j < optionLength-1; ++j) {
args.append(argv[++i]);
}
setOption(arg, args.toList());
}
} else {
javaNames.append(arg);
}
}
if (javaNames.isEmpty() && subPackages.isEmpty()) {
if (versionOption) {
exit();
} else {
usageError("main.No_packages_or_classes_specified");
}
}
if (!docletInvoker.validOptions(options.toList())) {
// error message already displayed
exit();
}
JavafxdocTool comp = JavafxdocTool.make0(context);
if (comp == null) return false;
if (showAccess == null) {
setFilter(defaultFilter);
}
LanguageVersion languageVersion = docletInvoker.languageVersion();
RootDocImpl root = comp.getRootDocImpl(
docLocale, encoding, showAccess,
javaNames.toList(), options.toList(), breakiterator,
subPackages.toList(), excludedPackages.toList(),
docClasses,
// legacy?
languageVersion == null || languageVersion == LanguageVersion.JAVA_1_1, quiet);
// pass off control to the doclet
boolean ok = root != null;
if (ok) ok = docletInvoker.start(root);
// We're done.
if (compOpts.get("-verbose") != null) {
tm = System.currentTimeMillis() - tm;
messager.notice("main.done_in", Long.toString(tm));
}
return ok;
}
|
diff --git a/src/com/episode6/android/common/ui/widget/HandyListView.java b/src/com/episode6/android/common/ui/widget/HandyListView.java
index 0c16995..3bdb5fc 100644
--- a/src/com/episode6/android/common/ui/widget/HandyListView.java
+++ b/src/com/episode6/android/common/ui/widget/HandyListView.java
@@ -1,83 +1,83 @@
package com.episode6.android.common.ui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
public class HandyListView extends ListView {
public interface OnSizeChangedListener {
public void onSizeChanged(int w, int h, int oldw, int oldh);
}
private View mEmptyListView = null;
private View mLoadingListView = null;
private OnSizeChangedListener mSizeListener = null;
public HandyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initHandyListView();
}
public HandyListView(Context context, AttributeSet attrs) {
super(context, attrs);
initHandyListView();
}
public HandyListView(Context context) {
super(context);
initHandyListView();
}
private void initHandyListView() {
}
@Override
public void setAdapter(ListAdapter adapter) {
- super.setAdapter(adapter);
if (mLoadingListView != null)
mLoadingListView.setVisibility(View.GONE);
setVisibility(View.VISIBLE);
- setEmptyView(mEmptyListView);
+ super.setEmptyView(mEmptyListView);
mEmptyListView = null;
+ super.setAdapter(adapter);
}
@Override
public View getEmptyView() {
if (mEmptyListView != null)
return mEmptyListView;
return super.getEmptyView();
}
@Override
public void setEmptyView(View emptyView) {
mEmptyListView = emptyView;
if (mEmptyListView != null)
mEmptyListView.setVisibility(View.GONE);
}
public void setLoadingListView(View loadingView) {
mLoadingListView = loadingView;
if (mLoadingListView != null) {
setVisibility(View.GONE);
mLoadingListView.setVisibility(View.VISIBLE);
}
}
public void setOnSizeChangedListener(OnSizeChangedListener listener) {
mSizeListener = listener;
}
@Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mSizeListener != null)
mSizeListener.onSizeChanged(w, h, oldw, oldh);
}
}
| false | true | public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
if (mLoadingListView != null)
mLoadingListView.setVisibility(View.GONE);
setVisibility(View.VISIBLE);
setEmptyView(mEmptyListView);
mEmptyListView = null;
}
| public void setAdapter(ListAdapter adapter) {
if (mLoadingListView != null)
mLoadingListView.setVisibility(View.GONE);
setVisibility(View.VISIBLE);
super.setEmptyView(mEmptyListView);
mEmptyListView = null;
super.setAdapter(adapter);
}
|
diff --git a/src/main/java/com/orbekk/protobuf/RequestDispatcher.java b/src/main/java/com/orbekk/protobuf/RequestDispatcher.java
index b0a4600..6af6e5e 100644
--- a/src/main/java/com/orbekk/protobuf/RequestDispatcher.java
+++ b/src/main/java/com/orbekk/protobuf/RequestDispatcher.java
@@ -1,119 +1,119 @@
package com.orbekk.protobuf;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.protobuf.Descriptors;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.RpcCallback;
import com.google.protobuf.Service;
public class RequestDispatcher extends Thread {
private static final Logger logger = Logger.getLogger(RequestDispatcher.class.getName());
public static int DEFAULT_QUEUE_SIZE = 5;
private volatile boolean isStopped = false;
private final BlockingQueue<Data.Response> output;
private final ServiceHolder services;
/** A pool that can be shared among all dispatchers. */
private final ExecutorService pool;
private static class RequestHandler implements Runnable {
private final Data.Request request;
private final Data.Response.Builder response =
Data.Response.newBuilder();
private final BlockingQueue<Data.Response> output;
private final ServiceHolder services;
private final Rpc rpc = new Rpc();
private final RpcCallback<Message> callback =
new RpcCallback<Message>() {
@Override public void run(Message responseMessage) {
if (responseMessage != null) {
response.setResponseProto(responseMessage.toByteString());
}
if (logger.isLoggable(Level.FINER)) {
logger.finer(String.format("I(%d): %s <= ",
request.getRequestId(), responseMessage));
}
rpc.writeTo(response);
try {
output.put(response.build());
} catch (InterruptedException e) {
// Terminate callback.
return;
}
}
};
public RequestHandler(Data.Request request,
BlockingQueue<Data.Response> output,
ServiceHolder services) {
this.request = request;
this.output = output;
this.services = services;
}
public void internalRun() throws InterruptedException {
+ response.setRequestId(request.getRequestId());
Service service = services.get(request.getFullServiceName());
if (service == null) {
response.setError(Data.Response.RpcError.UNKNOWN_SERVICE);
output.put(response.build());
return;
}
Descriptors.MethodDescriptor method =
service.getDescriptorForType()
.findMethodByName(request.getMethodName());
if (method == null) {
response.setError(Data.Response.RpcError.UNKNOWN_METHOD);
output.put(response.build());
return;
}
Message requestMessage = null;
try {
requestMessage = service.getRequestPrototype(method)
.toBuilder().mergeFrom(request.getRequestProto()).build();
} catch (InvalidProtocolBufferException e) {
response.setError(Data.Response.RpcError.INVALID_PROTOBUF);
output.put(response.build());
return;
}
if (logger.isLoggable(Level.FINER)) {
logger.fine(String.format("I(%d) => %s(%s)",
request.getRequestId(),
method.getFullName(),
requestMessage));
}
- response.setRequestId(request.getRequestId());
service.callMethod(method, rpc, requestMessage, callback);
}
@Override public void run() {
try {
internalRun();
} catch (InterruptedException e) {
// Terminate request.
return;
}
}
}
public RequestDispatcher(ExecutorService pool,
BlockingQueue<Data.Response> output,
ServiceHolder services) {
this.pool = pool;
this.output = output;
this.services = services;
}
public void handleRequest(Data.Request request) throws InterruptedException {
RequestHandler handler = new RequestHandler(request, output, services);
pool.execute(handler);
}
}
| false | true | public void internalRun() throws InterruptedException {
Service service = services.get(request.getFullServiceName());
if (service == null) {
response.setError(Data.Response.RpcError.UNKNOWN_SERVICE);
output.put(response.build());
return;
}
Descriptors.MethodDescriptor method =
service.getDescriptorForType()
.findMethodByName(request.getMethodName());
if (method == null) {
response.setError(Data.Response.RpcError.UNKNOWN_METHOD);
output.put(response.build());
return;
}
Message requestMessage = null;
try {
requestMessage = service.getRequestPrototype(method)
.toBuilder().mergeFrom(request.getRequestProto()).build();
} catch (InvalidProtocolBufferException e) {
response.setError(Data.Response.RpcError.INVALID_PROTOBUF);
output.put(response.build());
return;
}
if (logger.isLoggable(Level.FINER)) {
logger.fine(String.format("I(%d) => %s(%s)",
request.getRequestId(),
method.getFullName(),
requestMessage));
}
response.setRequestId(request.getRequestId());
service.callMethod(method, rpc, requestMessage, callback);
}
| public void internalRun() throws InterruptedException {
response.setRequestId(request.getRequestId());
Service service = services.get(request.getFullServiceName());
if (service == null) {
response.setError(Data.Response.RpcError.UNKNOWN_SERVICE);
output.put(response.build());
return;
}
Descriptors.MethodDescriptor method =
service.getDescriptorForType()
.findMethodByName(request.getMethodName());
if (method == null) {
response.setError(Data.Response.RpcError.UNKNOWN_METHOD);
output.put(response.build());
return;
}
Message requestMessage = null;
try {
requestMessage = service.getRequestPrototype(method)
.toBuilder().mergeFrom(request.getRequestProto()).build();
} catch (InvalidProtocolBufferException e) {
response.setError(Data.Response.RpcError.INVALID_PROTOBUF);
output.put(response.build());
return;
}
if (logger.isLoggable(Level.FINER)) {
logger.fine(String.format("I(%d) => %s(%s)",
request.getRequestId(),
method.getFullName(),
requestMessage));
}
service.callMethod(method, rpc, requestMessage, callback);
}
|
diff --git a/htmlunit/src/java/com/gargoylesoftware/htmlunit/Version.java b/htmlunit/src/java/com/gargoylesoftware/htmlunit/Version.java
index 4e622b628..3db5ff304 100644
--- a/htmlunit/src/java/com/gargoylesoftware/htmlunit/Version.java
+++ b/htmlunit/src/java/com/gargoylesoftware/htmlunit/Version.java
@@ -1,81 +1,81 @@
/*
* Copyright (c) 2002, 2004 Gargoyle Software Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment:
*
* "This product includes software developed by Gargoyle Software Inc.
* (http://www.GargoyleSoftware.com/)."
*
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
* 4. The name "Gargoyle Software" must not be used to endorse or promote
* products derived from this software without prior written permission.
* For written permission, please contact [email protected].
* 5. Products derived from this software may not be called "HtmlUnit", nor may
* "HtmlUnit" appear in their name, without prior written permission of
* Gargoyle Software Inc.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARGOYLE
* SOFTWARE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.gargoylesoftware.htmlunit;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.net.URL;
/**
* Class to display version information about HtmlUnit. This is the class
* that will be executed if the jar file is run.
*
* @version $Revision$
* @author <a href="mailto:[email protected]">Mike Bowler</a>
*/
public class Version {
/**
* The main entry point into this class.
* @param args The arguments passed on the command line
* @throws Exception If an error occurs
*/
public static void main( final String args[] ) throws Exception {
if( args.length == 1 && args[0].equals("-SanityCheck") ) {
new Version().runSanityCheck();
return;
}
final Package aPackage = Package.getPackage("com.gargoylesoftware.htmlunit");
System.out.println("HTMLUnit");
- System.out.println("Copyright (C) 2002, 2003 Gargoyle Software Inc. All rights reserved.");
+ System.out.println("Copyright (C) 2002, 2004 Gargoyle Software Inc. All rights reserved.");
if( aPackage != null ) {
System.out.println("Version: "+aPackage.getImplementationVersion());
}
}
private void runSanityCheck() throws Exception {
final WebClient webClient = new WebClient();
final HtmlPage page = (HtmlPage)webClient.getPage(
new URL("http://htmlunit.sourceforge.net/index.html") );
page.executeJavaScriptIfPossible("document.location", "SanityCheck", false, null);
System.out.println("SanityCheck complete.");
}
}
| true | true | public static void main( final String args[] ) throws Exception {
if( args.length == 1 && args[0].equals("-SanityCheck") ) {
new Version().runSanityCheck();
return;
}
final Package aPackage = Package.getPackage("com.gargoylesoftware.htmlunit");
System.out.println("HTMLUnit");
System.out.println("Copyright (C) 2002, 2003 Gargoyle Software Inc. All rights reserved.");
if( aPackage != null ) {
System.out.println("Version: "+aPackage.getImplementationVersion());
}
}
| public static void main( final String args[] ) throws Exception {
if( args.length == 1 && args[0].equals("-SanityCheck") ) {
new Version().runSanityCheck();
return;
}
final Package aPackage = Package.getPackage("com.gargoylesoftware.htmlunit");
System.out.println("HTMLUnit");
System.out.println("Copyright (C) 2002, 2004 Gargoyle Software Inc. All rights reserved.");
if( aPackage != null ) {
System.out.println("Version: "+aPackage.getImplementationVersion());
}
}
|
diff --git a/GuitarScoreVisualizer/src/main/java/com/livejournal/karino2/guitarscorevisualizer/EditActivity.java b/GuitarScoreVisualizer/src/main/java/com/livejournal/karino2/guitarscorevisualizer/EditActivity.java
index 245e974..9f75840 100644
--- a/GuitarScoreVisualizer/src/main/java/com/livejournal/karino2/guitarscorevisualizer/EditActivity.java
+++ b/GuitarScoreVisualizer/src/main/java/com/livejournal/karino2/guitarscorevisualizer/EditActivity.java
@@ -1,82 +1,82 @@
package com.livejournal.karino2.guitarscorevisualizer;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Date;
public class EditActivity extends Activity {
public static final String ARG_ITEM_ID = "item_id";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
getActionBar().setDisplayHomeAsUpEnabled(true);
long id = getIntent().getLongExtra(ARG_ITEM_ID, -1);
if(id == -1) {
score = new Score(new Date(), "", "");
} else {
score = Database.getInstance(this).getScoreById(id);
EditText etTitle = (EditText)findViewById(R.id.editTextTitle);
EditText etScore = (EditText)findViewById(R.id.editTextScore);
etTitle.setText(score.getTitle());
etScore.setText(score.getEncodedTexts());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.edit, menu);
return super.onCreateOptionsMenu(menu);
}
Score score;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
- case R.id.action_edit:
+ case R.id.action_save:
saveScoreIfNecessary();
setResult(Activity.RESULT_OK);
finish();
return true;
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, new Intent(this, ScoreListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
private void saveScoreIfNecessary() {
EditText etTitle = (EditText)findViewById(R.id.editTextTitle);
EditText etScore = (EditText)findViewById(R.id.editTextScore);
score.setTitle(etTitle.getText().toString());
score.setTextsString(etScore.getText().toString());
score.setModifiedAt(new Date());
score.setChords(null);
Database.getInstance(this).saveScore(score);
}
}
| true | true | public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_edit:
saveScoreIfNecessary();
setResult(Activity.RESULT_OK);
finish();
return true;
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, new Intent(this, ScoreListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
| public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_save:
saveScoreIfNecessary();
setResult(Activity.RESULT_OK);
finish();
return true;
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, new Intent(this, ScoreListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
|
diff --git a/src/HashTable.java b/src/HashTable.java
index fcb26ed..e88bd92 100644
--- a/src/HashTable.java
+++ b/src/HashTable.java
@@ -1,120 +1,118 @@
import java.math.BigInteger;
/**
* Provides the basic functionality for generating hash tables efficiently
* using double hashing
*/
public abstract class HashTable
{
/*
* Constant value used in determining the interval for double hashing
* it MUST be a prime number to minimize collision
*/
private static final int CONSTANT_INTERVAL = 5;
/*
* Returns the initial probe value for generating the hash table given the
* key
*
* NOTE: The size of the bucket being probed should be a prime number
* to ensure that the modulus for the probe and constant interval
* are co-prime
*
* @param key The key to be hashed
* @param bucketSize The size of the bucket(s) being probed, should
* be prime number to ensure maximum efficiency
*
* @return Returns a probe
*/
public static int getProbe(int key, int bucketSize)
{
// Avoid negative values as java does negative modulus wrong... fucking hack
return (key < 0) ? (bucketSize - (Math.abs(key) % bucketSize)) : (key % bucketSize);
}
public static BigInteger getProbe(BigInteger key, int bucketSize)
{
return key.mod(BigInteger.valueOf(bucketSize));
}
/*
* Returns the interval for incrementing the probe
*/
public static int getInterval(int key)
{
// Avoid negative values as java does negative modulus wrong... fucking hack
return (key < 0) ? (CONSTANT_INTERVAL - (((key % CONSTANT_INTERVAL) + CONSTANT_INTERVAL) % CONSTANT_INTERVAL))
: (CONSTANT_INTERVAL - (key % CONSTANT_INTERVAL));
}
public static BigInteger getInterval(BigInteger key)
{
// One-liner... fucking hack
return BigInteger.valueOf(CONSTANT_INTERVAL).subtract(key.mod(BigInteger.valueOf(CONSTANT_INTERVAL)));
}
/*
* Returns the nearest co-prime value for the size of the bucket(s), this
* is due to a fact of number theory where the number of collisions is
* minimized only if both the constant interval and the bucket size are
* both prime. The two values are only guaranteed to be relatively prime
* if they are BOTH prime.
*
* @see http://stackoverflow.com/questions/1145217/why-should-hash-functions-use-a-prime-number-modulus
* @see http://mathworld.wolfram.com/RelativelyPrime.html
*
* NOTE: If the two bucket is already co-prime with the constant interval
* then the size of the bucket is returned.
*
* NOTE: By using the nearest prime value of the bucket to ensure that it
* is co-prime the number of values selected is less than that of the
* original bucket.
*
* @param bucketSize The size of the bucket(s)
* @returns The bucketSize if it is already co-prime with the constant
* interval, or the nearest prime number.
*/
public static int getCoPrime(int bucketSize)
{
int a = CONSTANT_INTERVAL;
int b = bucketSize;
int c = 0;
int newBucketSize = 0;
// Quickly apply Euclid's Greatest Common Divisor algorithm, if
while (b != 0)
{
c = b;
b = a % b;
a = c;
}
// If a is 1 then the bucketSize is co-prime with constant interval
if (b == 1)
{
return bucketSize;
}
/*
* Otherwise return the nearest prime number as the co-prime, search for
- * the next nearest prime according to the Prime number denisty theorem
- * that states the probability of finding a prime number is 1/ln(bucketSize)
- *
- * @see http://en.wikipedia.org/wiki/Prime_number_theorem
+ * the next nearest prime incrementally until one is found
*/
- for (int i = 1; i <= (int)Math.ceil(Math.log(bucketSize)); ++i)
+ for (int i = 1; i <= (int)Math.ceil(Math.sqrt(bucketSize)); ++i)
{
/*
* Use the miller-rabin test to determine if the new bucketSize is a
* prime number, return it if it is a prime number
*
* @see http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
*/
if (MillerRabin32.miller_rabin_32(bucketSize - i))
{
newBucketSize = bucketSize - i;
+ break;
}
}
return newBucketSize;
}
}
| false | true | public static int getCoPrime(int bucketSize)
{
int a = CONSTANT_INTERVAL;
int b = bucketSize;
int c = 0;
int newBucketSize = 0;
// Quickly apply Euclid's Greatest Common Divisor algorithm, if
while (b != 0)
{
c = b;
b = a % b;
a = c;
}
// If a is 1 then the bucketSize is co-prime with constant interval
if (b == 1)
{
return bucketSize;
}
/*
* Otherwise return the nearest prime number as the co-prime, search for
* the next nearest prime according to the Prime number denisty theorem
* that states the probability of finding a prime number is 1/ln(bucketSize)
*
* @see http://en.wikipedia.org/wiki/Prime_number_theorem
*/
for (int i = 1; i <= (int)Math.ceil(Math.log(bucketSize)); ++i)
{
/*
* Use the miller-rabin test to determine if the new bucketSize is a
* prime number, return it if it is a prime number
*
* @see http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
*/
if (MillerRabin32.miller_rabin_32(bucketSize - i))
{
newBucketSize = bucketSize - i;
}
}
return newBucketSize;
}
| public static int getCoPrime(int bucketSize)
{
int a = CONSTANT_INTERVAL;
int b = bucketSize;
int c = 0;
int newBucketSize = 0;
// Quickly apply Euclid's Greatest Common Divisor algorithm, if
while (b != 0)
{
c = b;
b = a % b;
a = c;
}
// If a is 1 then the bucketSize is co-prime with constant interval
if (b == 1)
{
return bucketSize;
}
/*
* Otherwise return the nearest prime number as the co-prime, search for
* the next nearest prime incrementally until one is found
*/
for (int i = 1; i <= (int)Math.ceil(Math.sqrt(bucketSize)); ++i)
{
/*
* Use the miller-rabin test to determine if the new bucketSize is a
* prime number, return it if it is a prime number
*
* @see http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
*/
if (MillerRabin32.miller_rabin_32(bucketSize - i))
{
newBucketSize = bucketSize - i;
break;
}
}
return newBucketSize;
}
|
diff --git a/hudson-jetty-war-executable/src/main/java/org/eclipse/hudson/jetty/JettyLauncher.java b/hudson-jetty-war-executable/src/main/java/org/eclipse/hudson/jetty/JettyLauncher.java
index 1b132816..cadd59ad 100644
--- a/hudson-jetty-war-executable/src/main/java/org/eclipse/hudson/jetty/JettyLauncher.java
+++ b/hudson-jetty-war-executable/src/main/java/org/eclipse/hudson/jetty/JettyLauncher.java
@@ -1,138 +1,143 @@
/**
* *****************************************************************************
*
* Copyright (c) 2012 Oracle Corporation.
*
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*
* Winston Prakash
*
******************************************************************************
*/
package org.eclipse.hudson.jetty;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.security.SslSocketConnector;
import org.mortbay.jetty.webapp.WebAppContext;
/**
* Jetty Utility to launch the Jetty Server
*
* @author Winston Prakash
*/
public class JettyLauncher {
private static String contextPath = "/";
public static void start(String[] args, URL warUrl) throws Exception {
int httpPort = 8080;
int httpsPort = -1;
String keyStorePath = null;
String keyStorePassword = null;
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("--httpPort=")) {
String portStr = args[i].substring("--httpPort=".length());
httpPort = Integer.parseInt(portStr);
}
if (args[i].startsWith("--httpsPort=")) {
String portStr = args[i].substring("--httpsPort=".length());
httpsPort = Integer.parseInt(portStr);
}
if (args[i].startsWith("--httpsKeyStore=")) {
keyStorePath = args[i].substring("--httpsKeyStore=".length());
}
if (args[i].startsWith("--httpsKeyStorePassword=")) {
keyStorePassword = args[i].substring("--httpsKeyStorePassword=".length());
} else if (args[i].startsWith("--prefix=")) {
- contextPath = "/" + args[i].substring("--prefix=".length());
+ String prefix = args[i].substring("--prefix=".length());
+ if (prefix.startsWith("/")){
+ contextPath = prefix;
+ }else{
+ contextPath = "/" + prefix;
+ }
}
}
Server server = new Server();
List<Connector> connectors = new ArrayList<Connector>();
// HTTP connector
if (httpPort != -1) {
SelectChannelConnector httpConnector = new SelectChannelConnector();
httpConnector.setPort(httpPort);
connectors.add(httpConnector);
}
// HTTPS (SSL) connector
if (httpsPort != -1) {
SslSocketConnector httpsConnector = new SslSocketConnector();
httpsConnector.setPort(httpsPort);
if (keyStorePath != null) {
httpsConnector.setKeystore(keyStorePath);
}
if (keyStorePassword != null){
httpsConnector.setKeyPassword(keyStorePassword);
}
connectors.add(httpsConnector);
}
server.setConnectors(connectors.toArray(new Connector[connectors.size()]));
WebAppContext context = new WebAppContext();
File tempDir = new File(getHomeDir(), "war");
tempDir.mkdirs();
context.setTempDirectory(tempDir);
context.setContextPath(contextPath);
context.setDescriptor(warUrl.toExternalForm() + "/WEB-INF/web.xml");
context.setServer(server);
context.setWar(warUrl.toExternalForm());
// This is used by Windows Service Installer in Hudson Management
System.out.println("War - " + warUrl.getPath());
System.setProperty("executable-war", warUrl.getPath());
server.addHandler(context);
server.setStopAtShutdown(true);
server.start();
server.join();
}
/**
* Get the home directory for Hudson.
*/
private static File getHomeDir() {
// Check HUDSON_HOME system property
String hudsonHomeProperty = System.getProperty("HUDSON_HOME");
if (hudsonHomeProperty != null) {
return new File(hudsonHomeProperty.trim());
}
// Check if the environment variable is et
try {
String hudsonHomeEnv = System.getenv("HUDSON_HOME");
if (hudsonHomeEnv != null) {
return new File(hudsonHomeEnv.trim()).getAbsoluteFile();
}
} catch (Throwable _) {
// Some JDK could throw error if HUDSON_HOME is not set.
// Ignore and fall through
}
// Default hudson home
return new File(new File(System.getProperty("user.home")), ".hudson");
}
}
| true | true | public static void start(String[] args, URL warUrl) throws Exception {
int httpPort = 8080;
int httpsPort = -1;
String keyStorePath = null;
String keyStorePassword = null;
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("--httpPort=")) {
String portStr = args[i].substring("--httpPort=".length());
httpPort = Integer.parseInt(portStr);
}
if (args[i].startsWith("--httpsPort=")) {
String portStr = args[i].substring("--httpsPort=".length());
httpsPort = Integer.parseInt(portStr);
}
if (args[i].startsWith("--httpsKeyStore=")) {
keyStorePath = args[i].substring("--httpsKeyStore=".length());
}
if (args[i].startsWith("--httpsKeyStorePassword=")) {
keyStorePassword = args[i].substring("--httpsKeyStorePassword=".length());
} else if (args[i].startsWith("--prefix=")) {
contextPath = "/" + args[i].substring("--prefix=".length());
}
}
Server server = new Server();
List<Connector> connectors = new ArrayList<Connector>();
// HTTP connector
if (httpPort != -1) {
SelectChannelConnector httpConnector = new SelectChannelConnector();
httpConnector.setPort(httpPort);
connectors.add(httpConnector);
}
// HTTPS (SSL) connector
if (httpsPort != -1) {
SslSocketConnector httpsConnector = new SslSocketConnector();
httpsConnector.setPort(httpsPort);
if (keyStorePath != null) {
httpsConnector.setKeystore(keyStorePath);
}
if (keyStorePassword != null){
httpsConnector.setKeyPassword(keyStorePassword);
}
connectors.add(httpsConnector);
}
server.setConnectors(connectors.toArray(new Connector[connectors.size()]));
WebAppContext context = new WebAppContext();
File tempDir = new File(getHomeDir(), "war");
tempDir.mkdirs();
context.setTempDirectory(tempDir);
context.setContextPath(contextPath);
context.setDescriptor(warUrl.toExternalForm() + "/WEB-INF/web.xml");
context.setServer(server);
context.setWar(warUrl.toExternalForm());
// This is used by Windows Service Installer in Hudson Management
System.out.println("War - " + warUrl.getPath());
System.setProperty("executable-war", warUrl.getPath());
server.addHandler(context);
server.setStopAtShutdown(true);
server.start();
server.join();
}
| public static void start(String[] args, URL warUrl) throws Exception {
int httpPort = 8080;
int httpsPort = -1;
String keyStorePath = null;
String keyStorePassword = null;
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("--httpPort=")) {
String portStr = args[i].substring("--httpPort=".length());
httpPort = Integer.parseInt(portStr);
}
if (args[i].startsWith("--httpsPort=")) {
String portStr = args[i].substring("--httpsPort=".length());
httpsPort = Integer.parseInt(portStr);
}
if (args[i].startsWith("--httpsKeyStore=")) {
keyStorePath = args[i].substring("--httpsKeyStore=".length());
}
if (args[i].startsWith("--httpsKeyStorePassword=")) {
keyStorePassword = args[i].substring("--httpsKeyStorePassword=".length());
} else if (args[i].startsWith("--prefix=")) {
String prefix = args[i].substring("--prefix=".length());
if (prefix.startsWith("/")){
contextPath = prefix;
}else{
contextPath = "/" + prefix;
}
}
}
Server server = new Server();
List<Connector> connectors = new ArrayList<Connector>();
// HTTP connector
if (httpPort != -1) {
SelectChannelConnector httpConnector = new SelectChannelConnector();
httpConnector.setPort(httpPort);
connectors.add(httpConnector);
}
// HTTPS (SSL) connector
if (httpsPort != -1) {
SslSocketConnector httpsConnector = new SslSocketConnector();
httpsConnector.setPort(httpsPort);
if (keyStorePath != null) {
httpsConnector.setKeystore(keyStorePath);
}
if (keyStorePassword != null){
httpsConnector.setKeyPassword(keyStorePassword);
}
connectors.add(httpsConnector);
}
server.setConnectors(connectors.toArray(new Connector[connectors.size()]));
WebAppContext context = new WebAppContext();
File tempDir = new File(getHomeDir(), "war");
tempDir.mkdirs();
context.setTempDirectory(tempDir);
context.setContextPath(contextPath);
context.setDescriptor(warUrl.toExternalForm() + "/WEB-INF/web.xml");
context.setServer(server);
context.setWar(warUrl.toExternalForm());
// This is used by Windows Service Installer in Hudson Management
System.out.println("War - " + warUrl.getPath());
System.setProperty("executable-war", warUrl.getPath());
server.addHandler(context);
server.setStopAtShutdown(true);
server.start();
server.join();
}
|
diff --git a/resthub-core/src/main/java/org/resthub/core/util/PostInitializerRunner.java b/resthub-core/src/main/java/org/resthub/core/util/PostInitializerRunner.java
index 2dff5fcf..d87f0a70 100644
--- a/resthub-core/src/main/java/org/resthub/core/util/PostInitializerRunner.java
+++ b/resthub-core/src/main/java/org/resthub/core/util/PostInitializerRunner.java
@@ -1,154 +1,154 @@
package org.resthub.core.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.inject.Named;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
/**
* Runner for @PostInitialize annotation registration
*
* @author AlphaCSP
*/
@SuppressWarnings("rawtypes")
@Named("postInitializerRunner")
public class PostInitializerRunner implements ApplicationListener {
private static final Logger LOG = Logger.getLogger(PostInitializerRunner.class);
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) {
LOG.info("Scanning for Post Initializers...");
long startTime = System.currentTimeMillis();
ContextRefreshedEvent contextRefreshedEvent = (ContextRefreshedEvent) event;
ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
- Map beans = applicationContext.getBeansOfType(Object.class);
+ Map beans = applicationContext.getBeansOfType(Object.class, false, false);
List<PostInitializingMethod> postInitializingMethods = new LinkedList<PostInitializingMethod>();
for (Object beanNameObject : beans.keySet()) {
String beanName = (String) beanNameObject;
Object bean = beans.get(beanNameObject);
Class<?> beanClass = bean.getClass();
Method[] methods = beanClass.getMethods();
for (Method method : methods) {
if (getAnnotation(method, PostInitialize.class) != null) {
if (method.getParameterTypes().length == 0) {
int order = getAnnotation(method, PostInitialize.class).order();
postInitializingMethods.add(new PostInitializingMethod(method, bean, order, beanName));
} else {
LOG.warn("Post Initializer method can't have any arguments. " + method.toGenericString()
+ " in bean " + beanName + " won't be invoked");
}
}
}
}
Collections.sort(postInitializingMethods);
long endTime = System.currentTimeMillis();
if (LOG.isDebugEnabled())
LOG.debug("Application Context scan completed, took " + (endTime - startTime) + " ms, "
+ postInitializingMethods.size() + " post initializers found. Invoking now.");
for (PostInitializingMethod postInitializingMethod : postInitializingMethods) {
Method method = postInitializingMethod.getMethod();
try {
method.invoke(postInitializingMethod.getBeanInstance());
} catch (Throwable e) {
throw new BeanCreationException("Post Initialization of bean "
+ postInitializingMethod.getBeanName() + " failed.", e);
}
}
}
}
private <T extends Annotation> T getAnnotation(Method method, Class<T> annotationClass) {
do {
if (method.isAnnotationPresent(annotationClass)) {
return method.getAnnotation(annotationClass);
}
} while ((method = getSuperMethod(method)) != null);
return null;
}
@SuppressWarnings("unchecked")
private Method getSuperMethod(Method method) {
Class declaring = method.getDeclaringClass();
if (declaring.getSuperclass() != null) {
Class superClass = declaring.getSuperclass();
try {
Method superMethod = superClass.getMethod(method.getName(), method.getParameterTypes());
if (superMethod != null) {
return superMethod;
}
} catch (Exception e) {
return null;
}
}
return null;
}
private class PostInitializingMethod implements Comparable<PostInitializingMethod> {
private Method method;
private Object beanInstance;
private int order;
private String beanName;
private PostInitializingMethod(Method method, Object beanInstance, int order, String beanName) {
this.method = method;
this.beanInstance = beanInstance;
this.order = order;
this.beanName = beanName;
}
public Method getMethod() {
return method;
}
public Object getBeanInstance() {
return beanInstance;
}
public String getBeanName() {
return beanName;
}
@Override
public int compareTo(PostInitializingMethod anotherPostInitializingMethod) {
int thisVal = this.order;
int anotherVal = anotherPostInitializingMethod.order;
return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1));
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PostInitializingMethod that = (PostInitializingMethod) o;
return order == that.order && !(beanName != null ? !beanName.equals(that.beanName) : that.beanName != null)
&& !(method != null ? !method.equals(that.method) : that.method != null);
}
@Override
public int hashCode() {
int result;
result = (method != null ? method.hashCode() : 0);
result = 31 * result + (beanInstance != null ? beanInstance.hashCode() : 0);
result = 31 * result + order;
result = 31 * result + (beanName != null ? beanName.hashCode() : 0);
return result;
}
}
}
| true | true | public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) {
LOG.info("Scanning for Post Initializers...");
long startTime = System.currentTimeMillis();
ContextRefreshedEvent contextRefreshedEvent = (ContextRefreshedEvent) event;
ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
Map beans = applicationContext.getBeansOfType(Object.class);
List<PostInitializingMethod> postInitializingMethods = new LinkedList<PostInitializingMethod>();
for (Object beanNameObject : beans.keySet()) {
String beanName = (String) beanNameObject;
Object bean = beans.get(beanNameObject);
Class<?> beanClass = bean.getClass();
Method[] methods = beanClass.getMethods();
for (Method method : methods) {
if (getAnnotation(method, PostInitialize.class) != null) {
if (method.getParameterTypes().length == 0) {
int order = getAnnotation(method, PostInitialize.class).order();
postInitializingMethods.add(new PostInitializingMethod(method, bean, order, beanName));
} else {
LOG.warn("Post Initializer method can't have any arguments. " + method.toGenericString()
+ " in bean " + beanName + " won't be invoked");
}
}
}
}
Collections.sort(postInitializingMethods);
long endTime = System.currentTimeMillis();
if (LOG.isDebugEnabled())
LOG.debug("Application Context scan completed, took " + (endTime - startTime) + " ms, "
+ postInitializingMethods.size() + " post initializers found. Invoking now.");
for (PostInitializingMethod postInitializingMethod : postInitializingMethods) {
Method method = postInitializingMethod.getMethod();
try {
method.invoke(postInitializingMethod.getBeanInstance());
} catch (Throwable e) {
throw new BeanCreationException("Post Initialization of bean "
+ postInitializingMethod.getBeanName() + " failed.", e);
}
}
}
}
| public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) {
LOG.info("Scanning for Post Initializers...");
long startTime = System.currentTimeMillis();
ContextRefreshedEvent contextRefreshedEvent = (ContextRefreshedEvent) event;
ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
Map beans = applicationContext.getBeansOfType(Object.class, false, false);
List<PostInitializingMethod> postInitializingMethods = new LinkedList<PostInitializingMethod>();
for (Object beanNameObject : beans.keySet()) {
String beanName = (String) beanNameObject;
Object bean = beans.get(beanNameObject);
Class<?> beanClass = bean.getClass();
Method[] methods = beanClass.getMethods();
for (Method method : methods) {
if (getAnnotation(method, PostInitialize.class) != null) {
if (method.getParameterTypes().length == 0) {
int order = getAnnotation(method, PostInitialize.class).order();
postInitializingMethods.add(new PostInitializingMethod(method, bean, order, beanName));
} else {
LOG.warn("Post Initializer method can't have any arguments. " + method.toGenericString()
+ " in bean " + beanName + " won't be invoked");
}
}
}
}
Collections.sort(postInitializingMethods);
long endTime = System.currentTimeMillis();
if (LOG.isDebugEnabled())
LOG.debug("Application Context scan completed, took " + (endTime - startTime) + " ms, "
+ postInitializingMethods.size() + " post initializers found. Invoking now.");
for (PostInitializingMethod postInitializingMethod : postInitializingMethods) {
Method method = postInitializingMethod.getMethod();
try {
method.invoke(postInitializingMethod.getBeanInstance());
} catch (Throwable e) {
throw new BeanCreationException("Post Initialization of bean "
+ postInitializingMethod.getBeanName() + " failed.", e);
}
}
}
}
|
diff --git a/src/org/nutz/dao/impl/entity/field/OneLinkField.java b/src/org/nutz/dao/impl/entity/field/OneLinkField.java
index 66af7b5af..dd82f44c8 100644
--- a/src/org/nutz/dao/impl/entity/field/OneLinkField.java
+++ b/src/org/nutz/dao/impl/entity/field/OneLinkField.java
@@ -1,53 +1,53 @@
package org.nutz.dao.impl.entity.field;
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.LinkField;
import org.nutz.dao.entity.LinkType;
import org.nutz.dao.impl.EntityHolder;
import org.nutz.dao.impl.entity.info.LinkInfo;
import org.nutz.lang.Lang;
public class OneLinkField extends AbstractLinkField implements LinkField {
public OneLinkField(Entity<?> entity, EntityHolder holder, LinkInfo info) {
super(entity, holder, info);
this.targetType = info.one.target();
// 宿主实体的字段
hostField = entity.getField(info.one.field());
if (null == hostField)
throw Lang.makeThrow( "Invalid @One(field=%s) '%s' : %s<=>%s",
info.one.field(),
this.getName(),
this.getEntity().getType(),
this.getLinkedEntity().getType());
// 链接实体的字段 - 应该是主键
linkedField = hostField.getTypeMirror().isIntLike() ? this.getLinkedEntity().getIdField()
: this.getLinkedEntity().getNameField();
if (null == linkedField)
- throw Lang.makeThrow( "Fail to find linkedField for @Many(field=%s) '%s' : %s<=>%s",
- info.many.field(),
+ throw Lang.makeThrow( "Fail to find linkedField for @One(field=%s) '%s' : %s<=>%s",
+ info.one.field(),
this.getName(),
this.getEntity().getType(),
this.getLinkedEntity().getType());
}
public Condition createCondition(Object host) {
return Cnd.where(linkedField.getColumnName(), "=", hostField.getValue(host));
}
public void updateLinkedField(Object obj, Object linked) {}
public void saveLinkedField(Object obj, Object linked) {
Object v = linkedField.getValue(linked);
hostField.setValue(obj, v);
}
public LinkType getLinkType() {
return LinkType.ONE;
}
}
| true | true | public OneLinkField(Entity<?> entity, EntityHolder holder, LinkInfo info) {
super(entity, holder, info);
this.targetType = info.one.target();
// 宿主实体的字段
hostField = entity.getField(info.one.field());
if (null == hostField)
throw Lang.makeThrow( "Invalid @One(field=%s) '%s' : %s<=>%s",
info.one.field(),
this.getName(),
this.getEntity().getType(),
this.getLinkedEntity().getType());
// 链接实体的字段 - 应该是主键
linkedField = hostField.getTypeMirror().isIntLike() ? this.getLinkedEntity().getIdField()
: this.getLinkedEntity().getNameField();
if (null == linkedField)
throw Lang.makeThrow( "Fail to find linkedField for @Many(field=%s) '%s' : %s<=>%s",
info.many.field(),
this.getName(),
this.getEntity().getType(),
this.getLinkedEntity().getType());
}
| public OneLinkField(Entity<?> entity, EntityHolder holder, LinkInfo info) {
super(entity, holder, info);
this.targetType = info.one.target();
// 宿主实体的字段
hostField = entity.getField(info.one.field());
if (null == hostField)
throw Lang.makeThrow( "Invalid @One(field=%s) '%s' : %s<=>%s",
info.one.field(),
this.getName(),
this.getEntity().getType(),
this.getLinkedEntity().getType());
// 链接实体的字段 - 应该是主键
linkedField = hostField.getTypeMirror().isIntLike() ? this.getLinkedEntity().getIdField()
: this.getLinkedEntity().getNameField();
if (null == linkedField)
throw Lang.makeThrow( "Fail to find linkedField for @One(field=%s) '%s' : %s<=>%s",
info.one.field(),
this.getName(),
this.getEntity().getType(),
this.getLinkedEntity().getType());
}
|
diff --git a/plugins/org.jboss.tools.ws.jaxrs.core/src/org/jboss/tools/ws/jaxrs/core/internal/metamodel/validation/JaxrsJavaApplicationValidatorDelegate.java b/plugins/org.jboss.tools.ws.jaxrs.core/src/org/jboss/tools/ws/jaxrs/core/internal/metamodel/validation/JaxrsJavaApplicationValidatorDelegate.java
index b61901a1..e2cc30ca 100644
--- a/plugins/org.jboss.tools.ws.jaxrs.core/src/org/jboss/tools/ws/jaxrs/core/internal/metamodel/validation/JaxrsJavaApplicationValidatorDelegate.java
+++ b/plugins/org.jboss.tools.ws.jaxrs.core/src/org/jboss/tools/ws/jaxrs/core/internal/metamodel/validation/JaxrsJavaApplicationValidatorDelegate.java
@@ -1,80 +1,80 @@
/*******************************************************************************
* Copyright (c) 2012 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.ws.jaxrs.core.internal.metamodel.validation;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.jboss.tools.common.validation.TempMarkerManager;
import org.jboss.tools.ws.jaxrs.core.internal.metamodel.domain.JaxrsJavaApplication;
import org.jboss.tools.ws.jaxrs.core.internal.utils.Logger;
import org.jboss.tools.ws.jaxrs.core.jdt.Annotation;
import org.jboss.tools.ws.jaxrs.core.jdt.EnumJaxrsClassname;
import org.jboss.tools.ws.jaxrs.core.metamodel.quickfix.JaxrsValidationQuickFixes;
import org.jboss.tools.ws.jaxrs.core.preferences.JaxrsPreferences;
/**
* Java-based JAX-RS Application validator
*
* @author Xavier Coulon
*
*/
public class JaxrsJavaApplicationValidatorDelegate extends AbstractJaxrsElementValidatorDelegate<JaxrsJavaApplication> {
public JaxrsJavaApplicationValidatorDelegate(TempMarkerManager markerManager, JaxrsJavaApplication application) {
super(markerManager, application);
}
/*
* (non-Javadoc)
* @see org.jboss.tools.ws.jaxrs.core.internal.metamodel.validation.AbstractJaxrsElementValidatorDelegate#validate()
*/
@Override
public void validate() throws CoreException {
final JaxrsJavaApplication application = getElement();
deleteJaxrsMarkers(application.getResource());
final Annotation applicationPathAnnotation = application
.getAnnotation(EnumJaxrsClassname.APPLICATION_PATH.qualifiedName);
final IType appJavaElement = application.getJavaElement();
if (!application.isOverriden() && applicationPathAnnotation == null) {
addProblem(JaxrsValidationMessages.JAVA_APPLICATION_MISSING_APPLICATION_PATH_ANNOTATION,
JaxrsPreferences.JAVA_APPLICATION_MISSING_APPLICATION_PATH_ANNOTATION, new String[0],
- appJavaElement.getSourceRange().getLength(), appJavaElement.getSourceRange().getOffset(),
+ appJavaElement.getNameRange().getLength(), appJavaElement.getNameRange().getOffset(),
application.getResource(),
JaxrsValidationQuickFixes.JAVA_APPLICATION_MISSING_APPLICATION_PATH_ANNOTATION_ID);
}
if (!application.isJaxrsCoreApplicationSubclass()) {
addProblem(JaxrsValidationMessages.JAVA_APPLICATION_INVALID_TYPE_HIERARCHY,
JaxrsPreferences.JAVA_APPLICATION_INVALID_TYPE_HIERARCHY,
new String[] { appJavaElement.getFullyQualifiedName() }, application.getJavaElement()
.getSourceRange().getLength(), appJavaElement.getSourceRange().getOffset(),
application.getResource(), JaxrsValidationQuickFixes.JAVA_APPLICATION_INVALID_TYPE_HIERARCHY_ID);
}
if (application.getMetamodel().hasMultipleApplications()) {
final IResource javaResource = application.getResource();
ISourceRange javaNameRange = application.getJavaElement().getNameRange();
if (javaNameRange == null) {
Logger.warn("Cannot add a problem marker: unable to locate '"
+ application.getJavaElement().getElementName() + "' in resource '"
+ application.getJavaElement().getResource().getFullPath().toString() + "'. ");
} else {
addProblem(JaxrsValidationMessages.APPLICATION_TOO_MANY_OCCURRENCES,
JaxrsPreferences.APPLICATION_TOO_MANY_OCCURRENCES, new String[0],
javaNameRange.getLength(), javaNameRange.getOffset(), javaResource);
}
}
}
}
| true | true | public void validate() throws CoreException {
final JaxrsJavaApplication application = getElement();
deleteJaxrsMarkers(application.getResource());
final Annotation applicationPathAnnotation = application
.getAnnotation(EnumJaxrsClassname.APPLICATION_PATH.qualifiedName);
final IType appJavaElement = application.getJavaElement();
if (!application.isOverriden() && applicationPathAnnotation == null) {
addProblem(JaxrsValidationMessages.JAVA_APPLICATION_MISSING_APPLICATION_PATH_ANNOTATION,
JaxrsPreferences.JAVA_APPLICATION_MISSING_APPLICATION_PATH_ANNOTATION, new String[0],
appJavaElement.getSourceRange().getLength(), appJavaElement.getSourceRange().getOffset(),
application.getResource(),
JaxrsValidationQuickFixes.JAVA_APPLICATION_MISSING_APPLICATION_PATH_ANNOTATION_ID);
}
if (!application.isJaxrsCoreApplicationSubclass()) {
addProblem(JaxrsValidationMessages.JAVA_APPLICATION_INVALID_TYPE_HIERARCHY,
JaxrsPreferences.JAVA_APPLICATION_INVALID_TYPE_HIERARCHY,
new String[] { appJavaElement.getFullyQualifiedName() }, application.getJavaElement()
.getSourceRange().getLength(), appJavaElement.getSourceRange().getOffset(),
application.getResource(), JaxrsValidationQuickFixes.JAVA_APPLICATION_INVALID_TYPE_HIERARCHY_ID);
}
if (application.getMetamodel().hasMultipleApplications()) {
final IResource javaResource = application.getResource();
ISourceRange javaNameRange = application.getJavaElement().getNameRange();
if (javaNameRange == null) {
Logger.warn("Cannot add a problem marker: unable to locate '"
+ application.getJavaElement().getElementName() + "' in resource '"
+ application.getJavaElement().getResource().getFullPath().toString() + "'. ");
} else {
addProblem(JaxrsValidationMessages.APPLICATION_TOO_MANY_OCCURRENCES,
JaxrsPreferences.APPLICATION_TOO_MANY_OCCURRENCES, new String[0],
javaNameRange.getLength(), javaNameRange.getOffset(), javaResource);
}
}
}
| public void validate() throws CoreException {
final JaxrsJavaApplication application = getElement();
deleteJaxrsMarkers(application.getResource());
final Annotation applicationPathAnnotation = application
.getAnnotation(EnumJaxrsClassname.APPLICATION_PATH.qualifiedName);
final IType appJavaElement = application.getJavaElement();
if (!application.isOverriden() && applicationPathAnnotation == null) {
addProblem(JaxrsValidationMessages.JAVA_APPLICATION_MISSING_APPLICATION_PATH_ANNOTATION,
JaxrsPreferences.JAVA_APPLICATION_MISSING_APPLICATION_PATH_ANNOTATION, new String[0],
appJavaElement.getNameRange().getLength(), appJavaElement.getNameRange().getOffset(),
application.getResource(),
JaxrsValidationQuickFixes.JAVA_APPLICATION_MISSING_APPLICATION_PATH_ANNOTATION_ID);
}
if (!application.isJaxrsCoreApplicationSubclass()) {
addProblem(JaxrsValidationMessages.JAVA_APPLICATION_INVALID_TYPE_HIERARCHY,
JaxrsPreferences.JAVA_APPLICATION_INVALID_TYPE_HIERARCHY,
new String[] { appJavaElement.getFullyQualifiedName() }, application.getJavaElement()
.getSourceRange().getLength(), appJavaElement.getSourceRange().getOffset(),
application.getResource(), JaxrsValidationQuickFixes.JAVA_APPLICATION_INVALID_TYPE_HIERARCHY_ID);
}
if (application.getMetamodel().hasMultipleApplications()) {
final IResource javaResource = application.getResource();
ISourceRange javaNameRange = application.getJavaElement().getNameRange();
if (javaNameRange == null) {
Logger.warn("Cannot add a problem marker: unable to locate '"
+ application.getJavaElement().getElementName() + "' in resource '"
+ application.getJavaElement().getResource().getFullPath().toString() + "'. ");
} else {
addProblem(JaxrsValidationMessages.APPLICATION_TOO_MANY_OCCURRENCES,
JaxrsPreferences.APPLICATION_TOO_MANY_OCCURRENCES, new String[0],
javaNameRange.getLength(), javaNameRange.getOffset(), javaResource);
}
}
}
|
diff --git a/framework/freedomotic/src/it/freedomotic/util/PropertiesPanel_1.java b/framework/freedomotic/src/it/freedomotic/util/PropertiesPanel_1.java
index 1f77bb1b..66d05cd0 100644
--- a/framework/freedomotic/src/it/freedomotic/util/PropertiesPanel_1.java
+++ b/framework/freedomotic/src/it/freedomotic/util/PropertiesPanel_1.java
@@ -1,130 +1,130 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* PropertiesPanel.java
*
* Created on 1-ott-2010, 11.57.05
*/
package it.freedomotic.util;
import it.freedomotic.app.Freedomotic;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
/**
*
* @author enrico
*/
public class PropertiesPanel_1 extends javax.swing.JPanel {
private Component[][] table;
private int elements = 0;
private int rows;
private int cols;
private static final int MAX_ROWS = 100;
/**
* Creates new form PropertiesPanel
*/
public PropertiesPanel_1(int rows, int cols) {
initComponents();
this.setVisible(true);
this.setPreferredSize(new Dimension(500, 500));
this.rows = rows;
this.cols = cols;
table = new Component[MAX_ROWS][cols];
elements = 0;
this.setLayout(new SpringLayout());
}
public synchronized void addElement(Component component, final int row, final int col) {
if (component == null) {
throw new IllegalArgumentException();
}
try {
table[row][col] = component;
} catch (ArrayIndexOutOfBoundsException e) {
Freedomotic.logger.warning("Only " + MAX_ROWS + " statements are tracked in PropertiesPanel");
}
if (col == cols - 1) {//is the last col
- component.setMaximumSize(new Dimension(2000, 35));
- component.setPreferredSize(new Dimension(200, 35));
+ component.setMaximumSize(new Dimension(2000, 50));
+ component.setPreferredSize(new Dimension(200, 50));
} else {
- component.setMaximumSize(new Dimension(200, 35));
- component.setPreferredSize(new Dimension(200, 35));
+ component.setMaximumSize(new Dimension(200, 50));
+ component.setPreferredSize(new Dimension(200, 50));
}
add(component);
elements++;
}
public void layoutPanel() {
//Lay out the panel.
SpringUtilities.makeCompactGrid(this,
rows, cols, //rows, cols
5, 5, //initX, initY
5, 5);//xPad, yPad
this.validate();
}
public int addRow() {
return rows++;
}
public int addColumn() {
return cols++;
}
public int getRows() {
return rows;
}
public int getColumns() {
return cols;
}
public String getComponent(int row, int col) {
Component comp = table[row][col];
if (comp != null) {
if (comp instanceof JTextField) {
JTextField jTextField = (JTextField) comp;
return jTextField.getText();
} else {
if (comp instanceof JComboBox) {
JComboBox combo = (JComboBox) comp;
return combo.getSelectedItem().toString();
}
}
}
return null;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 296, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| false | true | public synchronized void addElement(Component component, final int row, final int col) {
if (component == null) {
throw new IllegalArgumentException();
}
try {
table[row][col] = component;
} catch (ArrayIndexOutOfBoundsException e) {
Freedomotic.logger.warning("Only " + MAX_ROWS + " statements are tracked in PropertiesPanel");
}
if (col == cols - 1) {//is the last col
component.setMaximumSize(new Dimension(2000, 35));
component.setPreferredSize(new Dimension(200, 35));
} else {
component.setMaximumSize(new Dimension(200, 35));
component.setPreferredSize(new Dimension(200, 35));
}
add(component);
elements++;
}
| public synchronized void addElement(Component component, final int row, final int col) {
if (component == null) {
throw new IllegalArgumentException();
}
try {
table[row][col] = component;
} catch (ArrayIndexOutOfBoundsException e) {
Freedomotic.logger.warning("Only " + MAX_ROWS + " statements are tracked in PropertiesPanel");
}
if (col == cols - 1) {//is the last col
component.setMaximumSize(new Dimension(2000, 50));
component.setPreferredSize(new Dimension(200, 50));
} else {
component.setMaximumSize(new Dimension(200, 50));
component.setPreferredSize(new Dimension(200, 50));
}
add(component);
elements++;
}
|
diff --git a/component/src/main/java/com/celements/photo/unpack/UnpackComponent.java b/component/src/main/java/com/celements/photo/unpack/UnpackComponent.java
index 7c81527..a480149 100644
--- a/component/src/main/java/com/celements/photo/unpack/UnpackComponent.java
+++ b/component/src/main/java/com/celements/photo/unpack/UnpackComponent.java
@@ -1,104 +1,104 @@
package com.celements.photo.unpack;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.context.Execution;
import org.xwiki.model.reference.DocumentReference;
import com.celements.photo.container.ImageLibStrings;
import com.celements.photo.utilities.AddAttachmentToDoc;
import com.celements.photo.utilities.Unzip;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
@Component
public class UnpackComponent implements IUnpackComponentRole {
@Requirement
Execution execution;
private static final Log LOGGER = LogFactory.getFactory().getInstance(
UnpackComponent.class);
public void unzipFileToAttachment(DocumentReference zipSrcDocRef, String attachmentName,
String unzipFileName, DocumentReference destinationDoc) {
try {
XWikiDocument zipSourceDoc = getContext().getWiki().getDocument(zipSrcDocRef,
getContext());
XWikiAttachment zipAtt = zipSourceDoc.getAttachment(attachmentName);
unzipFileToAttachment(zipAtt, attachmentName, destinationDoc);
} catch (XWikiException xwe) {
LOGGER.error("Exception getting zip source document", xwe);
}
}
public String unzipFileToAttachment(XWikiAttachment zipSrcFile, String attName,
DocumentReference destDocRef) {
String cleanName = attName;
if(zipSrcFile != null) {
LOGGER.info("START unzip: zip='" + zipSrcFile.getFilename() + "' file='" + attName +
"'");
if(isZipFile(zipSrcFile)){
ByteArrayOutputStream newAttOutStream = null;
try {
newAttOutStream = (new Unzip()).getFile(IOUtils.toByteArray(
zipSrcFile.getContentInputStream(getContext())), attName);
cleanName = attName.replace(System.getProperty("file.separator"), ".");
cleanName = getContext().getWiki().clearName(cleanName, false, true,
getContext());
XWikiDocument destDoc = getContext().getWiki().getDocument(destDocRef,
getContext());
XWikiAttachment att = (new AddAttachmentToDoc()).addAtachment(destDoc,
- newAttOutStream.toByteArray(), attName, getContext());
+ newAttOutStream.toByteArray(), cleanName, getContext());
LOGGER.info("attachment='" + att.getFilename() + "', doc='" + att.getDoc(
).getDocumentReference() + "' size='" + att.getFilesize() + "'");
} catch (IOException ioe) {
LOGGER.error("Exception while unpacking zip", ioe);
} catch (XWikiException xwe) {
LOGGER.error("Exception while unpacking zip", xwe);
} finally {
if(newAttOutStream != null) {
try {
newAttOutStream.close();
} catch (IOException ioe) {
LOGGER.error("Could not close input stream.", ioe);
}
}
}
}
} else {
LOGGER.error("Source document which should contain zip file is null: ["
+ zipSrcFile + "]");
}
LOGGER.info("END unzip: file='" + attName + "', cleaned name is '" + cleanName + "'");
return cleanName;
}
boolean isZipFile(XWikiAttachment file) {
return (file != null) && (file.getMimeType(getContext()).equalsIgnoreCase(
ImageLibStrings.MIME_ZIP) || file.getMimeType(getContext()).equalsIgnoreCase(
ImageLibStrings.MIME_ZIP_MICROSOFT));
}
boolean isImgFile(String fileName) {
return (fileName != null)
&& (fileName.toLowerCase().endsWith("." + ImageLibStrings.MIME_BMP)
|| fileName.toLowerCase().endsWith("." + ImageLibStrings.MIME_GIF)
|| fileName.toLowerCase().endsWith("." + ImageLibStrings.MIME_JPE)
|| fileName.toLowerCase().endsWith("." + ImageLibStrings.MIME_JPG)
|| fileName.toLowerCase().endsWith("." + ImageLibStrings.MIME_JPEG)
|| fileName.toLowerCase().endsWith("." + ImageLibStrings.MIME_PNG));
}
private XWikiContext getContext() {
return (XWikiContext) execution.getContext().getProperty("xwikicontext");
}
}
| true | true | public String unzipFileToAttachment(XWikiAttachment zipSrcFile, String attName,
DocumentReference destDocRef) {
String cleanName = attName;
if(zipSrcFile != null) {
LOGGER.info("START unzip: zip='" + zipSrcFile.getFilename() + "' file='" + attName +
"'");
if(isZipFile(zipSrcFile)){
ByteArrayOutputStream newAttOutStream = null;
try {
newAttOutStream = (new Unzip()).getFile(IOUtils.toByteArray(
zipSrcFile.getContentInputStream(getContext())), attName);
cleanName = attName.replace(System.getProperty("file.separator"), ".");
cleanName = getContext().getWiki().clearName(cleanName, false, true,
getContext());
XWikiDocument destDoc = getContext().getWiki().getDocument(destDocRef,
getContext());
XWikiAttachment att = (new AddAttachmentToDoc()).addAtachment(destDoc,
newAttOutStream.toByteArray(), attName, getContext());
LOGGER.info("attachment='" + att.getFilename() + "', doc='" + att.getDoc(
).getDocumentReference() + "' size='" + att.getFilesize() + "'");
} catch (IOException ioe) {
LOGGER.error("Exception while unpacking zip", ioe);
} catch (XWikiException xwe) {
LOGGER.error("Exception while unpacking zip", xwe);
} finally {
if(newAttOutStream != null) {
try {
newAttOutStream.close();
} catch (IOException ioe) {
LOGGER.error("Could not close input stream.", ioe);
}
}
}
}
} else {
LOGGER.error("Source document which should contain zip file is null: ["
+ zipSrcFile + "]");
}
LOGGER.info("END unzip: file='" + attName + "', cleaned name is '" + cleanName + "'");
return cleanName;
}
| public String unzipFileToAttachment(XWikiAttachment zipSrcFile, String attName,
DocumentReference destDocRef) {
String cleanName = attName;
if(zipSrcFile != null) {
LOGGER.info("START unzip: zip='" + zipSrcFile.getFilename() + "' file='" + attName +
"'");
if(isZipFile(zipSrcFile)){
ByteArrayOutputStream newAttOutStream = null;
try {
newAttOutStream = (new Unzip()).getFile(IOUtils.toByteArray(
zipSrcFile.getContentInputStream(getContext())), attName);
cleanName = attName.replace(System.getProperty("file.separator"), ".");
cleanName = getContext().getWiki().clearName(cleanName, false, true,
getContext());
XWikiDocument destDoc = getContext().getWiki().getDocument(destDocRef,
getContext());
XWikiAttachment att = (new AddAttachmentToDoc()).addAtachment(destDoc,
newAttOutStream.toByteArray(), cleanName, getContext());
LOGGER.info("attachment='" + att.getFilename() + "', doc='" + att.getDoc(
).getDocumentReference() + "' size='" + att.getFilesize() + "'");
} catch (IOException ioe) {
LOGGER.error("Exception while unpacking zip", ioe);
} catch (XWikiException xwe) {
LOGGER.error("Exception while unpacking zip", xwe);
} finally {
if(newAttOutStream != null) {
try {
newAttOutStream.close();
} catch (IOException ioe) {
LOGGER.error("Could not close input stream.", ioe);
}
}
}
}
} else {
LOGGER.error("Source document which should contain zip file is null: ["
+ zipSrcFile + "]");
}
LOGGER.info("END unzip: file='" + attName + "', cleaned name is '" + cleanName + "'");
return cleanName;
}
|
diff --git a/src/com/bigpupdev/synodroid/ui/SynodroidFragment.java b/src/com/bigpupdev/synodroid/ui/SynodroidFragment.java
index ef03bdc..61d9ef8 100644
--- a/src/com/bigpupdev/synodroid/ui/SynodroidFragment.java
+++ b/src/com/bigpupdev/synodroid/ui/SynodroidFragment.java
@@ -1,247 +1,247 @@
/**
* Copyright 2010 Eric Taix 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.bigpupdev.synodroid.ui;
import java.util.List;
import com.bigpupdev.synodroid.action.DetailTaskAction;
import com.bigpupdev.synodroid.action.SynoAction;
import com.bigpupdev.synodroid.protocol.ResponseHandler;
import com.bigpupdev.synodroid.server.SynoServer;
import com.bigpupdev.synodroid.R;
import com.bigpupdev.synodroid.Synodroid;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
/**
* The base class of an activity in Synodroid
*
* @author Eric Taix (eric.taix at gmail.com)
*/
public abstract class SynodroidFragment extends Fragment implements ResponseHandler {
protected List<SynoAction> postOTPActions = null;
protected boolean otp_dialog = false;
// A generic Handler which delegate to the activity
private Handler handler = new Handler() {
// The toast message
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msgP) {
final Activity a = SynodroidFragment.this.getActivity();
- final SynoServer server = ((Synodroid) a.getApplication()).getServer();
if (a != null){
+ final SynoServer server = ((Synodroid) a.getApplication()).getServer();
Synodroid app = (Synodroid) a.getApplication();
Style msg_style = null;
// According to the message
switch (msgP.what) {
case ResponseHandler.MSG_CONNECT_WITH_ACTION:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.w(Synodroid.DS_TAG,"SynodroidFragment: Received connect with action message.");
}catch (Exception ex){/*DO NOTHING*/}
((BaseActivity)a).showDialogToConnect(true, (List<SynoAction>) msgP.obj, true);
break;
case ResponseHandler.MSG_ERROR:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.w(Synodroid.DS_TAG,"SynodroidFragment: Received error message.");
}catch (Exception ex){/*DO NOTHING*/}
// Change the title
((BaseActivity)a).updateSMServer(null);
// Show the error
// Save the last error inside the server to surive UI rotation and
// pause/resume.
if (server != null) {
server.setLastError((String) msgP.obj);
android.view.View.OnClickListener ocl = new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
if (server != null) {
if (!server.isConnected()) {
((BaseActivity) a).showDialogToConnect(false, null, false);
}
}
Crouton.cancelAllCroutons();
}
};
Crouton.makeText(getActivity(), server.getLastError()+ "\n\n" + getText(R.string.click_dismiss), Synodroid.CROUTON_ERROR).setOnClickListener(ocl).show();
}
break;
case ResponseHandler.MSG_OTP_REQUESTED:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received OTP Request message.");
}catch (Exception ex){/*DO NOTHING*/}
postOTPActions = (List<SynoAction>)msgP.obj;
// Show the connection dialog
try {
((BaseActivity)a).showDialog(BaseActivity.OTP_REQUEST_DIALOG_ID);
} catch (Exception e) {/* Unable to show dialog probably because intent has been closed. Ignoring...*/}
break;
case ResponseHandler.MSG_CONNECTED:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received connected to server message.");
}catch (Exception ex){/*DO NOTHING*/}
((BaseActivity)a).updateSMServer(server);
break;
case ResponseHandler.MSG_CONNECTING:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received connected to server message.");
}catch (Exception ex){/*DO NOTHING*/}
((BaseActivity)a).updateSMServer(null);
break;
case MSG_OPERATION_PENDING:
if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received operation pending message.");
if (a instanceof HomeActivity){
((HomeActivity) a).updateRefreshStatus(true);
}
else if (a instanceof DetailActivity){
((DetailActivity) a).updateRefreshStatus(true);
}
else if (a instanceof SearchActivity){
((SearchActivity) a).updateRefreshStatus(true);
}
else if (a instanceof FileActivity){
((FileActivity) a).updateRefreshStatus(true);
}
else if (a instanceof BrowserActivity){
((BrowserActivity) a).updateRefreshStatus(true);
}
break;
case MSG_INFO:
if (msg_style == null) msg_style = Synodroid.CROUTON_INFO;
case MSG_ALERT:
if (msg_style == null) msg_style = Synodroid.CROUTON_ALERT;
case MSG_ERR:
if (msg_style == null) msg_style = Synodroid.CROUTON_ERROR;
case MSG_CONFIRM:
if (msg_style == null) msg_style = Synodroid.CROUTON_CONFIRM;
if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received toast message.");
final String text = (String) msgP.obj;
Runnable runnable = new Runnable() {
public void run() {
Crouton.makeText(a, text, Synodroid.CROUTON_CONFIRM).show();
}
};
a.runOnUiThread(runnable);
break;
default:
if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received default message.");
if (a instanceof HomeActivity){
((HomeActivity) a).updateRefreshStatus(false);
}
else if (a instanceof DetailActivity){
((DetailActivity) a).updateRefreshStatus(false);
}
else if (a instanceof SearchActivity){
((SearchActivity) a).updateRefreshStatus(false);
}
else if (a instanceof FileActivity){
((FileActivity) a).updateRefreshStatus(false);
}
else if (a instanceof BrowserActivity){
((BrowserActivity) a).updateRefreshStatus(false);
}
break;
}
// Delegate to the sub class in case it have something to do
SynodroidFragment.this.handleMessage(msgP);
}
}
};
public void onResume(){
super.onResume();
Activity a = getActivity();
Synodroid app = (Synodroid) a.getApplication();
try{
if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailMain: Resuming server.");
}catch (Exception ex){/*DO NOTHING*/}
SynoServer server = app.getServer();
if (server != null){
server.bindResponseHandler(this);
}
((BaseActivity) a).updateSMServer(server);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation change
super.onConfigurationChanged(newConfig);
}
/**
* Activity creation
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/*
* (non-Javadoc)
*
* @see com.bigpupdev.synodroid.common.protocol.ResponseHandler#handleReponse( android .os.Message)
*/
public final void handleReponse(Message msgP) {
handler.sendMessage(msgP);
}
/**
* Handle the message from a none UI thread. It is safe to interact with the UI in this method
*/
public abstract void handleMessage(Message msgP);
@Override
public void onDestroy(){
Crouton.cancelAllCroutons();
super.onDestroy();
}
public void setAlreadyCanceled(boolean value){
((BaseActivity) getActivity()).setAlreadyCanceled(value);
}
public void showDialogToConnect(boolean autoConnectIfOnlyOneServerP, final List<SynoAction> actionQueueP, final boolean automated){
((BaseActivity) getActivity()).showDialogToConnect(autoConnectIfOnlyOneServerP, actionQueueP, automated);
}
public List<SynoAction> getPostOTPActions(){
return postOTPActions;
}
public void resetPostOTPActions(){
postOTPActions = null;
}
public void setOTPDialog(boolean otp){
otp_dialog = otp;
}
}
| false | true | public void handleMessage(Message msgP) {
final Activity a = SynodroidFragment.this.getActivity();
final SynoServer server = ((Synodroid) a.getApplication()).getServer();
if (a != null){
Synodroid app = (Synodroid) a.getApplication();
Style msg_style = null;
// According to the message
switch (msgP.what) {
case ResponseHandler.MSG_CONNECT_WITH_ACTION:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.w(Synodroid.DS_TAG,"SynodroidFragment: Received connect with action message.");
}catch (Exception ex){/*DO NOTHING*/}
((BaseActivity)a).showDialogToConnect(true, (List<SynoAction>) msgP.obj, true);
break;
case ResponseHandler.MSG_ERROR:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.w(Synodroid.DS_TAG,"SynodroidFragment: Received error message.");
}catch (Exception ex){/*DO NOTHING*/}
// Change the title
((BaseActivity)a).updateSMServer(null);
// Show the error
// Save the last error inside the server to surive UI rotation and
// pause/resume.
if (server != null) {
server.setLastError((String) msgP.obj);
android.view.View.OnClickListener ocl = new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
if (server != null) {
if (!server.isConnected()) {
((BaseActivity) a).showDialogToConnect(false, null, false);
}
}
Crouton.cancelAllCroutons();
}
};
Crouton.makeText(getActivity(), server.getLastError()+ "\n\n" + getText(R.string.click_dismiss), Synodroid.CROUTON_ERROR).setOnClickListener(ocl).show();
}
break;
case ResponseHandler.MSG_OTP_REQUESTED:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received OTP Request message.");
}catch (Exception ex){/*DO NOTHING*/}
postOTPActions = (List<SynoAction>)msgP.obj;
// Show the connection dialog
try {
((BaseActivity)a).showDialog(BaseActivity.OTP_REQUEST_DIALOG_ID);
} catch (Exception e) {/* Unable to show dialog probably because intent has been closed. Ignoring...*/}
break;
case ResponseHandler.MSG_CONNECTED:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received connected to server message.");
}catch (Exception ex){/*DO NOTHING*/}
((BaseActivity)a).updateSMServer(server);
break;
case ResponseHandler.MSG_CONNECTING:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received connected to server message.");
}catch (Exception ex){/*DO NOTHING*/}
((BaseActivity)a).updateSMServer(null);
break;
case MSG_OPERATION_PENDING:
if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received operation pending message.");
if (a instanceof HomeActivity){
((HomeActivity) a).updateRefreshStatus(true);
}
else if (a instanceof DetailActivity){
((DetailActivity) a).updateRefreshStatus(true);
}
else if (a instanceof SearchActivity){
((SearchActivity) a).updateRefreshStatus(true);
}
else if (a instanceof FileActivity){
((FileActivity) a).updateRefreshStatus(true);
}
else if (a instanceof BrowserActivity){
((BrowserActivity) a).updateRefreshStatus(true);
}
break;
case MSG_INFO:
if (msg_style == null) msg_style = Synodroid.CROUTON_INFO;
case MSG_ALERT:
if (msg_style == null) msg_style = Synodroid.CROUTON_ALERT;
case MSG_ERR:
if (msg_style == null) msg_style = Synodroid.CROUTON_ERROR;
case MSG_CONFIRM:
if (msg_style == null) msg_style = Synodroid.CROUTON_CONFIRM;
if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received toast message.");
final String text = (String) msgP.obj;
Runnable runnable = new Runnable() {
public void run() {
Crouton.makeText(a, text, Synodroid.CROUTON_CONFIRM).show();
}
};
a.runOnUiThread(runnable);
break;
default:
if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received default message.");
if (a instanceof HomeActivity){
((HomeActivity) a).updateRefreshStatus(false);
}
else if (a instanceof DetailActivity){
((DetailActivity) a).updateRefreshStatus(false);
}
else if (a instanceof SearchActivity){
((SearchActivity) a).updateRefreshStatus(false);
}
else if (a instanceof FileActivity){
((FileActivity) a).updateRefreshStatus(false);
}
else if (a instanceof BrowserActivity){
((BrowserActivity) a).updateRefreshStatus(false);
}
break;
}
// Delegate to the sub class in case it have something to do
SynodroidFragment.this.handleMessage(msgP);
}
}
| public void handleMessage(Message msgP) {
final Activity a = SynodroidFragment.this.getActivity();
if (a != null){
final SynoServer server = ((Synodroid) a.getApplication()).getServer();
Synodroid app = (Synodroid) a.getApplication();
Style msg_style = null;
// According to the message
switch (msgP.what) {
case ResponseHandler.MSG_CONNECT_WITH_ACTION:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.w(Synodroid.DS_TAG,"SynodroidFragment: Received connect with action message.");
}catch (Exception ex){/*DO NOTHING*/}
((BaseActivity)a).showDialogToConnect(true, (List<SynoAction>) msgP.obj, true);
break;
case ResponseHandler.MSG_ERROR:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.w(Synodroid.DS_TAG,"SynodroidFragment: Received error message.");
}catch (Exception ex){/*DO NOTHING*/}
// Change the title
((BaseActivity)a).updateSMServer(null);
// Show the error
// Save the last error inside the server to surive UI rotation and
// pause/resume.
if (server != null) {
server.setLastError((String) msgP.obj);
android.view.View.OnClickListener ocl = new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
if (server != null) {
if (!server.isConnected()) {
((BaseActivity) a).showDialogToConnect(false, null, false);
}
}
Crouton.cancelAllCroutons();
}
};
Crouton.makeText(getActivity(), server.getLastError()+ "\n\n" + getText(R.string.click_dismiss), Synodroid.CROUTON_ERROR).setOnClickListener(ocl).show();
}
break;
case ResponseHandler.MSG_OTP_REQUESTED:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received OTP Request message.");
}catch (Exception ex){/*DO NOTHING*/}
postOTPActions = (List<SynoAction>)msgP.obj;
// Show the connection dialog
try {
((BaseActivity)a).showDialog(BaseActivity.OTP_REQUEST_DIALOG_ID);
} catch (Exception e) {/* Unable to show dialog probably because intent has been closed. Ignoring...*/}
break;
case ResponseHandler.MSG_CONNECTED:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received connected to server message.");
}catch (Exception ex){/*DO NOTHING*/}
((BaseActivity)a).updateSMServer(server);
break;
case ResponseHandler.MSG_CONNECTING:
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received connected to server message.");
}catch (Exception ex){/*DO NOTHING*/}
((BaseActivity)a).updateSMServer(null);
break;
case MSG_OPERATION_PENDING:
if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received operation pending message.");
if (a instanceof HomeActivity){
((HomeActivity) a).updateRefreshStatus(true);
}
else if (a instanceof DetailActivity){
((DetailActivity) a).updateRefreshStatus(true);
}
else if (a instanceof SearchActivity){
((SearchActivity) a).updateRefreshStatus(true);
}
else if (a instanceof FileActivity){
((FileActivity) a).updateRefreshStatus(true);
}
else if (a instanceof BrowserActivity){
((BrowserActivity) a).updateRefreshStatus(true);
}
break;
case MSG_INFO:
if (msg_style == null) msg_style = Synodroid.CROUTON_INFO;
case MSG_ALERT:
if (msg_style == null) msg_style = Synodroid.CROUTON_ALERT;
case MSG_ERR:
if (msg_style == null) msg_style = Synodroid.CROUTON_ERROR;
case MSG_CONFIRM:
if (msg_style == null) msg_style = Synodroid.CROUTON_CONFIRM;
if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received toast message.");
final String text = (String) msgP.obj;
Runnable runnable = new Runnable() {
public void run() {
Crouton.makeText(a, text, Synodroid.CROUTON_CONFIRM).show();
}
};
a.runOnUiThread(runnable);
break;
default:
if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received default message.");
if (a instanceof HomeActivity){
((HomeActivity) a).updateRefreshStatus(false);
}
else if (a instanceof DetailActivity){
((DetailActivity) a).updateRefreshStatus(false);
}
else if (a instanceof SearchActivity){
((SearchActivity) a).updateRefreshStatus(false);
}
else if (a instanceof FileActivity){
((FileActivity) a).updateRefreshStatus(false);
}
else if (a instanceof BrowserActivity){
((BrowserActivity) a).updateRefreshStatus(false);
}
break;
}
// Delegate to the sub class in case it have something to do
SynodroidFragment.this.handleMessage(msgP);
}
}
|
diff --git a/src/no/runsafe/creativetoolbox/command/OldPlotsCommand.java b/src/no/runsafe/creativetoolbox/command/OldPlotsCommand.java
index e8e0be9..4f01686 100644
--- a/src/no/runsafe/creativetoolbox/command/OldPlotsCommand.java
+++ b/src/no/runsafe/creativetoolbox/command/OldPlotsCommand.java
@@ -1,150 +1,150 @@
package no.runsafe.creativetoolbox.command;
import no.runsafe.PlayerData;
import no.runsafe.PlayerDatabase;
import no.runsafe.creativetoolbox.PlotFilter;
import no.runsafe.creativetoolbox.database.ApprovedPlotRepository;
import no.runsafe.framework.RunsafePlugin;
import no.runsafe.framework.command.RunsafeAsyncCommand;
import no.runsafe.framework.configuration.IConfiguration;
import no.runsafe.framework.event.IConfigurationChanged;
import no.runsafe.framework.server.RunsafeServer;
import no.runsafe.framework.server.RunsafeWorld;
import no.runsafe.framework.server.player.RunsafePlayer;
import no.runsafe.framework.timer.IScheduler;
import no.runsafe.worldguardbridge.WorldGuardInterface;
import java.util.*;
public class OldPlotsCommand extends RunsafeAsyncCommand implements IConfigurationChanged
{
public OldPlotsCommand(
ApprovedPlotRepository approvalRepository,
IConfiguration config,
PlotFilter filter,
WorldGuardInterface worldGuardInterface,
IScheduler scheduler
)
{
super("oldplots", scheduler);
repository = approvalRepository;
this.config = config;
plotFilter = filter;
worldGuard = worldGuardInterface;
}
@Override
public String requiredPermission()
{
return "runsafe.creative.scan.old-plots";
}
@Override
public String OnExecute(RunsafePlayer executor, String[] args)
{
if (!worldGuard.serverHasWorldGuard())
return "Unable to find WorldGuard!";
StringBuilder result = new StringBuilder();
Date now = new Date();
int count = 0;
ArrayList<String> banned = new ArrayList<String>();
List<String> approved;
approved = repository.getApprovedPlots();
HashMap<String, Long> seen = new HashMap<String, Long>();
if (!worldGuard.serverHasWorldGuard())
return "WorldGuard isn't active on the server.";
PlayerDatabase players = RunsafePlugin.Instances.get("RunsafeServices").getComponent(PlayerDatabase.class);
Map<String, Set<String>> checkList = worldGuard.getAllRegionsWithOwnersInWorld(getWorld());
long oldAfter = config.getConfigValueAsInt("old_after") * 1000;
int limit = config.getConfigValueAsInt("max_listed");
for (String region : plotFilter.apply(new ArrayList<String>(checkList.keySet())))
{
String info = null;
if (approved.contains(region))
continue;
boolean ok = false;
for (String owner : checkList.get(region))
{
owner = owner.toLowerCase();
if (!seen.containsKey(owner))
{
RunsafePlayer player = RunsafeServer.Instance.getPlayer(owner);
if (player.isOnline())
{
ok = true;
seen.put(owner, (long) 0);
break;
}
else
{
PlayerData data = players.get(owner);
if (data != null && data.getBanned() != null)
banned.add(owner);
if (data == null || (data.getLogin() == null && data.getLogout() == null))
seen.put(owner, null);
else if (data.getLogout() != null)
seen.put(owner, now.getTime() - data.getLogout().getTime());
else if (data.getLogin() != null)
seen.put(owner, now.getTime() - data.getLogin().getTime());
}
}
if (banned.contains(owner))
{
ok = false;
info = "banned";
break;
}
if (seen.get(owner) == null)
continue;
if (seen.get(owner) < oldAfter)
{
ok = true;
}
else
info = String.format("%.2f days", seen.get(owner) / 86400000.0);
}
if (!ok)
{
- if (executor != null && count++ > limit)
+ if (count++ > limit && executor != null)
{
result.append(String.format("== configured limit reached =="));
break;
}
result.append(String.format("%s (%s)\n", region, info));
}
}
if (result.length() == 0)
return "No old plots found.";
- else if (executor == null || count <= limit)
+ else if (count <= limit || executor == null)
result.append(String.format("%d plots found", count));
return result.toString();
}
@Override
public void OnConfigurationChanged()
{
world = RunsafeServer.Instance.getWorld(config.getConfigValueAsString("world"));
}
public RunsafeWorld getWorld()
{
if (world == null)
world = RunsafeServer.Instance.getWorld(config.getConfigValueAsString("world"));
return world;
}
private final ApprovedPlotRepository repository;
private final IConfiguration config;
private final PlotFilter plotFilter;
private RunsafeWorld world;
private final WorldGuardInterface worldGuard;
}
| false | true | public String OnExecute(RunsafePlayer executor, String[] args)
{
if (!worldGuard.serverHasWorldGuard())
return "Unable to find WorldGuard!";
StringBuilder result = new StringBuilder();
Date now = new Date();
int count = 0;
ArrayList<String> banned = new ArrayList<String>();
List<String> approved;
approved = repository.getApprovedPlots();
HashMap<String, Long> seen = new HashMap<String, Long>();
if (!worldGuard.serverHasWorldGuard())
return "WorldGuard isn't active on the server.";
PlayerDatabase players = RunsafePlugin.Instances.get("RunsafeServices").getComponent(PlayerDatabase.class);
Map<String, Set<String>> checkList = worldGuard.getAllRegionsWithOwnersInWorld(getWorld());
long oldAfter = config.getConfigValueAsInt("old_after") * 1000;
int limit = config.getConfigValueAsInt("max_listed");
for (String region : plotFilter.apply(new ArrayList<String>(checkList.keySet())))
{
String info = null;
if (approved.contains(region))
continue;
boolean ok = false;
for (String owner : checkList.get(region))
{
owner = owner.toLowerCase();
if (!seen.containsKey(owner))
{
RunsafePlayer player = RunsafeServer.Instance.getPlayer(owner);
if (player.isOnline())
{
ok = true;
seen.put(owner, (long) 0);
break;
}
else
{
PlayerData data = players.get(owner);
if (data != null && data.getBanned() != null)
banned.add(owner);
if (data == null || (data.getLogin() == null && data.getLogout() == null))
seen.put(owner, null);
else if (data.getLogout() != null)
seen.put(owner, now.getTime() - data.getLogout().getTime());
else if (data.getLogin() != null)
seen.put(owner, now.getTime() - data.getLogin().getTime());
}
}
if (banned.contains(owner))
{
ok = false;
info = "banned";
break;
}
if (seen.get(owner) == null)
continue;
if (seen.get(owner) < oldAfter)
{
ok = true;
}
else
info = String.format("%.2f days", seen.get(owner) / 86400000.0);
}
if (!ok)
{
if (executor != null && count++ > limit)
{
result.append(String.format("== configured limit reached =="));
break;
}
result.append(String.format("%s (%s)\n", region, info));
}
}
if (result.length() == 0)
return "No old plots found.";
else if (executor == null || count <= limit)
result.append(String.format("%d plots found", count));
return result.toString();
}
| public String OnExecute(RunsafePlayer executor, String[] args)
{
if (!worldGuard.serverHasWorldGuard())
return "Unable to find WorldGuard!";
StringBuilder result = new StringBuilder();
Date now = new Date();
int count = 0;
ArrayList<String> banned = new ArrayList<String>();
List<String> approved;
approved = repository.getApprovedPlots();
HashMap<String, Long> seen = new HashMap<String, Long>();
if (!worldGuard.serverHasWorldGuard())
return "WorldGuard isn't active on the server.";
PlayerDatabase players = RunsafePlugin.Instances.get("RunsafeServices").getComponent(PlayerDatabase.class);
Map<String, Set<String>> checkList = worldGuard.getAllRegionsWithOwnersInWorld(getWorld());
long oldAfter = config.getConfigValueAsInt("old_after") * 1000;
int limit = config.getConfigValueAsInt("max_listed");
for (String region : plotFilter.apply(new ArrayList<String>(checkList.keySet())))
{
String info = null;
if (approved.contains(region))
continue;
boolean ok = false;
for (String owner : checkList.get(region))
{
owner = owner.toLowerCase();
if (!seen.containsKey(owner))
{
RunsafePlayer player = RunsafeServer.Instance.getPlayer(owner);
if (player.isOnline())
{
ok = true;
seen.put(owner, (long) 0);
break;
}
else
{
PlayerData data = players.get(owner);
if (data != null && data.getBanned() != null)
banned.add(owner);
if (data == null || (data.getLogin() == null && data.getLogout() == null))
seen.put(owner, null);
else if (data.getLogout() != null)
seen.put(owner, now.getTime() - data.getLogout().getTime());
else if (data.getLogin() != null)
seen.put(owner, now.getTime() - data.getLogin().getTime());
}
}
if (banned.contains(owner))
{
ok = false;
info = "banned";
break;
}
if (seen.get(owner) == null)
continue;
if (seen.get(owner) < oldAfter)
{
ok = true;
}
else
info = String.format("%.2f days", seen.get(owner) / 86400000.0);
}
if (!ok)
{
if (count++ > limit && executor != null)
{
result.append(String.format("== configured limit reached =="));
break;
}
result.append(String.format("%s (%s)\n", region, info));
}
}
if (result.length() == 0)
return "No old plots found.";
else if (count <= limit || executor == null)
result.append(String.format("%d plots found", count));
return result.toString();
}
|
diff --git a/src/com/vhly/epubmaker/TxtSplit.java b/src/com/vhly/epubmaker/TxtSplit.java
index 8f81702..3376fc3 100644
--- a/src/com/vhly/epubmaker/TxtSplit.java
+++ b/src/com/vhly/epubmaker/TxtSplit.java
@@ -1,192 +1,195 @@
package com.vhly.epubmaker;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by IntelliJ IDEA.
* User: vhly[FR]
* Date: 13-12-3
* Email: [email protected]
*/
public class TxtSplit {
public static void main(String[] args) {
int argc = args.length;
if (argc != 2) {
System.out.println("Usage: TxtSplit <txt> <target folder>");
} else {
File file = new File(args[0]);
if (file.exists() && file.canRead()) {
File targetDir = new File(args[1]);
boolean bok = true;
if (!targetDir.exists()) {
bok = targetDir.mkdirs();
}
if (bok) {
String name = file.getName();
int index = name.lastIndexOf('.');
if (index != -1) {
name = name.substring(0, index);
}
targetDir = new File(targetDir, name);
if (!targetDir.exists()) {
bok = targetDir.mkdirs();
}
if (bok) {
StringBuilder sb = new StringBuilder();
FileReader fr = null;
BufferedReader br = null;
FileOutputStream fout = null;
OutputStreamWriter ow = null;
PrintWriter pw = null;
File outFile = null;
String line = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
Pattern pattern = Pattern.compile("^第.*章\\s+.*\\S");
Matcher matcher = pattern.matcher("abc");
int titleCount = 0;
StringBuilder ssb = new StringBuilder();
while (true) {
line = br.readLine();
if (line == null) {
if (sb.length() > 0) {
if (pw != null && ow != null && fout != null) {
pw.print(sb.toString());
sb.setLength(0);
printFoot(pw);
+ pw.close();
+ ow.close();
+ fout.close();
}
}
break;
}
line = line.replaceAll(">", ">");
line = line.replaceAll("<", "<");
line = line.replaceAll("&", "&");
line = line.trim();
if (line.length() > 0) {
matcher.reset(line);
if (matcher.find()) {
if (pw != null) {
if (sb.length() > 0) {
pw.print(sb.toString());
sb.setLength(0);
printFoot(pw);
}
pw.close();
}
if (ow != null) {
try {
ow.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
titleCount++;
int start = matcher.start();
int end = matcher.end();
String title = line.substring(start, end);
String s = toLongString(titleCount);
String entryName = s + ".xhtml";
outFile = new File(targetDir, entryName);
ssb.append("<chapter>\n");
ssb.append("<title>").append(title).append("</title>\n")
.append("<ename>").append(entryName).append("</ename>\n")
.append("<path>").append(outFile.getAbsolutePath()).append("</path>\n")
.append("</chapter>\n");
System.out.println(ssb.toString());
ssb.setLength(0);
fout = new FileOutputStream(outFile);
ow = new OutputStreamWriter(fout, "UTF-8");
pw = new PrintWriter(ow);
printHead(pw, title);
} else {
sb.append("\n<p>").append(line).append("</p>");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
private static void printFoot(PrintWriter pw) {
if (pw != null) {
pw.print("</body></html>");
}
}
private static void printHead(PrintWriter pw, String title) {
if (pw != null) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<!DOCTYPE html\n" +
" PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n" +
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\">");
sb.append("<head>");
if (title != null) {
sb.append("<title>").append(title).append("</title>");
}
sb.append("<meta name=\"author\" content=\"ePubMaker(vhly)\"/>");
sb.append("</head>");
sb.append("<body>\n");
sb.append("<h2>").append(title).append("</h2>");
pw.print(sb.toString());
sb = null;
}
}
private static String toLongString(int index) {
StringBuilder sb = new StringBuilder();
String si = Integer.toString(index);
int len = si.length();
if (len < 5) {
int cc = 5 - len;
for (int i = 0; i < cc; i++) {
sb.append('0');
}
sb.append(si);
} else {
sb.append(si);
}
String ret = sb.toString();
sb = null;
return ret;
}
}
| true | true | public static void main(String[] args) {
int argc = args.length;
if (argc != 2) {
System.out.println("Usage: TxtSplit <txt> <target folder>");
} else {
File file = new File(args[0]);
if (file.exists() && file.canRead()) {
File targetDir = new File(args[1]);
boolean bok = true;
if (!targetDir.exists()) {
bok = targetDir.mkdirs();
}
if (bok) {
String name = file.getName();
int index = name.lastIndexOf('.');
if (index != -1) {
name = name.substring(0, index);
}
targetDir = new File(targetDir, name);
if (!targetDir.exists()) {
bok = targetDir.mkdirs();
}
if (bok) {
StringBuilder sb = new StringBuilder();
FileReader fr = null;
BufferedReader br = null;
FileOutputStream fout = null;
OutputStreamWriter ow = null;
PrintWriter pw = null;
File outFile = null;
String line = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
Pattern pattern = Pattern.compile("^第.*章\\s+.*\\S");
Matcher matcher = pattern.matcher("abc");
int titleCount = 0;
StringBuilder ssb = new StringBuilder();
while (true) {
line = br.readLine();
if (line == null) {
if (sb.length() > 0) {
if (pw != null && ow != null && fout != null) {
pw.print(sb.toString());
sb.setLength(0);
printFoot(pw);
}
}
break;
}
line = line.replaceAll(">", ">");
line = line.replaceAll("<", "<");
line = line.replaceAll("&", "&");
line = line.trim();
if (line.length() > 0) {
matcher.reset(line);
if (matcher.find()) {
if (pw != null) {
if (sb.length() > 0) {
pw.print(sb.toString());
sb.setLength(0);
printFoot(pw);
}
pw.close();
}
if (ow != null) {
try {
ow.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
titleCount++;
int start = matcher.start();
int end = matcher.end();
String title = line.substring(start, end);
String s = toLongString(titleCount);
String entryName = s + ".xhtml";
outFile = new File(targetDir, entryName);
ssb.append("<chapter>\n");
ssb.append("<title>").append(title).append("</title>\n")
.append("<ename>").append(entryName).append("</ename>\n")
.append("<path>").append(outFile.getAbsolutePath()).append("</path>\n")
.append("</chapter>\n");
System.out.println(ssb.toString());
ssb.setLength(0);
fout = new FileOutputStream(outFile);
ow = new OutputStreamWriter(fout, "UTF-8");
pw = new PrintWriter(ow);
printHead(pw, title);
} else {
sb.append("\n<p>").append(line).append("</p>");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
| public static void main(String[] args) {
int argc = args.length;
if (argc != 2) {
System.out.println("Usage: TxtSplit <txt> <target folder>");
} else {
File file = new File(args[0]);
if (file.exists() && file.canRead()) {
File targetDir = new File(args[1]);
boolean bok = true;
if (!targetDir.exists()) {
bok = targetDir.mkdirs();
}
if (bok) {
String name = file.getName();
int index = name.lastIndexOf('.');
if (index != -1) {
name = name.substring(0, index);
}
targetDir = new File(targetDir, name);
if (!targetDir.exists()) {
bok = targetDir.mkdirs();
}
if (bok) {
StringBuilder sb = new StringBuilder();
FileReader fr = null;
BufferedReader br = null;
FileOutputStream fout = null;
OutputStreamWriter ow = null;
PrintWriter pw = null;
File outFile = null;
String line = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
Pattern pattern = Pattern.compile("^第.*章\\s+.*\\S");
Matcher matcher = pattern.matcher("abc");
int titleCount = 0;
StringBuilder ssb = new StringBuilder();
while (true) {
line = br.readLine();
if (line == null) {
if (sb.length() > 0) {
if (pw != null && ow != null && fout != null) {
pw.print(sb.toString());
sb.setLength(0);
printFoot(pw);
pw.close();
ow.close();
fout.close();
}
}
break;
}
line = line.replaceAll(">", ">");
line = line.replaceAll("<", "<");
line = line.replaceAll("&", "&");
line = line.trim();
if (line.length() > 0) {
matcher.reset(line);
if (matcher.find()) {
if (pw != null) {
if (sb.length() > 0) {
pw.print(sb.toString());
sb.setLength(0);
printFoot(pw);
}
pw.close();
}
if (ow != null) {
try {
ow.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
titleCount++;
int start = matcher.start();
int end = matcher.end();
String title = line.substring(start, end);
String s = toLongString(titleCount);
String entryName = s + ".xhtml";
outFile = new File(targetDir, entryName);
ssb.append("<chapter>\n");
ssb.append("<title>").append(title).append("</title>\n")
.append("<ename>").append(entryName).append("</ename>\n")
.append("<path>").append(outFile.getAbsolutePath()).append("</path>\n")
.append("</chapter>\n");
System.out.println(ssb.toString());
ssb.setLength(0);
fout = new FileOutputStream(outFile);
ow = new OutputStreamWriter(fout, "UTF-8");
pw = new PrintWriter(ow);
printHead(pw, title);
} else {
sb.append("\n<p>").append(line).append("</p>");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
|
diff --git a/src/main/java/knowledgeTest/controller/test/TestRunController.java b/src/main/java/knowledgeTest/controller/test/TestRunController.java
index 8e75e08..c05db2d 100644
--- a/src/main/java/knowledgeTest/controller/test/TestRunController.java
+++ b/src/main/java/knowledgeTest/controller/test/TestRunController.java
@@ -1,146 +1,148 @@
package knowledgeTest.controller.test;
import knowledgeTest.bean.RequestTask;
import knowledgeTest.bean.TaskModel;
import knowledgeTest.logic.service.UserService;
import knowledgeTest.model.Task;
import knowledgeTest.model.User;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
* Handles and retrieves runTest page.
*/
@Controller
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
@RequestMapping("/test/runTest")
public class TestRunController extends TestAbstractController {
protected static Logger logger = Logger.getLogger(TestRunController.class);
// list contain task for current user
private List<Task> taskArrayList = new ArrayList<>();
private TaskModel taskModel = new TaskModel();
@Autowired
private UserService userService;
/**
* Initiation of runTest JSP
* - initiating list of random tasks
* @param userId - path variable passed by URL and specify id of current user
* Retrieves /WEB-INF/jsp/content/test/runTest.jsp
*
* @return ModelAndView
*/
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public ModelAndView initTest(@PathVariable("userId") Long userId) {
logger.info("runTest.jsp ");
// initiating list of random tasks
taskArrayList = userService.getRandomListOfTasks(5);
User user = new User();
user.setUserId(userId);
// initiation of runTask JSP
return new ModelAndView("runTest", "user", user);
}
/**
* this method responses to GET request
* - saving user score if it positive;
* - returning next TaskModel if it's number less or equals taskArrayList size;
* @param requestTask - model to process JSON request from client
* Retrieves /WEB-INF/jsp/content/test/runTest.jsp
*
* @return TaskModel
*/
@RequestMapping(value = "/taskModel", method = RequestMethod.POST)
public @ResponseBody TaskModel getNextQuestion(@RequestBody RequestTask requestTask,
HttpServletRequest request, HttpServletResponse response) {
logger.info("runTest.jsp ");
if (requestTask.getUserId() != 0) {
User user = userService.findUserById(requestTask.getUserId());
/**
* if taskNum is null then sending first task
* if not null then sending next task and saving score if it is positive
* if taskNum value bigger then taskArrayList then redirecting to result page
*/
if (requestTask.getTaskNum() == null) {
// sending first task
taskModel = setJsonTaskModel(taskArrayList.get(0), requestTask.getUserId(), 0, null);
// sending next task
} else {
if (taskModel.getTaskNum() < taskArrayList.size() - 1) {
int taskNum = requestTask.getTaskNum();
int foo = user.getRating().getScore();
// saving score if it is positive
if (requestTask.getAnswerNum() != null) {
if (requestTask.getAnswerNum().equals(taskArrayList.get(taskNum).getCorrect())) {
userService.updateUserRating(requestTask.getUserId(), foo + 1);
}
}
// sending task with index 1, 2, 3, 4
taskModel = setJsonTaskModel(taskArrayList.get(taskNum + 1),
requestTask.getUserId(), taskNum + 1, null);
} else {
// redirecting to result page "/knowledgeTest/test/result"
- taskModel = setJsonTaskModel(null, null, null, "/test/result" + requestTask.getUserId());
+ //response.setStatus(301);
+ taskModel = setJsonTaskModel(null, null, null, "/test/result/" + requestTask.getUserId());
}
}
} else {
+ //response.setStatus(301);
taskModel = setJsonTaskModel(null, null, null, "/test/authorisation");
}
return taskModel;
}
/**
* Method setting TaskModel bean for JSON object
*
* @param task - current task to be work on;
* @param userId - current used Id;
* @param taskNum - number of current task in the list;
* @param redirect - specified as URL if redirect must be maid on client side
* @return TaskModel object
*/
protected TaskModel setJsonTaskModel(Task task, Long userId, Integer taskNum, String redirect) {
TaskModel model = new TaskModel();
model.setUserId(userId);
model.setTaskNum(taskNum);
if (task != null) {
model.setQuestion(task.getQuestion());
model.setAnswer1(task.getAnswer1());
model.setAnswer2(task.getAnswer2());
model.setAnswer3(task.getAnswer3());
model.setAnswer4(task.getAnswer4());
} else {
model.setQuestion(null);
model.setAnswer1(null);
model.setAnswer2(null);
model.setAnswer3(null);
model.setAnswer4(null);
}
model.setRedirectURL(redirect);
return model;
}
}
| false | true | public @ResponseBody TaskModel getNextQuestion(@RequestBody RequestTask requestTask,
HttpServletRequest request, HttpServletResponse response) {
logger.info("runTest.jsp ");
if (requestTask.getUserId() != 0) {
User user = userService.findUserById(requestTask.getUserId());
/**
* if taskNum is null then sending first task
* if not null then sending next task and saving score if it is positive
* if taskNum value bigger then taskArrayList then redirecting to result page
*/
if (requestTask.getTaskNum() == null) {
// sending first task
taskModel = setJsonTaskModel(taskArrayList.get(0), requestTask.getUserId(), 0, null);
// sending next task
} else {
if (taskModel.getTaskNum() < taskArrayList.size() - 1) {
int taskNum = requestTask.getTaskNum();
int foo = user.getRating().getScore();
// saving score if it is positive
if (requestTask.getAnswerNum() != null) {
if (requestTask.getAnswerNum().equals(taskArrayList.get(taskNum).getCorrect())) {
userService.updateUserRating(requestTask.getUserId(), foo + 1);
}
}
// sending task with index 1, 2, 3, 4
taskModel = setJsonTaskModel(taskArrayList.get(taskNum + 1),
requestTask.getUserId(), taskNum + 1, null);
} else {
// redirecting to result page "/knowledgeTest/test/result"
taskModel = setJsonTaskModel(null, null, null, "/test/result" + requestTask.getUserId());
}
}
} else {
taskModel = setJsonTaskModel(null, null, null, "/test/authorisation");
}
return taskModel;
}
| public @ResponseBody TaskModel getNextQuestion(@RequestBody RequestTask requestTask,
HttpServletRequest request, HttpServletResponse response) {
logger.info("runTest.jsp ");
if (requestTask.getUserId() != 0) {
User user = userService.findUserById(requestTask.getUserId());
/**
* if taskNum is null then sending first task
* if not null then sending next task and saving score if it is positive
* if taskNum value bigger then taskArrayList then redirecting to result page
*/
if (requestTask.getTaskNum() == null) {
// sending first task
taskModel = setJsonTaskModel(taskArrayList.get(0), requestTask.getUserId(), 0, null);
// sending next task
} else {
if (taskModel.getTaskNum() < taskArrayList.size() - 1) {
int taskNum = requestTask.getTaskNum();
int foo = user.getRating().getScore();
// saving score if it is positive
if (requestTask.getAnswerNum() != null) {
if (requestTask.getAnswerNum().equals(taskArrayList.get(taskNum).getCorrect())) {
userService.updateUserRating(requestTask.getUserId(), foo + 1);
}
}
// sending task with index 1, 2, 3, 4
taskModel = setJsonTaskModel(taskArrayList.get(taskNum + 1),
requestTask.getUserId(), taskNum + 1, null);
} else {
// redirecting to result page "/knowledgeTest/test/result"
//response.setStatus(301);
taskModel = setJsonTaskModel(null, null, null, "/test/result/" + requestTask.getUserId());
}
}
} else {
//response.setStatus(301);
taskModel = setJsonTaskModel(null, null, null, "/test/authorisation");
}
return taskModel;
}
|
diff --git a/src/main/java/gov/usgs/gdp/analysis/grid/FeatureCoverageWeightedGridStatistics.java b/src/main/java/gov/usgs/gdp/analysis/grid/FeatureCoverageWeightedGridStatistics.java
index f1269d26..774d126f 100644
--- a/src/main/java/gov/usgs/gdp/analysis/grid/FeatureCoverageWeightedGridStatistics.java
+++ b/src/main/java/gov/usgs/gdp/analysis/grid/FeatureCoverageWeightedGridStatistics.java
@@ -1,464 +1,464 @@
package gov.usgs.gdp.analysis.grid;
import gov.usgs.gdp.analysis.statistics.WeightedStatistics1D;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Formatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.geotools.data.FeatureSource;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.SchemaException;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.operation.TransformException;
import ucar.ma2.InvalidRangeException;
import ucar.ma2.Range;
import ucar.nc2.dt.GridCoordSystem;
import ucar.nc2.dt.GridDataset;
import ucar.nc2.dt.GridDatatype;
import ucar.nc2.ft.FeatureDataset;
import ucar.nc2.ft.FeatureDatasetFactoryManager;
import ucar.unidata.geoloc.LatLonRect;
import com.google.common.base.Preconditions;
import gov.usgs.gdp.analysis.GeoToolsNetCDFUtility;
import gov.usgs.gdp.analysis.grid.FeatureCoverageWeightedGridStatisticsWriter.Statistic;
import java.io.OutputStreamWriter;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import ucar.nc2.NetcdfFile;
import ucar.nc2.dataset.CoordinateAxis;
import ucar.nc2.dataset.CoordinateAxis1DTime;
import ucar.nc2.iosp.geotiff.GeoTiffIOServiceProvider;
public class FeatureCoverageWeightedGridStatistics {
public static void generate(
FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection,
String attributeName,
GridDataset gridDataset,
String variableName,
Range timeRange,
List<Statistic> statisticList,
BufferedWriter writer,
boolean groupByStatistic,
String delimiter)
throws IOException, InvalidRangeException, FactoryException, TransformException, SchemaException
{
GridDatatype gdt = gridDataset.findGridDatatype(variableName);
Preconditions.checkNotNull(gdt, "Variable named %s not found in gridDataset", variableName);
GridType gt = GridType.findGridType(gdt.getCoordinateSystem());
if( !(gt == GridType.YX || gt == GridType.TYX) ) {
throw new IllegalStateException("Currently require y-x or t-y-x grid for this operation");
}
LatLonRect llr = GeoToolsNetCDFUtility.getLatLonRectFromEnvelope(
featureCollection.getBounds(),
DefaultGeographicCRS.WGS84);
try {
Range[] ranges = getRangesFromLatLonRect(llr, gdt.getCoordinateSystem());
gdt = gdt.makeSubset(null, null, timeRange, null, ranges[1], ranges[0]);
} catch (InvalidRangeException ex) {
System.out.println(gdt.getCoordinateSystem().getLatLonBoundingBox());
System.out.println(llr);
Logger.getLogger(FeatureCoverageWeightedGridStatistics.class.getName()).log(Level.SEVERE, null, ex);
throw ex; // rethrow requested by IS
}
GridCoordSystem gcs = gdt.getCoordinateSystem();
Map<Object, GridCellCoverage> attributeCoverageMap =
GridCellCoverageFactory.generateByFeatureAttribute(
featureCollection,
attributeName,
gdt.getCoordinateSystem());
String variableUnits = gdt.getVariable().getUnitsString();
List<Object> attributeList = Collections.unmodifiableList(new ArrayList<Object>(attributeCoverageMap.keySet()));
FeatureCoverageWeightedGridStatisticsWriter writerX =
new FeatureCoverageWeightedGridStatisticsWriter(
attributeList,
variableName,
variableUnits,
statisticList,
groupByStatistic,
delimiter,
writer);
WeightedGridStatisticsVisitor v = null;
switch (gt) {
case YX:
v = new WeightedGridStatisticsVisitor_YX(attributeCoverageMap, writerX);
break;
case TYX:
v = new WeightedGridStatisticsVisitor_TYX(attributeCoverageMap, writerX, gcs.getTimeAxis1D(), timeRange);
break;
default:
throw new IllegalStateException("Currently require y-x or t-y-x grid for this operation");
}
GridCellTraverser gct = new GridCellTraverser(gdt);
gct.traverse(v);
}
// Handle bugs in NetCDF 4.1 for X and Y CoordinateAxis2D (c2d) with
// shapefile bound (LatLonRect) that doesn't interect any grid center
// (aka midpoint) *and* issue calculating edges for c2d axes with < 3
// grid cells in any dimension.
- private static Range[] getRangesFromLatLonRect(LatLonRect llr, GridCoordSystem gcs)
+ public static Range[] getRangesFromLatLonRect(LatLonRect llr, GridCoordSystem gcs)
throws InvalidRangeException
{
int[] lowerCornerIndices = new int[2];
int[] upperCornerIndices = new int[2];
gcs.findXYindexFromLatLon(llr.getLatMin(), llr.getLonMin(), lowerCornerIndices);
gcs.findXYindexFromLatLon(llr.getLatMax(), llr.getLonMax(), upperCornerIndices);
if (lowerCornerIndices[0] < 0 || lowerCornerIndices[1] < 0 ||
upperCornerIndices[0] < 0 || upperCornerIndices[1] < 0) {
throw new InvalidRangeException();
}
int lowerX;
int upperX;
int lowerY;
int upperY;
if(lowerCornerIndices[0] < upperCornerIndices[0]) {
lowerX = lowerCornerIndices[0];
upperX = upperCornerIndices[0];
} else {
upperX = lowerCornerIndices[0];
lowerX = upperCornerIndices[0];
}
if(lowerCornerIndices[1] < upperCornerIndices[1]) {
lowerY = lowerCornerIndices[1];
upperY = upperCornerIndices[1];
} else {
upperY = lowerCornerIndices[1];
lowerY = upperCornerIndices[1];
}
// Buffer X dimension to width of 3, otherwise grid cell width calc fails.
// NOTE: NetCDF ranges are upper edge inclusive
int deltaX = upperX - lowerX;
if (deltaX < 2) {
CoordinateAxis xAxis = gcs.getXHorizAxis();
int maxX = xAxis.getShape(xAxis.getRank() - 1) - 1; // inclusive
if (maxX < 2) {
throw new InvalidRangeException("Source grid too small");
}
if (deltaX == 0) {
if (lowerX > 0 && upperX < maxX) {
--lowerX;
++upperX;
} else {
// we're on an border cell
if (lowerX == 0) {
upperX = 2;
} else {
lowerX = maxX - 2;
}
}
} else if (deltaX == 1) {
if (lowerX == 0) {
++upperX;
} else {
--lowerX;
}
}
}
// Buffer Y dimension to width of 3, otherwise grid cell width calc fails.
// NOTE: NetCDF ranges are upper edge inclusive
int deltaY = upperY - lowerY;
- if (deltaY < 1) {
+ if (deltaY < 2) {
CoordinateAxis yAxis = gcs.getYHorizAxis();
int maxY = yAxis.getShape(0) - 1 ; // inclusive
if (maxY < 2) {
throw new InvalidRangeException("Source grid too small");
}
if (deltaY == 0) {
if (lowerY > 0 && upperY < maxY) {
--lowerY;
++upperY;
} else {
// we're on an border cell
if (lowerY == 0) {
upperY = 2;
} else {
lowerY = maxY - 2;
}
}
} else if (deltaY == 1) {
if (lowerY == 0) {
++upperY;
} else {
--lowerY;
}
}
}
return new Range[] {
new Range(lowerX, upperX),
new Range(lowerY, upperY),
};
}
protected static abstract class WeightedGridStatisticsVisitor extends FeatureCoverageGridCellVisitor {
protected Map<Object, WeightedStatistics1D> perAttributeStatistics;
protected WeightedStatistics1D allAttributeStatistics;
public WeightedGridStatisticsVisitor(Map<Object, GridCellCoverage> attributeCoverageMap) {
super(attributeCoverageMap);
}
protected Map<Object, WeightedStatistics1D> createPerAttributeStatisticsMap() {
Map map = new LinkedHashMap<Object, WeightedStatistics1D>();
for (Object attributeValue : attributeCoverageMap.keySet()) {
map.put(attributeValue, new WeightedStatistics1D());
}
return map;
}
@Override
public void yxStart() {
perAttributeStatistics = createPerAttributeStatisticsMap();
allAttributeStatistics = new WeightedStatistics1D();
}
@Override
public void processPerAttributeGridCellCoverage(double value, double coverage, Object attribute) {
perAttributeStatistics.get(attribute).accumulate(value, coverage);
}
@Override
public void processAllAttributeGridCellCoverage(double value, double coverage) {
allAttributeStatistics.accumulate(value, coverage);
}
}
protected static class WeightedGridStatisticsVisitor_YX extends WeightedGridStatisticsVisitor {
FeatureCoverageWeightedGridStatisticsWriter writer;
WeightedGridStatisticsVisitor_YX(
Map<Object, GridCellCoverage> attributeCoverageMap,
FeatureCoverageWeightedGridStatisticsWriter writer) {
super(attributeCoverageMap);
this.writer = writer;
}
@Override
public void traverseStart() {
try {
writer.writerHeader(null);
} catch (IOException ex) {
// TODO
}
}
@Override
public void traverseEnd() {
try {
writer.writeRow(
null,
perAttributeStatistics.values(),
allAttributeStatistics);
} catch (IOException ex) {
// TODO
}
}
}
protected static class WeightedGridStatisticsVisitor_TYX extends WeightedGridStatisticsVisitor {
protected Map<Object, WeightedStatistics1D> allTimestepPerAttributeStatistics;
protected WeightedStatistics1D allTimestepAllAttributeStatistics;
protected FeatureCoverageWeightedGridStatisticsWriter writer;
protected CoordinateAxis1DTime tAxis;
protected int tIndexOffset;
public WeightedGridStatisticsVisitor_TYX(
Map<Object, GridCellCoverage> attributeCoverageMap,
FeatureCoverageWeightedGridStatisticsWriter writer,
CoordinateAxis1DTime tAxis,
Range tRange) {
super(attributeCoverageMap);
this.writer = writer;
this.tAxis = tAxis;
this.tIndexOffset = tRange.first();
}
@Override
public void traverseStart() {
try {
writer.writerHeader(FeatureCoverageWeightedGridStatisticsWriter.TIMESTEPS_LABEL);
} catch (IOException ex) {
// TODO
}
allTimestepPerAttributeStatistics =
createPerAttributeStatisticsMap();
allTimestepAllAttributeStatistics = new WeightedStatistics1D();
}
@Override
public void processPerAttributeGridCellCoverage(double value, double coverage, Object attribute) {
super.processPerAttributeGridCellCoverage(value, coverage, attribute);
allTimestepPerAttributeStatistics.get(attribute).accumulate(value, coverage);
}
@Override
public void processAllAttributeGridCellCoverage(double value, double coverage) {
super.processAllAttributeGridCellCoverage(value, coverage);
allTimestepAllAttributeStatistics.accumulate(value, coverage);
}
@Override
public void tEnd(int tIndex) {
try {
writer.writeRow(
tAxis.getTimeDate(tIndexOffset + tIndex).toGMTString(),
perAttributeStatistics.values(),
allAttributeStatistics);
} catch (IOException e) {
// TODO
}
}
@Override
public void traverseEnd() {
try {
writer.writeRow(
FeatureCoverageWeightedGridStatisticsWriter.ALL_TIMESTEPS_LABEL,
allTimestepPerAttributeStatistics.values(),
allTimestepAllAttributeStatistics);
} catch (IOException ex) {
// TODO
}
}
}
// SIMPLE inline testing only, need unit tests...
public static void main(String[] args) throws Exception {
NetcdfFile.registerIOProvider(GeoTiffIOServiceProvider.class);
String ncLocation =
// "http://runoff.cr.usgs.gov:8086/thredds/dodsC/hydro/national/2.5arcmin";
// "http://internal.cida.usgs.gov/thredds/dodsC/misc/us_gfdl.A1.monthly.Tavg.1960-2099.nc";
// "http://localhost:18080/thredds/dodsC/ncml/gridded_obs.daily.Wind.ncml";
// "/Users/tkunicki/Downloads/thredds-data/CONUS_2001-2010.ncml";
// "/Users/tkunicki/Downloads/thredds-data/gridded_obs.daily.Wind.ncml";
// "dods://igsarm-cida-javadev1.er.usgs.gov:8081/thredds/dodsC/qpe/ncrfc.ncml";
// "dods://internal.cida.usgs.gov/thredds/dodsC/qpe/GRID.0530/200006_ncrfc_240ss.grd";
// "dods://michigan.glin.net:8080/thredds/dodsC/glos/all/GLCFS/Forecast/m201010900.out1.nc";
"dods://michigan.glin.net:8080/thredds/dodsC/glos/glcfs/michigan/ncas_his2d";
// "/Users/tkunicki/x.tiff";
String sfLocation =
// "/Users/tkunicki/Projects/GDP/GDP/src/main/resources/Sample_Files/Shapefiles/serap_hru_239.shp";
// "/Users/tkunicki/Downloads/lkm_hru/lkm_hru.shp";
// "/Users/tkunicki/Downloads/HUC12LM/lake_mich_12_alb_NAD83.shp";
// "/Users/tkunicki/Downloads/dbshapefiles/lk_mich.shp";
"/Users/tkunicki/Downloads/lk_mich/test.shp";
String attributeName =
// "GRID_CODE";
// "GRIDCODE";
// "OBJECTID";
"Id";
String variableName =
// "Wind";
// "P06M_NONE";
"eta";
// "depth";
// "I0B0";
Range timeRange =
new Range(30, 39);
// null;
FeatureDataset dataset = null;
FileDataStore dataStore = null;
long start = System.currentTimeMillis();
try {
dataset = FeatureDatasetFactoryManager.open(null, ncLocation, null, new Formatter());
dataStore = FileDataStoreFinder.getDataStore(new File(sfLocation));
FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = dataStore.getFeatureSource();
FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = featureSource.getFeatures();
// example csv dump...
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(System.out));
FeatureCoverageWeightedGridStatistics.generate(
featureCollection,
attributeName,
(GridDataset)dataset,
variableName,
timeRange,
Arrays.asList(new FeatureCoverageWeightedGridStatisticsWriter.Statistic[] {
FeatureCoverageWeightedGridStatisticsWriter.Statistic.mean,
FeatureCoverageWeightedGridStatisticsWriter.Statistic.maximum, }),
writer,
false,
","
);
} catch (IOException ex) {
Logger.getLogger(FeatureCoverageWeightedGridStatistics.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException ex) {
Logger.getLogger(FeatureCoverageWeightedGridStatistics.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} catch (Exception ex) {
Logger.getLogger(FeatureCoverageWeightedGridStatistics.class.getName()).log(Level.SEVERE, null, ex);
}finally {
if (dataset != null) {
try {
dataset.close();
} catch (IOException ex) {
Logger.getLogger(FeatureCoverageWeightedGridStatistics.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (dataStore != null) {
dataStore.dispose();
}
}
System.out.println("Completed in " + (System.currentTimeMillis() - start) + " ms.");
}
}
| false | true | private static Range[] getRangesFromLatLonRect(LatLonRect llr, GridCoordSystem gcs)
throws InvalidRangeException
{
int[] lowerCornerIndices = new int[2];
int[] upperCornerIndices = new int[2];
gcs.findXYindexFromLatLon(llr.getLatMin(), llr.getLonMin(), lowerCornerIndices);
gcs.findXYindexFromLatLon(llr.getLatMax(), llr.getLonMax(), upperCornerIndices);
if (lowerCornerIndices[0] < 0 || lowerCornerIndices[1] < 0 ||
upperCornerIndices[0] < 0 || upperCornerIndices[1] < 0) {
throw new InvalidRangeException();
}
int lowerX;
int upperX;
int lowerY;
int upperY;
if(lowerCornerIndices[0] < upperCornerIndices[0]) {
lowerX = lowerCornerIndices[0];
upperX = upperCornerIndices[0];
} else {
upperX = lowerCornerIndices[0];
lowerX = upperCornerIndices[0];
}
if(lowerCornerIndices[1] < upperCornerIndices[1]) {
lowerY = lowerCornerIndices[1];
upperY = upperCornerIndices[1];
} else {
upperY = lowerCornerIndices[1];
lowerY = upperCornerIndices[1];
}
// Buffer X dimension to width of 3, otherwise grid cell width calc fails.
// NOTE: NetCDF ranges are upper edge inclusive
int deltaX = upperX - lowerX;
if (deltaX < 2) {
CoordinateAxis xAxis = gcs.getXHorizAxis();
int maxX = xAxis.getShape(xAxis.getRank() - 1) - 1; // inclusive
if (maxX < 2) {
throw new InvalidRangeException("Source grid too small");
}
if (deltaX == 0) {
if (lowerX > 0 && upperX < maxX) {
--lowerX;
++upperX;
} else {
// we're on an border cell
if (lowerX == 0) {
upperX = 2;
} else {
lowerX = maxX - 2;
}
}
} else if (deltaX == 1) {
if (lowerX == 0) {
++upperX;
} else {
--lowerX;
}
}
}
// Buffer Y dimension to width of 3, otherwise grid cell width calc fails.
// NOTE: NetCDF ranges are upper edge inclusive
int deltaY = upperY - lowerY;
if (deltaY < 1) {
CoordinateAxis yAxis = gcs.getYHorizAxis();
int maxY = yAxis.getShape(0) - 1 ; // inclusive
if (maxY < 2) {
throw new InvalidRangeException("Source grid too small");
}
if (deltaY == 0) {
if (lowerY > 0 && upperY < maxY) {
--lowerY;
++upperY;
} else {
// we're on an border cell
if (lowerY == 0) {
upperY = 2;
} else {
lowerY = maxY - 2;
}
}
} else if (deltaY == 1) {
if (lowerY == 0) {
++upperY;
} else {
--lowerY;
}
}
}
return new Range[] {
new Range(lowerX, upperX),
new Range(lowerY, upperY),
};
}
| public static Range[] getRangesFromLatLonRect(LatLonRect llr, GridCoordSystem gcs)
throws InvalidRangeException
{
int[] lowerCornerIndices = new int[2];
int[] upperCornerIndices = new int[2];
gcs.findXYindexFromLatLon(llr.getLatMin(), llr.getLonMin(), lowerCornerIndices);
gcs.findXYindexFromLatLon(llr.getLatMax(), llr.getLonMax(), upperCornerIndices);
if (lowerCornerIndices[0] < 0 || lowerCornerIndices[1] < 0 ||
upperCornerIndices[0] < 0 || upperCornerIndices[1] < 0) {
throw new InvalidRangeException();
}
int lowerX;
int upperX;
int lowerY;
int upperY;
if(lowerCornerIndices[0] < upperCornerIndices[0]) {
lowerX = lowerCornerIndices[0];
upperX = upperCornerIndices[0];
} else {
upperX = lowerCornerIndices[0];
lowerX = upperCornerIndices[0];
}
if(lowerCornerIndices[1] < upperCornerIndices[1]) {
lowerY = lowerCornerIndices[1];
upperY = upperCornerIndices[1];
} else {
upperY = lowerCornerIndices[1];
lowerY = upperCornerIndices[1];
}
// Buffer X dimension to width of 3, otherwise grid cell width calc fails.
// NOTE: NetCDF ranges are upper edge inclusive
int deltaX = upperX - lowerX;
if (deltaX < 2) {
CoordinateAxis xAxis = gcs.getXHorizAxis();
int maxX = xAxis.getShape(xAxis.getRank() - 1) - 1; // inclusive
if (maxX < 2) {
throw new InvalidRangeException("Source grid too small");
}
if (deltaX == 0) {
if (lowerX > 0 && upperX < maxX) {
--lowerX;
++upperX;
} else {
// we're on an border cell
if (lowerX == 0) {
upperX = 2;
} else {
lowerX = maxX - 2;
}
}
} else if (deltaX == 1) {
if (lowerX == 0) {
++upperX;
} else {
--lowerX;
}
}
}
// Buffer Y dimension to width of 3, otherwise grid cell width calc fails.
// NOTE: NetCDF ranges are upper edge inclusive
int deltaY = upperY - lowerY;
if (deltaY < 2) {
CoordinateAxis yAxis = gcs.getYHorizAxis();
int maxY = yAxis.getShape(0) - 1 ; // inclusive
if (maxY < 2) {
throw new InvalidRangeException("Source grid too small");
}
if (deltaY == 0) {
if (lowerY > 0 && upperY < maxY) {
--lowerY;
++upperY;
} else {
// we're on an border cell
if (lowerY == 0) {
upperY = 2;
} else {
lowerY = maxY - 2;
}
}
} else if (deltaY == 1) {
if (lowerY == 0) {
++upperY;
} else {
--lowerY;
}
}
}
return new Range[] {
new Range(lowerX, upperX),
new Range(lowerY, upperY),
};
}
|
diff --git a/src/com/android/calendar/EmailAddressAdapter.java b/src/com/android/calendar/EmailAddressAdapter.java
index 46799609..bfcb986f 100644
--- a/src/com/android/calendar/EmailAddressAdapter.java
+++ b/src/com/android/calendar/EmailAddressAdapter.java
@@ -1,76 +1,76 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.calendar;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.text.util.Rfc822Token;
import android.view.View;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
// Customized from com.android.email.EmailAddressAdapter
public class EmailAddressAdapter extends ResourceCursorAdapter {
public static final int NAME_INDEX = 1;
public static final int DATA_INDEX = 2;
private static final String SORT_ORDER =
Contacts.TIMES_CONTACTED + " DESC, " + Contacts.DISPLAY_NAME;
private ContentResolver mContentResolver;
private static final String[] PROJECTION = {
Data._ID, // 0
Contacts.DISPLAY_NAME, // 1
Email.DATA // 2
};
public EmailAddressAdapter(Context context) {
super(context, android.R.layout.simple_dropdown_item_1line, null);
mContentResolver = context.getContentResolver();
}
@Override
public final String convertToString(Cursor cursor) {
return makeDisplayString(cursor);
}
private final String makeDisplayString(Cursor cursor) {
String name = cursor.getString(NAME_INDEX);
String address = cursor.getString(DATA_INDEX);
- return new Rfc822Token(address, name, null).toString();
+ return new Rfc822Token(name, address, null).toString();
}
@Override
public final void bindView(View view, Context context, Cursor cursor) {
((TextView) view).setText(makeDisplayString(cursor));
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
String filter = constraint == null ? "" : constraint.toString();
Uri uri = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, Uri.encode(filter));
return mContentResolver.query(uri, PROJECTION, null, null, SORT_ORDER);
}
}
| true | true | private final String makeDisplayString(Cursor cursor) {
String name = cursor.getString(NAME_INDEX);
String address = cursor.getString(DATA_INDEX);
return new Rfc822Token(address, name, null).toString();
}
| private final String makeDisplayString(Cursor cursor) {
String name = cursor.getString(NAME_INDEX);
String address = cursor.getString(DATA_INDEX);
return new Rfc822Token(name, address, null).toString();
}
|
diff --git a/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java b/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java
index a5442ad..b5f773a 100644
--- a/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java
+++ b/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java
@@ -1,994 +1,994 @@
package org.agmip.translators.dssat;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import org.agmip.core.types.AdvancedHashMap;
/**
* DSSAT Experiment Data I/O API Class
*
* @author Meng Zhang
* @version 1.0
*/
public class DssatXFileInput extends DssatCommonInput {
/**
* Constructor with no parameters
* Set jsonKey as "experiment"
*
*/
public DssatXFileInput() {
super();
jsonKey = "experiment";
}
/**
* DSSAT XFile Data input method for Controller using
*
* @param brMap The holder for BufferReader objects for all files
* @return result data holder object
*/
@Override
protected AdvancedHashMap readFile(HashMap brMap) throws IOException {
AdvancedHashMap ret = new AdvancedHashMap();
String line;
BufferedReader br;
char[] buf;
BufferedReader brw = null;
char[] bufW = null;
HashMap mapW;
String wid;
String fileName;
LinkedHashMap formats = new LinkedHashMap();
ArrayList trArr = new ArrayList();
ArrayList cuArr = new ArrayList();
ArrayList flArr = new ArrayList();
ArrayList saArr = new ArrayList();
ArrayList sadArr = new ArrayList();
ArrayList icArr = new ArrayList();
ArrayList icdArr = new ArrayList();
ArrayList plArr = new ArrayList();
ArrayList irArr = new ArrayList();
ArrayList irdArr = new ArrayList();
ArrayList feArr = new ArrayList();
ArrayList omArr = new ArrayList();
ArrayList chArr = new ArrayList();
ArrayList tiArr = new ArrayList();
ArrayList emArr = new ArrayList();
ArrayList haArr = new ArrayList();
ArrayList smArr = new ArrayList();
String eventKey = "data";
buf = (char[]) brMap.get("X");
mapW = (HashMap) brMap.get("W");
fileName = (String) brMap.get("Z");
wid = fileName.length() > 4 ? fileName.substring(0, 4) : fileName;
// If XFile is no been found
if (buf == null) {
// TODO reprot file not exist error
return ret;
} else {
br = new BufferedReader(new CharArrayReader(buf));
}
ret.put("treatment", trArr);
// ret.put("cultivar", cuArr);
// ret.put("field", flArr);
// ret.put("soil_analysis", saArr);
// ret.put("initial_condition", icArr);
// ret.put("plant", plArr);
// ret.put("irrigation", irArr);
// ret.put("fertilizer", feArr);
// ret.put("residue_organic", omArr);
// ret.put("chemical", chArr);
// ret.put("tillage", tiArr);
// ret.put("emvironment", emArr);
// ret.put("harvest", haArr);
// ret.put("simulation", smArr);
while ((line = br.readLine()) != null) {
// Get content type of line
judgeContentType(line);
// Read Exp title info
if (flg[0].startsWith("exp.details:") && flg[2].equals("")) {
// Set variables' formats
formats.clear();
formats.put("exname", 11);
formats.put("local_name", 61);
// Read line and save into return holder
ret.put(readLine(line.substring(13), formats));
ret.put("institutes", line.substring(14, 16).trim());
} // Read General Section
else if (flg[0].startsWith("general")) {
// People info
if (flg[1].equals("people") && flg[2].equals("data")) {
ret.put("people", line.trim());
} // Address info
else if (flg[1].equals("address") && flg[2].equals("data")) {
String[] addr = line.split(",[ ]*");
ret.put("fl_loc_1", "");
ret.put("fl_loc_2", "");
ret.put("fl_loc_3", "");
ret.put("institutes", line.trim());
// ret.put("address", line.trim()); // P.S. no longer to use this field
switch (addr.length) {
case 0:
break;
case 1:
ret.put("fl_loc_1", addr[0]);
break;
case 2:
ret.put("fl_loc_1", addr[1]);
ret.put("fl_loc_2", addr[0]);
break;
case 3:
ret.put("fl_loc_1", addr[2]);
ret.put("fl_loc_2", addr[1]);
ret.put("fl_loc_3", addr[0]);
break;
default:
ret.put("fl_loc_1", addr[addr.length - 1]);
ret.put("fl_loc_2", addr[addr.length - 2]);
String loc3 = "";
for (int i = 0; i < addr.length - 2; i++) {
loc3 += addr[i] + ", ";
}
ret.put("fl_loc_3", loc3.substring(0, loc3.length() - 2));
}
} // Site info
else if ((flg[1].equals("site") || flg[1].equals("sites")) && flg[2].equals("data")) {
//$ret[$flg[0]]["site"] = trim($line);
// P.S. site is missing in the master variables list
ret.put("site", line.trim());
} // Plot Info
else if (flg[1].startsWith("parea") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("parea", 7);
formats.put("prno", 6);
formats.put("plen", 6);
formats.put("pldr", 6);
formats.put("plsp", 6);
formats.put("play", 6);
formats.put("pltha", 6);
formats.put("hrno", 6);
formats.put("hlen", 6);
formats.put("plthm", 16);
// Read line and save into return holder
ret.put("plot_info", readLine(line, formats));
} // Notes field
else if (flg[1].equals("notes") && flg[2].equals("data")) {
//$ret[$flg[0]]["notes"] = addArray($ret[$flg[0]]["notes"], " ". trim($line), "");
if (!ret.containsKey("notes")) {
ret.put("notes", line.trim() + "\\r\\n");
} else {
String notes = (String) ret.get("notes");
notes += line.trim() + "\\r\\n";
ret.put("notes", notes);
}
} else {
}
} // Read TREATMENTS Section
else if (flg[0].startsWith("treatments")) {
// Read TREATMENTS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("trno", 2);
formats.put("sq", 2);
formats.put("op", 2);
formats.put("co", 2);
formats.put("tr_name", 26);
formats.put("ge", 3);
formats.put("fl", 3);
formats.put("sa", 3);
formats.put("ic", 3);
formats.put("pl", 3);
formats.put("ir", 3);
formats.put("fe", 3);
formats.put("om", 3);
formats.put("ch", 3);
formats.put("ti", 3);
formats.put("em", 3);
formats.put("ha", 3);
formats.put("sm", 3);
// Read line and save into return holder
trArr.add(readLine(line, formats));
} else {
}
} // Read CULTIVARS Section
else if (flg[0].startsWith("cultivars")) {
// Read CULTIVARS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ge", 2);
formats.put("cr", 3);
formats.put("cul_id", 7);
formats.put("cul_name", 17);
// Read line and save into return holder
cuArr.add(readLine(line, formats));
if (cuArr.size() == 1) {
ret.put("cr", line.substring(3, 5).trim()); // TODO keep for the early version; just first entry
}
} else {
}
} // Read FIELDS Section
else if (flg[0].startsWith("fields")) {
// Read field info 1st line
if (flg[1].startsWith("l id_") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("id_field", 9);
formats.put("wsta_id", 9); //P.S. id do not match with the master list "wth_id"; might have another id name
formats.put("flsl", 6);
formats.put("flob", 6);
formats.put("fl_drntype", 6);
formats.put("fldrd", 6);
formats.put("fldrs", 6);
formats.put("flst", 6);
formats.put("sltx", 6);
formats.put("sldp", 6);
formats.put("soil_id", 11);
formats.put("fl_name", line.length());
// Read line and save into return holder
addToArray(flArr, readLine(line, formats), "fl");
// Read weather station id
wid = line.substring(12, 20).trim();
}// // Read field info 2nd line
else if (flg[1].startsWith("l ...") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("fl_lat", 16);
formats.put("fl_long", 16);
formats.put("flele", 10);
formats.put("farea", 18);
formats.put("", 6); // P.S. id do not find in the master list (? it seems to be calculated by other fields)
formats.put("fllwr", 6);
formats.put("flsla", 6);
formats.put("flhst", 6); // P.S. id do not find in the master list (field histoy code)
formats.put("fhdur", 6); // P.S. id do not find in the master list (duration associated with field history code in years)
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// Read lat and long
String strLat = (String) tmp.get("fl_lat");
String strLong = (String) tmp.get("fl_long");
// If lat or long is not valid data, read data from weather file
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
// check if weather is validable
for (Object key : mapW.keySet()) {
if (((String) key).contains(wid)) {
bufW = (char[]) mapW.get(key);
break;
}
}
if (bufW != null) {
brw = new BufferedReader(new CharArrayReader(bufW));
String lineW;
while ((lineW = brw.readLine()) != null) {
if (lineW.startsWith("@ INSI")) {
lineW = brw.readLine();
strLat = lineW.substring(6, 15).trim();
strLong = lineW.substring(15, 24).trim();
break;
}
}
// check if lat and long are valid in the weather file; if not, set invalid value for them
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
strLat = defValI;
strLong = defValI;
}
} // if weather file is not avaliable to read, set invalid value for lat and long
else {
strLat = defValI;
strLong = defValI;
}
}
if (flArr.isEmpty()) {
- ret.put("fl_lat", strLong); // TODO Keep the meta data handling for the early version
- ret.put("fl_long", strLat); // TODO Keep the meta data handling for the early version
+ ret.put("fl_lat", strLat); // TODO Keep the meta data handling for the early version
+ ret.put("fl_long", strLong); // TODO Keep the meta data handling for the early version
}
- tmp.put("fl_lat", strLong);
- tmp.put("fl_long", strLat);
+ tmp.put("fl_lat", strLat);
+ tmp.put("fl_long", strLong);
addToArray(flArr, tmp, "fl");
}
} // Read SOIL ANALYSIS Section
else if (flg[0].startsWith("soil")) {
// Read SOIL ANALYSIS global data
if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sa", 2);
formats.put("sadat", 6);
formats.put("samhb", 6);
formats.put("sampx", 6);
formats.put("samke", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("sadat", translateDateStr((String) tmp.get("sadat")));
saArr.add(tmp);
sadArr = new ArrayList();
tmp.put(eventKey, sadArr);
} // Read SOIL ANALYSIS layer data
else if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "sa"
formats.put("sabl", 6);
formats.put("sabdm", 6);
formats.put("saoc", 6);
formats.put("sani", 6);
formats.put("saphw", 6);
formats.put("saphb", 6);
formats.put("sapx", 6);
formats.put("sake", 6);
formats.put("sasc", 6); // P.S. id do not find in the master list (Measured stable organic C by soil layer, g[C]/100g[Soil])
// Read line and save into return holder
sadArr.add(readLine(line, formats));
} else {
}
} // Read INITIAL CONDITIONS Section
else if (flg[0].startsWith("initial")) {
// Read INITIAL CONDITIONS global data
if (flg[1].startsWith("c pcr") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ic", 2);
formats.put("icpcr", 6);
formats.put("icdat", 6);
formats.put("icrt", 6);
formats.put("icnd", 6);
formats.put("icrz#", 6); // P.S. use the "icrz#" instead of "icrzno"
formats.put("icrze", 6);
formats.put("icwt", 6);
formats.put("icrag", 6);
formats.put("icrn", 6);
formats.put("icrp", 6);
formats.put("icrip", 6);
formats.put("icrdp", 6);
formats.put("ic_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("icdat", translateDateStr((String) tmp.get("icdat")));
icArr.add(tmp);
icdArr = new ArrayList();
tmp.put(eventKey, icdArr);
} else // INITIAL CONDITIONS layer data
if (flg[1].startsWith("c icbl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the detail (event) data index "ic"
formats.put("icbl", 6);
formats.put("ich2o", 6);
formats.put("icnh4", 6);
formats.put("icno3", 6);
// Read line and save into return holder
icdArr.add(readLine(line, formats));
} else {
}
} // Read PLANTING DETAILS Section
else if (flg[0].startsWith("planting")) {
// Read PLANTING data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("pl", 2);
formats.put("pdate", 6);
formats.put("pldae", 6);
formats.put("plpop", 6);
formats.put("plpoe", 6);
formats.put("plme", 6);
formats.put("plds", 6);
formats.put("plrs", 6);
formats.put("plrd", 6);
formats.put("pldp", 6);
formats.put("plmwt", 6);
formats.put("page", 6);
formats.put("penv", 6);
formats.put("plph", 6);
formats.put("plspl", 6);
formats.put("pl_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("pdate", translateDateStr((String) tmp.get("pdate")));
tmp.put("pldae", translateDateStr((String) tmp.get("pldae")));
plArr.add(tmp);
if (plArr.size() == 1) {
ret.put("pdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for the early version
}
} else {
}
} // Read IRRIGATION AND WATER MANAGEMENT Section
else if (flg[0].startsWith("irrigation")) {
// Read IRRIGATION global data
if (flg[1].startsWith("i efir") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ir", 2);
formats.put("ireff", 6);
formats.put("irmdp", 6);
formats.put("irthr", 6);
formats.put("irept", 6);
formats.put("irstg", 6);
formats.put("iame", 6);
formats.put("iamt", 6);
formats.put("ir_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
irArr.add(tmp);
irdArr = new ArrayList();
tmp.put(eventKey, irdArr);
} // Read IRRIGATION appliction data
else if (flg[1].startsWith("i idate") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "ir"
formats.put("idate", 6);
formats.put("irop", 6);
formats.put("irval", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("idate", translateDateStr((String) tmp.get("idate"))); // TODO DOY handling
irdArr.add(tmp);
} else {
}
} // Read FERTILIZERS (INORGANIC) Section
else if (flg[0].startsWith("fertilizers")) {
// Read FERTILIZERS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fe", 2);
formats.put("fdate", 6);
formats.put("fecd", 6);
formats.put("feacd", 6);
formats.put("fedep", 6);
formats.put("feamn", 6);
formats.put("feamp", 6);
formats.put("feamk", 6);
formats.put("feamc", 6);
formats.put("feamo", 6);
formats.put("feocd", 6);
formats.put("fe_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("fdate", translateDateStr((String) tmp.get("fdate"))); // TODO DOY handling
feArr.add(tmp);
} else {
}
} // Read RESIDUES AND OTHER ORGANIC MATERIALS Section
else if (flg[0].startsWith("residues")) {
// Read ORGANIC MATERIALS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("om", 2);
formats.put("omdat", 6); // P.S. id do not match with the master list "omday"
formats.put("omcd", 6);
formats.put("omamt", 6);
formats.put("omn%", 6); // P.S. id do not match with the master list "omnpct"
formats.put("omp%", 6); // P.S. id do not match with the master list "omppct"
formats.put("omk%", 6); // P.S. id do not match with the master list "omkpct"
formats.put("ominp", 6);
formats.put("omdep", 6);
formats.put("omacd", 6);
formats.put("om_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("omdat", translateDateStr((String) tmp.get("omdat"))); // TODO DOY handling
omArr.add(tmp);
} else {
}
} // Read CHEMICAL APPLICATIONS Section
else if (flg[0].startsWith("chemical")) {
// Read CHEMICAL APPLICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ch", 2);
formats.put("cdate", 6);
formats.put("chcd", 6);
formats.put("chamt", 6);
formats.put("chacd", 6);
formats.put("chdep", 6);
formats.put("ch_targets", 6);
formats.put("ch_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("cdate", translateDateStr((String) tmp.get("cdate")));
chArr.add(tmp);
} else {
}
} // Read TILLAGE Section
else if (flg[0].startsWith("tillage")) {
// Read TILLAGE data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ti", 2);
formats.put("tdate", 6);
formats.put("tiimp", 6);
formats.put("tidep", 6);
formats.put("ti_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("tdate", translateDateStr((String) tmp.get("tdate")));
tiArr.add(tmp);
} else {
}
} // Read ENVIRONMENT MODIFICATIONS Section
else if (flg[0].startsWith("environment")) {
// Read ENVIRONMENT MODIFICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("em", 2);
formats.put("emday", 6);
formats.put("ecdyl", 2);
formats.put("emdyl", 4);
formats.put("ecrad", 2);
formats.put("emrad", 4);
formats.put("ecmax", 2);
formats.put("emmax", 4);
formats.put("ecmin", 2);
formats.put("emmin", 4);
formats.put("ecrai", 2);
formats.put("emrai", 4);
formats.put("ecco2", 2);
formats.put("emco2", 4);
formats.put("ecdew", 2);
formats.put("emdew", 4);
formats.put("ecwnd", 2);
formats.put("emwnd", 4);
formats.put("em_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("emday", translateDateStr((String) tmp.get("emday")));
emArr.add(tmp);
} else {
}
} // Read HARVEST DETAILS Section
else if (flg[0].startsWith("harvest")) {
// Read HARVEST data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ha", 2);
formats.put("hdate", 6);
formats.put("hastg", 6);
formats.put("hacom", 6);
formats.put("hasiz", 6);
formats.put("hapc", 6);
formats.put("habpc", 6);
formats.put("ha_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("hdate", translateDateStr((String) tmp.get("hdate")));
haArr.add(tmp);
if (haArr.size() == 1) {
ret.put("hdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for early version
}
} else {
}
} // Read SIMULATION CONTROLS Section // P.S. no need to be divided
else if (flg[0].startsWith("simulation")) {
// Read general info
if (flg[1].startsWith("n general") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("general", 12);
// formats.put("nyers", 6);
// formats.put("nreps", 6);
// formats.put("start", 6);
// formats.put("sdate", 6);
// formats.put("rseed", 6);
// formats.put("sname", 26);
// formats.put("model", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("sdate", translateDateStr((String) tmp.get("sdate")));
tmp.put("general", line);
addToArray(smArr, tmp, "sm");
} // Read options info
else if (flg[1].startsWith("n options") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("options", 12);
// formats.put("water", 6);
// formats.put("nitro", 6);
// formats.put("symbi", 6);
// formats.put("phosp", 6);
// formats.put("potas", 6);
// formats.put("dises", 6);
// formats.put("chem", 6);
// formats.put("till", 6);
// formats.put("co2", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("options", line);
addToArray(smArr, tmp, "sm");
} // Read methods info
else if (flg[1].startsWith("n methods") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("methods", 12);
// formats.put("wther", 6);
// formats.put("incon", 6);
// formats.put("light", 6);
// formats.put("evapo", 6);
// formats.put("infil", 6);
// formats.put("photo", 6);
// formats.put("hydro", 6);
// formats.put("nswit", 6);
// formats.put("mesom", 6);
// formats.put("mesev", 6);
// formats.put("mesol", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("methods", line);
addToArray(smArr, tmp, "sm");
} // Read management info
else if (flg[1].startsWith("n management") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("management", 12);
// formats.put("plant", 6);
// formats.put("irrig", 6);
// formats.put("ferti", 6);
// formats.put("resid", 6);
// formats.put("harvs", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("management", line);
addToArray(smArr, tmp, "sm");
} // Read outputs info
else if (flg[1].startsWith("n outputs") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("outputs", 12);
// formats.put("fname", 6);
// formats.put("ovvew", 6);
// formats.put("sumry", 6);
// formats.put("fropt", 6);
// formats.put("grout", 6);
// formats.put("caout", 6);
// formats.put("waout", 6);
// formats.put("niout", 6);
// formats.put("miout", 6);
// formats.put("diout", 6);
// formats.put("long", 6);
// formats.put("chout", 6);
// formats.put("opout", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("outputs", line);
addToArray(smArr, tmp, "sm");
} // Read planting info
else if (flg[1].startsWith("n planting") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("planting", 12);
// formats.put("pfrst", 6);
// formats.put("plast", 6);
// formats.put("ph20l", 6);
// formats.put("ph2ou", 6);
// formats.put("ph20d", 6);
// formats.put("pstmx", 6);
// formats.put("pstmn", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("pfrst", translateDateStr((String) tmp.get("pfrst")));
// tmp.put("plast", translateDateStr((String) tmp.get("plast")));
tmp.put("planting", line);
addToArray(smArr, tmp, "sm");
} // Read irrigation info
else if (flg[1].startsWith("n irrigation") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("irrigation", 12);
// formats.put("imdep", 6);
// formats.put("ithrl", 6);
// formats.put("ithru", 6);
// formats.put("iroff", 6);
// formats.put("imeth", 6);
// formats.put("iramt", 6);
// formats.put("ireff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("irrigation", line);
addToArray(smArr, tmp, "sm");
} // Read nitrogen info
else if (flg[1].startsWith("n nitrogen") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("nitrogen", 12);
// formats.put("nmdep", 6);
// formats.put("nmthr", 6);
// formats.put("namnt", 6);
// formats.put("ncode", 6);
// formats.put("naoff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("nitrogen", line);
addToArray(smArr, tmp, "sm");
} // Read residues info
else if (flg[1].startsWith("n residues") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("residues", 12);
// formats.put("ripcn", 6);
// formats.put("rtime", 6);
// formats.put("ridep", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("residues", line);
addToArray(smArr, tmp, "sm");
} // Read harvest info
else if (flg[1].startsWith("n harvest") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("harvests", 12);
// formats.put("hfrst", 6); // P.S. Keep the original value
// formats.put("hlast", 6);
// formats.put("hpcnp", 6);
// formats.put("hrcnr", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("hlast", translateDateStr((String) tmp.get("hlast")));
tmp.put("harvests", line);
addToArray(smArr, tmp, "sm");
} else {
}
} else {
}
}
br.close();
if (brw != null) {
brw.close();
}
for (int i = 0; i < trArr.size(); i++) {
AdvancedHashMap treatment = (AdvancedHashMap) trArr.get(i);
// cultivar
if (!treatment.getOr("ge", "0").equals("0")) {
treatment.put("cultivar", getSectionData(cuArr, "ge", treatment.get("ge").toString()));
}
// field
if (!treatment.getOr("fl", "0").equals("0")) {
treatment.put("field", getSectionData(flArr, "fl", treatment.get("fl").toString()));
}
// soil_analysis
if (!treatment.getOr("sa", "0").equals("0")) {
treatment.put("soil_analysis", getSectionData(saArr, "sa", treatment.get("sa").toString()));
}
// initial_condition
if (!treatment.getOr("ic", "0").equals("0")) {
treatment.put("initial_condition", getSectionData(icArr, "ic", treatment.get("ic").toString()));
}
// plant
if (!treatment.getOr("pl", "0").equals("0")) {
treatment.put("plant", getSectionData(plArr, "pl", treatment.get("pl").toString()));
}
// irrigation
if (!treatment.getOr("ir", "0").equals("0")) {
treatment.put("irrigation", getSectionData(irArr, "ir", treatment.get("ir").toString()));
}
// fertilizer
if (!treatment.getOr("fe", "0").equals("0")) {
treatment.put("fertilizer", getSectionData(feArr, "fe", treatment.get("fe").toString()));
}
// residue_organic
if (!treatment.getOr("om", "0").equals("0")) {
treatment.put("residue_organic", getSectionData(omArr, "om", treatment.get("om").toString()));
}
// chemical
if (!treatment.getOr("ch", "0").equals("0")) {
treatment.put("chemical", getSectionData(chArr, "ch", treatment.get("ch").toString()));
}
// tillage
if (!treatment.getOr("ti", "0").equals("0")) {
treatment.put("tillage", getSectionData(tiArr, "ti", treatment.get("ti").toString()));
}
// emvironment
if (!treatment.getOr("em", "0").equals("0")) {
treatment.put("emvironment", getSectionData(emArr, "em", treatment.get("em").toString()));
}
// harvest
if (!treatment.getOr("ha", "0").equals("0")) {
treatment.put("harvest", getSectionData(haArr, "ha", treatment.get("ha").toString()));
}
// simulation
if (!treatment.getOr("sm", "0").equals("0")) {
treatment.put("simulation", getSectionData(smArr, "sm", treatment.get("sm").toString()));
}
// Revise the date value for FEDATE, IDATE, MLADAT
// Get Planting date
String pdate = "";
ArrayList plTmps = (ArrayList) treatment.getOr("planting", new ArrayList());
if (!plTmps.isEmpty()) {
pdate = (String) ((AdvancedHashMap) plTmps.get(0)).getOr("pdate", "");
if (pdate.length() > 5) {
pdate = pdate.substring(2);
}
}
// Fertilizer Date
ArrayList feTmps = (ArrayList) treatment.getOr("fertilizer", new ArrayList());
AdvancedHashMap feTmp;
for (int j = 0; j < feTmps.size(); j++) {
feTmp = (AdvancedHashMap) feTmps.get(j);
feTmp.put("fdate", translateDateStrForDOY((String) feTmp.get("fdate"), pdate));
}
// Initial condition date
AdvancedHashMap icTmp = (AdvancedHashMap) treatment.get("initial_condition");
if (icTmp != null) {
icTmp.put("idate", translateDateStrForDOY((String) icTmp.getOr("idate", defValI), pdate));
}
// Mulch application date
AdvancedHashMap omTmp = (AdvancedHashMap) treatment.get("residue_organic");
if (omTmp != null) {
omTmp.put("omdat", translateDateStrForDOY((String) omTmp.getOr("omdat", defValI), pdate));
}
}
compressData(ret);
return ret;
}
/**
* Set reading flgs for title lines (marked with *)
*
* @param line the string of reading line
*/
@Override
protected void setTitleFlgs(String line) {
flg[0] = line.substring(1).trim().toLowerCase();
flg[1] = "";
flg[2] = "";
}
/**
* Get the section data by given index value and key
*
* @param secArr Section data array
* @param key index variable name
* @param value index variable value
*/
private Object getSectionData(ArrayList secArr, Object key, String value) {
ArrayList ret = null;
// Get First data node
if (secArr.isEmpty()) {
return null;
}
// Define the section with single sub data
ArrayList singleSubRecSecList = new ArrayList();
singleSubRecSecList.add("ge");
singleSubRecSecList.add("fl");
singleSubRecSecList.add("pl");
singleSubRecSecList.add("om"); // TODO wait for confirmation that single sub record
singleSubRecSecList.add("ti"); // TODO wait for confirmation that single sub record
singleSubRecSecList.add("sm");
AdvancedHashMap fstNode = (AdvancedHashMap) secArr.get(0);
// If it contains multiple sub array of data, or it does not have multiple sub records
if (fstNode.containsKey("data") || singleSubRecSecList.contains(key)) {
for (int i = 0; i < secArr.size(); i++) {
if (((AdvancedHashMap) secArr.get(i)).get(key).equals(value)) {
return secArr.get(i);
}
}
} // If it is simple array
else {
ret = new ArrayList();
AdvancedHashMap node;
for (int i = 0; i < secArr.size(); i++) {
node = (AdvancedHashMap) secArr.get(i);
if (node.get(key).equals(value)) {
ret.add(node);
}
}
}
return ret;
}
}
| false | true | protected AdvancedHashMap readFile(HashMap brMap) throws IOException {
AdvancedHashMap ret = new AdvancedHashMap();
String line;
BufferedReader br;
char[] buf;
BufferedReader brw = null;
char[] bufW = null;
HashMap mapW;
String wid;
String fileName;
LinkedHashMap formats = new LinkedHashMap();
ArrayList trArr = new ArrayList();
ArrayList cuArr = new ArrayList();
ArrayList flArr = new ArrayList();
ArrayList saArr = new ArrayList();
ArrayList sadArr = new ArrayList();
ArrayList icArr = new ArrayList();
ArrayList icdArr = new ArrayList();
ArrayList plArr = new ArrayList();
ArrayList irArr = new ArrayList();
ArrayList irdArr = new ArrayList();
ArrayList feArr = new ArrayList();
ArrayList omArr = new ArrayList();
ArrayList chArr = new ArrayList();
ArrayList tiArr = new ArrayList();
ArrayList emArr = new ArrayList();
ArrayList haArr = new ArrayList();
ArrayList smArr = new ArrayList();
String eventKey = "data";
buf = (char[]) brMap.get("X");
mapW = (HashMap) brMap.get("W");
fileName = (String) brMap.get("Z");
wid = fileName.length() > 4 ? fileName.substring(0, 4) : fileName;
// If XFile is no been found
if (buf == null) {
// TODO reprot file not exist error
return ret;
} else {
br = new BufferedReader(new CharArrayReader(buf));
}
ret.put("treatment", trArr);
// ret.put("cultivar", cuArr);
// ret.put("field", flArr);
// ret.put("soil_analysis", saArr);
// ret.put("initial_condition", icArr);
// ret.put("plant", plArr);
// ret.put("irrigation", irArr);
// ret.put("fertilizer", feArr);
// ret.put("residue_organic", omArr);
// ret.put("chemical", chArr);
// ret.put("tillage", tiArr);
// ret.put("emvironment", emArr);
// ret.put("harvest", haArr);
// ret.put("simulation", smArr);
while ((line = br.readLine()) != null) {
// Get content type of line
judgeContentType(line);
// Read Exp title info
if (flg[0].startsWith("exp.details:") && flg[2].equals("")) {
// Set variables' formats
formats.clear();
formats.put("exname", 11);
formats.put("local_name", 61);
// Read line and save into return holder
ret.put(readLine(line.substring(13), formats));
ret.put("institutes", line.substring(14, 16).trim());
} // Read General Section
else if (flg[0].startsWith("general")) {
// People info
if (flg[1].equals("people") && flg[2].equals("data")) {
ret.put("people", line.trim());
} // Address info
else if (flg[1].equals("address") && flg[2].equals("data")) {
String[] addr = line.split(",[ ]*");
ret.put("fl_loc_1", "");
ret.put("fl_loc_2", "");
ret.put("fl_loc_3", "");
ret.put("institutes", line.trim());
// ret.put("address", line.trim()); // P.S. no longer to use this field
switch (addr.length) {
case 0:
break;
case 1:
ret.put("fl_loc_1", addr[0]);
break;
case 2:
ret.put("fl_loc_1", addr[1]);
ret.put("fl_loc_2", addr[0]);
break;
case 3:
ret.put("fl_loc_1", addr[2]);
ret.put("fl_loc_2", addr[1]);
ret.put("fl_loc_3", addr[0]);
break;
default:
ret.put("fl_loc_1", addr[addr.length - 1]);
ret.put("fl_loc_2", addr[addr.length - 2]);
String loc3 = "";
for (int i = 0; i < addr.length - 2; i++) {
loc3 += addr[i] + ", ";
}
ret.put("fl_loc_3", loc3.substring(0, loc3.length() - 2));
}
} // Site info
else if ((flg[1].equals("site") || flg[1].equals("sites")) && flg[2].equals("data")) {
//$ret[$flg[0]]["site"] = trim($line);
// P.S. site is missing in the master variables list
ret.put("site", line.trim());
} // Plot Info
else if (flg[1].startsWith("parea") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("parea", 7);
formats.put("prno", 6);
formats.put("plen", 6);
formats.put("pldr", 6);
formats.put("plsp", 6);
formats.put("play", 6);
formats.put("pltha", 6);
formats.put("hrno", 6);
formats.put("hlen", 6);
formats.put("plthm", 16);
// Read line and save into return holder
ret.put("plot_info", readLine(line, formats));
} // Notes field
else if (flg[1].equals("notes") && flg[2].equals("data")) {
//$ret[$flg[0]]["notes"] = addArray($ret[$flg[0]]["notes"], " ". trim($line), "");
if (!ret.containsKey("notes")) {
ret.put("notes", line.trim() + "\\r\\n");
} else {
String notes = (String) ret.get("notes");
notes += line.trim() + "\\r\\n";
ret.put("notes", notes);
}
} else {
}
} // Read TREATMENTS Section
else if (flg[0].startsWith("treatments")) {
// Read TREATMENTS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("trno", 2);
formats.put("sq", 2);
formats.put("op", 2);
formats.put("co", 2);
formats.put("tr_name", 26);
formats.put("ge", 3);
formats.put("fl", 3);
formats.put("sa", 3);
formats.put("ic", 3);
formats.put("pl", 3);
formats.put("ir", 3);
formats.put("fe", 3);
formats.put("om", 3);
formats.put("ch", 3);
formats.put("ti", 3);
formats.put("em", 3);
formats.put("ha", 3);
formats.put("sm", 3);
// Read line and save into return holder
trArr.add(readLine(line, formats));
} else {
}
} // Read CULTIVARS Section
else if (flg[0].startsWith("cultivars")) {
// Read CULTIVARS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ge", 2);
formats.put("cr", 3);
formats.put("cul_id", 7);
formats.put("cul_name", 17);
// Read line and save into return holder
cuArr.add(readLine(line, formats));
if (cuArr.size() == 1) {
ret.put("cr", line.substring(3, 5).trim()); // TODO keep for the early version; just first entry
}
} else {
}
} // Read FIELDS Section
else if (flg[0].startsWith("fields")) {
// Read field info 1st line
if (flg[1].startsWith("l id_") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("id_field", 9);
formats.put("wsta_id", 9); //P.S. id do not match with the master list "wth_id"; might have another id name
formats.put("flsl", 6);
formats.put("flob", 6);
formats.put("fl_drntype", 6);
formats.put("fldrd", 6);
formats.put("fldrs", 6);
formats.put("flst", 6);
formats.put("sltx", 6);
formats.put("sldp", 6);
formats.put("soil_id", 11);
formats.put("fl_name", line.length());
// Read line and save into return holder
addToArray(flArr, readLine(line, formats), "fl");
// Read weather station id
wid = line.substring(12, 20).trim();
}// // Read field info 2nd line
else if (flg[1].startsWith("l ...") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("fl_lat", 16);
formats.put("fl_long", 16);
formats.put("flele", 10);
formats.put("farea", 18);
formats.put("", 6); // P.S. id do not find in the master list (? it seems to be calculated by other fields)
formats.put("fllwr", 6);
formats.put("flsla", 6);
formats.put("flhst", 6); // P.S. id do not find in the master list (field histoy code)
formats.put("fhdur", 6); // P.S. id do not find in the master list (duration associated with field history code in years)
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// Read lat and long
String strLat = (String) tmp.get("fl_lat");
String strLong = (String) tmp.get("fl_long");
// If lat or long is not valid data, read data from weather file
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
// check if weather is validable
for (Object key : mapW.keySet()) {
if (((String) key).contains(wid)) {
bufW = (char[]) mapW.get(key);
break;
}
}
if (bufW != null) {
brw = new BufferedReader(new CharArrayReader(bufW));
String lineW;
while ((lineW = brw.readLine()) != null) {
if (lineW.startsWith("@ INSI")) {
lineW = brw.readLine();
strLat = lineW.substring(6, 15).trim();
strLong = lineW.substring(15, 24).trim();
break;
}
}
// check if lat and long are valid in the weather file; if not, set invalid value for them
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
strLat = defValI;
strLong = defValI;
}
} // if weather file is not avaliable to read, set invalid value for lat and long
else {
strLat = defValI;
strLong = defValI;
}
}
if (flArr.isEmpty()) {
ret.put("fl_lat", strLong); // TODO Keep the meta data handling for the early version
ret.put("fl_long", strLat); // TODO Keep the meta data handling for the early version
}
tmp.put("fl_lat", strLong);
tmp.put("fl_long", strLat);
addToArray(flArr, tmp, "fl");
}
} // Read SOIL ANALYSIS Section
else if (flg[0].startsWith("soil")) {
// Read SOIL ANALYSIS global data
if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sa", 2);
formats.put("sadat", 6);
formats.put("samhb", 6);
formats.put("sampx", 6);
formats.put("samke", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("sadat", translateDateStr((String) tmp.get("sadat")));
saArr.add(tmp);
sadArr = new ArrayList();
tmp.put(eventKey, sadArr);
} // Read SOIL ANALYSIS layer data
else if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "sa"
formats.put("sabl", 6);
formats.put("sabdm", 6);
formats.put("saoc", 6);
formats.put("sani", 6);
formats.put("saphw", 6);
formats.put("saphb", 6);
formats.put("sapx", 6);
formats.put("sake", 6);
formats.put("sasc", 6); // P.S. id do not find in the master list (Measured stable organic C by soil layer, g[C]/100g[Soil])
// Read line and save into return holder
sadArr.add(readLine(line, formats));
} else {
}
} // Read INITIAL CONDITIONS Section
else if (flg[0].startsWith("initial")) {
// Read INITIAL CONDITIONS global data
if (flg[1].startsWith("c pcr") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ic", 2);
formats.put("icpcr", 6);
formats.put("icdat", 6);
formats.put("icrt", 6);
formats.put("icnd", 6);
formats.put("icrz#", 6); // P.S. use the "icrz#" instead of "icrzno"
formats.put("icrze", 6);
formats.put("icwt", 6);
formats.put("icrag", 6);
formats.put("icrn", 6);
formats.put("icrp", 6);
formats.put("icrip", 6);
formats.put("icrdp", 6);
formats.put("ic_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("icdat", translateDateStr((String) tmp.get("icdat")));
icArr.add(tmp);
icdArr = new ArrayList();
tmp.put(eventKey, icdArr);
} else // INITIAL CONDITIONS layer data
if (flg[1].startsWith("c icbl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the detail (event) data index "ic"
formats.put("icbl", 6);
formats.put("ich2o", 6);
formats.put("icnh4", 6);
formats.put("icno3", 6);
// Read line and save into return holder
icdArr.add(readLine(line, formats));
} else {
}
} // Read PLANTING DETAILS Section
else if (flg[0].startsWith("planting")) {
// Read PLANTING data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("pl", 2);
formats.put("pdate", 6);
formats.put("pldae", 6);
formats.put("plpop", 6);
formats.put("plpoe", 6);
formats.put("plme", 6);
formats.put("plds", 6);
formats.put("plrs", 6);
formats.put("plrd", 6);
formats.put("pldp", 6);
formats.put("plmwt", 6);
formats.put("page", 6);
formats.put("penv", 6);
formats.put("plph", 6);
formats.put("plspl", 6);
formats.put("pl_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("pdate", translateDateStr((String) tmp.get("pdate")));
tmp.put("pldae", translateDateStr((String) tmp.get("pldae")));
plArr.add(tmp);
if (plArr.size() == 1) {
ret.put("pdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for the early version
}
} else {
}
} // Read IRRIGATION AND WATER MANAGEMENT Section
else if (flg[0].startsWith("irrigation")) {
// Read IRRIGATION global data
if (flg[1].startsWith("i efir") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ir", 2);
formats.put("ireff", 6);
formats.put("irmdp", 6);
formats.put("irthr", 6);
formats.put("irept", 6);
formats.put("irstg", 6);
formats.put("iame", 6);
formats.put("iamt", 6);
formats.put("ir_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
irArr.add(tmp);
irdArr = new ArrayList();
tmp.put(eventKey, irdArr);
} // Read IRRIGATION appliction data
else if (flg[1].startsWith("i idate") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "ir"
formats.put("idate", 6);
formats.put("irop", 6);
formats.put("irval", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("idate", translateDateStr((String) tmp.get("idate"))); // TODO DOY handling
irdArr.add(tmp);
} else {
}
} // Read FERTILIZERS (INORGANIC) Section
else if (flg[0].startsWith("fertilizers")) {
// Read FERTILIZERS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fe", 2);
formats.put("fdate", 6);
formats.put("fecd", 6);
formats.put("feacd", 6);
formats.put("fedep", 6);
formats.put("feamn", 6);
formats.put("feamp", 6);
formats.put("feamk", 6);
formats.put("feamc", 6);
formats.put("feamo", 6);
formats.put("feocd", 6);
formats.put("fe_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("fdate", translateDateStr((String) tmp.get("fdate"))); // TODO DOY handling
feArr.add(tmp);
} else {
}
} // Read RESIDUES AND OTHER ORGANIC MATERIALS Section
else if (flg[0].startsWith("residues")) {
// Read ORGANIC MATERIALS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("om", 2);
formats.put("omdat", 6); // P.S. id do not match with the master list "omday"
formats.put("omcd", 6);
formats.put("omamt", 6);
formats.put("omn%", 6); // P.S. id do not match with the master list "omnpct"
formats.put("omp%", 6); // P.S. id do not match with the master list "omppct"
formats.put("omk%", 6); // P.S. id do not match with the master list "omkpct"
formats.put("ominp", 6);
formats.put("omdep", 6);
formats.put("omacd", 6);
formats.put("om_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("omdat", translateDateStr((String) tmp.get("omdat"))); // TODO DOY handling
omArr.add(tmp);
} else {
}
} // Read CHEMICAL APPLICATIONS Section
else if (flg[0].startsWith("chemical")) {
// Read CHEMICAL APPLICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ch", 2);
formats.put("cdate", 6);
formats.put("chcd", 6);
formats.put("chamt", 6);
formats.put("chacd", 6);
formats.put("chdep", 6);
formats.put("ch_targets", 6);
formats.put("ch_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("cdate", translateDateStr((String) tmp.get("cdate")));
chArr.add(tmp);
} else {
}
} // Read TILLAGE Section
else if (flg[0].startsWith("tillage")) {
// Read TILLAGE data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ti", 2);
formats.put("tdate", 6);
formats.put("tiimp", 6);
formats.put("tidep", 6);
formats.put("ti_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("tdate", translateDateStr((String) tmp.get("tdate")));
tiArr.add(tmp);
} else {
}
} // Read ENVIRONMENT MODIFICATIONS Section
else if (flg[0].startsWith("environment")) {
// Read ENVIRONMENT MODIFICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("em", 2);
formats.put("emday", 6);
formats.put("ecdyl", 2);
formats.put("emdyl", 4);
formats.put("ecrad", 2);
formats.put("emrad", 4);
formats.put("ecmax", 2);
formats.put("emmax", 4);
formats.put("ecmin", 2);
formats.put("emmin", 4);
formats.put("ecrai", 2);
formats.put("emrai", 4);
formats.put("ecco2", 2);
formats.put("emco2", 4);
formats.put("ecdew", 2);
formats.put("emdew", 4);
formats.put("ecwnd", 2);
formats.put("emwnd", 4);
formats.put("em_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("emday", translateDateStr((String) tmp.get("emday")));
emArr.add(tmp);
} else {
}
} // Read HARVEST DETAILS Section
else if (flg[0].startsWith("harvest")) {
// Read HARVEST data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ha", 2);
formats.put("hdate", 6);
formats.put("hastg", 6);
formats.put("hacom", 6);
formats.put("hasiz", 6);
formats.put("hapc", 6);
formats.put("habpc", 6);
formats.put("ha_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("hdate", translateDateStr((String) tmp.get("hdate")));
haArr.add(tmp);
if (haArr.size() == 1) {
ret.put("hdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for early version
}
} else {
}
} // Read SIMULATION CONTROLS Section // P.S. no need to be divided
else if (flg[0].startsWith("simulation")) {
// Read general info
if (flg[1].startsWith("n general") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("general", 12);
// formats.put("nyers", 6);
// formats.put("nreps", 6);
// formats.put("start", 6);
// formats.put("sdate", 6);
// formats.put("rseed", 6);
// formats.put("sname", 26);
// formats.put("model", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("sdate", translateDateStr((String) tmp.get("sdate")));
tmp.put("general", line);
addToArray(smArr, tmp, "sm");
} // Read options info
else if (flg[1].startsWith("n options") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("options", 12);
// formats.put("water", 6);
// formats.put("nitro", 6);
// formats.put("symbi", 6);
// formats.put("phosp", 6);
// formats.put("potas", 6);
// formats.put("dises", 6);
// formats.put("chem", 6);
// formats.put("till", 6);
// formats.put("co2", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("options", line);
addToArray(smArr, tmp, "sm");
} // Read methods info
else if (flg[1].startsWith("n methods") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("methods", 12);
// formats.put("wther", 6);
// formats.put("incon", 6);
// formats.put("light", 6);
// formats.put("evapo", 6);
// formats.put("infil", 6);
// formats.put("photo", 6);
// formats.put("hydro", 6);
// formats.put("nswit", 6);
// formats.put("mesom", 6);
// formats.put("mesev", 6);
// formats.put("mesol", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("methods", line);
addToArray(smArr, tmp, "sm");
} // Read management info
else if (flg[1].startsWith("n management") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("management", 12);
// formats.put("plant", 6);
// formats.put("irrig", 6);
// formats.put("ferti", 6);
// formats.put("resid", 6);
// formats.put("harvs", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("management", line);
addToArray(smArr, tmp, "sm");
} // Read outputs info
else if (flg[1].startsWith("n outputs") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("outputs", 12);
// formats.put("fname", 6);
// formats.put("ovvew", 6);
// formats.put("sumry", 6);
// formats.put("fropt", 6);
// formats.put("grout", 6);
// formats.put("caout", 6);
// formats.put("waout", 6);
// formats.put("niout", 6);
// formats.put("miout", 6);
// formats.put("diout", 6);
// formats.put("long", 6);
// formats.put("chout", 6);
// formats.put("opout", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("outputs", line);
addToArray(smArr, tmp, "sm");
} // Read planting info
else if (flg[1].startsWith("n planting") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("planting", 12);
// formats.put("pfrst", 6);
// formats.put("plast", 6);
// formats.put("ph20l", 6);
// formats.put("ph2ou", 6);
// formats.put("ph20d", 6);
// formats.put("pstmx", 6);
// formats.put("pstmn", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("pfrst", translateDateStr((String) tmp.get("pfrst")));
// tmp.put("plast", translateDateStr((String) tmp.get("plast")));
tmp.put("planting", line);
addToArray(smArr, tmp, "sm");
} // Read irrigation info
else if (flg[1].startsWith("n irrigation") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("irrigation", 12);
// formats.put("imdep", 6);
// formats.put("ithrl", 6);
// formats.put("ithru", 6);
// formats.put("iroff", 6);
// formats.put("imeth", 6);
// formats.put("iramt", 6);
// formats.put("ireff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("irrigation", line);
addToArray(smArr, tmp, "sm");
} // Read nitrogen info
else if (flg[1].startsWith("n nitrogen") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("nitrogen", 12);
// formats.put("nmdep", 6);
// formats.put("nmthr", 6);
// formats.put("namnt", 6);
// formats.put("ncode", 6);
// formats.put("naoff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("nitrogen", line);
addToArray(smArr, tmp, "sm");
} // Read residues info
else if (flg[1].startsWith("n residues") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("residues", 12);
// formats.put("ripcn", 6);
// formats.put("rtime", 6);
// formats.put("ridep", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("residues", line);
addToArray(smArr, tmp, "sm");
} // Read harvest info
else if (flg[1].startsWith("n harvest") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("harvests", 12);
// formats.put("hfrst", 6); // P.S. Keep the original value
// formats.put("hlast", 6);
// formats.put("hpcnp", 6);
// formats.put("hrcnr", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("hlast", translateDateStr((String) tmp.get("hlast")));
tmp.put("harvests", line);
addToArray(smArr, tmp, "sm");
} else {
}
} else {
}
}
br.close();
if (brw != null) {
brw.close();
}
for (int i = 0; i < trArr.size(); i++) {
AdvancedHashMap treatment = (AdvancedHashMap) trArr.get(i);
// cultivar
if (!treatment.getOr("ge", "0").equals("0")) {
treatment.put("cultivar", getSectionData(cuArr, "ge", treatment.get("ge").toString()));
}
// field
if (!treatment.getOr("fl", "0").equals("0")) {
treatment.put("field", getSectionData(flArr, "fl", treatment.get("fl").toString()));
}
// soil_analysis
if (!treatment.getOr("sa", "0").equals("0")) {
treatment.put("soil_analysis", getSectionData(saArr, "sa", treatment.get("sa").toString()));
}
// initial_condition
if (!treatment.getOr("ic", "0").equals("0")) {
treatment.put("initial_condition", getSectionData(icArr, "ic", treatment.get("ic").toString()));
}
// plant
if (!treatment.getOr("pl", "0").equals("0")) {
treatment.put("plant", getSectionData(plArr, "pl", treatment.get("pl").toString()));
}
// irrigation
if (!treatment.getOr("ir", "0").equals("0")) {
treatment.put("irrigation", getSectionData(irArr, "ir", treatment.get("ir").toString()));
}
// fertilizer
if (!treatment.getOr("fe", "0").equals("0")) {
treatment.put("fertilizer", getSectionData(feArr, "fe", treatment.get("fe").toString()));
}
// residue_organic
if (!treatment.getOr("om", "0").equals("0")) {
treatment.put("residue_organic", getSectionData(omArr, "om", treatment.get("om").toString()));
}
// chemical
if (!treatment.getOr("ch", "0").equals("0")) {
treatment.put("chemical", getSectionData(chArr, "ch", treatment.get("ch").toString()));
}
// tillage
if (!treatment.getOr("ti", "0").equals("0")) {
treatment.put("tillage", getSectionData(tiArr, "ti", treatment.get("ti").toString()));
}
// emvironment
if (!treatment.getOr("em", "0").equals("0")) {
treatment.put("emvironment", getSectionData(emArr, "em", treatment.get("em").toString()));
}
// harvest
if (!treatment.getOr("ha", "0").equals("0")) {
treatment.put("harvest", getSectionData(haArr, "ha", treatment.get("ha").toString()));
}
// simulation
if (!treatment.getOr("sm", "0").equals("0")) {
treatment.put("simulation", getSectionData(smArr, "sm", treatment.get("sm").toString()));
}
// Revise the date value for FEDATE, IDATE, MLADAT
// Get Planting date
String pdate = "";
ArrayList plTmps = (ArrayList) treatment.getOr("planting", new ArrayList());
if (!plTmps.isEmpty()) {
pdate = (String) ((AdvancedHashMap) plTmps.get(0)).getOr("pdate", "");
if (pdate.length() > 5) {
pdate = pdate.substring(2);
}
}
// Fertilizer Date
ArrayList feTmps = (ArrayList) treatment.getOr("fertilizer", new ArrayList());
AdvancedHashMap feTmp;
for (int j = 0; j < feTmps.size(); j++) {
feTmp = (AdvancedHashMap) feTmps.get(j);
feTmp.put("fdate", translateDateStrForDOY((String) feTmp.get("fdate"), pdate));
}
// Initial condition date
AdvancedHashMap icTmp = (AdvancedHashMap) treatment.get("initial_condition");
if (icTmp != null) {
icTmp.put("idate", translateDateStrForDOY((String) icTmp.getOr("idate", defValI), pdate));
}
// Mulch application date
AdvancedHashMap omTmp = (AdvancedHashMap) treatment.get("residue_organic");
if (omTmp != null) {
omTmp.put("omdat", translateDateStrForDOY((String) omTmp.getOr("omdat", defValI), pdate));
}
}
compressData(ret);
return ret;
}
| protected AdvancedHashMap readFile(HashMap brMap) throws IOException {
AdvancedHashMap ret = new AdvancedHashMap();
String line;
BufferedReader br;
char[] buf;
BufferedReader brw = null;
char[] bufW = null;
HashMap mapW;
String wid;
String fileName;
LinkedHashMap formats = new LinkedHashMap();
ArrayList trArr = new ArrayList();
ArrayList cuArr = new ArrayList();
ArrayList flArr = new ArrayList();
ArrayList saArr = new ArrayList();
ArrayList sadArr = new ArrayList();
ArrayList icArr = new ArrayList();
ArrayList icdArr = new ArrayList();
ArrayList plArr = new ArrayList();
ArrayList irArr = new ArrayList();
ArrayList irdArr = new ArrayList();
ArrayList feArr = new ArrayList();
ArrayList omArr = new ArrayList();
ArrayList chArr = new ArrayList();
ArrayList tiArr = new ArrayList();
ArrayList emArr = new ArrayList();
ArrayList haArr = new ArrayList();
ArrayList smArr = new ArrayList();
String eventKey = "data";
buf = (char[]) brMap.get("X");
mapW = (HashMap) brMap.get("W");
fileName = (String) brMap.get("Z");
wid = fileName.length() > 4 ? fileName.substring(0, 4) : fileName;
// If XFile is no been found
if (buf == null) {
// TODO reprot file not exist error
return ret;
} else {
br = new BufferedReader(new CharArrayReader(buf));
}
ret.put("treatment", trArr);
// ret.put("cultivar", cuArr);
// ret.put("field", flArr);
// ret.put("soil_analysis", saArr);
// ret.put("initial_condition", icArr);
// ret.put("plant", plArr);
// ret.put("irrigation", irArr);
// ret.put("fertilizer", feArr);
// ret.put("residue_organic", omArr);
// ret.put("chemical", chArr);
// ret.put("tillage", tiArr);
// ret.put("emvironment", emArr);
// ret.put("harvest", haArr);
// ret.put("simulation", smArr);
while ((line = br.readLine()) != null) {
// Get content type of line
judgeContentType(line);
// Read Exp title info
if (flg[0].startsWith("exp.details:") && flg[2].equals("")) {
// Set variables' formats
formats.clear();
formats.put("exname", 11);
formats.put("local_name", 61);
// Read line and save into return holder
ret.put(readLine(line.substring(13), formats));
ret.put("institutes", line.substring(14, 16).trim());
} // Read General Section
else if (flg[0].startsWith("general")) {
// People info
if (flg[1].equals("people") && flg[2].equals("data")) {
ret.put("people", line.trim());
} // Address info
else if (flg[1].equals("address") && flg[2].equals("data")) {
String[] addr = line.split(",[ ]*");
ret.put("fl_loc_1", "");
ret.put("fl_loc_2", "");
ret.put("fl_loc_3", "");
ret.put("institutes", line.trim());
// ret.put("address", line.trim()); // P.S. no longer to use this field
switch (addr.length) {
case 0:
break;
case 1:
ret.put("fl_loc_1", addr[0]);
break;
case 2:
ret.put("fl_loc_1", addr[1]);
ret.put("fl_loc_2", addr[0]);
break;
case 3:
ret.put("fl_loc_1", addr[2]);
ret.put("fl_loc_2", addr[1]);
ret.put("fl_loc_3", addr[0]);
break;
default:
ret.put("fl_loc_1", addr[addr.length - 1]);
ret.put("fl_loc_2", addr[addr.length - 2]);
String loc3 = "";
for (int i = 0; i < addr.length - 2; i++) {
loc3 += addr[i] + ", ";
}
ret.put("fl_loc_3", loc3.substring(0, loc3.length() - 2));
}
} // Site info
else if ((flg[1].equals("site") || flg[1].equals("sites")) && flg[2].equals("data")) {
//$ret[$flg[0]]["site"] = trim($line);
// P.S. site is missing in the master variables list
ret.put("site", line.trim());
} // Plot Info
else if (flg[1].startsWith("parea") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("parea", 7);
formats.put("prno", 6);
formats.put("plen", 6);
formats.put("pldr", 6);
formats.put("plsp", 6);
formats.put("play", 6);
formats.put("pltha", 6);
formats.put("hrno", 6);
formats.put("hlen", 6);
formats.put("plthm", 16);
// Read line and save into return holder
ret.put("plot_info", readLine(line, formats));
} // Notes field
else if (flg[1].equals("notes") && flg[2].equals("data")) {
//$ret[$flg[0]]["notes"] = addArray($ret[$flg[0]]["notes"], " ". trim($line), "");
if (!ret.containsKey("notes")) {
ret.put("notes", line.trim() + "\\r\\n");
} else {
String notes = (String) ret.get("notes");
notes += line.trim() + "\\r\\n";
ret.put("notes", notes);
}
} else {
}
} // Read TREATMENTS Section
else if (flg[0].startsWith("treatments")) {
// Read TREATMENTS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("trno", 2);
formats.put("sq", 2);
formats.put("op", 2);
formats.put("co", 2);
formats.put("tr_name", 26);
formats.put("ge", 3);
formats.put("fl", 3);
formats.put("sa", 3);
formats.put("ic", 3);
formats.put("pl", 3);
formats.put("ir", 3);
formats.put("fe", 3);
formats.put("om", 3);
formats.put("ch", 3);
formats.put("ti", 3);
formats.put("em", 3);
formats.put("ha", 3);
formats.put("sm", 3);
// Read line and save into return holder
trArr.add(readLine(line, formats));
} else {
}
} // Read CULTIVARS Section
else if (flg[0].startsWith("cultivars")) {
// Read CULTIVARS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ge", 2);
formats.put("cr", 3);
formats.put("cul_id", 7);
formats.put("cul_name", 17);
// Read line and save into return holder
cuArr.add(readLine(line, formats));
if (cuArr.size() == 1) {
ret.put("cr", line.substring(3, 5).trim()); // TODO keep for the early version; just first entry
}
} else {
}
} // Read FIELDS Section
else if (flg[0].startsWith("fields")) {
// Read field info 1st line
if (flg[1].startsWith("l id_") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("id_field", 9);
formats.put("wsta_id", 9); //P.S. id do not match with the master list "wth_id"; might have another id name
formats.put("flsl", 6);
formats.put("flob", 6);
formats.put("fl_drntype", 6);
formats.put("fldrd", 6);
formats.put("fldrs", 6);
formats.put("flst", 6);
formats.put("sltx", 6);
formats.put("sldp", 6);
formats.put("soil_id", 11);
formats.put("fl_name", line.length());
// Read line and save into return holder
addToArray(flArr, readLine(line, formats), "fl");
// Read weather station id
wid = line.substring(12, 20).trim();
}// // Read field info 2nd line
else if (flg[1].startsWith("l ...") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("fl_lat", 16);
formats.put("fl_long", 16);
formats.put("flele", 10);
formats.put("farea", 18);
formats.put("", 6); // P.S. id do not find in the master list (? it seems to be calculated by other fields)
formats.put("fllwr", 6);
formats.put("flsla", 6);
formats.put("flhst", 6); // P.S. id do not find in the master list (field histoy code)
formats.put("fhdur", 6); // P.S. id do not find in the master list (duration associated with field history code in years)
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// Read lat and long
String strLat = (String) tmp.get("fl_lat");
String strLong = (String) tmp.get("fl_long");
// If lat or long is not valid data, read data from weather file
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
// check if weather is validable
for (Object key : mapW.keySet()) {
if (((String) key).contains(wid)) {
bufW = (char[]) mapW.get(key);
break;
}
}
if (bufW != null) {
brw = new BufferedReader(new CharArrayReader(bufW));
String lineW;
while ((lineW = brw.readLine()) != null) {
if (lineW.startsWith("@ INSI")) {
lineW = brw.readLine();
strLat = lineW.substring(6, 15).trim();
strLong = lineW.substring(15, 24).trim();
break;
}
}
// check if lat and long are valid in the weather file; if not, set invalid value for them
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
strLat = defValI;
strLong = defValI;
}
} // if weather file is not avaliable to read, set invalid value for lat and long
else {
strLat = defValI;
strLong = defValI;
}
}
if (flArr.isEmpty()) {
ret.put("fl_lat", strLat); // TODO Keep the meta data handling for the early version
ret.put("fl_long", strLong); // TODO Keep the meta data handling for the early version
}
tmp.put("fl_lat", strLat);
tmp.put("fl_long", strLong);
addToArray(flArr, tmp, "fl");
}
} // Read SOIL ANALYSIS Section
else if (flg[0].startsWith("soil")) {
// Read SOIL ANALYSIS global data
if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sa", 2);
formats.put("sadat", 6);
formats.put("samhb", 6);
formats.put("sampx", 6);
formats.put("samke", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("sadat", translateDateStr((String) tmp.get("sadat")));
saArr.add(tmp);
sadArr = new ArrayList();
tmp.put(eventKey, sadArr);
} // Read SOIL ANALYSIS layer data
else if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "sa"
formats.put("sabl", 6);
formats.put("sabdm", 6);
formats.put("saoc", 6);
formats.put("sani", 6);
formats.put("saphw", 6);
formats.put("saphb", 6);
formats.put("sapx", 6);
formats.put("sake", 6);
formats.put("sasc", 6); // P.S. id do not find in the master list (Measured stable organic C by soil layer, g[C]/100g[Soil])
// Read line and save into return holder
sadArr.add(readLine(line, formats));
} else {
}
} // Read INITIAL CONDITIONS Section
else if (flg[0].startsWith("initial")) {
// Read INITIAL CONDITIONS global data
if (flg[1].startsWith("c pcr") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ic", 2);
formats.put("icpcr", 6);
formats.put("icdat", 6);
formats.put("icrt", 6);
formats.put("icnd", 6);
formats.put("icrz#", 6); // P.S. use the "icrz#" instead of "icrzno"
formats.put("icrze", 6);
formats.put("icwt", 6);
formats.put("icrag", 6);
formats.put("icrn", 6);
formats.put("icrp", 6);
formats.put("icrip", 6);
formats.put("icrdp", 6);
formats.put("ic_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("icdat", translateDateStr((String) tmp.get("icdat")));
icArr.add(tmp);
icdArr = new ArrayList();
tmp.put(eventKey, icdArr);
} else // INITIAL CONDITIONS layer data
if (flg[1].startsWith("c icbl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the detail (event) data index "ic"
formats.put("icbl", 6);
formats.put("ich2o", 6);
formats.put("icnh4", 6);
formats.put("icno3", 6);
// Read line and save into return holder
icdArr.add(readLine(line, formats));
} else {
}
} // Read PLANTING DETAILS Section
else if (flg[0].startsWith("planting")) {
// Read PLANTING data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("pl", 2);
formats.put("pdate", 6);
formats.put("pldae", 6);
formats.put("plpop", 6);
formats.put("plpoe", 6);
formats.put("plme", 6);
formats.put("plds", 6);
formats.put("plrs", 6);
formats.put("plrd", 6);
formats.put("pldp", 6);
formats.put("plmwt", 6);
formats.put("page", 6);
formats.put("penv", 6);
formats.put("plph", 6);
formats.put("plspl", 6);
formats.put("pl_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("pdate", translateDateStr((String) tmp.get("pdate")));
tmp.put("pldae", translateDateStr((String) tmp.get("pldae")));
plArr.add(tmp);
if (plArr.size() == 1) {
ret.put("pdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for the early version
}
} else {
}
} // Read IRRIGATION AND WATER MANAGEMENT Section
else if (flg[0].startsWith("irrigation")) {
// Read IRRIGATION global data
if (flg[1].startsWith("i efir") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ir", 2);
formats.put("ireff", 6);
formats.put("irmdp", 6);
formats.put("irthr", 6);
formats.put("irept", 6);
formats.put("irstg", 6);
formats.put("iame", 6);
formats.put("iamt", 6);
formats.put("ir_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
irArr.add(tmp);
irdArr = new ArrayList();
tmp.put(eventKey, irdArr);
} // Read IRRIGATION appliction data
else if (flg[1].startsWith("i idate") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "ir"
formats.put("idate", 6);
formats.put("irop", 6);
formats.put("irval", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("idate", translateDateStr((String) tmp.get("idate"))); // TODO DOY handling
irdArr.add(tmp);
} else {
}
} // Read FERTILIZERS (INORGANIC) Section
else if (flg[0].startsWith("fertilizers")) {
// Read FERTILIZERS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fe", 2);
formats.put("fdate", 6);
formats.put("fecd", 6);
formats.put("feacd", 6);
formats.put("fedep", 6);
formats.put("feamn", 6);
formats.put("feamp", 6);
formats.put("feamk", 6);
formats.put("feamc", 6);
formats.put("feamo", 6);
formats.put("feocd", 6);
formats.put("fe_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("fdate", translateDateStr((String) tmp.get("fdate"))); // TODO DOY handling
feArr.add(tmp);
} else {
}
} // Read RESIDUES AND OTHER ORGANIC MATERIALS Section
else if (flg[0].startsWith("residues")) {
// Read ORGANIC MATERIALS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("om", 2);
formats.put("omdat", 6); // P.S. id do not match with the master list "omday"
formats.put("omcd", 6);
formats.put("omamt", 6);
formats.put("omn%", 6); // P.S. id do not match with the master list "omnpct"
formats.put("omp%", 6); // P.S. id do not match with the master list "omppct"
formats.put("omk%", 6); // P.S. id do not match with the master list "omkpct"
formats.put("ominp", 6);
formats.put("omdep", 6);
formats.put("omacd", 6);
formats.put("om_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("omdat", translateDateStr((String) tmp.get("omdat"))); // TODO DOY handling
omArr.add(tmp);
} else {
}
} // Read CHEMICAL APPLICATIONS Section
else if (flg[0].startsWith("chemical")) {
// Read CHEMICAL APPLICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ch", 2);
formats.put("cdate", 6);
formats.put("chcd", 6);
formats.put("chamt", 6);
formats.put("chacd", 6);
formats.put("chdep", 6);
formats.put("ch_targets", 6);
formats.put("ch_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("cdate", translateDateStr((String) tmp.get("cdate")));
chArr.add(tmp);
} else {
}
} // Read TILLAGE Section
else if (flg[0].startsWith("tillage")) {
// Read TILLAGE data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ti", 2);
formats.put("tdate", 6);
formats.put("tiimp", 6);
formats.put("tidep", 6);
formats.put("ti_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("tdate", translateDateStr((String) tmp.get("tdate")));
tiArr.add(tmp);
} else {
}
} // Read ENVIRONMENT MODIFICATIONS Section
else if (flg[0].startsWith("environment")) {
// Read ENVIRONMENT MODIFICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("em", 2);
formats.put("emday", 6);
formats.put("ecdyl", 2);
formats.put("emdyl", 4);
formats.put("ecrad", 2);
formats.put("emrad", 4);
formats.put("ecmax", 2);
formats.put("emmax", 4);
formats.put("ecmin", 2);
formats.put("emmin", 4);
formats.put("ecrai", 2);
formats.put("emrai", 4);
formats.put("ecco2", 2);
formats.put("emco2", 4);
formats.put("ecdew", 2);
formats.put("emdew", 4);
formats.put("ecwnd", 2);
formats.put("emwnd", 4);
formats.put("em_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("emday", translateDateStr((String) tmp.get("emday")));
emArr.add(tmp);
} else {
}
} // Read HARVEST DETAILS Section
else if (flg[0].startsWith("harvest")) {
// Read HARVEST data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ha", 2);
formats.put("hdate", 6);
formats.put("hastg", 6);
formats.put("hacom", 6);
formats.put("hasiz", 6);
formats.put("hapc", 6);
formats.put("habpc", 6);
formats.put("ha_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("hdate", translateDateStr((String) tmp.get("hdate")));
haArr.add(tmp);
if (haArr.size() == 1) {
ret.put("hdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for early version
}
} else {
}
} // Read SIMULATION CONTROLS Section // P.S. no need to be divided
else if (flg[0].startsWith("simulation")) {
// Read general info
if (flg[1].startsWith("n general") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("general", 12);
// formats.put("nyers", 6);
// formats.put("nreps", 6);
// formats.put("start", 6);
// formats.put("sdate", 6);
// formats.put("rseed", 6);
// formats.put("sname", 26);
// formats.put("model", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("sdate", translateDateStr((String) tmp.get("sdate")));
tmp.put("general", line);
addToArray(smArr, tmp, "sm");
} // Read options info
else if (flg[1].startsWith("n options") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("options", 12);
// formats.put("water", 6);
// formats.put("nitro", 6);
// formats.put("symbi", 6);
// formats.put("phosp", 6);
// formats.put("potas", 6);
// formats.put("dises", 6);
// formats.put("chem", 6);
// formats.put("till", 6);
// formats.put("co2", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("options", line);
addToArray(smArr, tmp, "sm");
} // Read methods info
else if (flg[1].startsWith("n methods") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("methods", 12);
// formats.put("wther", 6);
// formats.put("incon", 6);
// formats.put("light", 6);
// formats.put("evapo", 6);
// formats.put("infil", 6);
// formats.put("photo", 6);
// formats.put("hydro", 6);
// formats.put("nswit", 6);
// formats.put("mesom", 6);
// formats.put("mesev", 6);
// formats.put("mesol", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("methods", line);
addToArray(smArr, tmp, "sm");
} // Read management info
else if (flg[1].startsWith("n management") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("management", 12);
// formats.put("plant", 6);
// formats.put("irrig", 6);
// formats.put("ferti", 6);
// formats.put("resid", 6);
// formats.put("harvs", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("management", line);
addToArray(smArr, tmp, "sm");
} // Read outputs info
else if (flg[1].startsWith("n outputs") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("outputs", 12);
// formats.put("fname", 6);
// formats.put("ovvew", 6);
// formats.put("sumry", 6);
// formats.put("fropt", 6);
// formats.put("grout", 6);
// formats.put("caout", 6);
// formats.put("waout", 6);
// formats.put("niout", 6);
// formats.put("miout", 6);
// formats.put("diout", 6);
// formats.put("long", 6);
// formats.put("chout", 6);
// formats.put("opout", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("outputs", line);
addToArray(smArr, tmp, "sm");
} // Read planting info
else if (flg[1].startsWith("n planting") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("planting", 12);
// formats.put("pfrst", 6);
// formats.put("plast", 6);
// formats.put("ph20l", 6);
// formats.put("ph2ou", 6);
// formats.put("ph20d", 6);
// formats.put("pstmx", 6);
// formats.put("pstmn", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("pfrst", translateDateStr((String) tmp.get("pfrst")));
// tmp.put("plast", translateDateStr((String) tmp.get("plast")));
tmp.put("planting", line);
addToArray(smArr, tmp, "sm");
} // Read irrigation info
else if (flg[1].startsWith("n irrigation") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("irrigation", 12);
// formats.put("imdep", 6);
// formats.put("ithrl", 6);
// formats.put("ithru", 6);
// formats.put("iroff", 6);
// formats.put("imeth", 6);
// formats.put("iramt", 6);
// formats.put("ireff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("irrigation", line);
addToArray(smArr, tmp, "sm");
} // Read nitrogen info
else if (flg[1].startsWith("n nitrogen") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("nitrogen", 12);
// formats.put("nmdep", 6);
// formats.put("nmthr", 6);
// formats.put("namnt", 6);
// formats.put("ncode", 6);
// formats.put("naoff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("nitrogen", line);
addToArray(smArr, tmp, "sm");
} // Read residues info
else if (flg[1].startsWith("n residues") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("residues", 12);
// formats.put("ripcn", 6);
// formats.put("rtime", 6);
// formats.put("ridep", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("residues", line);
addToArray(smArr, tmp, "sm");
} // Read harvest info
else if (flg[1].startsWith("n harvest") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("harvests", 12);
// formats.put("hfrst", 6); // P.S. Keep the original value
// formats.put("hlast", 6);
// formats.put("hpcnp", 6);
// formats.put("hrcnr", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("hlast", translateDateStr((String) tmp.get("hlast")));
tmp.put("harvests", line);
addToArray(smArr, tmp, "sm");
} else {
}
} else {
}
}
br.close();
if (brw != null) {
brw.close();
}
for (int i = 0; i < trArr.size(); i++) {
AdvancedHashMap treatment = (AdvancedHashMap) trArr.get(i);
// cultivar
if (!treatment.getOr("ge", "0").equals("0")) {
treatment.put("cultivar", getSectionData(cuArr, "ge", treatment.get("ge").toString()));
}
// field
if (!treatment.getOr("fl", "0").equals("0")) {
treatment.put("field", getSectionData(flArr, "fl", treatment.get("fl").toString()));
}
// soil_analysis
if (!treatment.getOr("sa", "0").equals("0")) {
treatment.put("soil_analysis", getSectionData(saArr, "sa", treatment.get("sa").toString()));
}
// initial_condition
if (!treatment.getOr("ic", "0").equals("0")) {
treatment.put("initial_condition", getSectionData(icArr, "ic", treatment.get("ic").toString()));
}
// plant
if (!treatment.getOr("pl", "0").equals("0")) {
treatment.put("plant", getSectionData(plArr, "pl", treatment.get("pl").toString()));
}
// irrigation
if (!treatment.getOr("ir", "0").equals("0")) {
treatment.put("irrigation", getSectionData(irArr, "ir", treatment.get("ir").toString()));
}
// fertilizer
if (!treatment.getOr("fe", "0").equals("0")) {
treatment.put("fertilizer", getSectionData(feArr, "fe", treatment.get("fe").toString()));
}
// residue_organic
if (!treatment.getOr("om", "0").equals("0")) {
treatment.put("residue_organic", getSectionData(omArr, "om", treatment.get("om").toString()));
}
// chemical
if (!treatment.getOr("ch", "0").equals("0")) {
treatment.put("chemical", getSectionData(chArr, "ch", treatment.get("ch").toString()));
}
// tillage
if (!treatment.getOr("ti", "0").equals("0")) {
treatment.put("tillage", getSectionData(tiArr, "ti", treatment.get("ti").toString()));
}
// emvironment
if (!treatment.getOr("em", "0").equals("0")) {
treatment.put("emvironment", getSectionData(emArr, "em", treatment.get("em").toString()));
}
// harvest
if (!treatment.getOr("ha", "0").equals("0")) {
treatment.put("harvest", getSectionData(haArr, "ha", treatment.get("ha").toString()));
}
// simulation
if (!treatment.getOr("sm", "0").equals("0")) {
treatment.put("simulation", getSectionData(smArr, "sm", treatment.get("sm").toString()));
}
// Revise the date value for FEDATE, IDATE, MLADAT
// Get Planting date
String pdate = "";
ArrayList plTmps = (ArrayList) treatment.getOr("planting", new ArrayList());
if (!plTmps.isEmpty()) {
pdate = (String) ((AdvancedHashMap) plTmps.get(0)).getOr("pdate", "");
if (pdate.length() > 5) {
pdate = pdate.substring(2);
}
}
// Fertilizer Date
ArrayList feTmps = (ArrayList) treatment.getOr("fertilizer", new ArrayList());
AdvancedHashMap feTmp;
for (int j = 0; j < feTmps.size(); j++) {
feTmp = (AdvancedHashMap) feTmps.get(j);
feTmp.put("fdate", translateDateStrForDOY((String) feTmp.get("fdate"), pdate));
}
// Initial condition date
AdvancedHashMap icTmp = (AdvancedHashMap) treatment.get("initial_condition");
if (icTmp != null) {
icTmp.put("idate", translateDateStrForDOY((String) icTmp.getOr("idate", defValI), pdate));
}
// Mulch application date
AdvancedHashMap omTmp = (AdvancedHashMap) treatment.get("residue_organic");
if (omTmp != null) {
omTmp.put("omdat", translateDateStrForDOY((String) omTmp.getOr("omdat", defValI), pdate));
}
}
compressData(ret);
return ret;
}
|
diff --git a/tools/rimd/src/org/rikulo/rimd/RikuloLinkRenderer.java b/tools/rimd/src/org/rikulo/rimd/RikuloLinkRenderer.java
index 1e532d9..5628568 100755
--- a/tools/rimd/src/org/rikulo/rimd/RikuloLinkRenderer.java
+++ b/tools/rimd/src/org/rikulo/rimd/RikuloLinkRenderer.java
@@ -1,86 +1,87 @@
//Copyright (C) 2012 Potix Corporation. All Rights Reserved.
//History: Sat, July 07, 2012
// Author: tomyeh
package org.rikulo.rimd;
import org.pegdown.LinkRenderer;
import org.pegdown.ast.ExpLinkNode;
public class RikuloLinkRenderer extends LinkRenderer {
final String _api, _source, _dart, _ext;
RikuloLinkRenderer(String api, String source, String ext) {
_api = api;
_dart = api.substring(0, api.lastIndexOf('/') + 1);
_source = source;
_ext = ext;
}
public Rendering render(ExpLinkNode node, String text) {
String url = node.url;
boolean bApi = false;
if ((bApi = url.equals("api:")) || url.equals("dart:")) {
//package: [view](api:) or [html](dart:)
final String urlPrefix = bApi ? _api: _dart;
return new Rendering(urlPrefix + text.replace('/', '_') + ".html",
"<code>" + text + "</code>");
} else if ((bApi = url.startsWith("api:")) || url.startsWith("dart:")) {
/* Link to a class: [ViewConfig](api:view/impl) or [CSSStyleDecalration](dart:html)
* Link to a method: [View.requestLayout()](api:view)
* Link to a getter: [View.width](api:view) or [View.width](api:view:get)
* Link to a setter: [View.width](api:view:set)
* Link to a global variable: [activity](api:app)
*/
final String urlPrefix = bApi ? _api: _dart;
boolean bGet = url.endsWith(":get"), bSet = !bGet && url.endsWith(":set");
if (bGet || bSet)
url = url.substring(0, url.length() - 4);
final String pkg = url.substring(bApi ? 4: 5).replace('/', '_');
int i = text.lastIndexOf('(');
- final boolean bMethod = i >= 0;
+// final boolean bMethod = i >= 0;
final String info = i >= 0 ? text.substring(0, i): text;
i = info.indexOf('.');
boolean bVar = i < 0 && Character.isLowerCase(text.charAt(0));
if (bVar)
return new Rendering(urlPrefix + pkg + ".html#" + info,
"<code>" + text + "</code>");
String mtd = i >= 0 ? info.substring(i + 1).trim(): null;
boolean bOp = mtd != null && mtd.startsWith("operator");
if (bOp) {
if (mtd.indexOf('[') > 0)
mtd = mtd.indexOf('=') > 0 ? ":setindex": ":index";
else if (mtd.indexOf("==") > 0)
mtd = ":eq";
else if (mtd.indexOf('+') > 0)
mtd = ":add";
else if (mtd.indexOf('-') > 0)
mtd = ":sub";
else if (mtd.indexOf('*') > 0)
mtd = ":mul";
else if (mtd.indexOf('/') > 0)
mtd = ":div";
else
bOp = false;
}
final String clsnm = i >= 0 ?
info.substring(0, i) + ".html#"
- + (bSet ? "set:": bGet || (!bMethod && !bOp) ? "get:": "") + mtd:
+// + (bSet ? "set:": bGet || (!bMethod && !bOp) ? "get:": "")
+ + mtd:
info + _ext;
return new Rendering(urlPrefix + pkg + "/" + clsnm,
"<code>" + text + "</code>");
} else if (url.startsWith("source:")) { //source: [name](source:path)
String path = url.substring(7);
if (path.length() > 0 && path.charAt(path.length() - 1) != '/')
path += '/';
return new Rendering(_source + path + text,
"<code>" + text + "</code>");
} else {
final int i = url.lastIndexOf(".md");
final char cc;
if (i >= 0 && ((i + 3) == url.length() || (cc=url.charAt(i + 3)) == '#' || cc == '?'))
return new Rendering(
url.substring(0, i+1) + "html" + url.substring(i + 3), text);
}
return super.render(node, text);
}
}
| false | true | public Rendering render(ExpLinkNode node, String text) {
String url = node.url;
boolean bApi = false;
if ((bApi = url.equals("api:")) || url.equals("dart:")) {
//package: [view](api:) or [html](dart:)
final String urlPrefix = bApi ? _api: _dart;
return new Rendering(urlPrefix + text.replace('/', '_') + ".html",
"<code>" + text + "</code>");
} else if ((bApi = url.startsWith("api:")) || url.startsWith("dart:")) {
/* Link to a class: [ViewConfig](api:view/impl) or [CSSStyleDecalration](dart:html)
* Link to a method: [View.requestLayout()](api:view)
* Link to a getter: [View.width](api:view) or [View.width](api:view:get)
* Link to a setter: [View.width](api:view:set)
* Link to a global variable: [activity](api:app)
*/
final String urlPrefix = bApi ? _api: _dart;
boolean bGet = url.endsWith(":get"), bSet = !bGet && url.endsWith(":set");
if (bGet || bSet)
url = url.substring(0, url.length() - 4);
final String pkg = url.substring(bApi ? 4: 5).replace('/', '_');
int i = text.lastIndexOf('(');
final boolean bMethod = i >= 0;
final String info = i >= 0 ? text.substring(0, i): text;
i = info.indexOf('.');
boolean bVar = i < 0 && Character.isLowerCase(text.charAt(0));
if (bVar)
return new Rendering(urlPrefix + pkg + ".html#" + info,
"<code>" + text + "</code>");
String mtd = i >= 0 ? info.substring(i + 1).trim(): null;
boolean bOp = mtd != null && mtd.startsWith("operator");
if (bOp) {
if (mtd.indexOf('[') > 0)
mtd = mtd.indexOf('=') > 0 ? ":setindex": ":index";
else if (mtd.indexOf("==") > 0)
mtd = ":eq";
else if (mtd.indexOf('+') > 0)
mtd = ":add";
else if (mtd.indexOf('-') > 0)
mtd = ":sub";
else if (mtd.indexOf('*') > 0)
mtd = ":mul";
else if (mtd.indexOf('/') > 0)
mtd = ":div";
else
bOp = false;
}
final String clsnm = i >= 0 ?
info.substring(0, i) + ".html#"
+ (bSet ? "set:": bGet || (!bMethod && !bOp) ? "get:": "") + mtd:
info + _ext;
return new Rendering(urlPrefix + pkg + "/" + clsnm,
"<code>" + text + "</code>");
} else if (url.startsWith("source:")) { //source: [name](source:path)
String path = url.substring(7);
if (path.length() > 0 && path.charAt(path.length() - 1) != '/')
path += '/';
return new Rendering(_source + path + text,
"<code>" + text + "</code>");
} else {
final int i = url.lastIndexOf(".md");
final char cc;
if (i >= 0 && ((i + 3) == url.length() || (cc=url.charAt(i + 3)) == '#' || cc == '?'))
return new Rendering(
url.substring(0, i+1) + "html" + url.substring(i + 3), text);
}
return super.render(node, text);
}
| public Rendering render(ExpLinkNode node, String text) {
String url = node.url;
boolean bApi = false;
if ((bApi = url.equals("api:")) || url.equals("dart:")) {
//package: [view](api:) or [html](dart:)
final String urlPrefix = bApi ? _api: _dart;
return new Rendering(urlPrefix + text.replace('/', '_') + ".html",
"<code>" + text + "</code>");
} else if ((bApi = url.startsWith("api:")) || url.startsWith("dart:")) {
/* Link to a class: [ViewConfig](api:view/impl) or [CSSStyleDecalration](dart:html)
* Link to a method: [View.requestLayout()](api:view)
* Link to a getter: [View.width](api:view) or [View.width](api:view:get)
* Link to a setter: [View.width](api:view:set)
* Link to a global variable: [activity](api:app)
*/
final String urlPrefix = bApi ? _api: _dart;
boolean bGet = url.endsWith(":get"), bSet = !bGet && url.endsWith(":set");
if (bGet || bSet)
url = url.substring(0, url.length() - 4);
final String pkg = url.substring(bApi ? 4: 5).replace('/', '_');
int i = text.lastIndexOf('(');
// final boolean bMethod = i >= 0;
final String info = i >= 0 ? text.substring(0, i): text;
i = info.indexOf('.');
boolean bVar = i < 0 && Character.isLowerCase(text.charAt(0));
if (bVar)
return new Rendering(urlPrefix + pkg + ".html#" + info,
"<code>" + text + "</code>");
String mtd = i >= 0 ? info.substring(i + 1).trim(): null;
boolean bOp = mtd != null && mtd.startsWith("operator");
if (bOp) {
if (mtd.indexOf('[') > 0)
mtd = mtd.indexOf('=') > 0 ? ":setindex": ":index";
else if (mtd.indexOf("==") > 0)
mtd = ":eq";
else if (mtd.indexOf('+') > 0)
mtd = ":add";
else if (mtd.indexOf('-') > 0)
mtd = ":sub";
else if (mtd.indexOf('*') > 0)
mtd = ":mul";
else if (mtd.indexOf('/') > 0)
mtd = ":div";
else
bOp = false;
}
final String clsnm = i >= 0 ?
info.substring(0, i) + ".html#"
// + (bSet ? "set:": bGet || (!bMethod && !bOp) ? "get:": "")
+ mtd:
info + _ext;
return new Rendering(urlPrefix + pkg + "/" + clsnm,
"<code>" + text + "</code>");
} else if (url.startsWith("source:")) { //source: [name](source:path)
String path = url.substring(7);
if (path.length() > 0 && path.charAt(path.length() - 1) != '/')
path += '/';
return new Rendering(_source + path + text,
"<code>" + text + "</code>");
} else {
final int i = url.lastIndexOf(".md");
final char cc;
if (i >= 0 && ((i + 3) == url.length() || (cc=url.charAt(i + 3)) == '#' || cc == '?'))
return new Rendering(
url.substring(0, i+1) + "html" + url.substring(i + 3), text);
}
return super.render(node, text);
}
|
diff --git a/src/main/java/netty/rpc/client/ClientHandler.java b/src/main/java/netty/rpc/client/ClientHandler.java
index a80f7e9..f9973a0 100644
--- a/src/main/java/netty/rpc/client/ClientHandler.java
+++ b/src/main/java/netty/rpc/client/ClientHandler.java
@@ -1,50 +1,50 @@
package netty.rpc.client;
import java.util.concurrent.ConcurrentHashMap;
import netty.rpc.coder.Transport;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 客户端消息处理
* @author steven.qiu
*
*/
public class ClientHandler extends SimpleChannelUpstreamHandler{
private static final Logger logger = LoggerFactory.getLogger(ClientHandler.class);
private ConcurrentHashMap<String, ResultHandler> callbackHandlerMap;
public ClientHandler(ConcurrentHashMap<String, ResultHandler> callbackHandlerMap){
this.callbackHandlerMap = callbackHandlerMap;
}
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e){
Transport transport = (Transport)e.getMessage();
String keyString = new String(transport.getKey());
ResultHandler handler = callbackHandlerMap.remove(keyString);
if(handler!=null){
handler.processor(transport.getValue());
}else{
- logger.error("Can not find the handle with the key {}", keyString);
+ logger.warn("Can not find the handle with the key {}", keyString);
}
}
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception{
super.channelClosed(ctx, e);
}
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception{
logger.error("Client Catch a Exception", e.getCause());
e.getChannel().close();
}
}
| true | true | public void messageReceived(ChannelHandlerContext ctx, MessageEvent e){
Transport transport = (Transport)e.getMessage();
String keyString = new String(transport.getKey());
ResultHandler handler = callbackHandlerMap.remove(keyString);
if(handler!=null){
handler.processor(transport.getValue());
}else{
logger.error("Can not find the handle with the key {}", keyString);
}
}
| public void messageReceived(ChannelHandlerContext ctx, MessageEvent e){
Transport transport = (Transport)e.getMessage();
String keyString = new String(transport.getKey());
ResultHandler handler = callbackHandlerMap.remove(keyString);
if(handler!=null){
handler.processor(transport.getValue());
}else{
logger.warn("Can not find the handle with the key {}", keyString);
}
}
|
diff --git a/SoarSuite/Applications/TestJavaSML/Application.java b/SoarSuite/Applications/TestJavaSML/Application.java
index 9564bdab3..6bb02f080 100644
--- a/SoarSuite/Applications/TestJavaSML/Application.java
+++ b/SoarSuite/Applications/TestJavaSML/Application.java
@@ -1,425 +1,425 @@
import sml.Agent;
import sml.Identifier;
import sml.IntElement;
import sml.Kernel;
import sml.StringElement;
/********************************************************************************************
*
* Application.java
*
* Description:
*
* Created on Nov 6, 2004
* @author Douglas Pearson
*
* Developed by ThreePenny Software <a href="http://www.threepenny.net">www.threepenny.net</a>
********************************************************************************************/
import sml.* ;
/************************************************************************
*
* Simple test app for working out SML (Soar Markup Language) interface through Java
*
************************************************************************/
public class Application
{
private Kernel m_Kernel ;
public static class EventListener implements Agent.RunEventInterface, Agent.PrintEventInterface, Agent.ProductionEventInterface,
Agent.xmlEventInterface, Agent.OutputEventInterface, Agent.OutputNotificationInterface,
Kernel.AgentEventInterface, Kernel.SystemEventInterface, Kernel.RhsFunctionInterface
{
// We'll test to make sure we can keep a ClientXML object that we're passed.
public ClientXML m_Keep = null ;
public void runEventHandler(int eventID, Object data, Agent agent, int phase)
{
System.out.println("Received run event in Java") ;
Application me = (Application)data ;
}
// We pass back the agent's name because the Java Agent object may not yet
// exist for this agent yet. The underlying C++ object *will* exist by the
// time this method is called. So instead we look up the Agent object
// from the kernel with GetAgent().
public void agentEventHandler(int eventID, Object data, String agentName)
{
System.out.println("Received agent event in Java") ;
Application me = (Application)data ;
Agent agent = me.m_Kernel.GetAgent(agentName) ;
if (agent == null)
throw new IllegalStateException("Error in agent event handler -- got event for agent that hasn't been created yet in ClientSML") ;
}
public void productionEventHandler(int eventID, Object data, Agent agent, String prodName, String instantiation)
{
System.out.println("Received production event in Java") ;
}
public void systemEventHandler(int eventID, Object data, Kernel kernel)
{
System.out.println("Received system event in Java") ;
}
public void printEventHandler(int eventID, Object data, Agent agent, String message)
{
System.out.println("Received print event in Java: " + message) ;
}
public void outputNotificationHandler(Object data, Agent agent)
{
System.out.println("Received an output notification in Java") ;
}
public void xmlEventHandler(int eventID, Object data, Agent agent, ClientXML xml)
{
String xmlText = xml.GenerateXMLString(true) ;
System.out.println("Received xml trace event in Java: " + xmlText) ;
String allChildren = "" ;
if (xml.GetNumberChildren() > 0)
{
ClientXML child = new ClientXML() ;
xml.GetChild(child, 0) ;
String childText = child.GenerateXMLString(true) ;
allChildren += childText ;
child.delete() ;
}
if (m_Keep != null)
m_Keep.delete() ;
m_Keep = new ClientXML(xml) ;
// No need to explicitly delete xml now. The Java version is like C++
// where you need to copy the object to keep it, which means you don't need to
// explicitly delete it.
//xml.delete() ;
}
public String rhsFunctionHandler(int eventID, Object data, String agentName, String functionName, String argument)
{
System.out.println("Received rhs function event in Java for function: " + functionName + "(" + argument + ")") ;
return "My rhs result " + argument ;
}
public void outputEventHandler(Object data, String agentName, String attributeName, WMElement pWmeAdded)
{
System.out.println("Received output event in Java for wme: " + pWmeAdded.GetIdentifierName() + " ^" + pWmeAdded.GetAttribute() + " " + pWmeAdded.GetValueAsString()) ;
// Retrieve the application class pointer (to test our user data was passed successfully) and then print out the tree of wmes from the wme added down.
Application app = (Application)data ;
app.printWMEs(pWmeAdded) ;
}
}
public void printWMEs(WMElement pRoot)
{
if (pRoot.GetParent() == null)
System.out.println("Top Identifier " + pRoot.GetValueAsString()) ;
else
{
System.out.println("(" + pRoot.GetParent().GetIdentifierSymbol() + " ^" + pRoot.GetAttribute() + " " + pRoot.GetValueAsString() + ")") ;
}
if (pRoot.IsIdentifier())
{
// NOTE: Can't just cast to (Identifier) in Java because the underlying C++ object needs to be cast
// so we use a conversion method.
Identifier pID = pRoot.ConvertToIdentifier() ;
int size = pID.GetNumberChildren() ;
for (int i = 0 ; i < size ; i++)
{
WMElement pWME = pID.GetChild(i) ;
printWMEs(pWME) ;
}
}
}
private void Test()
{
// Make sure the kernel was ok
if (m_Kernel.HadError())
throw new IllegalStateException("Error initializing kernel: " + m_Kernel.GetLastErrorDescription()) ;
String version = m_Kernel.GetSoarKernelVersion() ;
System.out.println("Soar version " + version) ;
// Create an agent
Agent agent = m_Kernel.CreateAgent("javatest") ;
Agent pAgent = agent ; // So it's easier copying existing C++ code here
Kernel pKernel = m_Kernel ;
// We test the kernel for an error after creating an agent as the agent
// object may not be properly constructed if the create call failed so
// we store errors in the kernel in this case.
if (m_Kernel.HadError())
throw new IllegalStateException("Error creating agent: " + m_Kernel.GetLastErrorDescription()) ;
String cwd = agent.ExecuteCommandLine("pwd") ;
String path = pKernel.GetLibraryLocation() ;
path += "/../Tests/testjavasml.soar" ;
// Load some productions
boolean load = agent.LoadProductions(path) ;
if (!load || agent.HadError())
throw new IllegalStateException("Error loading productions from testjavasml.soar: " + agent.GetLastErrorDescription()) ;
Identifier pInputLink = agent.GetInputLink() ;
if (pInputLink == null)
throw new IllegalStateException("Error getting the input link") ;
// Some random adds
Identifier pID = pAgent.CreateIdWME(pInputLink, "plane") ;
StringElement pWME1 = pAgent.CreateStringWME(pID, "type", "Boeing747") ;
IntElement pWME2 = pAgent.CreateIntWME(pID, "speed", 200) ;
// Then add some tic tac toe stuff which should trigger output
Identifier pSquare = pAgent.CreateIdWME(pInputLink, "square") ;
StringElement pEmpty = pAgent.CreateStringWME(pSquare, "content", "RANDOM") ;
IntElement pRow = pAgent.CreateIntWME(pSquare, "row", 1) ;
IntElement pCol = pAgent.CreateIntWME(pSquare, "col", 2) ;
boolean ok = pAgent.Commit() ;
// Quick test of init-soar
pAgent.InitSoar() ;
// Update the square's value to be empty. This ensures that the update
// call is doing something. Otherwise, when we run we won't get a match.
pAgent.Update(pEmpty, "EMPTY") ;
ok = pAgent.Commit() ;
/*******************************************************
// Register some event handlers
// Each call takes an object from a class that implements a handler method
// (E.g. listener has "runEventHandler").
// The type for that method is fixed by SML (there are examples above for each)
// I'm using one listener class for all events but each could be in its own class or they
// could be methods in "this" class.
// The last parameter is an arbitrary data object which will be passed back to us in the callback.
// I'm just passing in "this" but it could be anything.
// The integer we get back is only required when we unregister the handler.
********************************************************/
EventListener listener = new EventListener() ;
int jRunCallback = pAgent.RegisterForRunEvent(smlRunEventId.smlEVENT_AFTER_DECISION_CYCLE, listener, this) ;
int jProdCallback = pAgent.RegisterForProductionEvent(smlProductionEventId.smlEVENT_AFTER_PRODUCTION_FIRED, listener, this) ;
int jPrintCallback = pAgent.RegisterForPrintEvent(smlPrintEventId.smlEVENT_PRINT, listener, this) ;
int jSystemCallback = pKernel.RegisterForSystemEvent(smlSystemEventId.smlEVENT_AFTER_RESTART, listener, this) ;
int jSystemCallback2 = pKernel.RegisterForSystemEvent(smlSystemEventId.smlEVENT_SYSTEM_START, listener, this) ;
int jAgentCallback = pKernel.RegisterForAgentEvent(smlAgentEventId.smlEVENT_BEFORE_AGENT_REINITIALIZED, listener, this) ;
int jRhsCallback = pKernel.AddRhsFunction("test-rhs", listener, this) ;
int jTraceCallback = pAgent.RegisterForXMLEvent(smlXMLEventId.smlEVENT_XML_TRACE_OUTPUT, listener, this) ;
int jOutputCallback = pAgent.AddOutputHandler("move", listener, this) ;
int jOutputNotification = pAgent.RegisterForOutputNotification(listener, this) ;
// Trigger an agent event by doing init-soar
pAgent.InitSoar() ;
//pAgent.ExecuteCommandLine("watch 5") ;
// Now we should match (if we really loaded the tictactoe example rules) and so generate some real output
- String trace = pAgent.RunSelfTilOutput(20) ; // Should just cause Soar to run a decision or two (this is a test that run til output works stops at output)
+ String trace = pAgent.RunSelfTilOutput() ; // Should just cause Soar to run a decision or two (this is a test that run til output works stops at output)
System.out.println(trace) ;
// Trigger an agent event by doing init-soar
pAgent.InitSoar() ;
// Having rolled everything back we should be able to run forward again
// This tests that initSoar really works.
- String trace1 = pAgent.RunSelfTilOutput(20) ;
+ String trace1 = pAgent.RunSelfTilOutput() ;
System.out.println(trace1) ;
// See if our RHS function worked
String value = pAgent.GetOutputLink().GetParameterValue("test") ;
if (value == null)
throw new IllegalStateException("RHS function failed to set a value for ^test") ;
System.out.println("Value of ^test (via RHS function) is: " + value) ;
// Now stress things a little
// String traceLong = pAgent.Run(500) ;
if (listener.m_Keep == null)
throw new IllegalStateException("The xmlEventHandler wasn't called (so m_Keep is null)") ;
// Try to access m_Keep to make sure the underlying XML object's not been deleted
String testXML = listener.m_Keep.GenerateXMLString(true) ;
System.out.println("Last trace message: " + testXML) ;
listener.m_Keep.delete() ;
System.out.println("Unregister callbacks") ;
// Unregister our callbacks
// (This isn't required, I'm just testing that it works)
pAgent.UnregisterForXMLEvent(jTraceCallback) ;
pAgent.UnregisterForRunEvent(jRunCallback) ;
pAgent.UnregisterForProductionEvent(jProdCallback) ;
pAgent.UnregisterForPrintEvent(jPrintCallback) ;
pAgent.UnregisterForOutputNotification(jOutputNotification) ;
pAgent.RemoveOutputHandler(jOutputCallback) ;
pKernel.UnregisterForSystemEvent(jSystemCallback) ;
pKernel.UnregisterForSystemEvent(jSystemCallback2) ;
pKernel.UnregisterForAgentEvent(jAgentCallback) ;
pKernel.RemoveRhsFunction(jRhsCallback) ;
//String trace2 = pAgent.RunSelfTilOutput(20) ;
//System.out.println(trace2) ;
// Clean up
m_Kernel.Shutdown() ;
// Delete the kernel, releasing all of the owned objects (hope this works ok in Java...)
m_Kernel.delete() ;
}
// We create a file to say we succeeded or not, deleting any existing results beforehand
// The filename shows if things succeeded or not and the contents can explain further.
public void reportResult(String testName, boolean success, String msg)
{
try
{
// Decide on the filename to use for success/failure
String kSuccess = testName + "-success.txt" ;
String kFailure = testName + "-failure.txt" ;
// Remove any existing result files
java.io.File successFile = new java.io.File(kSuccess) ;
java.io.File failFile = new java.io.File(kFailure) ;
successFile.delete() ;
failFile.delete() ;
// Create the output file
java.io.FileWriter outfile = new java.io.FileWriter(success ? successFile : failFile) ;
if (success)
{
outfile.write("Tests SUCCEEDED") ;
outfile.write(msg) ;
System.out.println("Tests SUCCEEDED") ;
}
else
{
outfile.write("ERROR *** Tests FAILED");
outfile.write(msg) ;
System.out.println("ERROR *** Tests FAILED") ;
System.out.println(msg) ;
}
outfile.close();
}
catch (Exception e)
{
System.out.println("Exception occurred when writing results to file") ;
}
}
private void TestListener() throws Exception
{
// Sleep for 20 seconds so others can connect to us if they wish to test that
// (for this part we'll use the default port)
System.out.println("############ Listener Test ############") ;
m_Kernel = Kernel.CreateKernelInCurrentThread("SoarKernelSML", false, Kernel.GetDefaultPort()) ;
//m_Kernel.SetTraceCommunications(true) ;
for (int i = 0 ; i < 200 ; i++)
{
//System.out.println("Checking " + i) ;
m_Kernel.CheckForIncomingCommands() ;
Thread.sleep(100) ;
}
m_Kernel.delete() ;
}
private void TestRemote() throws Exception
{
// Now repeat the tests but with a kernel that's running in a different process (needs a listener to exist for this)
System.out.println("############ Remote Test ############") ;
// Initialize the remote kernel
m_Kernel = Kernel.CreateRemoteConnection(true, null, Kernel.GetDefaultPort()) ;
if (m_Kernel.HadError())
{
System.out.println("Failed to connect to the listener...was one running?") ;
return ;
}
Test() ;
}
public Application(String[] args)
{
boolean success = true ;
String msg = "" ;
boolean remote = false ;
boolean listener = false ;
for (int arg = 0 ; arg < args.length ; arg++)
{
if (args[arg].equals("-remote"))
remote = true ;
if (args[arg].equals("-listener"))
listener = true ;
}
try
{
boolean localTests = !remote && !listener ;
if (localTests)
{
// Now repeat the tests but with a kernel that's running in a different thread
System.out.println("############ Current Thread ############") ;
// Initialize the kernel
m_Kernel = Kernel.CreateKernelInCurrentThread("SoarKernelSML", false, 12345) ;
Test() ;
// Now repeat the tests but with a kernel that's running in a different thread
System.out.println("############ New Thread ############") ;
m_Kernel = Kernel.CreateKernelInNewThread("SoarKernelSML", 13131) ;
Test() ;
}
if (remote)
TestRemote() ;
else if (listener)
TestListener() ;
}
catch (Throwable t)
{
success = false ;
msg = t.toString() ;
}
finally
{
reportResult("testjavasml", success, msg) ;
}
}
public static void main(String[] args)
{
new Application(args);
}
}
| false | true | private void Test()
{
// Make sure the kernel was ok
if (m_Kernel.HadError())
throw new IllegalStateException("Error initializing kernel: " + m_Kernel.GetLastErrorDescription()) ;
String version = m_Kernel.GetSoarKernelVersion() ;
System.out.println("Soar version " + version) ;
// Create an agent
Agent agent = m_Kernel.CreateAgent("javatest") ;
Agent pAgent = agent ; // So it's easier copying existing C++ code here
Kernel pKernel = m_Kernel ;
// We test the kernel for an error after creating an agent as the agent
// object may not be properly constructed if the create call failed so
// we store errors in the kernel in this case.
if (m_Kernel.HadError())
throw new IllegalStateException("Error creating agent: " + m_Kernel.GetLastErrorDescription()) ;
String cwd = agent.ExecuteCommandLine("pwd") ;
String path = pKernel.GetLibraryLocation() ;
path += "/../Tests/testjavasml.soar" ;
// Load some productions
boolean load = agent.LoadProductions(path) ;
if (!load || agent.HadError())
throw new IllegalStateException("Error loading productions from testjavasml.soar: " + agent.GetLastErrorDescription()) ;
Identifier pInputLink = agent.GetInputLink() ;
if (pInputLink == null)
throw new IllegalStateException("Error getting the input link") ;
// Some random adds
Identifier pID = pAgent.CreateIdWME(pInputLink, "plane") ;
StringElement pWME1 = pAgent.CreateStringWME(pID, "type", "Boeing747") ;
IntElement pWME2 = pAgent.CreateIntWME(pID, "speed", 200) ;
// Then add some tic tac toe stuff which should trigger output
Identifier pSquare = pAgent.CreateIdWME(pInputLink, "square") ;
StringElement pEmpty = pAgent.CreateStringWME(pSquare, "content", "RANDOM") ;
IntElement pRow = pAgent.CreateIntWME(pSquare, "row", 1) ;
IntElement pCol = pAgent.CreateIntWME(pSquare, "col", 2) ;
boolean ok = pAgent.Commit() ;
// Quick test of init-soar
pAgent.InitSoar() ;
// Update the square's value to be empty. This ensures that the update
// call is doing something. Otherwise, when we run we won't get a match.
pAgent.Update(pEmpty, "EMPTY") ;
ok = pAgent.Commit() ;
/*******************************************************
// Register some event handlers
// Each call takes an object from a class that implements a handler method
// (E.g. listener has "runEventHandler").
// The type for that method is fixed by SML (there are examples above for each)
// I'm using one listener class for all events but each could be in its own class or they
// could be methods in "this" class.
// The last parameter is an arbitrary data object which will be passed back to us in the callback.
// I'm just passing in "this" but it could be anything.
// The integer we get back is only required when we unregister the handler.
********************************************************/
EventListener listener = new EventListener() ;
int jRunCallback = pAgent.RegisterForRunEvent(smlRunEventId.smlEVENT_AFTER_DECISION_CYCLE, listener, this) ;
int jProdCallback = pAgent.RegisterForProductionEvent(smlProductionEventId.smlEVENT_AFTER_PRODUCTION_FIRED, listener, this) ;
int jPrintCallback = pAgent.RegisterForPrintEvent(smlPrintEventId.smlEVENT_PRINT, listener, this) ;
int jSystemCallback = pKernel.RegisterForSystemEvent(smlSystemEventId.smlEVENT_AFTER_RESTART, listener, this) ;
int jSystemCallback2 = pKernel.RegisterForSystemEvent(smlSystemEventId.smlEVENT_SYSTEM_START, listener, this) ;
int jAgentCallback = pKernel.RegisterForAgentEvent(smlAgentEventId.smlEVENT_BEFORE_AGENT_REINITIALIZED, listener, this) ;
int jRhsCallback = pKernel.AddRhsFunction("test-rhs", listener, this) ;
int jTraceCallback = pAgent.RegisterForXMLEvent(smlXMLEventId.smlEVENT_XML_TRACE_OUTPUT, listener, this) ;
int jOutputCallback = pAgent.AddOutputHandler("move", listener, this) ;
int jOutputNotification = pAgent.RegisterForOutputNotification(listener, this) ;
// Trigger an agent event by doing init-soar
pAgent.InitSoar() ;
//pAgent.ExecuteCommandLine("watch 5") ;
// Now we should match (if we really loaded the tictactoe example rules) and so generate some real output
String trace = pAgent.RunSelfTilOutput(20) ; // Should just cause Soar to run a decision or two (this is a test that run til output works stops at output)
System.out.println(trace) ;
// Trigger an agent event by doing init-soar
pAgent.InitSoar() ;
// Having rolled everything back we should be able to run forward again
// This tests that initSoar really works.
String trace1 = pAgent.RunSelfTilOutput(20) ;
System.out.println(trace1) ;
// See if our RHS function worked
String value = pAgent.GetOutputLink().GetParameterValue("test") ;
if (value == null)
throw new IllegalStateException("RHS function failed to set a value for ^test") ;
System.out.println("Value of ^test (via RHS function) is: " + value) ;
// Now stress things a little
// String traceLong = pAgent.Run(500) ;
if (listener.m_Keep == null)
throw new IllegalStateException("The xmlEventHandler wasn't called (so m_Keep is null)") ;
// Try to access m_Keep to make sure the underlying XML object's not been deleted
String testXML = listener.m_Keep.GenerateXMLString(true) ;
System.out.println("Last trace message: " + testXML) ;
listener.m_Keep.delete() ;
System.out.println("Unregister callbacks") ;
// Unregister our callbacks
// (This isn't required, I'm just testing that it works)
pAgent.UnregisterForXMLEvent(jTraceCallback) ;
pAgent.UnregisterForRunEvent(jRunCallback) ;
pAgent.UnregisterForProductionEvent(jProdCallback) ;
pAgent.UnregisterForPrintEvent(jPrintCallback) ;
pAgent.UnregisterForOutputNotification(jOutputNotification) ;
pAgent.RemoveOutputHandler(jOutputCallback) ;
pKernel.UnregisterForSystemEvent(jSystemCallback) ;
pKernel.UnregisterForSystemEvent(jSystemCallback2) ;
pKernel.UnregisterForAgentEvent(jAgentCallback) ;
pKernel.RemoveRhsFunction(jRhsCallback) ;
//String trace2 = pAgent.RunSelfTilOutput(20) ;
//System.out.println(trace2) ;
// Clean up
m_Kernel.Shutdown() ;
// Delete the kernel, releasing all of the owned objects (hope this works ok in Java...)
m_Kernel.delete() ;
}
| private void Test()
{
// Make sure the kernel was ok
if (m_Kernel.HadError())
throw new IllegalStateException("Error initializing kernel: " + m_Kernel.GetLastErrorDescription()) ;
String version = m_Kernel.GetSoarKernelVersion() ;
System.out.println("Soar version " + version) ;
// Create an agent
Agent agent = m_Kernel.CreateAgent("javatest") ;
Agent pAgent = agent ; // So it's easier copying existing C++ code here
Kernel pKernel = m_Kernel ;
// We test the kernel for an error after creating an agent as the agent
// object may not be properly constructed if the create call failed so
// we store errors in the kernel in this case.
if (m_Kernel.HadError())
throw new IllegalStateException("Error creating agent: " + m_Kernel.GetLastErrorDescription()) ;
String cwd = agent.ExecuteCommandLine("pwd") ;
String path = pKernel.GetLibraryLocation() ;
path += "/../Tests/testjavasml.soar" ;
// Load some productions
boolean load = agent.LoadProductions(path) ;
if (!load || agent.HadError())
throw new IllegalStateException("Error loading productions from testjavasml.soar: " + agent.GetLastErrorDescription()) ;
Identifier pInputLink = agent.GetInputLink() ;
if (pInputLink == null)
throw new IllegalStateException("Error getting the input link") ;
// Some random adds
Identifier pID = pAgent.CreateIdWME(pInputLink, "plane") ;
StringElement pWME1 = pAgent.CreateStringWME(pID, "type", "Boeing747") ;
IntElement pWME2 = pAgent.CreateIntWME(pID, "speed", 200) ;
// Then add some tic tac toe stuff which should trigger output
Identifier pSquare = pAgent.CreateIdWME(pInputLink, "square") ;
StringElement pEmpty = pAgent.CreateStringWME(pSquare, "content", "RANDOM") ;
IntElement pRow = pAgent.CreateIntWME(pSquare, "row", 1) ;
IntElement pCol = pAgent.CreateIntWME(pSquare, "col", 2) ;
boolean ok = pAgent.Commit() ;
// Quick test of init-soar
pAgent.InitSoar() ;
// Update the square's value to be empty. This ensures that the update
// call is doing something. Otherwise, when we run we won't get a match.
pAgent.Update(pEmpty, "EMPTY") ;
ok = pAgent.Commit() ;
/*******************************************************
// Register some event handlers
// Each call takes an object from a class that implements a handler method
// (E.g. listener has "runEventHandler").
// The type for that method is fixed by SML (there are examples above for each)
// I'm using one listener class for all events but each could be in its own class or they
// could be methods in "this" class.
// The last parameter is an arbitrary data object which will be passed back to us in the callback.
// I'm just passing in "this" but it could be anything.
// The integer we get back is only required when we unregister the handler.
********************************************************/
EventListener listener = new EventListener() ;
int jRunCallback = pAgent.RegisterForRunEvent(smlRunEventId.smlEVENT_AFTER_DECISION_CYCLE, listener, this) ;
int jProdCallback = pAgent.RegisterForProductionEvent(smlProductionEventId.smlEVENT_AFTER_PRODUCTION_FIRED, listener, this) ;
int jPrintCallback = pAgent.RegisterForPrintEvent(smlPrintEventId.smlEVENT_PRINT, listener, this) ;
int jSystemCallback = pKernel.RegisterForSystemEvent(smlSystemEventId.smlEVENT_AFTER_RESTART, listener, this) ;
int jSystemCallback2 = pKernel.RegisterForSystemEvent(smlSystemEventId.smlEVENT_SYSTEM_START, listener, this) ;
int jAgentCallback = pKernel.RegisterForAgentEvent(smlAgentEventId.smlEVENT_BEFORE_AGENT_REINITIALIZED, listener, this) ;
int jRhsCallback = pKernel.AddRhsFunction("test-rhs", listener, this) ;
int jTraceCallback = pAgent.RegisterForXMLEvent(smlXMLEventId.smlEVENT_XML_TRACE_OUTPUT, listener, this) ;
int jOutputCallback = pAgent.AddOutputHandler("move", listener, this) ;
int jOutputNotification = pAgent.RegisterForOutputNotification(listener, this) ;
// Trigger an agent event by doing init-soar
pAgent.InitSoar() ;
//pAgent.ExecuteCommandLine("watch 5") ;
// Now we should match (if we really loaded the tictactoe example rules) and so generate some real output
String trace = pAgent.RunSelfTilOutput() ; // Should just cause Soar to run a decision or two (this is a test that run til output works stops at output)
System.out.println(trace) ;
// Trigger an agent event by doing init-soar
pAgent.InitSoar() ;
// Having rolled everything back we should be able to run forward again
// This tests that initSoar really works.
String trace1 = pAgent.RunSelfTilOutput() ;
System.out.println(trace1) ;
// See if our RHS function worked
String value = pAgent.GetOutputLink().GetParameterValue("test") ;
if (value == null)
throw new IllegalStateException("RHS function failed to set a value for ^test") ;
System.out.println("Value of ^test (via RHS function) is: " + value) ;
// Now stress things a little
// String traceLong = pAgent.Run(500) ;
if (listener.m_Keep == null)
throw new IllegalStateException("The xmlEventHandler wasn't called (so m_Keep is null)") ;
// Try to access m_Keep to make sure the underlying XML object's not been deleted
String testXML = listener.m_Keep.GenerateXMLString(true) ;
System.out.println("Last trace message: " + testXML) ;
listener.m_Keep.delete() ;
System.out.println("Unregister callbacks") ;
// Unregister our callbacks
// (This isn't required, I'm just testing that it works)
pAgent.UnregisterForXMLEvent(jTraceCallback) ;
pAgent.UnregisterForRunEvent(jRunCallback) ;
pAgent.UnregisterForProductionEvent(jProdCallback) ;
pAgent.UnregisterForPrintEvent(jPrintCallback) ;
pAgent.UnregisterForOutputNotification(jOutputNotification) ;
pAgent.RemoveOutputHandler(jOutputCallback) ;
pKernel.UnregisterForSystemEvent(jSystemCallback) ;
pKernel.UnregisterForSystemEvent(jSystemCallback2) ;
pKernel.UnregisterForAgentEvent(jAgentCallback) ;
pKernel.RemoveRhsFunction(jRhsCallback) ;
//String trace2 = pAgent.RunSelfTilOutput(20) ;
//System.out.println(trace2) ;
// Clean up
m_Kernel.Shutdown() ;
// Delete the kernel, releasing all of the owned objects (hope this works ok in Java...)
m_Kernel.delete() ;
}
|
diff --git a/components/dotnet-executable/src/main/java/npanday/executable/impl/CompilerContextImpl.java b/components/dotnet-executable/src/main/java/npanday/executable/impl/CompilerContextImpl.java
index 76d892fe..9e94845c 100644
--- a/components/dotnet-executable/src/main/java/npanday/executable/impl/CompilerContextImpl.java
+++ b/components/dotnet-executable/src/main/java/npanday/executable/impl/CompilerContextImpl.java
@@ -1,585 +1,589 @@
/*
* 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.executable.impl;
import npanday.ArtifactTypeHelper;
import npanday.executable.CommandExecutor;
import npanday.executable.ExecutionException;
import npanday.executable.CapabilityMatcher;
import npanday.executable.CommandFilter;
import npanday.PlatformUnsupportedException;
import npanday.executable.compiler.*;
import npanday.artifact.ArtifactContext;
import npanday.artifact.ArtifactException;
import npanday.ArtifactType;
import org.apache.maven.project.MavenProject;
import org.apache.maven.artifact.Artifact;
import npanday.registry.Repository;
import npanday.registry.RepositoryRegistry;
import npanday.RepositoryNotFoundException;
import npanday.vendor.Vendor;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import java.util.*;
import java.io.File;
/**
* Provides an implementation of the Compiler Context.
*
* @author Shane Isbell
*/
public final class CompilerContextImpl
implements CompilerContext, LogEnabled
{
/**
* The maven project
*/
private MavenProject project;
private CompilerConfig config;
private List<Artifact> libraries;
private List<Artifact> modules;
private CompilerExecutable netCompiler;
private CompilerCapability compilerCapability;
private CompilerRequirement compilerRequirement;
private CommandFilter commandFilter;
private ArtifactContext artifactContext;
private RepositoryRegistry repositoryRegistry;
/**
* A logger for writing log messages
*/
private Logger logger;
private List<File> linkedResources;
/** @deprecated */
private List<File> embeddedResources;
private List<String> embeddedResourceArgs;
private File win32icon;
private List<File> win32resources;
public List<File> getLinkedResources()
{
return linkedResources;
}
public List<File> getEmbeddedResources()
{
return embeddedResources;
}
public List<String> getEmbeddedResourceArgs()
{
return embeddedResourceArgs;
}
public File getWin32Icon()
{
return win32icon;
}
public List<File> getWin32Resources()
{
return win32resources;
}
public void enableLogging( Logger logger )
{
this.logger = logger;
}
public CompilerRequirement getCompilerRequirement()
{
return compilerRequirement;
}
public List<String> getCoreAssemblyNames()
{
return compilerCapability.getCoreAssemblies();
}
public List<Artifact> getModuleDependencies()
{
return modules;
}
public List<Artifact> getDirectModuleDependencies()
{
List<Artifact> artifacts;
try
{
artifacts = artifactContext.getNetModulesFor( project.getArtifact() );
}
catch ( ArtifactException e )
{
logger.error( "NPANDAY-061-000: Improper Initialization of the Net Modules", e );
return new ArrayList<Artifact>();
//TODO: How to handle this: usually implies improper init of ArtifactContext
}
if ( config.isTestCompile() && ArtifactTypeHelper.isDotnetModule( config.getArtifactType() ) )
{
artifacts.add( project.getArtifact() );
}
if ( config.isTestCompile() &&
ArtifactTypeHelper.isDotnetModule( project.getArtifact().getType() ) &&
project.getArtifact().getFile() != null && project.getArtifact().getFile().exists() )
{
artifacts.add( project.getArtifact() );
}
return artifacts;
}
public KeyInfo getKeyInfo()
{
if ( ( compilerRequirement.getVendor().equals( Vendor.MICROSOFT ) &&
compilerRequirement.getFrameworkVersion().equals( "1.1.4322" ) ) || config.getKeyInfo() == null )
{
return KeyInfo.Factory.createDefaultKeyInfo();
}
else
{
return config.getKeyInfo();
}
}
public List<Artifact> getLibraryDependencies()
{
if ( config.isTestCompile()
&& ( ArtifactTypeHelper.isDotnetLibrary( config.getArtifactType() )
|| ArtifactTypeHelper.isDotnetMavenPlugin( config.getArtifactType() ))
&& project.getArtifact().getFile() != null && project.getArtifact().getFile().exists()
&& !libraries.contains( project.getArtifact() ) && !ArtifactTypeHelper.isDotnetModule( project.getArtifact().getType() )
)
{
libraries.add( project.getArtifact() );
}
return libraries;
}
public Logger getLogger()
{
return logger;
}
public CompilerConfig getNetCompilerConfig()
{
return config;
}
public CompilerCapability getCompilerCapability()
{
return compilerCapability;
}
public String getSourceDirectoryName()
{
return ( config.isTestCompile() ) ? project.getBuild().getDirectory() + File.separator + "build-test-sources"
: project.getBuild().getDirectory() + File.separator + "build-sources";
}
public File getTargetDirectory()
{
return new File( project.getBuild().getDirectory() );
}
/**
* This method will return a File where File.isExist() returns false, if NetCompile.compile has not been
* invoked.
*
* @return
* @throws InvalidArtifactException
*/
public File getArtifact()
throws InvalidArtifactException
{
ArtifactType artifactType = config.getArtifactType();
if ( artifactType == null || artifactType.equals( ArtifactType.NULL ) )
{
throw new InvalidArtifactException( "NPANDAY-061-001: Artifact Type cannot be null" );
}
//TODO: The test-plugin has a dependency on this fileName/dir. If we change it here, it will break the plugin. Fix this encapsulation issue.
String fileName = ( config.isTestCompile() ) ? project.getBuild().getDirectory() + File.separator +
project.getArtifactId() + "-test.dll" : project.getBuild().getDirectory() + File.separator +
project.getArtifactId() + "." + artifactType.getExtension();
return new File( fileName );
}
public CompilerExecutable getCompilerExecutable()
throws ExecutionException
{
return netCompiler;
}
public CommandFilter getCommandFilter()
{
return commandFilter;
}
public Repository find( String repositoryName )
throws RepositoryNotFoundException
{
Repository repository = repositoryRegistry.find( repositoryName );
if ( repository == null )
{
throw new RepositoryNotFoundException(
"NPANDAY-061-002: Could not find repository: Name = " + repositoryName );
}
return repository;
}
private String getGacRootForMono()
throws PlatformUnsupportedException
{
String path = System.getenv( "PATH" );
if ( path != null )
{
String[] tokens = path.split( System.getProperty( "path.separator" ) );
for ( String token : tokens )
{
File gacRoot = new File( new File( token ).getParentFile(), "lib/mono/gac/" );
if ( gacRoot.exists() )
{
return gacRoot.getAbsolutePath();
}
}
}
//check settings file
String monoRoot = System.getenv( "MONO_ROOT" );
if ( monoRoot != null && !new File( monoRoot ).exists() )
{
logger.warn( "MONO_ROOT has been incorrectly set. Trying /usr : MONO_ROOT = " + monoRoot );
}
else if ( monoRoot != null )
{
return ( !monoRoot.endsWith( File.separator ) ) ? monoRoot + File.separator : monoRoot;
}
if ( new File( "/usr/lib/mono/gac/" ).exists() )
{
// Linux default location
return new File( "/usr/lib/mono/gac/" ).getAbsolutePath();
}
else if ( new File( "/Library/Frameworks/Mono.framework/Home/lib/mono/gac/" ).exists() )
{
// Mac OS X default location
return new File( "/Library/Frameworks/Mono.framework/Home/lib/mono/gac/" ).getAbsolutePath();
}
else
{
throw new PlatformUnsupportedException(
"NPANDAY-061-008: Could not locate Global Assembly Cache for Mono. Try setting the MONO_ROOT environmental variable." );
}
}
public void init( CompilerRequirement compilerRequirement, CompilerConfig config, MavenProject project,
CapabilityMatcher capabilityMatcher )
throws PlatformUnsupportedException
{
this.project = project;
this.config = config;
this.compilerRequirement = compilerRequirement;
libraries = new ArrayList<Artifact>();
modules = new ArrayList<Artifact>();
artifactContext.init( project, project.getRemoteArtifactRepositories(), config.getLocalRepository() );
Set<Artifact> artifacts = project.getDependencyArtifacts();//Can add WFC deps prior
if ( artifacts != null )
{
for ( Artifact artifact : artifacts )
{
String type = artifact.getType();
ArtifactType artifactType = ArtifactType.getArtifactTypeForPackagingName( type );
if ( ArtifactTypeHelper.isDotnetModule( type ))
{
modules.add( artifact );
}
- else if ( (artifactType != null && (artifactType.getExtension().equals( "library" )
- || artifactType.getExtension().equals( "exe" )) ) || type.equals( "jar" ) )
+ else if ( (artifactType != null && (
+ artifactType.getTargetCompileType().equals( "library" )
+ || artifactType.getExtension().equals( "dll" )
+ || artifactType.getExtension().equals( "exe" ))
+ )
+ || type.equals( "jar" ) )
{
libraries.add( artifact );
}
//Resolving here since the GAC path is vendor and framework aware
else if ( ArtifactTypeHelper.isDotnetGac( type ) )
{
// TODO: Duplicate code with VendorInfoRepositoryImpl.getGlobalAssemblyCacheDirectoryFor
String gacRoot = null;
if ( compilerRequirement.getVendor().equals( Vendor.MICROSOFT ) &&
compilerRequirement.getFrameworkVersion().equals( "1.1.4322" ) )
{
gacRoot = System.getenv( "SystemRoot" ) + "\\assembly\\GAC\\";
}
else if ( compilerRequirement.getVendor().equals( Vendor.MICROSOFT ) )
{
// Layout changed since 2.0
// http://discuss.joelonsoftware.com/default.asp?dotnet.12.383883.5
gacRoot = System.getenv( "SystemRoot" ) + "\\assembly\\GAC_MSIL\\";
}
else if ( compilerRequirement.getVendor().equals( Vendor.MONO ) )
{
gacRoot = getGacRootForMono();
}
if ( gacRoot != null )
{
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
}
else if ( type.equals( "gac" ) )
{
String gacRoot = ( compilerRequirement.getVendor().equals( Vendor.MONO ) ) ? getGacRootForMono()
: System.getenv( "SystemRoot" ) + "\\assembly\\GAC\\";
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
else if ( type.equals( "gac_32" ) )
{
String gacRoot = ( compilerRequirement.getVendor().equals( Vendor.MONO ) ) ? getGacRootForMono()
: System.getenv( "SystemRoot" ) + "\\assembly\\GAC_32\\";
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
else if ( type.equals( "gac_msil" ) )
{
String gacRoot = ( compilerRequirement.getVendor().equals( Vendor.MONO ) ) ? getGacRootForMono()
: System.getenv( "SystemRoot" ) + "\\assembly\\GAC_MSIL\\";
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
else if ( type.equals( "com_reference" ) )
{
moveInteropDllToBuildDirectory( artifact );
libraries.add( artifact );
}
}
}
compilerCapability = capabilityMatcher.matchCompilerCapabilityFor( compilerRequirement );
String className = compilerCapability.getPluginClassName();
try
{
Class cc = Class.forName( className );
netCompiler = (CompilerExecutable) cc.newInstance();
netCompiler.init( this );//TODO: Add ArtifactInfo?
}
catch ( ClassNotFoundException e )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-004: Unable to create NetCompiler: Class Name = " + className, e );
}
catch ( InstantiationException e )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-005: Unable to create NetCompiler: Class Name = " + className, e );
}
catch ( IllegalAccessException e )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-006: Unable to create NetCompiler: Class Name = " + className, e );
}
commandFilter =
CommandFilter.Factory.createDefaultCommandFilter( compilerCapability.getCommandCapability(), logger );
String basedir = project.getBuild().getDirectory() + File.separator + "assembly-resources" + File.separator;
linkedResources = new File( basedir, "linkresource" ).exists() ? Arrays.asList(
new File( basedir, "linkresource" ).listFiles() ) : new ArrayList<File>();
getEmbeddedResources( new File( basedir, "resource" ) );
win32resources = new File( basedir, "win32res" ).exists() ? Arrays.asList(
new File( basedir, "win32res" ).listFiles() ) : new ArrayList<File>();
File win32IconDir = new File( basedir, "win32icon" );
if ( win32IconDir.exists() )
{
File[] icons = win32IconDir.listFiles();
if ( icons.length > 1 )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-007: There is more than one win32icon in resource directory: Number = " + icons
.length );
}
if ( icons.length == 1 )
{
win32icon = icons[0];
}
}
}
private void getEmbeddedResources( File basedir )
{
List<File> embeddedResources = new ArrayList<File>();
List<String> embeddedResourceArgs = new ArrayList<String>();
if ( basedir.exists() )
{
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir( basedir );
scanner.scan();
for ( String file : scanner.getIncludedFiles() )
{
File f = new File(basedir, file);
embeddedResources.add(f);
if (f.getName().endsWith(".resources")) {
embeddedResourceArgs.add(f.getAbsolutePath());
} else {
String resourceName = project.getArtifactId() + "." + file.replace(File.separatorChar, '.');
embeddedResourceArgs.add(f.getAbsolutePath() + "," + resourceName);
}
}
}
this.embeddedResources = embeddedResources;
this.embeddedResourceArgs = embeddedResourceArgs;
}
private void moveInteropDllToBuildDirectory(Artifact artifact) throws PlatformUnsupportedException
{
try
{
File file = artifact.getFile();
String oldPath = file.getAbsolutePath();
String target = project.getBuild().getDirectory();
String newPath = target + File.separator + "Interop." + artifact.getArtifactId() + ".dll";
if ( oldPath.contains( target ) ) //already copied to target
return ;
logger.info( "NPANDAY-000-000:[COM Reference] copying file ["+ oldPath+"] to [" + target +"]" );
FileUtils.copyFileToDirectory( file, new File( target ) );
logger.info( "NPANDAY-000-000:[COM Reference] deleting directory ["+ file.getParentFile() +"]" );
FileUtils.deleteDirectory( file.getParentFile() );
logger.info( "NPANDAY-000-000:[COM Reference] updating artifact path to ["+ newPath +"]" );
artifact.setFile( new File( newPath ) );
}catch(Exception e)
{
throw new PlatformUnsupportedException (e);
}
}
/*
* Installs the artifact to the gac so that it can be used in aspnet
*/
private void installArtifactGacFile(Artifact artifact)
{
try
{
CommandExecutor commandExecutor = CommandExecutor.Factory.createDefaultCommmandExecutor();
String executable = "gacutil";
List<String> commands = new ArrayList<String>();
//searching for the .dll to be installed.
String sourceDir = config.getIncludeSources().get( 0 );
String[] sourceDirTokens = sourceDir.split( "\\\\" );
String sDir = "";
//constructing the directory for the.dll
for(int i=0;i<sourceDirTokens.length-3;i++)
{
if(sDir.equalsIgnoreCase( "" ))
{
sDir = sourceDirTokens[i];
}
else
{
sDir = sDir +"\\"+sourceDirTokens[i];
}
}
String dll = artifact.getArtifactId()+".dll";
String dllSysPath ="";
List<File> potentialDlls= FileUtils.getFiles( new File(sDir), "**" , null );
for(File cFile: potentialDlls)
{
String pSysPath = cFile.getAbsolutePath();
String[] pathTokens = pSysPath.split( "\\\\" );
if(pathTokens[pathTokens.length-1].equalsIgnoreCase( dll ) )
{
dllSysPath = cFile.getAbsolutePath();
//break;
}
}
commands.add( "/i "+dllSysPath );
commandExecutor.executeCommand( executable, commands);
}
catch(Exception e)
{
System.out.println("NPANDAY-000-000: Could not install artifact to GAC artifact:" +artifact.getArtifactId());
}
}
private void setArtifactGacFile( String gacRoot, Artifact artifact )
throws PlatformUnsupportedException
{
// TODO: Refactor to PathUtil.getGlobalAssemblyCacheFileFor
File gacFile = new File( gacRoot, artifact.getArtifactId() + File.separator + artifact.getVersion() + "__" +
artifact.getClassifier() + File.separator + artifact.getArtifactId() + ".dll" );
// first check if the artifact is not yet installed
if ( !gacFile.exists() )
{
installArtifactGacFile(artifact);
}
// after installing the gac check if it is installed in the system.
if ( !gacFile.exists() )
{
// TODO: this will only work on Windows
//check for gac_msil
gacRoot = System.getenv( "SystemRoot" ) + "\\assembly\\GAC_MSIL\\";
gacFile = new File( gacRoot, artifact.getArtifactId() + File.separator + artifact.getVersion() + "__" +
artifact.getClassifier() + File.separator + artifact.getArtifactId() + ".dll" );
if ( !gacFile.exists() )
{
throw new PlatformUnsupportedException(
"NPANDAY-000-000: Could not find GAC dependency: File = " + gacFile.getAbsolutePath() );
}
}
artifact.setFile( gacFile );
}
}
| true | true | public void init( CompilerRequirement compilerRequirement, CompilerConfig config, MavenProject project,
CapabilityMatcher capabilityMatcher )
throws PlatformUnsupportedException
{
this.project = project;
this.config = config;
this.compilerRequirement = compilerRequirement;
libraries = new ArrayList<Artifact>();
modules = new ArrayList<Artifact>();
artifactContext.init( project, project.getRemoteArtifactRepositories(), config.getLocalRepository() );
Set<Artifact> artifacts = project.getDependencyArtifacts();//Can add WFC deps prior
if ( artifacts != null )
{
for ( Artifact artifact : artifacts )
{
String type = artifact.getType();
ArtifactType artifactType = ArtifactType.getArtifactTypeForPackagingName( type );
if ( ArtifactTypeHelper.isDotnetModule( type ))
{
modules.add( artifact );
}
else if ( (artifactType != null && (artifactType.getExtension().equals( "library" )
|| artifactType.getExtension().equals( "exe" )) ) || type.equals( "jar" ) )
{
libraries.add( artifact );
}
//Resolving here since the GAC path is vendor and framework aware
else if ( ArtifactTypeHelper.isDotnetGac( type ) )
{
// TODO: Duplicate code with VendorInfoRepositoryImpl.getGlobalAssemblyCacheDirectoryFor
String gacRoot = null;
if ( compilerRequirement.getVendor().equals( Vendor.MICROSOFT ) &&
compilerRequirement.getFrameworkVersion().equals( "1.1.4322" ) )
{
gacRoot = System.getenv( "SystemRoot" ) + "\\assembly\\GAC\\";
}
else if ( compilerRequirement.getVendor().equals( Vendor.MICROSOFT ) )
{
// Layout changed since 2.0
// http://discuss.joelonsoftware.com/default.asp?dotnet.12.383883.5
gacRoot = System.getenv( "SystemRoot" ) + "\\assembly\\GAC_MSIL\\";
}
else if ( compilerRequirement.getVendor().equals( Vendor.MONO ) )
{
gacRoot = getGacRootForMono();
}
if ( gacRoot != null )
{
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
}
else if ( type.equals( "gac" ) )
{
String gacRoot = ( compilerRequirement.getVendor().equals( Vendor.MONO ) ) ? getGacRootForMono()
: System.getenv( "SystemRoot" ) + "\\assembly\\GAC\\";
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
else if ( type.equals( "gac_32" ) )
{
String gacRoot = ( compilerRequirement.getVendor().equals( Vendor.MONO ) ) ? getGacRootForMono()
: System.getenv( "SystemRoot" ) + "\\assembly\\GAC_32\\";
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
else if ( type.equals( "gac_msil" ) )
{
String gacRoot = ( compilerRequirement.getVendor().equals( Vendor.MONO ) ) ? getGacRootForMono()
: System.getenv( "SystemRoot" ) + "\\assembly\\GAC_MSIL\\";
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
else if ( type.equals( "com_reference" ) )
{
moveInteropDllToBuildDirectory( artifact );
libraries.add( artifact );
}
}
}
compilerCapability = capabilityMatcher.matchCompilerCapabilityFor( compilerRequirement );
String className = compilerCapability.getPluginClassName();
try
{
Class cc = Class.forName( className );
netCompiler = (CompilerExecutable) cc.newInstance();
netCompiler.init( this );//TODO: Add ArtifactInfo?
}
catch ( ClassNotFoundException e )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-004: Unable to create NetCompiler: Class Name = " + className, e );
}
catch ( InstantiationException e )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-005: Unable to create NetCompiler: Class Name = " + className, e );
}
catch ( IllegalAccessException e )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-006: Unable to create NetCompiler: Class Name = " + className, e );
}
commandFilter =
CommandFilter.Factory.createDefaultCommandFilter( compilerCapability.getCommandCapability(), logger );
String basedir = project.getBuild().getDirectory() + File.separator + "assembly-resources" + File.separator;
linkedResources = new File( basedir, "linkresource" ).exists() ? Arrays.asList(
new File( basedir, "linkresource" ).listFiles() ) : new ArrayList<File>();
getEmbeddedResources( new File( basedir, "resource" ) );
win32resources = new File( basedir, "win32res" ).exists() ? Arrays.asList(
new File( basedir, "win32res" ).listFiles() ) : new ArrayList<File>();
File win32IconDir = new File( basedir, "win32icon" );
if ( win32IconDir.exists() )
{
File[] icons = win32IconDir.listFiles();
if ( icons.length > 1 )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-007: There is more than one win32icon in resource directory: Number = " + icons
.length );
}
if ( icons.length == 1 )
{
win32icon = icons[0];
}
}
}
| public void init( CompilerRequirement compilerRequirement, CompilerConfig config, MavenProject project,
CapabilityMatcher capabilityMatcher )
throws PlatformUnsupportedException
{
this.project = project;
this.config = config;
this.compilerRequirement = compilerRequirement;
libraries = new ArrayList<Artifact>();
modules = new ArrayList<Artifact>();
artifactContext.init( project, project.getRemoteArtifactRepositories(), config.getLocalRepository() );
Set<Artifact> artifacts = project.getDependencyArtifacts();//Can add WFC deps prior
if ( artifacts != null )
{
for ( Artifact artifact : artifacts )
{
String type = artifact.getType();
ArtifactType artifactType = ArtifactType.getArtifactTypeForPackagingName( type );
if ( ArtifactTypeHelper.isDotnetModule( type ))
{
modules.add( artifact );
}
else if ( (artifactType != null && (
artifactType.getTargetCompileType().equals( "library" )
|| artifactType.getExtension().equals( "dll" )
|| artifactType.getExtension().equals( "exe" ))
)
|| type.equals( "jar" ) )
{
libraries.add( artifact );
}
//Resolving here since the GAC path is vendor and framework aware
else if ( ArtifactTypeHelper.isDotnetGac( type ) )
{
// TODO: Duplicate code with VendorInfoRepositoryImpl.getGlobalAssemblyCacheDirectoryFor
String gacRoot = null;
if ( compilerRequirement.getVendor().equals( Vendor.MICROSOFT ) &&
compilerRequirement.getFrameworkVersion().equals( "1.1.4322" ) )
{
gacRoot = System.getenv( "SystemRoot" ) + "\\assembly\\GAC\\";
}
else if ( compilerRequirement.getVendor().equals( Vendor.MICROSOFT ) )
{
// Layout changed since 2.0
// http://discuss.joelonsoftware.com/default.asp?dotnet.12.383883.5
gacRoot = System.getenv( "SystemRoot" ) + "\\assembly\\GAC_MSIL\\";
}
else if ( compilerRequirement.getVendor().equals( Vendor.MONO ) )
{
gacRoot = getGacRootForMono();
}
if ( gacRoot != null )
{
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
}
else if ( type.equals( "gac" ) )
{
String gacRoot = ( compilerRequirement.getVendor().equals( Vendor.MONO ) ) ? getGacRootForMono()
: System.getenv( "SystemRoot" ) + "\\assembly\\GAC\\";
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
else if ( type.equals( "gac_32" ) )
{
String gacRoot = ( compilerRequirement.getVendor().equals( Vendor.MONO ) ) ? getGacRootForMono()
: System.getenv( "SystemRoot" ) + "\\assembly\\GAC_32\\";
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
else if ( type.equals( "gac_msil" ) )
{
String gacRoot = ( compilerRequirement.getVendor().equals( Vendor.MONO ) ) ? getGacRootForMono()
: System.getenv( "SystemRoot" ) + "\\assembly\\GAC_MSIL\\";
setArtifactGacFile( gacRoot, artifact );
libraries.add( artifact );
}
else if ( type.equals( "com_reference" ) )
{
moveInteropDllToBuildDirectory( artifact );
libraries.add( artifact );
}
}
}
compilerCapability = capabilityMatcher.matchCompilerCapabilityFor( compilerRequirement );
String className = compilerCapability.getPluginClassName();
try
{
Class cc = Class.forName( className );
netCompiler = (CompilerExecutable) cc.newInstance();
netCompiler.init( this );//TODO: Add ArtifactInfo?
}
catch ( ClassNotFoundException e )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-004: Unable to create NetCompiler: Class Name = " + className, e );
}
catch ( InstantiationException e )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-005: Unable to create NetCompiler: Class Name = " + className, e );
}
catch ( IllegalAccessException e )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-006: Unable to create NetCompiler: Class Name = " + className, e );
}
commandFilter =
CommandFilter.Factory.createDefaultCommandFilter( compilerCapability.getCommandCapability(), logger );
String basedir = project.getBuild().getDirectory() + File.separator + "assembly-resources" + File.separator;
linkedResources = new File( basedir, "linkresource" ).exists() ? Arrays.asList(
new File( basedir, "linkresource" ).listFiles() ) : new ArrayList<File>();
getEmbeddedResources( new File( basedir, "resource" ) );
win32resources = new File( basedir, "win32res" ).exists() ? Arrays.asList(
new File( basedir, "win32res" ).listFiles() ) : new ArrayList<File>();
File win32IconDir = new File( basedir, "win32icon" );
if ( win32IconDir.exists() )
{
File[] icons = win32IconDir.listFiles();
if ( icons.length > 1 )
{
throw new PlatformUnsupportedException(
"NPANDAY-061-007: There is more than one win32icon in resource directory: Number = " + icons
.length );
}
if ( icons.length == 1 )
{
win32icon = icons[0];
}
}
}
|
diff --git a/src/MultiPlayer.java b/src/MultiPlayer.java
index 2dba522..910969f 100644
--- a/src/MultiPlayer.java
+++ b/src/MultiPlayer.java
@@ -1,291 +1,295 @@
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.GameState;
import org.newdawn.slick.state.StateBasedGame;
public class MultiPlayer implements GameState {
Image player, map, esctest;
boolean esc = false;
float mod = (float) 0.3;
float playerX=400, playerY=300;
int mouseX, mouseY;
int mapWidth=2560, mapHeight=1570;
float viewBottomRightX, viewBottomRightY, viewTopLeftX, viewTopLeftY;
public MultiPlayer(){
}
@Override
public void init(GameContainer gc, StateBasedGame sg)
throws SlickException {
viewBottomRightX=(mapWidth+1600)/2;
viewBottomRightY=(mapHeight+1200)/2;
viewTopLeftX=(mapWidth-1600)/2;
viewTopLeftY=(mapHeight-1200)/2;
System.out.println(-viewTopLeftX+viewBottomRightX);
player = new Image("data/player.png");
map = new Image("data/map.jpeg");
//esctest = new Image("data/player.png");
}
@Override
public void render(GameContainer gc, StateBasedGame sg, Graphics gfx)
throws SlickException {
map.draw(0, 0, viewTopLeftX, viewTopLeftY, viewBottomRightX, viewBottomRightY);
player.drawCentered(playerX, playerY);
//esctest.drawCentered(10, 10);
}
@Override
public void update(GameContainer gc, StateBasedGame sg, int delta)
throws SlickException {
System.out.println(-viewTopLeftX+viewBottomRightX);
Input input = gc.getInput();
double r = 0;
mouseX = input.getMouseX();
mouseY = input.getMouseY();
r = Math.atan2(mouseY-playerY, mouseX-playerX);
player.setRotation((float) Math.toDegrees(r));
if(input.isKeyDown(Input.KEY_W))
{
if(viewTopLeftY>0 && playerY>300){
playerY-=mod;
}
else if(viewTopLeftY>0){
viewTopLeftY-=mod;
+ viewBottomRightY-=mod;
}
else if(playerY>25){
playerY-=mod;
}
}
if(input.isKeyDown(Input.KEY_A))
{
if(viewTopLeftX>0 && playerX>400){
playerX-=mod;
}
else if(viewTopLeftX>0){
viewTopLeftX-=mod;
+ viewBottomRightX-=mod;
}
else if(playerX>25){
playerX-=mod;
}
}
if(input.isKeyDown(Input.KEY_S))
{
if(viewTopLeftY<600 && playerY<300){
playerY+=mod;
}
else if(viewTopLeftY<600){
viewTopLeftY+=mod;
+ viewBottomRightY+=mod;
}
else if(playerY<575){
playerY+=mod;
}
}
if(input.isKeyDown(Input.KEY_D))
{
if(viewTopLeftX<800 && playerX<400){
playerX+=mod;
}
else if(viewTopLeftX<800){
viewTopLeftX+=mod;
+ viewBottomRightX+=mod;
}
else if(playerX<775){
playerX+=mod;
}
}
/*if(input.isKeyDown(Input.KEY_ESCAPE)){
if(!esc){
esctest.setAlpha(1);
esc = true;
System.out.println("EscMenu Alpha:"+esctest.getAlpha());
try{
Thread.sleep(500);
}catch(InterruptedException e){}
}
else{
esctest.setAlpha(0);
esc = false;
System.out.println("EscMenu Alpha:"+esctest.getAlpha());
try{
Thread.sleep(500);
}catch(InterruptedException e){}
}
}*/
}
@Override
public void keyPressed(int key, char c) {
}
@Override
public void keyReleased(int arg0, char arg1) {
// TODO Auto-generated method stub
}
@Override
public void leave(GameContainer arg0, StateBasedGame arg1)
throws SlickException {
// TODO Auto-generated method stub
}
//SPACING
//SPACING
//SPACING
//SPACING
//SPACING
@Override
public void mouseClicked(int arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(int arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(int arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void mouseWheelMoved(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void inputEnded() {
// TODO Auto-generated method stub
}
@Override
public void inputStarted() {
// TODO Auto-generated method stub
}
@Override
public boolean isAcceptingInput() {
// TODO Auto-generated method stub
return false;
}
@Override
public void setInput(Input arg0) {
// TODO Auto-generated method stub
}
@Override
public void controllerButtonPressed(int arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void controllerButtonReleased(int arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void controllerDownPressed(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void controllerDownReleased(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void controllerLeftPressed(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void controllerLeftReleased(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void controllerRightPressed(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void controllerRightReleased(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void controllerUpPressed(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void controllerUpReleased(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void enter(GameContainer arg0, StateBasedGame arg1)
throws SlickException {
// TODO Auto-generated method stub
}
@Override
public int getID() {
// TODO Auto-generated method stub
return 0;
}
}
| false | true | public void update(GameContainer gc, StateBasedGame sg, int delta)
throws SlickException {
System.out.println(-viewTopLeftX+viewBottomRightX);
Input input = gc.getInput();
double r = 0;
mouseX = input.getMouseX();
mouseY = input.getMouseY();
r = Math.atan2(mouseY-playerY, mouseX-playerX);
player.setRotation((float) Math.toDegrees(r));
if(input.isKeyDown(Input.KEY_W))
{
if(viewTopLeftY>0 && playerY>300){
playerY-=mod;
}
else if(viewTopLeftY>0){
viewTopLeftY-=mod;
}
else if(playerY>25){
playerY-=mod;
}
}
if(input.isKeyDown(Input.KEY_A))
{
if(viewTopLeftX>0 && playerX>400){
playerX-=mod;
}
else if(viewTopLeftX>0){
viewTopLeftX-=mod;
}
else if(playerX>25){
playerX-=mod;
}
}
if(input.isKeyDown(Input.KEY_S))
{
if(viewTopLeftY<600 && playerY<300){
playerY+=mod;
}
else if(viewTopLeftY<600){
viewTopLeftY+=mod;
}
else if(playerY<575){
playerY+=mod;
}
}
if(input.isKeyDown(Input.KEY_D))
{
if(viewTopLeftX<800 && playerX<400){
playerX+=mod;
}
else if(viewTopLeftX<800){
viewTopLeftX+=mod;
}
else if(playerX<775){
playerX+=mod;
}
}
/*if(input.isKeyDown(Input.KEY_ESCAPE)){
if(!esc){
esctest.setAlpha(1);
esc = true;
System.out.println("EscMenu Alpha:"+esctest.getAlpha());
try{
Thread.sleep(500);
}catch(InterruptedException e){}
}
else{
esctest.setAlpha(0);
esc = false;
System.out.println("EscMenu Alpha:"+esctest.getAlpha());
try{
Thread.sleep(500);
}catch(InterruptedException e){}
}
}*/
| public void update(GameContainer gc, StateBasedGame sg, int delta)
throws SlickException {
System.out.println(-viewTopLeftX+viewBottomRightX);
Input input = gc.getInput();
double r = 0;
mouseX = input.getMouseX();
mouseY = input.getMouseY();
r = Math.atan2(mouseY-playerY, mouseX-playerX);
player.setRotation((float) Math.toDegrees(r));
if(input.isKeyDown(Input.KEY_W))
{
if(viewTopLeftY>0 && playerY>300){
playerY-=mod;
}
else if(viewTopLeftY>0){
viewTopLeftY-=mod;
viewBottomRightY-=mod;
}
else if(playerY>25){
playerY-=mod;
}
}
if(input.isKeyDown(Input.KEY_A))
{
if(viewTopLeftX>0 && playerX>400){
playerX-=mod;
}
else if(viewTopLeftX>0){
viewTopLeftX-=mod;
viewBottomRightX-=mod;
}
else if(playerX>25){
playerX-=mod;
}
}
if(input.isKeyDown(Input.KEY_S))
{
if(viewTopLeftY<600 && playerY<300){
playerY+=mod;
}
else if(viewTopLeftY<600){
viewTopLeftY+=mod;
viewBottomRightY+=mod;
}
else if(playerY<575){
playerY+=mod;
}
}
if(input.isKeyDown(Input.KEY_D))
{
if(viewTopLeftX<800 && playerX<400){
playerX+=mod;
}
else if(viewTopLeftX<800){
viewTopLeftX+=mod;
viewBottomRightX+=mod;
}
else if(playerX<775){
playerX+=mod;
}
}
/*if(input.isKeyDown(Input.KEY_ESCAPE)){
if(!esc){
esctest.setAlpha(1);
esc = true;
System.out.println("EscMenu Alpha:"+esctest.getAlpha());
try{
Thread.sleep(500);
}catch(InterruptedException e){}
}
else{
esctest.setAlpha(0);
esc = false;
System.out.println("EscMenu Alpha:"+esctest.getAlpha());
try{
Thread.sleep(500);
}catch(InterruptedException e){}
}
}*/
|
diff --git a/tool/src/java/org/sakaiproject/evaluation/tool/producers/TakeEvalProducer.java b/tool/src/java/org/sakaiproject/evaluation/tool/producers/TakeEvalProducer.java
index eee661e4..9a81adad 100644
--- a/tool/src/java/org/sakaiproject/evaluation/tool/producers/TakeEvalProducer.java
+++ b/tool/src/java/org/sakaiproject/evaluation/tool/producers/TakeEvalProducer.java
@@ -1,754 +1,755 @@
/**
* TakeEvalProducer.java - evaluation - Sep 18, 2006 11:35:56 AM - azeckoski
* $URL$
* $Id$
**************************************************************************
* Copyright (c) 2008 Centre for Applied Research in Educational Technologies, University of Cambridge
* Licensed under the Educational Community License version 1.0
*
* A copy of the Educational Community License has been included in this
* distribution and is available at: http://www.opensource.org/licenses/ecl1.php
*
* Aaron Zeckoski ([email protected]) ([email protected]) ([email protected])
*/
package org.sakaiproject.evaluation.tool.producers;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.evaluation.constant.EvalConstants;
import org.sakaiproject.evaluation.logic.EvalAuthoringService;
import org.sakaiproject.evaluation.logic.EvalCommonLogic;
import org.sakaiproject.evaluation.logic.EvalEvaluationService;
import org.sakaiproject.evaluation.logic.EvalSettings;
import org.sakaiproject.evaluation.logic.exceptions.ResponseSaveException;
import org.sakaiproject.evaluation.logic.externals.ExternalHierarchyLogic;
import org.sakaiproject.evaluation.logic.model.EvalGroup;
import org.sakaiproject.evaluation.logic.model.EvalUser;
import org.sakaiproject.evaluation.model.EvalAnswer;
import org.sakaiproject.evaluation.model.EvalAssignGroup;
import org.sakaiproject.evaluation.model.EvalAssignUser;
import org.sakaiproject.evaluation.model.EvalEvaluation;
import org.sakaiproject.evaluation.model.EvalResponse;
import org.sakaiproject.evaluation.model.EvalTemplateItem;
import org.sakaiproject.evaluation.tool.LocalResponsesLogic;
import org.sakaiproject.evaluation.tool.locators.ResponseAnswersBeanLocator;
import org.sakaiproject.evaluation.tool.renderers.ItemRenderer;
import org.sakaiproject.evaluation.tool.utils.RenderingUtils;
import org.sakaiproject.evaluation.tool.viewparams.EvalCategoryViewParameters;
import org.sakaiproject.evaluation.tool.viewparams.EvalViewParameters;
import org.sakaiproject.evaluation.utils.EvalUtils;
import org.sakaiproject.evaluation.utils.TemplateItemDataList;
import org.sakaiproject.evaluation.utils.TemplateItemUtils;
import org.sakaiproject.evaluation.utils.TemplateItemDataList.DataTemplateItem;
import org.sakaiproject.evaluation.utils.TemplateItemDataList.HierarchyNodeGroup;
import org.sakaiproject.evaluation.utils.TemplateItemDataList.TemplateItemGroup;
import com.sun.java_cup.internal.assoc;
import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.messageutil.TargettedMessage;
import uk.org.ponder.messageutil.TargettedMessageList;
import uk.org.ponder.rsf.components.ELReference;
import uk.org.ponder.rsf.components.UIBoundBoolean;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIELBinding;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInternalLink;
import uk.org.ponder.rsf.components.UIMessage;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UIOutputMany;
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.components.decorators.DecoratorList;
import uk.org.ponder.rsf.components.decorators.UICSSDecorator;
import uk.org.ponder.rsf.components.decorators.UIFreeAttributeDecorator;
import uk.org.ponder.rsf.components.decorators.UIIDStrategyDecorator;
import uk.org.ponder.rsf.components.decorators.UILabelTargetDecorator;
import uk.org.ponder.rsf.components.decorators.UIStyleDecorator;
import uk.org.ponder.rsf.flow.ARIResult;
import uk.org.ponder.rsf.flow.ActionResultInterceptor;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCase;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParamsReporter;
/**
* This page is for a user with take evaluation permission to fill and submit the evaluation
*
* @author Aaron Zeckoski ([email protected])
*/
public class TakeEvalProducer implements ViewComponentProducer, ViewParamsReporter, NavigationCaseReporter, ActionResultInterceptor {
private static final String SELECT_KEY_ASSISTANT = "assistant";
private static final String SELECT_KEY_INSTRUCTOR = "instructor";
private static Log log = LogFactory.getLog(TakeEvalProducer.class);
public static final String VIEW_ID = "take_eval";
public String getViewID() {
return VIEW_ID;
}
private EvalCommonLogic commonLogic;
public void setCommonLogic(EvalCommonLogic commonLogic) {
this.commonLogic = commonLogic;
}
private EvalAuthoringService authoringService;
public void setAuthoringService(EvalAuthoringService authoringService) {
this.authoringService = authoringService;
}
private EvalEvaluationService evaluationService;
public void setEvaluationService(EvalEvaluationService evaluationService) {
this.evaluationService = evaluationService;
}
ItemRenderer itemRenderer;
public void setItemRenderer(ItemRenderer itemRenderer) {
this.itemRenderer = itemRenderer;
}
private LocalResponsesLogic localResponsesLogic;
public void setLocalResponsesLogic(LocalResponsesLogic localResponsesLogic) {
this.localResponsesLogic = localResponsesLogic;
}
private ExternalHierarchyLogic hierarchyLogic;
public void setExternalHierarchyLogic(ExternalHierarchyLogic logic) {
this.hierarchyLogic = logic;
}
private EvalSettings evalSettings;
public void setEvalSettings(EvalSettings evalSettings) {
this.evalSettings = evalSettings;
}
private TargettedMessageList messages;
public void setMessages(TargettedMessageList messages) {
this.messages = messages;
}
private Locale locale;
public void setLocale(Locale locale) {
this.locale = locale;
}
private MessageLocator messageLocator;
public void setMessageLocator(MessageLocator messageLocator) {
this.messageLocator = messageLocator;
}
private HttpServletResponse httpServletResponse;
public void setHttpServletResponse(HttpServletResponse httpServletResponse) {
this.httpServletResponse = httpServletResponse;
}
Long responseId;
int displayNumber=1;
int renderedItemCount=0;
/**
* Map of key to Answers for the current response<br/>
* key = templateItemId + answer.associatedType + answer.associatedId
*/
Map<String, EvalAnswer> answerMap = new HashMap<String, EvalAnswer>();
/**
* If this is a re-opened response this will contain an {@link EvalResponse}
*/
EvalResponse response;
/* (non-Javadoc)
* @see uk.org.ponder.rsf.view.ComponentProducer#fillComponents(uk.org.ponder.rsf.components.UIContainer, uk.org.ponder.rsf.viewstate.ViewParameters, uk.org.ponder.rsf.view.ComponentChecker)
*/
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
// force the headers to expire this - http://jira.sakaiproject.org/jira/browse/EVALSYS-621
RenderingUtils.setNoCacheHeaders(httpServletResponse);
boolean canAccess = false; // can a user access this evaluation
boolean userCanAccess = false; // can THIS user take this evaluation
String currentUserId = commonLogic.getCurrentUserId();
// use a date which is related to the current users locale
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
UIMessage.make(tofill, "page-title", "takeeval.page.title");
UIInternalLink.make(tofill, "summary-link", UIMessage.make("summary.page.title"),
new SimpleViewParameters(SummaryProducer.VIEW_ID));
// get passed in get params
EvalViewParameters evalTakeViewParams = (EvalViewParameters) viewparams;
Long evaluationId = evalTakeViewParams.evaluationId;
if (evaluationId == null) {
// redirect over to the main view maybe?? (not sure how to do this in RSF)
log.error("User ("+currentUserId+") cannot take evaluation, eval id is not set");
throw new IllegalArgumentException("Invalid evaluationId: id must be set and cannot be null, cannot load evaluation");
}
String evalGroupId = evalTakeViewParams.evalGroupId;
responseId = evalTakeViewParams.responseId;
// get the evaluation based on the passed in VPs
EvalEvaluation eval = evaluationService.getEvaluationById(evaluationId);
if (eval == null) {
throw new IllegalArgumentException("Invalid evaluationId ("+evaluationId+"), cannot load evaluation");
}
UIMessage.make(tofill, "eval-title-header", "takeeval.eval.title.header");
UIOutput.make(tofill, "evalTitle", eval.getTitle());
/* check the states of the evaluation first to give the user a tip that this eval is not takeable,
* also avoids wasting time checking permissions when the evaluation certainly is closed,
* also allows us to give the user a nice custom message
*/
String evalState = evaluationService.returnAndFixEvalState(eval, true); // make sure state is up to date
if (EvalUtils.checkStateBefore(evalState, EvalConstants.EVALUATION_STATE_ACTIVE, false)) {
String dueDate = "--------";
if (eval.getDueDate() != null) {
dueDate = df.format(eval.getDueDate());
}
UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.not.open",
new String[] {df.format(eval.getStartDate()), dueDate} );
log.info("User ("+currentUserId+") cannot take evaluation yet, not open until: " + eval.getStartDate());
} else if (EvalUtils.checkStateAfter(evalState, EvalConstants.EVALUATION_STATE_CLOSED, true)) {
UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.closed",
new String[] {df.format(eval.getDueDate())} );
log.info("User ("+currentUserId+") cannot take evaluation anymore, closed on: " + eval.getDueDate());
} else {
// eval state is possible to take eval
canAccess = true;
}
List<EvalGroup> validGroups = new ArrayList<EvalGroup>(); // stores EvalGroup objects
if (canAccess) {
// eval is accessible so check user can take it
if (evalGroupId != null) {
// there was an eval group passed in so make sure things are ok
if (evaluationService.canTakeEvaluation(currentUserId, evaluationId, evalGroupId)) {
userCanAccess = true;
}
} else {
// select the first eval group the current user can take evaluation in,
// also store the total number so we can give the user a list to choose from if there are more than one
Map<Long, List<EvalAssignGroup>> m = evaluationService.getAssignGroupsForEvals(new Long[] {evaluationId}, true, null);
if ( commonLogic.isUserAdmin(currentUserId) ) {
// special case, the super admin can always access
userCanAccess = true;
List<EvalAssignGroup> assignGroups = m.get(evaluationId);
for (int i = 0; i < assignGroups.size(); i++) {
EvalAssignGroup assignGroup = assignGroups.get(i);
if (evalGroupId == null) {
// set the evalGroupId to the first valid group if unset
evalGroupId = assignGroup.getEvalGroupId();
}
validGroups.add( commonLogic.makeEvalGroupObject( assignGroup.getEvalGroupId() ));
}
} else {
EvalGroup[] evalGroups;
if ( EvalConstants.EVALUATION_AUTHCONTROL_NONE.equals(eval.getAuthControl()) ) {
// anonymous eval allows any group to be evaluated
List<EvalAssignGroup> assignGroups = m.get(evaluationId);
evalGroups = new EvalGroup[assignGroups.size()];
for (int i = 0; i < assignGroups.size(); i++) {
EvalAssignGroup assignGroup = assignGroups.get(i);
evalGroups[i] = commonLogic.makeEvalGroupObject( assignGroup.getEvalGroupId() );
}
} else {
List<EvalAssignUser> userAssignments = evaluationService.getParticipantsForEval(evaluationId, currentUserId, null,
EvalAssignUser.TYPE_EVALUATOR, null, null, null);
Set<String> evalGroupIds = EvalUtils.getGroupIdsFromUserAssignments(userAssignments);
List<EvalGroup> groups = EvalUtils.makeGroupsFromGroupsIds(evalGroupIds, commonLogic);
evalGroups = EvalUtils.getGroupsInCommon(groups, m.get(evaluationId) );
}
for (int i = 0; i < evalGroups.length; i++) {
EvalGroup group = evalGroups[i];
if (evaluationService.canTakeEvaluation(currentUserId, evaluationId, group.evalGroupId)) {
if (evalGroupId == null) {
// set the evalGroupId to the first valid group if unset
evalGroupId = group.evalGroupId;
userCanAccess = true;
}
validGroups.add( commonLogic.makeEvalGroupObject(group.evalGroupId) );
}
}
}
}
if (userCanAccess) {
// check if we had a failure during a previous submit and get the missingKeys out if there are some
Set<String> missingKeys = new HashSet<String>();
if (messages.isError() && messages.size() > 0) {
for (int i = 0; i < messages.size(); i++) {
TargettedMessage message = messages.messageAt(i);
Exception e = message.exception;
if (e instanceof ResponseSaveException) {
ResponseSaveException rse = (ResponseSaveException) e;
if (rse.missingItemAnswerKeys != null
&& rse.missingItemAnswerKeys.length > 0) {
for (int j = 0; j < rse.missingItemAnswerKeys.length; j++) {
missingKeys.add(rse.missingItemAnswerKeys[j]);
}
}
break;
}
}
}
// load up the response if this user has one already
if (responseId == null) {
response = evaluationService.getResponseForUserAndGroup(
evaluationId, currentUserId, evalGroupId);
if (response == null) {
// create the initial response if there is not one
// EVALSYS-360 because of a hibernate issue this will not work, do a binding instead -AZ
//responseId = localResponsesLogic.createResponse(evaluationId, currentUserId, evalGroupId);
} else {
responseId = response.getId();
}
}
if (responseId != null) {
// load up the previous responses for this user (no need to attempt to load if the response is new, there will be no answers yet)
answerMap = localResponsesLogic.getAnswersMapByTempItemAndAssociated(responseId);
}
// show the switch group selection and form if there are other valid groups for this user
if (validGroups.size() > 1) {
String[] values = new String[validGroups.size()];
String[] labels = new String[validGroups.size()];
for (int i=0; i<validGroups.size(); i++) {
EvalGroup group = validGroups.get(i);
values[i] = group.evalGroupId;
labels[i] = group.title;
}
// show the switch group selection and form
UIBranchContainer showSwitchGroup = UIBranchContainer.make(tofill, "show-switch-group:");
UIMessage.make(showSwitchGroup, "switch-group-header", "takeeval.switch.group.header");
UIForm chooseGroupForm = UIForm.make(showSwitchGroup, "switch-group-form",
new EvalViewParameters(TakeEvalProducer.VIEW_ID, evaluationId, responseId, evalGroupId));
UISelect.make(chooseGroupForm, "switch-group-list", values, labels, "#{evalGroupId}");
UIMessage.make(chooseGroupForm, "switch-group-button", "takeeval.switch.group.button");
}
// fill in group title
EvalGroup evalGroup = commonLogic.makeEvalGroupObject( evalGroupId );
UIBranchContainer groupTitle = UIBranchContainer.make(tofill, "show-group-title:");
UIMessage.make(groupTitle, "group-title-header", "takeeval.group.title.header");
UIOutput.make(groupTitle, "group-title", evalGroup.title );
// show instructions if not null
if (eval.getInstructions() != null && !("".equals(eval.getInstructions())) ) {
UIBranchContainer instructions = UIBranchContainer.make(tofill, "show-eval-instructions:");
UIMessage.make(instructions, "eval-instructions-header", "takeeval.instructions.header");
UIVerbatim.make(instructions, "eval-instructions", eval.getInstructions());
}
// get the setting and make sure it cannot be null (fix for http://www.caret.cam.ac.uk/jira/browse/CTL-531)
Boolean studentAllowedLeaveUnanswered = (Boolean) evalSettings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
if (studentAllowedLeaveUnanswered == null) {
studentAllowedLeaveUnanswered = EvalUtils.safeBool(eval.getBlankResponsesAllowed(), false);
}
// show a warning to the user if all items must be filled in
if ( studentAllowedLeaveUnanswered == false ) {
UIBranchContainer note = UIBranchContainer.make(tofill, "show-eval-note:");
UIMessage.make(note, "eval-note-text", "takeeval.user.must.answer.all.note");
}
UIBranchContainer formBranch = UIBranchContainer.make(tofill, "form-branch:");
UIForm form = UIForm.make(formBranch, "evaluationForm");
// bind the evaluation and evalGroup to the ones in the take eval bean
String evalOTP = "evaluationBeanLocator.";
form.parameters.add( new UIELBinding("#{takeEvalBean.eval}", new ELReference(evalOTP + eval.getId())) );
form.parameters.add( new UIELBinding("#{takeEvalBean.evalGroupId}", evalGroupId) );
// BEGIN the complex task of rendering the evaluation items
// make the TI data structure
TemplateItemDataList tidl = new TemplateItemDataList(evaluationId, evalGroupId,
evaluationService, authoringService, hierarchyLogic, null);
Set<String> instructorIds = tidl.getAssociateIds(EvalConstants.ITEM_CATEGORY_INSTRUCTOR);
Set<String> assistantIds = tidl.getAssociateIds(EvalConstants.ITEM_CATEGORY_ASSISTANT);
List<String> associatedTypes = tidl.getAssociateTypes();
// SELECTION Code - EVALSYS-618
Boolean selectionsEnabled = (Boolean) evalSettings
.get(EvalSettings.ENABLE_INSTRUCTOR_ASSISTANT_SELECTION);
String instructorSelectionOption = EvalAssignGroup.SELECTION_OPTION_ALL;
String assistantSelectionOption = EvalAssignGroup.SELECTION_OPTION_ALL;
Map<String, String[]> savedSelections = new HashMap<String, String[]>();
if(response!=null){
savedSelections = response.getSelections();
}
if (selectionsEnabled) {
// only do the selection calculations if it is enabled
EvalAssignGroup assignGroup = evaluationService.getAssignGroupByEvalAndGroupId(
evaluationId, evalGroupId);
Map<String, String> selectorType = new HashMap<String, String>();
instructorSelectionOption = EvalUtils.getSelectionSetting(
EvalAssignGroup.SELECTION_TYPE_INSTRUCTOR, assignGroup, null);
selectorType.put(SELECT_KEY_INSTRUCTOR, instructorSelectionOption);
Boolean assistantsEnabled = (Boolean) evalSettings
.get(EvalSettings.ENABLE_ASSISTANT_CATEGORY);
if (assistantsEnabled) {
assistantSelectionOption = EvalUtils.getSelectionSetting(
EvalAssignGroup.SELECTION_TYPE_ASSISTANT, assignGroup, null);
selectorType.put(SELECT_KEY_ASSISTANT, assistantSelectionOption);
}
if (response != null) {
// emit currently selected people into hidden element
// for JS use
Set<String> savedIds = new HashSet<String>();
for (Iterator<String> selector = savedSelections
.keySet().iterator(); selector.hasNext();) {
String selectKey = (String) selector.next();
String[] usersFound = savedSelections
.get(selectKey);
savedIds.add(usersFound[0]);
}
UIOutput savedSel = UIOutput
.make(formBranch, "selectedPeopleInResponse",
savedIds.toString());
savedSel.decorators = new DecoratorList(
new UIIDStrategyDecorator(
"selectedPeopleInResponse"));
}
- for (Iterator<String> selector = selectorType.keySet().iterator(); selector.hasNext();) {
- // FIXME findbugs says that getting keys like this is inefficient, use Map.Entry
- String selectKey = (String) selector.next();
- String selectValue = (String) selectorType.get(selectKey);
+ Iterator<Map.Entry<String, String>> selector = selectorType.entrySet().iterator();
+ while (selector.hasNext()) {
+ Map.Entry<String, String> pairs = selector.next();
+ String selectKey = (String) pairs.getKey();
+ String selectValue = (String) pairs.getValue();
String uiTag = "select-" + selectKey;
String selectionOTP = "#{takeEvalBean.selection" + selectKey + "Ids}";
Set<String> selectUserIds = new HashSet<String>();
if (selectKey.equals(SELECT_KEY_INSTRUCTOR)) {
selectUserIds = instructorIds;
} else if (selectKey.equals(SELECT_KEY_ASSISTANT)) {
selectUserIds = assistantIds;
}
// We render the selection controls if there are at least two
// Instructors/TAs
if (selectUserIds.size() > 1 && associatedTypes.contains(selectKey) ) {
if (selectValue.equals(EvalAssignGroup.SELECTION_OPTION_ALL)) {
// nothing special to do in all case
//form.parameters.add(new UIELBinding(selectionOTP, "all"));
} else if (EvalAssignGroup.SELECTION_OPTION_MULTIPLE.equals(selectValue)) {
UIBranchContainer showSwitchGroup = UIBranchContainer.make(
form, uiTag + "-multiple:");
// Things for building the UISelect of Assignment Checkboxes
List<String> assLabels = new ArrayList<String>();
List<String> assValues = new ArrayList<String>();
UISelect assSelect = UISelect.makeMultiple(showSwitchGroup, uiTag + "-multiple-holder", new String[] {}, new String[] {}, selectionOTP, new String[] {});
String assSelectID = assSelect.getFullID();
for (String userId : selectUserIds) {
EvalUser user = commonLogic.getEvalUserById(userId);
assValues.add(user.userId);
assLabels.add(user.displayName);
UIBranchContainer row = UIBranchContainer.make(showSwitchGroup, uiTag + "-multiple-row:");
UISelectChoice choice = UISelectChoice.make(row, uiTag + "-multiple-box", assSelectID, assLabels.size()-1);
UISelectLabel lb = UISelectLabel.make(row, uiTag + "-multiple-label", assSelectID, assLabels.size()-1);
UILabelTargetDecorator.targetLabel(lb, choice);
}
assSelect.optionlist = UIOutputMany.make(assValues.toArray(new String[] {}));
assSelect.optionnames = UIOutputMany.make(assLabels.toArray(new String[] {}));
} else if (EvalAssignGroup.SELECTION_OPTION_ONE.equals(selectValue)) {
List<String> value = new ArrayList<String>();
List<String> label = new ArrayList<String>();
value.add("default");
label.add(messageLocator.getMessage("takeeval.selection.dropdown"));
List<EvalUser> users = commonLogic.getEvalUsersByIds(selectUserIds.toArray(new String[selectUserIds.size()]));
for (EvalUser user : users) {
value.add(user.userId);
label.add(user.displayName);
}
UIBranchContainer showSwitchGroup = UIBranchContainer.make(
form, uiTag + "-one:");
UIOutput.make(showSwitchGroup, uiTag + "-one-header");
UISelect.make(showSwitchGroup, uiTag + "-one-list", value
.toArray(new String[value.size()]), label
.toArray(new String[label.size()]), selectionOTP);
} else {
throw new IllegalStateException("Invalid selection option ("
+ selectValue + "): do not know how to handle this.");
}
} else if (selectUserIds.size() == 1 && associatedTypes.contains(selectKey) ) {
// handle case where there are selections set but ONLY 1 user in the role.
for (String userId : selectUserIds) {
form.parameters.add(new UIELBinding(selectionOTP, userId));
}
}else{
// handle case where there are selections set but no users in the roles.
form.parameters.add(new UIELBinding(selectionOTP, "none"));
}
}
}
// loop through the TIGs and handle each associated category
Boolean useCourseCategoryOnly = (Boolean) evalSettings.get(EvalSettings.ITEM_USE_COURSE_CATEGORY_ONLY);
for (TemplateItemGroup tig : tidl.getTemplateItemGroups()) {
UIBranchContainer categorySectionBranch = UIBranchContainer.make(form, "categorySection:");
// only do headers if we are allowed to use categories
if (! useCourseCategoryOnly) {
// handle printing the category header
if (EvalConstants.ITEM_CATEGORY_COURSE.equals(tig.associateType) ) {
UIMessage.make(categorySectionBranch, "categoryHeader", "takeeval.group.questions.header");
} else if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(tig.associateType)) {
showHeaders(categorySectionBranch, tig.associateType, tig.associateId, instructorIds, instructorSelectionOption,savedSelections);
} else if (EvalConstants.ITEM_CATEGORY_ASSISTANT.equals(tig.associateType)) {
showHeaders(categorySectionBranch, tig.associateType, tig.associateId, assistantIds, assistantSelectionOption,savedSelections);
}
}
// loop through the hierarchy node groups
for (HierarchyNodeGroup hng : tig.hierarchyNodeGroups) {
// render a node title
if (hng.node != null) {
// Showing the section title is system configurable via the administrate view
Boolean showHierSectionTitle = (Boolean) evalSettings.get(EvalSettings.DISPLAY_HIERARCHY_HEADERS);
if (showHierSectionTitle) {
UIBranchContainer nodeTitleBranch = UIBranchContainer.make(categorySectionBranch, "itemrow:nodeSection");
UIOutput.make(nodeTitleBranch, "nodeTitle", hng.node.title);
}
}
List<DataTemplateItem> dtis = hng.getDataTemplateItems(false);
for (int i = 0; i < dtis.size(); i++) {
DataTemplateItem dti = dtis.get(i);
UIBranchContainer nodeItemsBranch = UIBranchContainer.make(categorySectionBranch, "itemrow:templateItem");
if (i % 2 == 1) {
nodeItemsBranch.decorate( new UIStyleDecorator("itemsListOddLine") ); // must match the existing CSS class
}
renderItemPrep(nodeItemsBranch, form, dti, eval, missingKeys);
}
}
}
UICommand.make(form, "submitEvaluation", UIMessage.make("takeeval.submit.button"), "#{takeEvalBean.submitEvaluation}");
} else {
// user cannot access eval so give them a sad message
EvalUser current = commonLogic.getEvalUserById(currentUserId);
UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.user.cannot.take",
new String[] {current.displayName, current.email, current.username});
log.info("User ("+currentUserId+") cannot take evaluation: " + eval.getId());
}
}
}
/**
* Render each group header
* @param categorySectionBranch the parent container
* @param associateType Assistant or Instructor value
* @param associateId userIds for Assistants
* @param instructorIds userIds for Instructors
* @param selectionOption Selection setting for this user
* @param savedSelections
*/
private void showHeaders(UIBranchContainer categorySectionBranch, String associateType, String associateId,
Set<String> instructorIds, String selectionOption, Map<String, String[]> savedSelections) {
EvalUser user = commonLogic.getEvalUserById(associateId);
UIMessage header = UIMessage.make(categorySectionBranch,
"categoryHeader", "takeeval." + associateType.toLowerCase()
+ ".questions.header",
new Object[] { user.displayName });
// EVALSYS-618: support for JS: add display name to title attribute of
// legend and hide category items
header.decorators = new DecoratorList(new UIFreeAttributeDecorator(
"title", user.displayName));
categorySectionBranch.decorators = new DecoratorList(
new UIFreeAttributeDecorator(new String[] { "name", "class" },
new String[] { user.userId, associateType.toLowerCase() + "Branch" }));
if (!EvalAssignGroup.SELECTION_OPTION_ALL.equals(selectionOption)
&& instructorIds.size() > 1) {
Map<String, String> cssHide = new HashMap<String, String>();
cssHide.put("display", "none");
categorySectionBranch.decorators.add(new UICSSDecorator(cssHide));
}
}
/**
* Prepare to render an item, this handles blocks correctly
*
* @param parent the parent container
* @param form the form this item will associate with
* @param dti the wrapped template item we will render
* @param eval the eval, needed for calculating rendering props
* @param missingKeys the invalid keys, needed for calculating rendering props
*/
private void renderItemPrep(UIBranchContainer parent, UIForm form, DataTemplateItem dti, EvalEvaluation eval, Set<String> missingKeys) {
int displayIncrement = 0; // stores the increment in the display number
String[] currentAnswerOTP = null; // holds array of bindings for items
EvalTemplateItem templateItem = dti.templateItem;
if (! TemplateItemUtils.isAnswerable(templateItem)) {
// nothing to bind for unanswerable items unless it is a block parent
if ( dti.blockChildItems != null ) {
// Handle the BLOCK PARENT special case - block item being rendered
// get the child items for this block
List<EvalTemplateItem> childList = dti.blockChildItems;
currentAnswerOTP = new String[childList.size()];
// for each child item, construct a binding
for (int j = 0; j < childList.size(); j++) {
EvalTemplateItem currChildItem = childList.get(j);
// set up OTP paths
String[] childAnswerOTP = setupCurrentAnswerBindings(form, currChildItem, dti.associateId);
if (childAnswerOTP != null) {
currentAnswerOTP[j] = childAnswerOTP[0];
}
renderedItemCount++;
}
displayIncrement = currentAnswerOTP.length;
}
} else {
// non-block and answerable items
currentAnswerOTP = setupCurrentAnswerBindings(form, templateItem, dti.associateId);
displayIncrement++;
}
// setup the render properties to send along
Map<String, Object> renderProps = RenderingUtils.makeRenderProps(dti, eval, missingKeys, null);
// render the item
itemRenderer.renderItem(parent, "renderedItem:", currentAnswerOTP, templateItem, displayNumber, false, renderProps);
/* increment the item counters, if we displayed 1 item, increment by 1,
* if we displayed a block, renderedItem has been incremented for each child, increment displayNumber by the number of blockChildren,
* here we are simply adding the display increment to the overall number -AZ
*/
displayNumber += displayIncrement;
renderedItemCount++;
}
/**
* Generates the correct OTP path for the current answer associated with this templateItem,
* also handles the binding of the item to answer and the associatedId
* @param form the form to bind this data into
* @param templateItem the template item which the answer should associate with
* @param associatedId the associated ID to bind this TI with
* @return an array of binding strings from the TI to the answer (first) and NA (second) which will bind to the input elements
*/
private String[] setupCurrentAnswerBindings(UIForm form, EvalTemplateItem templateItem, String associatedId) {
// the associated type is set only if the associatedId is set
String associatedType = null;
if (associatedId != null) {
associatedType = templateItem.getCategory(); // type will match the template item category
}
// set up OTP paths for answerable items
String responseAnswersOTP = "responseAnswersBeanLocator.";
String currAnswerOTP;
boolean newAnswer = false;
if (responseId == null) {
// it should not be the case that we have no response
//throw new IllegalStateException("There is no response, something has failed to load correctly for takeeval");
// EVALSYS-360 - have to use this again and add a binding for start time
form.parameters.add( new UIELBinding("takeEvalBean.startDate", new Date()) );
currAnswerOTP = responseAnswersOTP + ResponseAnswersBeanLocator.NEW_1 + "." + ResponseAnswersBeanLocator.NEW_PREFIX + renderedItemCount + ".";
newAnswer = true;
} else {
// if the user has answered this question before, point at their response
String key = TemplateItemUtils.makeTemplateItemAnswerKey(templateItem.getId(), associatedType, associatedId);
EvalAnswer currAnswer = answerMap.get(key);
if (currAnswer == null) {
// this is a new answer
newAnswer = true;
currAnswerOTP = responseAnswersOTP + responseId + "." + ResponseAnswersBeanLocator.NEW_PREFIX + (renderedItemCount) + ".";
} else {
// existing answer
newAnswer = false;
currAnswerOTP = responseAnswersOTP + responseId + "." + currAnswer.getId() + ".";
}
}
if (newAnswer) {
// ADD in the bindings for the new answers
// bind the template item to the answer
form.parameters.add( new UIELBinding(currAnswerOTP + "templateItem",
new ELReference("templateItemWBL." + templateItem.getId())) );
// bind the item to the answer
form.parameters.add( new UIELBinding(currAnswerOTP + "item",
new ELReference("itemWBL." + templateItem.getItem().getId())) );
// bind the associated id (current instructor id or environment) and type to the current answer
if (associatedId != null) {
// only do the binding if this is not null, otherwise it will bind in empty strings
form.parameters.add( new UIELBinding(currAnswerOTP + "associatedId", associatedId) );
form.parameters.add( new UIELBinding(currAnswerOTP + "associatedType", associatedType) );
}
}
// generate binding for the UI input element (UIInput, UISelect, etc.) to the correct part of answer
String[] bindings = new String[3];
// set the primary binding depending on the item type
String itemType = TemplateItemUtils.getTemplateItemType(templateItem);
if ( EvalConstants.ITEM_TYPE_MULTIPLEANSWER.equals(itemType) ) {
bindings[0] = currAnswerOTP + "multipleAnswers";
} else if ( EvalConstants.ITEM_TYPE_TEXT.equals(itemType) ) {
bindings[0] = currAnswerOTP + "text";
} else {
// this is the default binding (scaled and MC)
bindings[0] = currAnswerOTP + "numeric";
}
// set the NA and comment bindings
bindings[1] = currAnswerOTP + "NA";
bindings[2] = currAnswerOTP + "comment";
return bindings;
}
/* (non-Javadoc)
* @see uk.org.ponder.rsf.viewstate.ViewParamsReporter#getViewParameters()
*/
public ViewParameters getViewParameters() {
return new EvalViewParameters();
}
/* (non-Javadoc)
* @see uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter#reportNavigationCases()
*/
public List<NavigationCase> reportNavigationCases() {
List<NavigationCase> i = new ArrayList<NavigationCase>();
i.add(new NavigationCase("success", new SimpleViewParameters(SummaryProducer.VIEW_ID)));
return i;
}
/* (non-Javadoc)
* @see uk.org.ponder.rsf.flow.ActionResultInterceptor#interceptActionResult(uk.org.ponder.rsf.flow.ARIResult, uk.org.ponder.rsf.viewstate.ViewParameters, java.lang.Object)
*/
public void interceptActionResult(ARIResult result, ViewParameters incoming, Object actionReturn) {
EvalViewParameters etvp = (EvalViewParameters) incoming;
if (etvp.evalCategory != null) {
result.resultingView = new EvalCategoryViewParameters(ShowEvalCategoryProducer.VIEW_ID, etvp.evalCategory);
}
}
}
| true | true | public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
// force the headers to expire this - http://jira.sakaiproject.org/jira/browse/EVALSYS-621
RenderingUtils.setNoCacheHeaders(httpServletResponse);
boolean canAccess = false; // can a user access this evaluation
boolean userCanAccess = false; // can THIS user take this evaluation
String currentUserId = commonLogic.getCurrentUserId();
// use a date which is related to the current users locale
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
UIMessage.make(tofill, "page-title", "takeeval.page.title");
UIInternalLink.make(tofill, "summary-link", UIMessage.make("summary.page.title"),
new SimpleViewParameters(SummaryProducer.VIEW_ID));
// get passed in get params
EvalViewParameters evalTakeViewParams = (EvalViewParameters) viewparams;
Long evaluationId = evalTakeViewParams.evaluationId;
if (evaluationId == null) {
// redirect over to the main view maybe?? (not sure how to do this in RSF)
log.error("User ("+currentUserId+") cannot take evaluation, eval id is not set");
throw new IllegalArgumentException("Invalid evaluationId: id must be set and cannot be null, cannot load evaluation");
}
String evalGroupId = evalTakeViewParams.evalGroupId;
responseId = evalTakeViewParams.responseId;
// get the evaluation based on the passed in VPs
EvalEvaluation eval = evaluationService.getEvaluationById(evaluationId);
if (eval == null) {
throw new IllegalArgumentException("Invalid evaluationId ("+evaluationId+"), cannot load evaluation");
}
UIMessage.make(tofill, "eval-title-header", "takeeval.eval.title.header");
UIOutput.make(tofill, "evalTitle", eval.getTitle());
/* check the states of the evaluation first to give the user a tip that this eval is not takeable,
* also avoids wasting time checking permissions when the evaluation certainly is closed,
* also allows us to give the user a nice custom message
*/
String evalState = evaluationService.returnAndFixEvalState(eval, true); // make sure state is up to date
if (EvalUtils.checkStateBefore(evalState, EvalConstants.EVALUATION_STATE_ACTIVE, false)) {
String dueDate = "--------";
if (eval.getDueDate() != null) {
dueDate = df.format(eval.getDueDate());
}
UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.not.open",
new String[] {df.format(eval.getStartDate()), dueDate} );
log.info("User ("+currentUserId+") cannot take evaluation yet, not open until: " + eval.getStartDate());
} else if (EvalUtils.checkStateAfter(evalState, EvalConstants.EVALUATION_STATE_CLOSED, true)) {
UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.closed",
new String[] {df.format(eval.getDueDate())} );
log.info("User ("+currentUserId+") cannot take evaluation anymore, closed on: " + eval.getDueDate());
} else {
// eval state is possible to take eval
canAccess = true;
}
List<EvalGroup> validGroups = new ArrayList<EvalGroup>(); // stores EvalGroup objects
if (canAccess) {
// eval is accessible so check user can take it
if (evalGroupId != null) {
// there was an eval group passed in so make sure things are ok
if (evaluationService.canTakeEvaluation(currentUserId, evaluationId, evalGroupId)) {
userCanAccess = true;
}
} else {
// select the first eval group the current user can take evaluation in,
// also store the total number so we can give the user a list to choose from if there are more than one
Map<Long, List<EvalAssignGroup>> m = evaluationService.getAssignGroupsForEvals(new Long[] {evaluationId}, true, null);
if ( commonLogic.isUserAdmin(currentUserId) ) {
// special case, the super admin can always access
userCanAccess = true;
List<EvalAssignGroup> assignGroups = m.get(evaluationId);
for (int i = 0; i < assignGroups.size(); i++) {
EvalAssignGroup assignGroup = assignGroups.get(i);
if (evalGroupId == null) {
// set the evalGroupId to the first valid group if unset
evalGroupId = assignGroup.getEvalGroupId();
}
validGroups.add( commonLogic.makeEvalGroupObject( assignGroup.getEvalGroupId() ));
}
} else {
EvalGroup[] evalGroups;
if ( EvalConstants.EVALUATION_AUTHCONTROL_NONE.equals(eval.getAuthControl()) ) {
// anonymous eval allows any group to be evaluated
List<EvalAssignGroup> assignGroups = m.get(evaluationId);
evalGroups = new EvalGroup[assignGroups.size()];
for (int i = 0; i < assignGroups.size(); i++) {
EvalAssignGroup assignGroup = assignGroups.get(i);
evalGroups[i] = commonLogic.makeEvalGroupObject( assignGroup.getEvalGroupId() );
}
} else {
List<EvalAssignUser> userAssignments = evaluationService.getParticipantsForEval(evaluationId, currentUserId, null,
EvalAssignUser.TYPE_EVALUATOR, null, null, null);
Set<String> evalGroupIds = EvalUtils.getGroupIdsFromUserAssignments(userAssignments);
List<EvalGroup> groups = EvalUtils.makeGroupsFromGroupsIds(evalGroupIds, commonLogic);
evalGroups = EvalUtils.getGroupsInCommon(groups, m.get(evaluationId) );
}
for (int i = 0; i < evalGroups.length; i++) {
EvalGroup group = evalGroups[i];
if (evaluationService.canTakeEvaluation(currentUserId, evaluationId, group.evalGroupId)) {
if (evalGroupId == null) {
// set the evalGroupId to the first valid group if unset
evalGroupId = group.evalGroupId;
userCanAccess = true;
}
validGroups.add( commonLogic.makeEvalGroupObject(group.evalGroupId) );
}
}
}
}
if (userCanAccess) {
// check if we had a failure during a previous submit and get the missingKeys out if there are some
Set<String> missingKeys = new HashSet<String>();
if (messages.isError() && messages.size() > 0) {
for (int i = 0; i < messages.size(); i++) {
TargettedMessage message = messages.messageAt(i);
Exception e = message.exception;
if (e instanceof ResponseSaveException) {
ResponseSaveException rse = (ResponseSaveException) e;
if (rse.missingItemAnswerKeys != null
&& rse.missingItemAnswerKeys.length > 0) {
for (int j = 0; j < rse.missingItemAnswerKeys.length; j++) {
missingKeys.add(rse.missingItemAnswerKeys[j]);
}
}
break;
}
}
}
// load up the response if this user has one already
if (responseId == null) {
response = evaluationService.getResponseForUserAndGroup(
evaluationId, currentUserId, evalGroupId);
if (response == null) {
// create the initial response if there is not one
// EVALSYS-360 because of a hibernate issue this will not work, do a binding instead -AZ
//responseId = localResponsesLogic.createResponse(evaluationId, currentUserId, evalGroupId);
} else {
responseId = response.getId();
}
}
if (responseId != null) {
// load up the previous responses for this user (no need to attempt to load if the response is new, there will be no answers yet)
answerMap = localResponsesLogic.getAnswersMapByTempItemAndAssociated(responseId);
}
// show the switch group selection and form if there are other valid groups for this user
if (validGroups.size() > 1) {
String[] values = new String[validGroups.size()];
String[] labels = new String[validGroups.size()];
for (int i=0; i<validGroups.size(); i++) {
EvalGroup group = validGroups.get(i);
values[i] = group.evalGroupId;
labels[i] = group.title;
}
// show the switch group selection and form
UIBranchContainer showSwitchGroup = UIBranchContainer.make(tofill, "show-switch-group:");
UIMessage.make(showSwitchGroup, "switch-group-header", "takeeval.switch.group.header");
UIForm chooseGroupForm = UIForm.make(showSwitchGroup, "switch-group-form",
new EvalViewParameters(TakeEvalProducer.VIEW_ID, evaluationId, responseId, evalGroupId));
UISelect.make(chooseGroupForm, "switch-group-list", values, labels, "#{evalGroupId}");
UIMessage.make(chooseGroupForm, "switch-group-button", "takeeval.switch.group.button");
}
// fill in group title
EvalGroup evalGroup = commonLogic.makeEvalGroupObject( evalGroupId );
UIBranchContainer groupTitle = UIBranchContainer.make(tofill, "show-group-title:");
UIMessage.make(groupTitle, "group-title-header", "takeeval.group.title.header");
UIOutput.make(groupTitle, "group-title", evalGroup.title );
// show instructions if not null
if (eval.getInstructions() != null && !("".equals(eval.getInstructions())) ) {
UIBranchContainer instructions = UIBranchContainer.make(tofill, "show-eval-instructions:");
UIMessage.make(instructions, "eval-instructions-header", "takeeval.instructions.header");
UIVerbatim.make(instructions, "eval-instructions", eval.getInstructions());
}
// get the setting and make sure it cannot be null (fix for http://www.caret.cam.ac.uk/jira/browse/CTL-531)
Boolean studentAllowedLeaveUnanswered = (Boolean) evalSettings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
if (studentAllowedLeaveUnanswered == null) {
studentAllowedLeaveUnanswered = EvalUtils.safeBool(eval.getBlankResponsesAllowed(), false);
}
// show a warning to the user if all items must be filled in
if ( studentAllowedLeaveUnanswered == false ) {
UIBranchContainer note = UIBranchContainer.make(tofill, "show-eval-note:");
UIMessage.make(note, "eval-note-text", "takeeval.user.must.answer.all.note");
}
UIBranchContainer formBranch = UIBranchContainer.make(tofill, "form-branch:");
UIForm form = UIForm.make(formBranch, "evaluationForm");
// bind the evaluation and evalGroup to the ones in the take eval bean
String evalOTP = "evaluationBeanLocator.";
form.parameters.add( new UIELBinding("#{takeEvalBean.eval}", new ELReference(evalOTP + eval.getId())) );
form.parameters.add( new UIELBinding("#{takeEvalBean.evalGroupId}", evalGroupId) );
// BEGIN the complex task of rendering the evaluation items
// make the TI data structure
TemplateItemDataList tidl = new TemplateItemDataList(evaluationId, evalGroupId,
evaluationService, authoringService, hierarchyLogic, null);
Set<String> instructorIds = tidl.getAssociateIds(EvalConstants.ITEM_CATEGORY_INSTRUCTOR);
Set<String> assistantIds = tidl.getAssociateIds(EvalConstants.ITEM_CATEGORY_ASSISTANT);
List<String> associatedTypes = tidl.getAssociateTypes();
// SELECTION Code - EVALSYS-618
Boolean selectionsEnabled = (Boolean) evalSettings
.get(EvalSettings.ENABLE_INSTRUCTOR_ASSISTANT_SELECTION);
String instructorSelectionOption = EvalAssignGroup.SELECTION_OPTION_ALL;
String assistantSelectionOption = EvalAssignGroup.SELECTION_OPTION_ALL;
Map<String, String[]> savedSelections = new HashMap<String, String[]>();
if(response!=null){
savedSelections = response.getSelections();
}
if (selectionsEnabled) {
// only do the selection calculations if it is enabled
EvalAssignGroup assignGroup = evaluationService.getAssignGroupByEvalAndGroupId(
evaluationId, evalGroupId);
Map<String, String> selectorType = new HashMap<String, String>();
instructorSelectionOption = EvalUtils.getSelectionSetting(
EvalAssignGroup.SELECTION_TYPE_INSTRUCTOR, assignGroup, null);
selectorType.put(SELECT_KEY_INSTRUCTOR, instructorSelectionOption);
Boolean assistantsEnabled = (Boolean) evalSettings
.get(EvalSettings.ENABLE_ASSISTANT_CATEGORY);
if (assistantsEnabled) {
assistantSelectionOption = EvalUtils.getSelectionSetting(
EvalAssignGroup.SELECTION_TYPE_ASSISTANT, assignGroup, null);
selectorType.put(SELECT_KEY_ASSISTANT, assistantSelectionOption);
}
if (response != null) {
// emit currently selected people into hidden element
// for JS use
Set<String> savedIds = new HashSet<String>();
for (Iterator<String> selector = savedSelections
.keySet().iterator(); selector.hasNext();) {
String selectKey = (String) selector.next();
String[] usersFound = savedSelections
.get(selectKey);
savedIds.add(usersFound[0]);
}
UIOutput savedSel = UIOutput
.make(formBranch, "selectedPeopleInResponse",
savedIds.toString());
savedSel.decorators = new DecoratorList(
new UIIDStrategyDecorator(
"selectedPeopleInResponse"));
}
for (Iterator<String> selector = selectorType.keySet().iterator(); selector.hasNext();) {
// FIXME findbugs says that getting keys like this is inefficient, use Map.Entry
String selectKey = (String) selector.next();
String selectValue = (String) selectorType.get(selectKey);
String uiTag = "select-" + selectKey;
String selectionOTP = "#{takeEvalBean.selection" + selectKey + "Ids}";
Set<String> selectUserIds = new HashSet<String>();
if (selectKey.equals(SELECT_KEY_INSTRUCTOR)) {
selectUserIds = instructorIds;
} else if (selectKey.equals(SELECT_KEY_ASSISTANT)) {
selectUserIds = assistantIds;
}
// We render the selection controls if there are at least two
// Instructors/TAs
if (selectUserIds.size() > 1 && associatedTypes.contains(selectKey) ) {
if (selectValue.equals(EvalAssignGroup.SELECTION_OPTION_ALL)) {
// nothing special to do in all case
//form.parameters.add(new UIELBinding(selectionOTP, "all"));
} else if (EvalAssignGroup.SELECTION_OPTION_MULTIPLE.equals(selectValue)) {
UIBranchContainer showSwitchGroup = UIBranchContainer.make(
form, uiTag + "-multiple:");
// Things for building the UISelect of Assignment Checkboxes
List<String> assLabels = new ArrayList<String>();
List<String> assValues = new ArrayList<String>();
UISelect assSelect = UISelect.makeMultiple(showSwitchGroup, uiTag + "-multiple-holder", new String[] {}, new String[] {}, selectionOTP, new String[] {});
String assSelectID = assSelect.getFullID();
for (String userId : selectUserIds) {
EvalUser user = commonLogic.getEvalUserById(userId);
assValues.add(user.userId);
assLabels.add(user.displayName);
UIBranchContainer row = UIBranchContainer.make(showSwitchGroup, uiTag + "-multiple-row:");
UISelectChoice choice = UISelectChoice.make(row, uiTag + "-multiple-box", assSelectID, assLabels.size()-1);
UISelectLabel lb = UISelectLabel.make(row, uiTag + "-multiple-label", assSelectID, assLabels.size()-1);
UILabelTargetDecorator.targetLabel(lb, choice);
}
assSelect.optionlist = UIOutputMany.make(assValues.toArray(new String[] {}));
assSelect.optionnames = UIOutputMany.make(assLabels.toArray(new String[] {}));
} else if (EvalAssignGroup.SELECTION_OPTION_ONE.equals(selectValue)) {
List<String> value = new ArrayList<String>();
List<String> label = new ArrayList<String>();
value.add("default");
label.add(messageLocator.getMessage("takeeval.selection.dropdown"));
List<EvalUser> users = commonLogic.getEvalUsersByIds(selectUserIds.toArray(new String[selectUserIds.size()]));
for (EvalUser user : users) {
value.add(user.userId);
label.add(user.displayName);
}
UIBranchContainer showSwitchGroup = UIBranchContainer.make(
form, uiTag + "-one:");
UIOutput.make(showSwitchGroup, uiTag + "-one-header");
UISelect.make(showSwitchGroup, uiTag + "-one-list", value
.toArray(new String[value.size()]), label
.toArray(new String[label.size()]), selectionOTP);
} else {
throw new IllegalStateException("Invalid selection option ("
+ selectValue + "): do not know how to handle this.");
}
} else if (selectUserIds.size() == 1 && associatedTypes.contains(selectKey) ) {
// handle case where there are selections set but ONLY 1 user in the role.
for (String userId : selectUserIds) {
form.parameters.add(new UIELBinding(selectionOTP, userId));
}
}else{
// handle case where there are selections set but no users in the roles.
form.parameters.add(new UIELBinding(selectionOTP, "none"));
}
}
}
// loop through the TIGs and handle each associated category
Boolean useCourseCategoryOnly = (Boolean) evalSettings.get(EvalSettings.ITEM_USE_COURSE_CATEGORY_ONLY);
for (TemplateItemGroup tig : tidl.getTemplateItemGroups()) {
UIBranchContainer categorySectionBranch = UIBranchContainer.make(form, "categorySection:");
// only do headers if we are allowed to use categories
if (! useCourseCategoryOnly) {
// handle printing the category header
if (EvalConstants.ITEM_CATEGORY_COURSE.equals(tig.associateType) ) {
UIMessage.make(categorySectionBranch, "categoryHeader", "takeeval.group.questions.header");
} else if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(tig.associateType)) {
showHeaders(categorySectionBranch, tig.associateType, tig.associateId, instructorIds, instructorSelectionOption,savedSelections);
} else if (EvalConstants.ITEM_CATEGORY_ASSISTANT.equals(tig.associateType)) {
showHeaders(categorySectionBranch, tig.associateType, tig.associateId, assistantIds, assistantSelectionOption,savedSelections);
}
}
// loop through the hierarchy node groups
for (HierarchyNodeGroup hng : tig.hierarchyNodeGroups) {
// render a node title
if (hng.node != null) {
// Showing the section title is system configurable via the administrate view
Boolean showHierSectionTitle = (Boolean) evalSettings.get(EvalSettings.DISPLAY_HIERARCHY_HEADERS);
if (showHierSectionTitle) {
UIBranchContainer nodeTitleBranch = UIBranchContainer.make(categorySectionBranch, "itemrow:nodeSection");
UIOutput.make(nodeTitleBranch, "nodeTitle", hng.node.title);
}
}
List<DataTemplateItem> dtis = hng.getDataTemplateItems(false);
for (int i = 0; i < dtis.size(); i++) {
DataTemplateItem dti = dtis.get(i);
UIBranchContainer nodeItemsBranch = UIBranchContainer.make(categorySectionBranch, "itemrow:templateItem");
if (i % 2 == 1) {
nodeItemsBranch.decorate( new UIStyleDecorator("itemsListOddLine") ); // must match the existing CSS class
}
renderItemPrep(nodeItemsBranch, form, dti, eval, missingKeys);
}
}
}
UICommand.make(form, "submitEvaluation", UIMessage.make("takeeval.submit.button"), "#{takeEvalBean.submitEvaluation}");
} else {
// user cannot access eval so give them a sad message
EvalUser current = commonLogic.getEvalUserById(currentUserId);
UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.user.cannot.take",
new String[] {current.displayName, current.email, current.username});
log.info("User ("+currentUserId+") cannot take evaluation: " + eval.getId());
}
}
}
| public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
// force the headers to expire this - http://jira.sakaiproject.org/jira/browse/EVALSYS-621
RenderingUtils.setNoCacheHeaders(httpServletResponse);
boolean canAccess = false; // can a user access this evaluation
boolean userCanAccess = false; // can THIS user take this evaluation
String currentUserId = commonLogic.getCurrentUserId();
// use a date which is related to the current users locale
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
UIMessage.make(tofill, "page-title", "takeeval.page.title");
UIInternalLink.make(tofill, "summary-link", UIMessage.make("summary.page.title"),
new SimpleViewParameters(SummaryProducer.VIEW_ID));
// get passed in get params
EvalViewParameters evalTakeViewParams = (EvalViewParameters) viewparams;
Long evaluationId = evalTakeViewParams.evaluationId;
if (evaluationId == null) {
// redirect over to the main view maybe?? (not sure how to do this in RSF)
log.error("User ("+currentUserId+") cannot take evaluation, eval id is not set");
throw new IllegalArgumentException("Invalid evaluationId: id must be set and cannot be null, cannot load evaluation");
}
String evalGroupId = evalTakeViewParams.evalGroupId;
responseId = evalTakeViewParams.responseId;
// get the evaluation based on the passed in VPs
EvalEvaluation eval = evaluationService.getEvaluationById(evaluationId);
if (eval == null) {
throw new IllegalArgumentException("Invalid evaluationId ("+evaluationId+"), cannot load evaluation");
}
UIMessage.make(tofill, "eval-title-header", "takeeval.eval.title.header");
UIOutput.make(tofill, "evalTitle", eval.getTitle());
/* check the states of the evaluation first to give the user a tip that this eval is not takeable,
* also avoids wasting time checking permissions when the evaluation certainly is closed,
* also allows us to give the user a nice custom message
*/
String evalState = evaluationService.returnAndFixEvalState(eval, true); // make sure state is up to date
if (EvalUtils.checkStateBefore(evalState, EvalConstants.EVALUATION_STATE_ACTIVE, false)) {
String dueDate = "--------";
if (eval.getDueDate() != null) {
dueDate = df.format(eval.getDueDate());
}
UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.not.open",
new String[] {df.format(eval.getStartDate()), dueDate} );
log.info("User ("+currentUserId+") cannot take evaluation yet, not open until: " + eval.getStartDate());
} else if (EvalUtils.checkStateAfter(evalState, EvalConstants.EVALUATION_STATE_CLOSED, true)) {
UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.closed",
new String[] {df.format(eval.getDueDate())} );
log.info("User ("+currentUserId+") cannot take evaluation anymore, closed on: " + eval.getDueDate());
} else {
// eval state is possible to take eval
canAccess = true;
}
List<EvalGroup> validGroups = new ArrayList<EvalGroup>(); // stores EvalGroup objects
if (canAccess) {
// eval is accessible so check user can take it
if (evalGroupId != null) {
// there was an eval group passed in so make sure things are ok
if (evaluationService.canTakeEvaluation(currentUserId, evaluationId, evalGroupId)) {
userCanAccess = true;
}
} else {
// select the first eval group the current user can take evaluation in,
// also store the total number so we can give the user a list to choose from if there are more than one
Map<Long, List<EvalAssignGroup>> m = evaluationService.getAssignGroupsForEvals(new Long[] {evaluationId}, true, null);
if ( commonLogic.isUserAdmin(currentUserId) ) {
// special case, the super admin can always access
userCanAccess = true;
List<EvalAssignGroup> assignGroups = m.get(evaluationId);
for (int i = 0; i < assignGroups.size(); i++) {
EvalAssignGroup assignGroup = assignGroups.get(i);
if (evalGroupId == null) {
// set the evalGroupId to the first valid group if unset
evalGroupId = assignGroup.getEvalGroupId();
}
validGroups.add( commonLogic.makeEvalGroupObject( assignGroup.getEvalGroupId() ));
}
} else {
EvalGroup[] evalGroups;
if ( EvalConstants.EVALUATION_AUTHCONTROL_NONE.equals(eval.getAuthControl()) ) {
// anonymous eval allows any group to be evaluated
List<EvalAssignGroup> assignGroups = m.get(evaluationId);
evalGroups = new EvalGroup[assignGroups.size()];
for (int i = 0; i < assignGroups.size(); i++) {
EvalAssignGroup assignGroup = assignGroups.get(i);
evalGroups[i] = commonLogic.makeEvalGroupObject( assignGroup.getEvalGroupId() );
}
} else {
List<EvalAssignUser> userAssignments = evaluationService.getParticipantsForEval(evaluationId, currentUserId, null,
EvalAssignUser.TYPE_EVALUATOR, null, null, null);
Set<String> evalGroupIds = EvalUtils.getGroupIdsFromUserAssignments(userAssignments);
List<EvalGroup> groups = EvalUtils.makeGroupsFromGroupsIds(evalGroupIds, commonLogic);
evalGroups = EvalUtils.getGroupsInCommon(groups, m.get(evaluationId) );
}
for (int i = 0; i < evalGroups.length; i++) {
EvalGroup group = evalGroups[i];
if (evaluationService.canTakeEvaluation(currentUserId, evaluationId, group.evalGroupId)) {
if (evalGroupId == null) {
// set the evalGroupId to the first valid group if unset
evalGroupId = group.evalGroupId;
userCanAccess = true;
}
validGroups.add( commonLogic.makeEvalGroupObject(group.evalGroupId) );
}
}
}
}
if (userCanAccess) {
// check if we had a failure during a previous submit and get the missingKeys out if there are some
Set<String> missingKeys = new HashSet<String>();
if (messages.isError() && messages.size() > 0) {
for (int i = 0; i < messages.size(); i++) {
TargettedMessage message = messages.messageAt(i);
Exception e = message.exception;
if (e instanceof ResponseSaveException) {
ResponseSaveException rse = (ResponseSaveException) e;
if (rse.missingItemAnswerKeys != null
&& rse.missingItemAnswerKeys.length > 0) {
for (int j = 0; j < rse.missingItemAnswerKeys.length; j++) {
missingKeys.add(rse.missingItemAnswerKeys[j]);
}
}
break;
}
}
}
// load up the response if this user has one already
if (responseId == null) {
response = evaluationService.getResponseForUserAndGroup(
evaluationId, currentUserId, evalGroupId);
if (response == null) {
// create the initial response if there is not one
// EVALSYS-360 because of a hibernate issue this will not work, do a binding instead -AZ
//responseId = localResponsesLogic.createResponse(evaluationId, currentUserId, evalGroupId);
} else {
responseId = response.getId();
}
}
if (responseId != null) {
// load up the previous responses for this user (no need to attempt to load if the response is new, there will be no answers yet)
answerMap = localResponsesLogic.getAnswersMapByTempItemAndAssociated(responseId);
}
// show the switch group selection and form if there are other valid groups for this user
if (validGroups.size() > 1) {
String[] values = new String[validGroups.size()];
String[] labels = new String[validGroups.size()];
for (int i=0; i<validGroups.size(); i++) {
EvalGroup group = validGroups.get(i);
values[i] = group.evalGroupId;
labels[i] = group.title;
}
// show the switch group selection and form
UIBranchContainer showSwitchGroup = UIBranchContainer.make(tofill, "show-switch-group:");
UIMessage.make(showSwitchGroup, "switch-group-header", "takeeval.switch.group.header");
UIForm chooseGroupForm = UIForm.make(showSwitchGroup, "switch-group-form",
new EvalViewParameters(TakeEvalProducer.VIEW_ID, evaluationId, responseId, evalGroupId));
UISelect.make(chooseGroupForm, "switch-group-list", values, labels, "#{evalGroupId}");
UIMessage.make(chooseGroupForm, "switch-group-button", "takeeval.switch.group.button");
}
// fill in group title
EvalGroup evalGroup = commonLogic.makeEvalGroupObject( evalGroupId );
UIBranchContainer groupTitle = UIBranchContainer.make(tofill, "show-group-title:");
UIMessage.make(groupTitle, "group-title-header", "takeeval.group.title.header");
UIOutput.make(groupTitle, "group-title", evalGroup.title );
// show instructions if not null
if (eval.getInstructions() != null && !("".equals(eval.getInstructions())) ) {
UIBranchContainer instructions = UIBranchContainer.make(tofill, "show-eval-instructions:");
UIMessage.make(instructions, "eval-instructions-header", "takeeval.instructions.header");
UIVerbatim.make(instructions, "eval-instructions", eval.getInstructions());
}
// get the setting and make sure it cannot be null (fix for http://www.caret.cam.ac.uk/jira/browse/CTL-531)
Boolean studentAllowedLeaveUnanswered = (Boolean) evalSettings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
if (studentAllowedLeaveUnanswered == null) {
studentAllowedLeaveUnanswered = EvalUtils.safeBool(eval.getBlankResponsesAllowed(), false);
}
// show a warning to the user if all items must be filled in
if ( studentAllowedLeaveUnanswered == false ) {
UIBranchContainer note = UIBranchContainer.make(tofill, "show-eval-note:");
UIMessage.make(note, "eval-note-text", "takeeval.user.must.answer.all.note");
}
UIBranchContainer formBranch = UIBranchContainer.make(tofill, "form-branch:");
UIForm form = UIForm.make(formBranch, "evaluationForm");
// bind the evaluation and evalGroup to the ones in the take eval bean
String evalOTP = "evaluationBeanLocator.";
form.parameters.add( new UIELBinding("#{takeEvalBean.eval}", new ELReference(evalOTP + eval.getId())) );
form.parameters.add( new UIELBinding("#{takeEvalBean.evalGroupId}", evalGroupId) );
// BEGIN the complex task of rendering the evaluation items
// make the TI data structure
TemplateItemDataList tidl = new TemplateItemDataList(evaluationId, evalGroupId,
evaluationService, authoringService, hierarchyLogic, null);
Set<String> instructorIds = tidl.getAssociateIds(EvalConstants.ITEM_CATEGORY_INSTRUCTOR);
Set<String> assistantIds = tidl.getAssociateIds(EvalConstants.ITEM_CATEGORY_ASSISTANT);
List<String> associatedTypes = tidl.getAssociateTypes();
// SELECTION Code - EVALSYS-618
Boolean selectionsEnabled = (Boolean) evalSettings
.get(EvalSettings.ENABLE_INSTRUCTOR_ASSISTANT_SELECTION);
String instructorSelectionOption = EvalAssignGroup.SELECTION_OPTION_ALL;
String assistantSelectionOption = EvalAssignGroup.SELECTION_OPTION_ALL;
Map<String, String[]> savedSelections = new HashMap<String, String[]>();
if(response!=null){
savedSelections = response.getSelections();
}
if (selectionsEnabled) {
// only do the selection calculations if it is enabled
EvalAssignGroup assignGroup = evaluationService.getAssignGroupByEvalAndGroupId(
evaluationId, evalGroupId);
Map<String, String> selectorType = new HashMap<String, String>();
instructorSelectionOption = EvalUtils.getSelectionSetting(
EvalAssignGroup.SELECTION_TYPE_INSTRUCTOR, assignGroup, null);
selectorType.put(SELECT_KEY_INSTRUCTOR, instructorSelectionOption);
Boolean assistantsEnabled = (Boolean) evalSettings
.get(EvalSettings.ENABLE_ASSISTANT_CATEGORY);
if (assistantsEnabled) {
assistantSelectionOption = EvalUtils.getSelectionSetting(
EvalAssignGroup.SELECTION_TYPE_ASSISTANT, assignGroup, null);
selectorType.put(SELECT_KEY_ASSISTANT, assistantSelectionOption);
}
if (response != null) {
// emit currently selected people into hidden element
// for JS use
Set<String> savedIds = new HashSet<String>();
for (Iterator<String> selector = savedSelections
.keySet().iterator(); selector.hasNext();) {
String selectKey = (String) selector.next();
String[] usersFound = savedSelections
.get(selectKey);
savedIds.add(usersFound[0]);
}
UIOutput savedSel = UIOutput
.make(formBranch, "selectedPeopleInResponse",
savedIds.toString());
savedSel.decorators = new DecoratorList(
new UIIDStrategyDecorator(
"selectedPeopleInResponse"));
}
Iterator<Map.Entry<String, String>> selector = selectorType.entrySet().iterator();
while (selector.hasNext()) {
Map.Entry<String, String> pairs = selector.next();
String selectKey = (String) pairs.getKey();
String selectValue = (String) pairs.getValue();
String uiTag = "select-" + selectKey;
String selectionOTP = "#{takeEvalBean.selection" + selectKey + "Ids}";
Set<String> selectUserIds = new HashSet<String>();
if (selectKey.equals(SELECT_KEY_INSTRUCTOR)) {
selectUserIds = instructorIds;
} else if (selectKey.equals(SELECT_KEY_ASSISTANT)) {
selectUserIds = assistantIds;
}
// We render the selection controls if there are at least two
// Instructors/TAs
if (selectUserIds.size() > 1 && associatedTypes.contains(selectKey) ) {
if (selectValue.equals(EvalAssignGroup.SELECTION_OPTION_ALL)) {
// nothing special to do in all case
//form.parameters.add(new UIELBinding(selectionOTP, "all"));
} else if (EvalAssignGroup.SELECTION_OPTION_MULTIPLE.equals(selectValue)) {
UIBranchContainer showSwitchGroup = UIBranchContainer.make(
form, uiTag + "-multiple:");
// Things for building the UISelect of Assignment Checkboxes
List<String> assLabels = new ArrayList<String>();
List<String> assValues = new ArrayList<String>();
UISelect assSelect = UISelect.makeMultiple(showSwitchGroup, uiTag + "-multiple-holder", new String[] {}, new String[] {}, selectionOTP, new String[] {});
String assSelectID = assSelect.getFullID();
for (String userId : selectUserIds) {
EvalUser user = commonLogic.getEvalUserById(userId);
assValues.add(user.userId);
assLabels.add(user.displayName);
UIBranchContainer row = UIBranchContainer.make(showSwitchGroup, uiTag + "-multiple-row:");
UISelectChoice choice = UISelectChoice.make(row, uiTag + "-multiple-box", assSelectID, assLabels.size()-1);
UISelectLabel lb = UISelectLabel.make(row, uiTag + "-multiple-label", assSelectID, assLabels.size()-1);
UILabelTargetDecorator.targetLabel(lb, choice);
}
assSelect.optionlist = UIOutputMany.make(assValues.toArray(new String[] {}));
assSelect.optionnames = UIOutputMany.make(assLabels.toArray(new String[] {}));
} else if (EvalAssignGroup.SELECTION_OPTION_ONE.equals(selectValue)) {
List<String> value = new ArrayList<String>();
List<String> label = new ArrayList<String>();
value.add("default");
label.add(messageLocator.getMessage("takeeval.selection.dropdown"));
List<EvalUser> users = commonLogic.getEvalUsersByIds(selectUserIds.toArray(new String[selectUserIds.size()]));
for (EvalUser user : users) {
value.add(user.userId);
label.add(user.displayName);
}
UIBranchContainer showSwitchGroup = UIBranchContainer.make(
form, uiTag + "-one:");
UIOutput.make(showSwitchGroup, uiTag + "-one-header");
UISelect.make(showSwitchGroup, uiTag + "-one-list", value
.toArray(new String[value.size()]), label
.toArray(new String[label.size()]), selectionOTP);
} else {
throw new IllegalStateException("Invalid selection option ("
+ selectValue + "): do not know how to handle this.");
}
} else if (selectUserIds.size() == 1 && associatedTypes.contains(selectKey) ) {
// handle case where there are selections set but ONLY 1 user in the role.
for (String userId : selectUserIds) {
form.parameters.add(new UIELBinding(selectionOTP, userId));
}
}else{
// handle case where there are selections set but no users in the roles.
form.parameters.add(new UIELBinding(selectionOTP, "none"));
}
}
}
// loop through the TIGs and handle each associated category
Boolean useCourseCategoryOnly = (Boolean) evalSettings.get(EvalSettings.ITEM_USE_COURSE_CATEGORY_ONLY);
for (TemplateItemGroup tig : tidl.getTemplateItemGroups()) {
UIBranchContainer categorySectionBranch = UIBranchContainer.make(form, "categorySection:");
// only do headers if we are allowed to use categories
if (! useCourseCategoryOnly) {
// handle printing the category header
if (EvalConstants.ITEM_CATEGORY_COURSE.equals(tig.associateType) ) {
UIMessage.make(categorySectionBranch, "categoryHeader", "takeeval.group.questions.header");
} else if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(tig.associateType)) {
showHeaders(categorySectionBranch, tig.associateType, tig.associateId, instructorIds, instructorSelectionOption,savedSelections);
} else if (EvalConstants.ITEM_CATEGORY_ASSISTANT.equals(tig.associateType)) {
showHeaders(categorySectionBranch, tig.associateType, tig.associateId, assistantIds, assistantSelectionOption,savedSelections);
}
}
// loop through the hierarchy node groups
for (HierarchyNodeGroup hng : tig.hierarchyNodeGroups) {
// render a node title
if (hng.node != null) {
// Showing the section title is system configurable via the administrate view
Boolean showHierSectionTitle = (Boolean) evalSettings.get(EvalSettings.DISPLAY_HIERARCHY_HEADERS);
if (showHierSectionTitle) {
UIBranchContainer nodeTitleBranch = UIBranchContainer.make(categorySectionBranch, "itemrow:nodeSection");
UIOutput.make(nodeTitleBranch, "nodeTitle", hng.node.title);
}
}
List<DataTemplateItem> dtis = hng.getDataTemplateItems(false);
for (int i = 0; i < dtis.size(); i++) {
DataTemplateItem dti = dtis.get(i);
UIBranchContainer nodeItemsBranch = UIBranchContainer.make(categorySectionBranch, "itemrow:templateItem");
if (i % 2 == 1) {
nodeItemsBranch.decorate( new UIStyleDecorator("itemsListOddLine") ); // must match the existing CSS class
}
renderItemPrep(nodeItemsBranch, form, dti, eval, missingKeys);
}
}
}
UICommand.make(form, "submitEvaluation", UIMessage.make("takeeval.submit.button"), "#{takeEvalBean.submitEvaluation}");
} else {
// user cannot access eval so give them a sad message
EvalUser current = commonLogic.getEvalUserById(currentUserId);
UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.user.cannot.take",
new String[] {current.displayName, current.email, current.username});
log.info("User ("+currentUserId+") cannot take evaluation: " + eval.getId());
}
}
}
|
diff --git a/src/net/sourceforge/peers/sip/core/useragent/UserAgent.java b/src/net/sourceforge/peers/sip/core/useragent/UserAgent.java
index 405880d..23ae51f 100644
--- a/src/net/sourceforge/peers/sip/core/useragent/UserAgent.java
+++ b/src/net/sourceforge/peers/sip/core/useragent/UserAgent.java
@@ -1,340 +1,340 @@
/*
This file is part of Peers, a java SIP softphone.
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
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/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.core.useragent;
import java.io.File;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.peers.Config;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.media.CaptureRtpSender;
import net.sourceforge.peers.media.Echo;
import net.sourceforge.peers.media.IncomingRtpReader;
import net.sourceforge.peers.media.MediaMode;
import net.sourceforge.peers.media.SoundManager;
import net.sourceforge.peers.sdp.SDPManager;
import net.sourceforge.peers.sip.Utils;
import net.sourceforge.peers.sip.core.useragent.handlers.ByeHandler;
import net.sourceforge.peers.sip.core.useragent.handlers.CancelHandler;
import net.sourceforge.peers.sip.core.useragent.handlers.InviteHandler;
import net.sourceforge.peers.sip.core.useragent.handlers.OptionsHandler;
import net.sourceforge.peers.sip.core.useragent.handlers.RegisterHandler;
import net.sourceforge.peers.sip.syntaxencoding.SipURI;
import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException;
import net.sourceforge.peers.sip.transaction.Transaction;
import net.sourceforge.peers.sip.transaction.TransactionManager;
import net.sourceforge.peers.sip.transactionuser.DialogManager;
import net.sourceforge.peers.sip.transport.SipMessage;
import net.sourceforge.peers.sip.transport.SipRequest;
import net.sourceforge.peers.sip.transport.SipResponse;
import net.sourceforge.peers.sip.transport.TransportManager;
public class UserAgent {
public final static String CONFIG_FILE = "conf" + File.separator + "peers.xml";
public final static int RTP_DEFAULT_PORT = 8000;
private Config config;
private List<String> peers;
//private List<Dialog> dialogs;
private CaptureRtpSender captureRtpSender;
private IncomingRtpReader incomingRtpReader;
//TODO factorize echo and captureRtpSender
private Echo echo;
private UAC uac;
private UAS uas;
private ChallengeManager challengeManager;
private DialogManager dialogManager;
private TransactionManager transactionManager;
private TransportManager transportManager;
private int cseqCounter;
private SipListener sipListener;
private SDPManager sdpManager;
private SoundManager soundManager;
public UserAgent(SipListener sipListener) {
this.sipListener = sipListener;
config = new Config(Utils.getPeersHome() + CONFIG_FILE);
- cseqCounter = 0;
+ cseqCounter = 1;
StringBuffer buf = new StringBuffer();
buf.append("starting user agent [");
buf.append("myAddress: ");
buf.append(config.getInetAddress().getHostAddress()).append(", ");
buf.append("sipPort: ");
buf.append(config.getSipPort()).append(", ");
buf.append("userpart: ");
buf.append(config.getUserPart()).append(", ");
buf.append("domain: ");
buf.append(config.getDomain()).append("]");
Logger.info(buf.toString());
//transaction user
dialogManager = new DialogManager();
//transaction
transactionManager = new TransactionManager();
//transport
transportManager = new TransportManager(transactionManager,
config.getInetAddress(),
config.getSipPort());
transactionManager.setTransportManager(transportManager);
//core
InviteHandler inviteHandler = new InviteHandler(this,
dialogManager,
transactionManager,
transportManager);
CancelHandler cancelHandler = new CancelHandler(this,
dialogManager,
transactionManager,
transportManager);
ByeHandler byeHandler = new ByeHandler(this,
dialogManager,
transactionManager,
transportManager);
OptionsHandler optionsHandler = new OptionsHandler(this,
transactionManager,
transportManager);
RegisterHandler registerHandler = new RegisterHandler(this,
transactionManager,
transportManager);
InitialRequestManager initialRequestManager =
new InitialRequestManager(
this,
inviteHandler,
cancelHandler,
byeHandler,
optionsHandler,
registerHandler,
dialogManager,
transactionManager,
transportManager);
MidDialogRequestManager midDialogRequestManager =
new MidDialogRequestManager(
this,
inviteHandler,
cancelHandler,
byeHandler,
optionsHandler,
registerHandler,
dialogManager,
transactionManager,
transportManager);
uas = new UAS(this,
initialRequestManager,
midDialogRequestManager,
dialogManager,
transactionManager,
transportManager);
uac = new UAC(this,
initialRequestManager,
midDialogRequestManager,
dialogManager,
transactionManager,
transportManager);
if (config.getPassword() != null) {
challengeManager = new ChallengeManager(config,
initialRequestManager);
registerHandler.setChallengeManager(challengeManager);
inviteHandler.setChallengeManager(challengeManager);
}
peers = new ArrayList<String>();
//dialogs = new ArrayList<Dialog>();
if (config.getPassword() != null) {
try {
uac.register();
} catch (SipUriSyntaxException e) {
Logger.error("syntax error", e);
}
}
sdpManager = new SDPManager(this);
inviteHandler.setSdpManager(sdpManager);
optionsHandler.setSdpManager(sdpManager);
soundManager = new SoundManager(config.isMediaDebug());
}
public void close() {
transportManager.close();
}
/**
* Gives the sipMessage if sipMessage is a SipRequest or
* the SipRequest corresponding to the SipResponse
* if sipMessage is a SipResponse
* @param sipMessage
* @return null if sipMessage is neither a SipRequest neither a SipResponse
*/
public SipRequest getSipRequest(SipMessage sipMessage) {
if (sipMessage instanceof SipRequest) {
return (SipRequest) sipMessage;
} else if (sipMessage instanceof SipResponse) {
SipResponse sipResponse = (SipResponse) sipMessage;
Transaction transaction = (Transaction)transactionManager
.getClientTransaction(sipResponse);
if (transaction == null) {
transaction = (Transaction)transactionManager
.getServerTransaction(sipResponse);
}
if (transaction == null) {
return null;
}
return transaction.getRequest();
} else {
return null;
}
}
// public List<Dialog> getDialogs() {
// return dialogs;
// }
public List<String> getPeers() {
return peers;
}
// public Dialog getDialog(String peer) {
// for (Dialog dialog : dialogs) {
// String remoteUri = dialog.getRemoteUri();
// if (remoteUri != null) {
// if (remoteUri.contains(peer)) {
// return dialog;
// }
// }
// }
// return null;
// }
public String generateCSeq(String method) {
StringBuffer buf = new StringBuffer();
buf.append(cseqCounter++);
buf.append(' ');
buf.append(method);
return buf.toString();
}
public boolean isRegistered() {
return uac.getInitialRequestManager().getRegisterHandler()
.isRegistered();
}
public CaptureRtpSender getCaptureRtpSender() {
return captureRtpSender;
}
public void setCaptureRtpSender(CaptureRtpSender captureRtpSender) {
this.captureRtpSender = captureRtpSender;
}
public IncomingRtpReader getIncomingRtpReader() {
return incomingRtpReader;
}
public void setIncomingRtpReader(IncomingRtpReader incomingRtpReader) {
this.incomingRtpReader = incomingRtpReader;
}
public UAS getUas() {
return uas;
}
public UAC getUac() {
return uac;
}
public DialogManager getDialogManager() {
return dialogManager;
}
public InetAddress getMyAddress() {
return config.getInetAddress();
}
public int getSipPort() {
return config.getSipPort();
}
public int getRtpPort() {
return config.getRtpPort();
}
public String getDomain() {
return config.getDomain();
}
public String getUserpart() {
return config.getUserPart();
}
public MediaMode getMediaMode() {
return config.getMediaMode();
}
public boolean isMediaDebug() {
return config.isMediaDebug();
}
public SipURI getOutboundProxy() {
return config.getOutboundProxy();
}
public Echo getEcho() {
return echo;
}
public void setEcho(Echo echo) {
this.echo = echo;
}
public SipListener getSipListener() {
return sipListener;
}
public SoundManager getSoundManager() {
return soundManager;
}
public Config getConfig() {
return config;
}
}
| true | true | public UserAgent(SipListener sipListener) {
this.sipListener = sipListener;
config = new Config(Utils.getPeersHome() + CONFIG_FILE);
cseqCounter = 0;
StringBuffer buf = new StringBuffer();
buf.append("starting user agent [");
buf.append("myAddress: ");
buf.append(config.getInetAddress().getHostAddress()).append(", ");
buf.append("sipPort: ");
buf.append(config.getSipPort()).append(", ");
buf.append("userpart: ");
buf.append(config.getUserPart()).append(", ");
buf.append("domain: ");
buf.append(config.getDomain()).append("]");
Logger.info(buf.toString());
//transaction user
dialogManager = new DialogManager();
//transaction
transactionManager = new TransactionManager();
//transport
transportManager = new TransportManager(transactionManager,
config.getInetAddress(),
config.getSipPort());
transactionManager.setTransportManager(transportManager);
//core
InviteHandler inviteHandler = new InviteHandler(this,
dialogManager,
transactionManager,
transportManager);
CancelHandler cancelHandler = new CancelHandler(this,
dialogManager,
transactionManager,
transportManager);
ByeHandler byeHandler = new ByeHandler(this,
dialogManager,
transactionManager,
transportManager);
OptionsHandler optionsHandler = new OptionsHandler(this,
transactionManager,
transportManager);
RegisterHandler registerHandler = new RegisterHandler(this,
transactionManager,
transportManager);
InitialRequestManager initialRequestManager =
new InitialRequestManager(
this,
inviteHandler,
cancelHandler,
byeHandler,
optionsHandler,
registerHandler,
dialogManager,
transactionManager,
transportManager);
MidDialogRequestManager midDialogRequestManager =
new MidDialogRequestManager(
this,
inviteHandler,
cancelHandler,
byeHandler,
optionsHandler,
registerHandler,
dialogManager,
transactionManager,
transportManager);
uas = new UAS(this,
initialRequestManager,
midDialogRequestManager,
dialogManager,
transactionManager,
transportManager);
uac = new UAC(this,
initialRequestManager,
midDialogRequestManager,
dialogManager,
transactionManager,
transportManager);
if (config.getPassword() != null) {
challengeManager = new ChallengeManager(config,
initialRequestManager);
registerHandler.setChallengeManager(challengeManager);
inviteHandler.setChallengeManager(challengeManager);
}
peers = new ArrayList<String>();
//dialogs = new ArrayList<Dialog>();
if (config.getPassword() != null) {
try {
uac.register();
} catch (SipUriSyntaxException e) {
Logger.error("syntax error", e);
}
}
sdpManager = new SDPManager(this);
inviteHandler.setSdpManager(sdpManager);
optionsHandler.setSdpManager(sdpManager);
soundManager = new SoundManager(config.isMediaDebug());
}
| public UserAgent(SipListener sipListener) {
this.sipListener = sipListener;
config = new Config(Utils.getPeersHome() + CONFIG_FILE);
cseqCounter = 1;
StringBuffer buf = new StringBuffer();
buf.append("starting user agent [");
buf.append("myAddress: ");
buf.append(config.getInetAddress().getHostAddress()).append(", ");
buf.append("sipPort: ");
buf.append(config.getSipPort()).append(", ");
buf.append("userpart: ");
buf.append(config.getUserPart()).append(", ");
buf.append("domain: ");
buf.append(config.getDomain()).append("]");
Logger.info(buf.toString());
//transaction user
dialogManager = new DialogManager();
//transaction
transactionManager = new TransactionManager();
//transport
transportManager = new TransportManager(transactionManager,
config.getInetAddress(),
config.getSipPort());
transactionManager.setTransportManager(transportManager);
//core
InviteHandler inviteHandler = new InviteHandler(this,
dialogManager,
transactionManager,
transportManager);
CancelHandler cancelHandler = new CancelHandler(this,
dialogManager,
transactionManager,
transportManager);
ByeHandler byeHandler = new ByeHandler(this,
dialogManager,
transactionManager,
transportManager);
OptionsHandler optionsHandler = new OptionsHandler(this,
transactionManager,
transportManager);
RegisterHandler registerHandler = new RegisterHandler(this,
transactionManager,
transportManager);
InitialRequestManager initialRequestManager =
new InitialRequestManager(
this,
inviteHandler,
cancelHandler,
byeHandler,
optionsHandler,
registerHandler,
dialogManager,
transactionManager,
transportManager);
MidDialogRequestManager midDialogRequestManager =
new MidDialogRequestManager(
this,
inviteHandler,
cancelHandler,
byeHandler,
optionsHandler,
registerHandler,
dialogManager,
transactionManager,
transportManager);
uas = new UAS(this,
initialRequestManager,
midDialogRequestManager,
dialogManager,
transactionManager,
transportManager);
uac = new UAC(this,
initialRequestManager,
midDialogRequestManager,
dialogManager,
transactionManager,
transportManager);
if (config.getPassword() != null) {
challengeManager = new ChallengeManager(config,
initialRequestManager);
registerHandler.setChallengeManager(challengeManager);
inviteHandler.setChallengeManager(challengeManager);
}
peers = new ArrayList<String>();
//dialogs = new ArrayList<Dialog>();
if (config.getPassword() != null) {
try {
uac.register();
} catch (SipUriSyntaxException e) {
Logger.error("syntax error", e);
}
}
sdpManager = new SDPManager(this);
inviteHandler.setSdpManager(sdpManager);
optionsHandler.setSdpManager(sdpManager);
soundManager = new SoundManager(config.isMediaDebug());
}
|
diff --git a/src/main/java/org/sonar/dev/TrimMojo.java b/src/main/java/org/sonar/dev/TrimMojo.java
index 9c55cf1..d5edffe 100644
--- a/src/main/java/org/sonar/dev/TrimMojo.java
+++ b/src/main/java/org/sonar/dev/TrimMojo.java
@@ -1,142 +1,143 @@
/*
* Sonar Development Maven Plugin
* Copyright (C) 2010 SonarSource
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.dev;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import java.io.IOException;
/**
* @goal trim
*/
public class TrimMojo extends AbstractMojo {
/**
* @parameter
* @required
*/
private File directory;
/**
* List of ant-style patterns. If
* this is not specified, allfiles in the project source directories are included.
*
* @parameter
*/
private String[] includes;
/**
* @parameter
*/
private String[] excludes;
/**
* Specifies the encoding of the source files.
*
* @parameter expression="${encoding}" default-value="${project.build.sourceEncoding}"
*/
private String sourceEncoding;
public void execute() throws MojoExecutionException, MojoFailureException {
if (shouldExecute()) {
trimDirectory();
}
}
private void trimDirectory() throws MojoExecutionException {
File[] files = scanFiles();
for (File file : files) {
StringBuilder sb = new StringBuilder();
try {
LineIterator lines = FileUtils.lineIterator(file, sourceEncoding);
while (lines.hasNext()) {
String line = lines.nextLine();
if (StringUtils.isNotBlank(line)) {
sb.append(StringUtils.trim(line));
sb.append(IOUtils.LINE_SEPARATOR);
}
}
FileUtils.writeStringToFile(file, sb.toString(), sourceEncoding);
} catch (IOException e) {
throw new MojoExecutionException("Can not trim the file " + file, e);
}
}
getLog().info("Trimmed files: " + files.length);
}
private boolean shouldExecute() {
return directory != null && directory.exists();
}
/**
* gets a list of all files in the source directory.
*
* @return the list of all files in the source directory;
*/
private File[] scanFiles() {
String[] defaultIncludes = {"**\\*"};
DirectoryScanner ds = new DirectoryScanner();
if (includes == null) {
ds.setIncludes(defaultIncludes);
} else {
ds.setIncludes(includes);
}
- ds.addDefaultExcludes(); // .svn, ...
+ // .svn, ...
+ ds.addDefaultExcludes();
if (excludes != null) {
ds.setExcludes(excludes);
}
ds.setBasedir(directory);
getLog().info("Scanning directory " + directory);
ds.scan();
int maxFiles = ds.getIncludedFiles().length;
File[] result = new File[maxFiles];
for (int i = 0; i < maxFiles; i++) {
result[i] = new File(directory, ds.getIncludedFiles()[i]);
}
return result;
}
void setDirectory(File directory) {
this.directory = directory;
}
void setIncludes(String[] includes) {
this.includes = includes;
}
void setExcludes(String[] excludes) {
this.excludes = excludes;
}
void setSourceEncoding(String sourceEncoding) {
this.sourceEncoding = sourceEncoding;
}
}
| true | true | private File[] scanFiles() {
String[] defaultIncludes = {"**\\*"};
DirectoryScanner ds = new DirectoryScanner();
if (includes == null) {
ds.setIncludes(defaultIncludes);
} else {
ds.setIncludes(includes);
}
ds.addDefaultExcludes(); // .svn, ...
if (excludes != null) {
ds.setExcludes(excludes);
}
ds.setBasedir(directory);
getLog().info("Scanning directory " + directory);
ds.scan();
int maxFiles = ds.getIncludedFiles().length;
File[] result = new File[maxFiles];
for (int i = 0; i < maxFiles; i++) {
result[i] = new File(directory, ds.getIncludedFiles()[i]);
}
return result;
}
| private File[] scanFiles() {
String[] defaultIncludes = {"**\\*"};
DirectoryScanner ds = new DirectoryScanner();
if (includes == null) {
ds.setIncludes(defaultIncludes);
} else {
ds.setIncludes(includes);
}
// .svn, ...
ds.addDefaultExcludes();
if (excludes != null) {
ds.setExcludes(excludes);
}
ds.setBasedir(directory);
getLog().info("Scanning directory " + directory);
ds.scan();
int maxFiles = ds.getIncludedFiles().length;
File[] result = new File[maxFiles];
for (int i = 0; i < maxFiles; i++) {
result[i] = new File(directory, ds.getIncludedFiles()[i]);
}
return result;
}
|
diff --git a/src/rs/pedjaapps/KernelTuner/ChangeVoltage.java b/src/rs/pedjaapps/KernelTuner/ChangeVoltage.java
index 2dcfecf..7f88ba3 100644
--- a/src/rs/pedjaapps/KernelTuner/ChangeVoltage.java
+++ b/src/rs/pedjaapps/KernelTuner/ChangeVoltage.java
@@ -1,417 +1,417 @@
package rs.pedjaapps.KernelTuner;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
public class ChangeVoltage extends AsyncTask<String, Void, String> {
Context context;
public ChangeVoltage(Context context) {
this.context = context;
preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
SharedPreferences preferences;
@Override
protected String doInBackground(String... args) {
List<String> voltageFreqs = CPUInfo.voltageFreqs();
List<Integer> voltages = CPUInfo.voltages();
Process localProcess;
if(new File(CPUInfo.VOLTAGE_PATH).exists()){
if(args[0].equals("minus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("plus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleplus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = voltages.get(Integer.parseInt(args[1])) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleminus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = voltages.get(Integer.parseInt(args[1])) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleseek")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = Integer.parseInt(args[1]);
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ args[2]
+ " "
+ volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+args[2], args[2]+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
else if(new File(CPUInfo.VOLTAGE_PATH_TEGRA_3).exists()){
if(args[0].equals("minus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
- .writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
+ .writeBytes("chmod 777 /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
- + " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
+ + " > /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("plus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
- .writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
+ .writeBytes("chmod 777 /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
- + " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
+ + " > /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleplus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
- .writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
+ .writeBytes("chmod 777 /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
int volt = voltages.get(Integer.parseInt(args[1])) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
- + " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
+ + " > /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleminus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
- .writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
+ .writeBytes("chmod 777 /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
int volt = voltages.get(Integer.parseInt(args[1])) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
- + " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
+ + " > /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleseek")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
- .writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
+ .writeBytes("chmod 777 /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
int volt = Integer.parseInt(args[1]);
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ args[2]
+ " "
+ volt
- + " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
+ + " > /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+args[2], args[2]+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
return "";
}
@Override
protected void onPostExecute(String result){
VoltageFragment.notifyChanges();
VoltageAdapter.pd.dismiss();
}
}
| false | true | protected String doInBackground(String... args) {
List<String> voltageFreqs = CPUInfo.voltageFreqs();
List<Integer> voltages = CPUInfo.voltages();
Process localProcess;
if(new File(CPUInfo.VOLTAGE_PATH).exists()){
if(args[0].equals("minus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("plus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleplus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = voltages.get(Integer.parseInt(args[1])) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleminus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = voltages.get(Integer.parseInt(args[1])) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleseek")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = Integer.parseInt(args[1]);
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ args[2]
+ " "
+ volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+args[2], args[2]+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
else if(new File(CPUInfo.VOLTAGE_PATH_TEGRA_3).exists()){
if(args[0].equals("minus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("plus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleplus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = voltages.get(Integer.parseInt(args[1])) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleminus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = voltages.get(Integer.parseInt(args[1])) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleseek")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = Integer.parseInt(args[1]);
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ args[2]
+ " "
+ volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+args[2], args[2]+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
return "";
}
| protected String doInBackground(String... args) {
List<String> voltageFreqs = CPUInfo.voltageFreqs();
List<Integer> voltages = CPUInfo.voltages();
Process localProcess;
if(new File(CPUInfo.VOLTAGE_PATH).exists()){
if(args[0].equals("minus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("plus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleplus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = voltages.get(Integer.parseInt(args[1])) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleminus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = voltages.get(Integer.parseInt(args[1])) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleseek")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
int volt = Integer.parseInt(args[1]);
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ args[2]
+ " "
+ volt
+ " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+args[2], args[2]+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
else if(new File(CPUInfo.VOLTAGE_PATH_TEGRA_3).exists()){
if(args[0].equals("minus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
+ " > /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("plus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
for (int i = 0; i < voltageFreqs.size(); i++) {
int volt = voltages.get(i) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(i)
+ " "
+volt
+ " > /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(i), voltageFreqs.get(i)+" "+ volt);
editor.commit();
}
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleplus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
int volt = voltages.get(Integer.parseInt(args[1])) + 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
+ " > /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleminus")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
int volt = voltages.get(Integer.parseInt(args[1])) - 12500;
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ voltageFreqs.get(Integer.parseInt(args[1]))
+ " "
+volt
+ " > /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+voltageFreqs.get(Integer.parseInt(args[1])), voltageFreqs.get(Integer.parseInt(args[1]))+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else if(args[0].equals("singleseek")){
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(
localProcess.getOutputStream());
localDataOutputStream
.writeBytes("chmod 777 /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
int volt = Integer.parseInt(args[1]);
if(volt>=700000 && volt <=1400000){
localDataOutputStream
.writeBytes("echo "
+ args[2]
+ " "
+ volt
+ " > /sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n");
SharedPreferences.Editor editor = preferences.edit();
editor.putString("voltage_"+args[2], args[2]+" "+ volt);
editor.commit();
}
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
return "";
}
|
diff --git a/src/main/java/com/englishtown/vertx/jersey/impl/DefaultJerseyHandlerConfigurator.java b/src/main/java/com/englishtown/vertx/jersey/impl/DefaultJerseyHandlerConfigurator.java
index c751b84..087661f 100644
--- a/src/main/java/com/englishtown/vertx/jersey/impl/DefaultJerseyHandlerConfigurator.java
+++ b/src/main/java/com/englishtown/vertx/jersey/impl/DefaultJerseyHandlerConfigurator.java
@@ -1,152 +1,152 @@
/*
* The MIT License (MIT)
* Copyright © 2013 Englishtown <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the “Software”), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.englishtown.vertx.jersey.impl;
import com.englishtown.vertx.jersey.ApplicationHandlerDelegate;
import com.englishtown.vertx.jersey.JerseyHandlerConfigurator;
import org.glassfish.jersey.server.ApplicationHandler;
import org.glassfish.jersey.server.ResourceConfig;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.platform.Container;
import java.net.URI;
/**
* Default {@link JerseyHandlerConfigurator} implementation
*/
public class DefaultJerseyHandlerConfigurator implements JerseyHandlerConfigurator {
public static final String CONFIG_BASE_PATH = "base_path";
public static final String CONFIG_MAX_BODY_SIZE = "max_body_size";
public static final String CONFIG_RESOURCES = "resources";
public static final String CONFIG_FEATURES = "features";
public static final String CONFIG_BINDERS = "binders";
public static final int DEFAULT_MAX_BODY_SIZE = 1024 * 1000; // Default max body size to 1MB
private JsonObject config;
@Override
public void init(Vertx vertx, Container container) {
config = container.config();
if (config == null) {
throw new IllegalStateException("The vert.x container configuration is null");
}
}
/**
* Returns the base URI used by Jersey
*
* @return base URI
*/
@Override
public URI getBaseUri() {
checkState();
String basePath = config.getString(CONFIG_BASE_PATH, "/");
// TODO: Does basePath need the trailing "/"?
// if (!basePath.endsWith("/")) {
// basePath += "/";
// }
return URI.create(basePath);
}
/**
* Returns the Jersey {@link org.glassfish.jersey.server.ApplicationHandler} instance
*
* @return the application handler instance
*/
@Override
public ApplicationHandlerDelegate getApplicationHandler() {
ApplicationHandler handler = new ApplicationHandler(getResourceConfig());
return new DefaultApplicationHandlerDelegate(handler);
}
/**
* The max body size in bytes when reading the vert.x input stream
*
* @return the max body size bytes
*/
@Override
public int getMaxBodySize() {
checkState();
return config.getNumber(CONFIG_MAX_BODY_SIZE, DEFAULT_MAX_BODY_SIZE).intValue();
}
protected ResourceConfig getResourceConfig() {
checkState();
JsonArray resources = config.getArray(CONFIG_RESOURCES, null);
if (resources == null || resources.size() == 0) {
- throw new RuntimeException("At lease one resource package name must be specified in the config " +
+ throw new RuntimeException("At least one resource package name must be specified in the config " +
CONFIG_RESOURCES);
}
String[] resourceArr = new String[resources.size()];
for (int i = 0; i < resources.size(); i++) {
resourceArr[i] = String.valueOf(resources.get(i));
}
ResourceConfig rc = new ResourceConfig();
rc.packages(resourceArr);
ClassLoader cl = Thread.currentThread().getContextClassLoader();
JsonArray features = config.getArray(CONFIG_FEATURES, null);
if (features != null && features.size() > 0) {
for (int i = 0; i < features.size(); i++) {
try {
Class<?> clazz = cl.loadClass(String.valueOf(features.get(i)));
rc.register(clazz);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
JsonArray binders = config.getArray(CONFIG_BINDERS, null);
if (binders != null && binders.size() > 0) {
for (int i = 0; i < binders.size(); i++) {
try {
Class<?> clazz = cl.loadClass(String.valueOf(binders.get(i)));
rc.register(clazz.newInstance());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
return rc;
}
private void checkState() {
if (config == null) {
throw new IllegalStateException("The configurator has not been initialized.");
}
}
}
| true | true | protected ResourceConfig getResourceConfig() {
checkState();
JsonArray resources = config.getArray(CONFIG_RESOURCES, null);
if (resources == null || resources.size() == 0) {
throw new RuntimeException("At lease one resource package name must be specified in the config " +
CONFIG_RESOURCES);
}
String[] resourceArr = new String[resources.size()];
for (int i = 0; i < resources.size(); i++) {
resourceArr[i] = String.valueOf(resources.get(i));
}
ResourceConfig rc = new ResourceConfig();
rc.packages(resourceArr);
ClassLoader cl = Thread.currentThread().getContextClassLoader();
JsonArray features = config.getArray(CONFIG_FEATURES, null);
if (features != null && features.size() > 0) {
for (int i = 0; i < features.size(); i++) {
try {
Class<?> clazz = cl.loadClass(String.valueOf(features.get(i)));
rc.register(clazz);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
JsonArray binders = config.getArray(CONFIG_BINDERS, null);
if (binders != null && binders.size() > 0) {
for (int i = 0; i < binders.size(); i++) {
try {
Class<?> clazz = cl.loadClass(String.valueOf(binders.get(i)));
rc.register(clazz.newInstance());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
return rc;
}
| protected ResourceConfig getResourceConfig() {
checkState();
JsonArray resources = config.getArray(CONFIG_RESOURCES, null);
if (resources == null || resources.size() == 0) {
throw new RuntimeException("At least one resource package name must be specified in the config " +
CONFIG_RESOURCES);
}
String[] resourceArr = new String[resources.size()];
for (int i = 0; i < resources.size(); i++) {
resourceArr[i] = String.valueOf(resources.get(i));
}
ResourceConfig rc = new ResourceConfig();
rc.packages(resourceArr);
ClassLoader cl = Thread.currentThread().getContextClassLoader();
JsonArray features = config.getArray(CONFIG_FEATURES, null);
if (features != null && features.size() > 0) {
for (int i = 0; i < features.size(); i++) {
try {
Class<?> clazz = cl.loadClass(String.valueOf(features.get(i)));
rc.register(clazz);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
JsonArray binders = config.getArray(CONFIG_BINDERS, null);
if (binders != null && binders.size() > 0) {
for (int i = 0; i < binders.size(); i++) {
try {
Class<?> clazz = cl.loadClass(String.valueOf(binders.get(i)));
rc.register(clazz.newInstance());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
return rc;
}
|
diff --git a/src/main/java/water/DTask.java b/src/main/java/water/DTask.java
index b97f82d06..d9855cd28 100644
--- a/src/main/java/water/DTask.java
+++ b/src/main/java/water/DTask.java
@@ -1,53 +1,53 @@
package water;
import water.H2O.H2OCountedCompleter;
/** Objects which are passed & remotely executed.<p>
* <p>
* Efficient serialization methods for subclasses will be automatically
* generated, but explicit ones can be provided. Transient fields will
* <em>not</em> be mirrored between the VMs.
* <ol>
* <li>On the local vm, this task will be serialized and sent to a remote.</li>
* <li>On the remote, the task will be deserialized.</li>
* <li>On the remote, the {@link #invoke(H2ONode)} method will be executed.</li>
* <li>On the remote, the task will be serialized and sent to the local vm</li>
* <li>On the local vm, the task will be deserialized
* <em>into the original instance</em></li>
* <li>On the local vm, the {@link #onAck()} method will be executed.</li>
* <li>On the remote, the {@link #onAckAck()} method will be executed.</li>
* </ol>
*/
public abstract class DTask<T> extends H2OCountedCompleter implements Freezable {
// Track if the reply came via TCP - which means a timeout on ACKing the TCP
// result does NOT need to get the entire result again, just that the client
// needs more time to process the TCP result.
transient boolean _repliedTcp; // Any return/reply/result was sent via TCP
/** Top-level remote execution hook. Called on the <em>remote</em>. */
public void dinvoke( H2ONode sender ) { compute2(); }
/** 2nd top-level execution hook. After the primary task has received a
* result (ACK) and before we have sent an ACKACK, this method is executed
* on the <em>local vm</em>. Transients from the local vm are available here.
*/
public void onAck() {}
/** 3rd top-level execution hook. After the original vm sent an ACKACK,
* this method is executed on the <em>remote</em>. Transients from the remote
* vm are available here.
*/
public void onAckAck() {}
// The abstract methods to be filled in by subclasses. These are automatically
// filled in by any subclass of DTask during class-load-time, unless one
// is already defined. These methods are NOT DECLARED ABSTRACT, because javac
// thinks they will be called by subclasses relying on the auto-gen.
- private Error barf() {
+ private RuntimeException barf() {
return new RuntimeException(getClass().toString()+" should be automatically overridden in the subclass by the auto-serialization code");
}
@Override public AutoBuffer write(AutoBuffer bb) { throw barf(); }
@Override public <F extends Freezable> F read(AutoBuffer bb) { throw barf(); }
@Override public <F extends Freezable> F newInstance() { throw barf(); }
@Override public int frozenType() { throw barf(); }
}
| true | true | private Error barf() {
return new RuntimeException(getClass().toString()+" should be automatically overridden in the subclass by the auto-serialization code");
}
| private RuntimeException barf() {
return new RuntimeException(getClass().toString()+" should be automatically overridden in the subclass by the auto-serialization code");
}
|
diff --git a/src/fr/frozentux/craftguard2/listener/PlayerListener.java b/src/fr/frozentux/craftguard2/listener/PlayerListener.java
index 9af6035..79d7969 100644
--- a/src/fr/frozentux/craftguard2/listener/PlayerListener.java
+++ b/src/fr/frozentux/craftguard2/listener/PlayerListener.java
@@ -1,62 +1,62 @@
package fr.frozentux.craftguard2.listener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.inventory.InventoryType.SlotType;
import org.bukkit.inventory.ItemStack;
import fr.frozentux.craftguard2.CraftGuardPlugin;
/**
* Listener for all players-related actions including login and inventory click
* @author FrozenTux
*
*/
public class PlayerListener implements Listener {
private CraftGuardPlugin plugin;
public PlayerListener(CraftGuardPlugin plugin){
this.plugin = plugin;
}
@EventHandler
public void onInventoryClick(InventoryClickEvent e){
SlotType slotType = e.getSlotType();
InventoryType invType = e.getInventory().getType();
int slot = e.getSlot();
Player player = (Player)e.getWhoClicked();
if(slotType == SlotType.RESULT && (invType.equals(InventoryType.CRAFTING) || invType.equals(InventoryType.CRAFTING)) && slot == 0 && e.getInventory().getItem(0) != null){
ItemStack object = e.getInventory().getItem(slot);
int id = object.getTypeId();
byte metadata = object.getData().getData();
e.setCancelled(!CraftPermissionChecker.checkCraft(player, id, metadata, plugin));
}
- if(!plugin.getConfiguration().getBooleanKey("checkFurnaces"))return;
+ if(!plugin.getConfiguration().getBooleanKey("checkfurnaces"))return;
if(invType.equals(InventoryType.FURNACE) && (slotType == SlotType.CONTAINER || slotType == SlotType.FUEL || slotType == SlotType.QUICKBAR) && (e.isShiftClick() || e.getSlot() == 0 || e.getSlot() == 1)){
ItemStack object;
if(e.isShiftClick())object = e.getCurrentItem();
else{
if(e.getSlot() == 0 && e.getCursor() != null)object = e.getCursor();
else if(e.getSlot() == 1 && e.getInventory().getItem(0) != null)object = e.getInventory().getItem(0);
else return;
}
int id = object.getTypeId();
byte metadata = object.getData().getData();
CraftPermissionChecker.checkFurnace(player, id, metadata, plugin);
}
}
}
| true | true | public void onInventoryClick(InventoryClickEvent e){
SlotType slotType = e.getSlotType();
InventoryType invType = e.getInventory().getType();
int slot = e.getSlot();
Player player = (Player)e.getWhoClicked();
if(slotType == SlotType.RESULT && (invType.equals(InventoryType.CRAFTING) || invType.equals(InventoryType.CRAFTING)) && slot == 0 && e.getInventory().getItem(0) != null){
ItemStack object = e.getInventory().getItem(slot);
int id = object.getTypeId();
byte metadata = object.getData().getData();
e.setCancelled(!CraftPermissionChecker.checkCraft(player, id, metadata, plugin));
}
if(!plugin.getConfiguration().getBooleanKey("checkFurnaces"))return;
if(invType.equals(InventoryType.FURNACE) && (slotType == SlotType.CONTAINER || slotType == SlotType.FUEL || slotType == SlotType.QUICKBAR) && (e.isShiftClick() || e.getSlot() == 0 || e.getSlot() == 1)){
ItemStack object;
if(e.isShiftClick())object = e.getCurrentItem();
else{
if(e.getSlot() == 0 && e.getCursor() != null)object = e.getCursor();
else if(e.getSlot() == 1 && e.getInventory().getItem(0) != null)object = e.getInventory().getItem(0);
else return;
}
int id = object.getTypeId();
byte metadata = object.getData().getData();
CraftPermissionChecker.checkFurnace(player, id, metadata, plugin);
}
}
| public void onInventoryClick(InventoryClickEvent e){
SlotType slotType = e.getSlotType();
InventoryType invType = e.getInventory().getType();
int slot = e.getSlot();
Player player = (Player)e.getWhoClicked();
if(slotType == SlotType.RESULT && (invType.equals(InventoryType.CRAFTING) || invType.equals(InventoryType.CRAFTING)) && slot == 0 && e.getInventory().getItem(0) != null){
ItemStack object = e.getInventory().getItem(slot);
int id = object.getTypeId();
byte metadata = object.getData().getData();
e.setCancelled(!CraftPermissionChecker.checkCraft(player, id, metadata, plugin));
}
if(!plugin.getConfiguration().getBooleanKey("checkfurnaces"))return;
if(invType.equals(InventoryType.FURNACE) && (slotType == SlotType.CONTAINER || slotType == SlotType.FUEL || slotType == SlotType.QUICKBAR) && (e.isShiftClick() || e.getSlot() == 0 || e.getSlot() == 1)){
ItemStack object;
if(e.isShiftClick())object = e.getCurrentItem();
else{
if(e.getSlot() == 0 && e.getCursor() != null)object = e.getCursor();
else if(e.getSlot() == 1 && e.getInventory().getItem(0) != null)object = e.getInventory().getItem(0);
else return;
}
int id = object.getTypeId();
byte metadata = object.getData().getData();
CraftPermissionChecker.checkFurnace(player, id, metadata, plugin);
}
}
|
diff --git a/src/com/fsck/k9/helper/ContactsSdk3_4.java b/src/com/fsck/k9/helper/ContactsSdk3_4.java
index d01f8e8b..773ead78 100644
--- a/src/com/fsck/k9/helper/ContactsSdk3_4.java
+++ b/src/com/fsck/k9/helper/ContactsSdk3_4.java
@@ -1,257 +1,260 @@
package com.fsck.k9.helper;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Contacts;
import com.fsck.k9.mail.Address;
/**
* Access the contacts on the device using the old API (introduced in SDK 1).
*
* @see android.provider.Contacts
*/
@SuppressWarnings("deprecation")
public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts
{
/**
* The order in which the search results are returned by
* {@link #searchContacts(CharSequence)}.
*/
private static final String SORT_ORDER =
Contacts.ContactMethods.TIMES_CONTACTED + " DESC, " +
Contacts.ContactMethods.DISPLAY_NAME + ", " +
Contacts.ContactMethods._ID;
/**
* Array of columns to load from the database.
*
* Important: The _ID field is needed by
* {@link com.fsck.k9.EmailAddressAdapter} or more specificly by
* {@link android.widget.ResourceCursorAdapter}.
*/
private static final String PROJECTION[] =
{
Contacts.ContactMethods._ID,
Contacts.ContactMethods.DISPLAY_NAME,
Contacts.ContactMethods.DATA,
Contacts.ContactMethods.PERSON_ID
};
/**
* Index of the name field in the projection. This must match the order in
* {@link #PROJECTION}.
*/
private static final int NAME_INDEX = 1;
/**
* Index of the email address field in the projection. This must match the
* order in {@link #PROJECTION}.
*/
private static final int EMAIL_INDEX = 2;
/**
* Index of the contact id field in the projection. This must match the order in
* {@link #PROJECTION}.
*/
private static final int CONTACT_ID_INDEX = 3;
public ContactsSdk3_4(final Context context)
{
super(context);
}
@Override
public void createContact(final Activity activity, final Address email)
{
final Uri contactUri = Uri.fromParts("mailto", email.getAddress(), null);
final Intent contactIntent = new Intent(Contacts.Intents.SHOW_OR_CREATE_CONTACT);
contactIntent.setData(contactUri);
// Pass along full E-mail string for possible create dialog
contactIntent.putExtra(Contacts.Intents.EXTRA_CREATE_DESCRIPTION,
email.toString());
// Only provide personal name hint if we have one
final String senderPersonal = email.getPersonal();
if (senderPersonal != null)
{
contactIntent.putExtra(Contacts.Intents.Insert.NAME, senderPersonal);
}
activity.startActivity(contactIntent);
}
@Override
public String getOwnerName()
{
String name = null;
final Cursor c = mContentResolver.query(
Uri.withAppendedPath(Contacts.People.CONTENT_URI, "owner"),
PROJECTION,
null,
null,
null);
if (c != null)
{
if (c.getCount() > 0)
{
c.moveToFirst();
name = getName(c);
}
c.close();
}
return name;
}
@Override
public boolean isInContacts(final String emailAddress)
{
boolean result = false;
final Cursor c = getContactByAddress(emailAddress);
if (c != null)
{
if (c.getCount() > 0)
{
result = true;
}
c.close();
}
return result;
}
@Override
public Cursor searchContacts(final CharSequence constraint)
{
final String where;
final String[] args;
if (constraint == null)
{
where = null;
args = null;
}
else
{
where = Contacts.ContactMethods.KIND + " = " + Contacts.KIND_EMAIL +
" AND" + "(" +
Contacts.People.NAME + " LIKE ?" +
") OR (" +
+ Contacts.People.NAME + " LIKE ?" +
+ ") OR (" +
Contacts.ContactMethods.DATA + " LIKE ?" +
")";
final String filter = constraint.toString() + "%";
- args = new String[] {filter, filter};
+ final String filter2 = "% " + filter;
+ args = new String[] {filter, filter2, filter};
}
final Cursor c = mContentResolver.query(
Contacts.ContactMethods.CONTENT_URI,
PROJECTION,
where,
args,
SORT_ORDER);
if (c != null)
{
/*
* To prevent expensive execution in the UI thread:
* Cursors get lazily executed, so if you don't call anything on
* the cursor before returning it from the background thread you'll
* have a complied program for the cursor, but it won't have been
* executed to generate the data yet. Often the execution is more
* expensive than the compilation...
*/
c.getCount();
}
return c;
}
@Override
public String getNameForAddress(String address)
{
if (address == null)
{
return null;
}
final Cursor c = getContactByAddress(address);
String name = null;
if (c != null)
{
if (c.getCount() > 0)
{
c.moveToFirst();
name = getName(c);
}
c.close();
}
return name;
}
@Override
public String getName(Cursor c)
{
return c.getString(NAME_INDEX);
}
@Override
public String getEmail(Cursor c)
{
return c.getString(EMAIL_INDEX);
}
@Override
public void markAsContacted(final Address[] addresses)
{
//TODO: Optimize! Potentially a lot of database queries
for (final Address address : addresses)
{
final Cursor c = getContactByAddress(address.getAddress());
if (c != null)
{
if (c.getCount() > 0)
{
c.moveToFirst();
final long personId = c.getLong(CONTACT_ID_INDEX);
Contacts.People.markAsContacted(mContentResolver, personId);
}
c.close();
}
}
}
/**
* Return a {@link Cursor} instance that can be used to fetch information
* about the contact with the given email address.
*
* @param address The email address to search for.
* @return A {@link Cursor} instance that can be used to fetch information
* about the contact with the given email address
*/
private Cursor getContactByAddress(String address)
{
final String where = Contacts.ContactMethods.KIND + " = " + Contacts.KIND_EMAIL +
" AND " +
Contacts.ContactMethods.DATA + " = ?";
final String[] args = new String[] {address};
final Cursor c = mContentResolver.query(
Contacts.ContactMethods.CONTENT_URI,
PROJECTION,
where,
args,
SORT_ORDER);
return c;
}
}
| false | true | public Cursor searchContacts(final CharSequence constraint)
{
final String where;
final String[] args;
if (constraint == null)
{
where = null;
args = null;
}
else
{
where = Contacts.ContactMethods.KIND + " = " + Contacts.KIND_EMAIL +
" AND" + "(" +
Contacts.People.NAME + " LIKE ?" +
") OR (" +
Contacts.ContactMethods.DATA + " LIKE ?" +
")";
final String filter = constraint.toString() + "%";
args = new String[] {filter, filter};
}
final Cursor c = mContentResolver.query(
Contacts.ContactMethods.CONTENT_URI,
PROJECTION,
where,
args,
SORT_ORDER);
if (c != null)
{
/*
* To prevent expensive execution in the UI thread:
* Cursors get lazily executed, so if you don't call anything on
* the cursor before returning it from the background thread you'll
* have a complied program for the cursor, but it won't have been
* executed to generate the data yet. Often the execution is more
* expensive than the compilation...
*/
c.getCount();
}
return c;
}
| public Cursor searchContacts(final CharSequence constraint)
{
final String where;
final String[] args;
if (constraint == null)
{
where = null;
args = null;
}
else
{
where = Contacts.ContactMethods.KIND + " = " + Contacts.KIND_EMAIL +
" AND" + "(" +
Contacts.People.NAME + " LIKE ?" +
") OR (" +
Contacts.People.NAME + " LIKE ?" +
") OR (" +
Contacts.ContactMethods.DATA + " LIKE ?" +
")";
final String filter = constraint.toString() + "%";
final String filter2 = "% " + filter;
args = new String[] {filter, filter2, filter};
}
final Cursor c = mContentResolver.query(
Contacts.ContactMethods.CONTENT_URI,
PROJECTION,
where,
args,
SORT_ORDER);
if (c != null)
{
/*
* To prevent expensive execution in the UI thread:
* Cursors get lazily executed, so if you don't call anything on
* the cursor before returning it from the background thread you'll
* have a complied program for the cursor, but it won't have been
* executed to generate the data yet. Often the execution is more
* expensive than the compilation...
*/
c.getCount();
}
return c;
}
|
diff --git a/src/com/android/contacts/editor/PhotoActionPopup.java b/src/com/android/contacts/editor/PhotoActionPopup.java
index ac2d64fd3..cca6f9d08 100644
--- a/src/com/android/contacts/editor/PhotoActionPopup.java
+++ b/src/com/android/contacts/editor/PhotoActionPopup.java
@@ -1,138 +1,138 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.contacts.editor;
import com.android.contacts.R;
import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListPopupWindow;
import java.util.ArrayList;
/**
* Shows a popup asking the user what to do for a photo. The result is pased back to the Listener
*/
public class PhotoActionPopup {
public static final String TAG = "PhotoActionPopup";
public static final int MODE_NO_PHOTO = 0;
public static final int MODE_READ_ONLY_ALLOW_PRIMARY = 1;
public static final int MODE_PHOTO_DISALLOW_PRIMARY = 2;
public static final int MODE_PHOTO_ALLOW_PRIMARY = 3;
public static ListPopupWindow createPopupMenu(Context context, View anchorView,
final Listener listener, int mode) {
// Build choices, depending on the current mode. We assume this Dialog is never called
// if there are NO choices (e.g. a read-only picture is already super-primary)
final ArrayList<ChoiceListItem> choices = new ArrayList<ChoiceListItem>(4);
// Use as Primary
if (mode == MODE_PHOTO_ALLOW_PRIMARY || mode == MODE_READ_ONLY_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_USE_AS_PRIMARY,
context.getString(R.string.use_photo_as_primary)));
}
// Remove
if (mode == MODE_PHOTO_DISALLOW_PRIMARY || mode == MODE_PHOTO_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_REMOVE,
context.getString(R.string.removePhoto)));
}
// Take photo (if there is already a photo, it says "Take new photo")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.take_photo :R.string.take_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_TAKE_PHOTO,
context.getString(resId)));
}
// Select from Gallery (or "Select new from Gallery")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.pick_photo :R.string.pick_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_PICK_PHOTO,
context.getString(resId)));
}
final ListAdapter adapter = new ArrayAdapter<ChoiceListItem>(context,
- android.R.layout.select_dialog_item, choices);
+ R.layout.select_dialog_item, choices);
final ListPopupWindow listPopupWindow = new ListPopupWindow(context);
final OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ChoiceListItem choice = choices.get(position);
listPopupWindow.dismiss();
switch (choice.getId()) {
case ChoiceListItem.ID_USE_AS_PRIMARY:
listener.onUseAsPrimaryChosen();
break;
case ChoiceListItem.ID_REMOVE:
listener.onRemovePictureChosen();
break;
case ChoiceListItem.ID_TAKE_PHOTO:
listener.onTakePhotoChosen();
break;
case ChoiceListItem.ID_PICK_PHOTO:
listener.onPickFromGalleryChosen();
break;
}
}
};
listPopupWindow.setAnchorView(anchorView);
listPopupWindow.setAdapter(adapter);
listPopupWindow.setOnItemClickListener(clickListener);
listPopupWindow.setWidth(context.getResources().getDimensionPixelSize(
R.dimen.photo_action_popup_width));
listPopupWindow.setModal(true);
listPopupWindow.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
return listPopupWindow;
}
private static final class ChoiceListItem {
private final int mId;
private final String mCaption;
public static final int ID_USE_AS_PRIMARY = 0;
public static final int ID_TAKE_PHOTO = 1;
public static final int ID_PICK_PHOTO = 2;
public static final int ID_REMOVE = 3;
public ChoiceListItem(int id, String caption) {
mId = id;
mCaption = caption;
}
@Override
public String toString() {
return mCaption;
}
public int getId() {
return mId;
}
}
public interface Listener {
void onUseAsPrimaryChosen();
void onRemovePictureChosen();
void onTakePhotoChosen();
void onPickFromGalleryChosen();
}
}
| true | true | public static ListPopupWindow createPopupMenu(Context context, View anchorView,
final Listener listener, int mode) {
// Build choices, depending on the current mode. We assume this Dialog is never called
// if there are NO choices (e.g. a read-only picture is already super-primary)
final ArrayList<ChoiceListItem> choices = new ArrayList<ChoiceListItem>(4);
// Use as Primary
if (mode == MODE_PHOTO_ALLOW_PRIMARY || mode == MODE_READ_ONLY_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_USE_AS_PRIMARY,
context.getString(R.string.use_photo_as_primary)));
}
// Remove
if (mode == MODE_PHOTO_DISALLOW_PRIMARY || mode == MODE_PHOTO_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_REMOVE,
context.getString(R.string.removePhoto)));
}
// Take photo (if there is already a photo, it says "Take new photo")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.take_photo :R.string.take_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_TAKE_PHOTO,
context.getString(resId)));
}
// Select from Gallery (or "Select new from Gallery")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.pick_photo :R.string.pick_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_PICK_PHOTO,
context.getString(resId)));
}
final ListAdapter adapter = new ArrayAdapter<ChoiceListItem>(context,
android.R.layout.select_dialog_item, choices);
final ListPopupWindow listPopupWindow = new ListPopupWindow(context);
final OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ChoiceListItem choice = choices.get(position);
listPopupWindow.dismiss();
switch (choice.getId()) {
case ChoiceListItem.ID_USE_AS_PRIMARY:
listener.onUseAsPrimaryChosen();
break;
case ChoiceListItem.ID_REMOVE:
listener.onRemovePictureChosen();
break;
case ChoiceListItem.ID_TAKE_PHOTO:
listener.onTakePhotoChosen();
break;
case ChoiceListItem.ID_PICK_PHOTO:
listener.onPickFromGalleryChosen();
break;
}
}
};
listPopupWindow.setAnchorView(anchorView);
listPopupWindow.setAdapter(adapter);
listPopupWindow.setOnItemClickListener(clickListener);
listPopupWindow.setWidth(context.getResources().getDimensionPixelSize(
R.dimen.photo_action_popup_width));
listPopupWindow.setModal(true);
listPopupWindow.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
return listPopupWindow;
}
| public static ListPopupWindow createPopupMenu(Context context, View anchorView,
final Listener listener, int mode) {
// Build choices, depending on the current mode. We assume this Dialog is never called
// if there are NO choices (e.g. a read-only picture is already super-primary)
final ArrayList<ChoiceListItem> choices = new ArrayList<ChoiceListItem>(4);
// Use as Primary
if (mode == MODE_PHOTO_ALLOW_PRIMARY || mode == MODE_READ_ONLY_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_USE_AS_PRIMARY,
context.getString(R.string.use_photo_as_primary)));
}
// Remove
if (mode == MODE_PHOTO_DISALLOW_PRIMARY || mode == MODE_PHOTO_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_REMOVE,
context.getString(R.string.removePhoto)));
}
// Take photo (if there is already a photo, it says "Take new photo")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.take_photo :R.string.take_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_TAKE_PHOTO,
context.getString(resId)));
}
// Select from Gallery (or "Select new from Gallery")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.pick_photo :R.string.pick_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_PICK_PHOTO,
context.getString(resId)));
}
final ListAdapter adapter = new ArrayAdapter<ChoiceListItem>(context,
R.layout.select_dialog_item, choices);
final ListPopupWindow listPopupWindow = new ListPopupWindow(context);
final OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ChoiceListItem choice = choices.get(position);
listPopupWindow.dismiss();
switch (choice.getId()) {
case ChoiceListItem.ID_USE_AS_PRIMARY:
listener.onUseAsPrimaryChosen();
break;
case ChoiceListItem.ID_REMOVE:
listener.onRemovePictureChosen();
break;
case ChoiceListItem.ID_TAKE_PHOTO:
listener.onTakePhotoChosen();
break;
case ChoiceListItem.ID_PICK_PHOTO:
listener.onPickFromGalleryChosen();
break;
}
}
};
listPopupWindow.setAnchorView(anchorView);
listPopupWindow.setAdapter(adapter);
listPopupWindow.setOnItemClickListener(clickListener);
listPopupWindow.setWidth(context.getResources().getDimensionPixelSize(
R.dimen.photo_action_popup_width));
listPopupWindow.setModal(true);
listPopupWindow.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
return listPopupWindow;
}
|
diff --git a/src/edu/cudenver/bios/powersvc/resource/ParameterResourceHelper.java b/src/edu/cudenver/bios/powersvc/resource/ParameterResourceHelper.java
index 73607f0..5bdd05e 100644
--- a/src/edu/cudenver/bios/powersvc/resource/ParameterResourceHelper.java
+++ b/src/edu/cudenver/bios/powersvc/resource/ParameterResourceHelper.java
@@ -1,445 +1,445 @@
package edu.cudenver.bios.powersvc.resource;
import java.util.ArrayList;
import org.apache.commons.math.linear.Array2DRowRealMatrix;
import org.apache.commons.math.linear.RealMatrix;
import org.restlet.data.Status;
import org.restlet.resource.ResourceException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import edu.cudenver.bios.matrix.ColumnMetaData;
import edu.cudenver.bios.matrix.EssenceMatrix;
import edu.cudenver.bios.matrix.RowMetaData;
import edu.cudenver.bios.matrix.ColumnMetaData.PredictorType;
import edu.cudenver.bios.powersamplesize.parameters.LinearModelPowerSampleSizeParameters;
import edu.cudenver.bios.powersamplesize.parameters.PowerSampleSizeParameters;
import edu.cudenver.bios.powersamplesize.parameters.SimplePowerSampleSizeParameters;
import edu.cudenver.bios.powersamplesize.parameters.LinearModelPowerSampleSizeParameters.PowerMethod;
import edu.cudenver.bios.powersamplesize.parameters.LinearModelPowerSampleSizeParameters.TestStatistic;
import edu.cudenver.bios.powersvc.application.PowerConstants;
import edu.cudenver.bios.powersvc.application.PowerLogger;
/**
* Parsing of model parameters from DOM tree.
*
* @author kreidles
*
*/
public class ParameterResourceHelper
{
public static PowerSampleSizeParameters powerSampleSizeParametersFromDomNode(String modelName, Node node)
throws ResourceException
{
if (PowerConstants.TEST_ONE_SAMPLE_STUDENT_T.equals(modelName))
{
return ParameterResourceHelper.simpleParamsFromDomNode(node);
}
else if (PowerConstants.TEST_GLMM.equals(modelName))
{
return ParameterResourceHelper.linearModelParamsFromDomNode(node);
}
else
{
PowerLogger.getInstance().warn("Invalid model name found while parsing parameters: " + modelName);
return null;
}
}
/**
* Parse simple inputs for power/sample size calculations from a DOM tree
*
* @param node
* @return SimplePowerSampleSizeParameters object
* @throws ResourceException
*/
public static SimplePowerSampleSizeParameters simpleParamsFromDomNode(Node node) throws ResourceException
{
SimplePowerSampleSizeParameters powerParams = new SimplePowerSampleSizeParameters();
// make sure the root node is a power parameters
if (!PowerConstants.TAG_PARAMS.equals(node.getNodeName()))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid root node '" + node.getNodeName() + "' when parsing parameter object");
// get the parameter attributes
NamedNodeMap attrs = node.getAttributes();
if (attrs != null)
{
/* parse required parameters: mu0, muA, sigma, alpha, sample size */
Node mu0 = attrs.getNamedItem(PowerConstants.ATTR_MU0);
if (mu0 != null) powerParams.setMu0(Double.parseDouble(mu0.getNodeValue()));
Node muA = attrs.getNamedItem(PowerConstants.ATTR_MUA);
if (muA != null) powerParams.setMuA(Double.parseDouble(muA.getNodeValue()));
Node sigma = attrs.getNamedItem(PowerConstants.ATTR_SIGMA_ERROR);
if (sigma != null) powerParams.setSigma(Double.parseDouble(sigma.getNodeValue()));
Node alpha = attrs.getNamedItem(PowerConstants.ATTR_ALPHA);
if (alpha != null) powerParams.setAlpha(Double.parseDouble(alpha.getNodeValue()));
Node sampleSize = attrs.getNamedItem(PowerConstants.ATTR_SAMPLESIZE);
if (sampleSize != null) powerParams.setSampleSize(Integer.parseInt(sampleSize.getNodeValue()));
Node power = attrs.getNamedItem(PowerConstants.ATTR_POWER);
if (power != null) powerParams.setPower(Double.parseDouble(power.getNodeValue()));
// parse optional parameters: oneTailed, simulate, simulationSize
Node oneTailed = attrs.getNamedItem(PowerConstants.ATTR_ONE_TAILED);
if (oneTailed != null) powerParams.setOneTailed(Boolean.parseBoolean(oneTailed.getNodeValue()));
}
return powerParams;
}
/**
* Get linear model parameters from a DOM tree
*
* @param node
* @return
* @throws ResourceException
*/
public static LinearModelPowerSampleSizeParameters linearModelParamsFromDomNode(Node node) throws ResourceException
{
LinearModelPowerSampleSizeParameters params = new LinearModelPowerSampleSizeParameters();
// make sure the root node is a power parameters
if (!node.getNodeName().equals(PowerConstants.TAG_PARAMS))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid root node '" + node.getNodeName() + "' when parsing parameter object");
// get the parameter attributes
NamedNodeMap attrs = node.getAttributes();
if (attrs != null)
{
/* parse required attributes: alpha */
Node alpha = attrs.getNamedItem(PowerConstants.ATTR_ALPHA);
if (alpha != null) params.setAlpha(Double.parseDouble(alpha.getNodeValue()));
// TODO: extract this from design or essence matrix. It's silly to specify
Node sampleSize = attrs.getNamedItem(PowerConstants.ATTR_SAMPLESIZE);
if (sampleSize != null) params.setSampleSize(Integer.parseInt(sampleSize.getNodeValue()));
// parse desired power
Node power = attrs.getNamedItem(PowerConstants.ATTR_POWER);
if (power != null) params.setPower(Double.parseDouble(power.getNodeValue()));
/* parse the power method */
Node powerMethod = attrs.getNamedItem(PowerConstants.ATTR_POWER_METHOD);
if (powerMethod != null)
{
String powerMethodName = powerMethod.getNodeValue();
if (powerMethodName != null)
{
if (PowerConstants.POWER_METHOD_QUANTILE.equals(powerMethodName))
params.setPowerMethod(PowerMethod.QUANTILE_POWER);
else if (PowerConstants.POWER_METHOD_UNCONDITIONAL.equals(powerMethodName))
params.setPowerMethod(PowerMethod.UNCONDITIONAL_POWER);
else
params.setPowerMethod(PowerMethod.CONDITIONAL_POWER);
}
}
/* parse the quantile (if using quantile power) */
Node quantile = attrs.getNamedItem(PowerConstants.ATTR_QUANTILE);
if (quantile != null) params.setQuantile(Double.parseDouble(quantile.getNodeValue()));
/* parse the test statistic */
Node stat = attrs.getNamedItem(PowerConstants.ATTR_STATISTIC);
if (stat != null)
{
String statName = stat.getNodeValue();
if (statName != null)
{
if (PowerConstants.STATISTIC_UNIREP.equals(statName))
params.setTestStatistic(TestStatistic.UNIREP);
else if (PowerConstants.STATISTIC_HOTELLING_LAWLEY_TRACE.equals(statName))
params.setTestStatistic(TestStatistic.HOTELLING_LAWLEY_TRACE);
else if (PowerConstants.STATISTIC_PILLAU_BARTLETT_TRACE.equals(statName))
- params.setTestStatistic(TestStatistic.PILLAU_BARTLETT_TRACE);
+ params.setTestStatistic(TestStatistic.PILLAI_BARTLETT_TRACE);
else if (PowerConstants.STATISTIC_WILKS_LAMBDA.equals(statName))
params.setTestStatistic(TestStatistic.WILKS_LAMBDA);
else
{
PowerLogger.getInstance().warn("Invalid statistic name '" + statName + "', defaulting to Hotelling-Lawley Trace");
}
}
}
}
// parse the matrix inputs: beta, design, theta, sigma, C-contrast, U-contrast
NodeList children = node.getChildNodes();
if (children != null && children.getLength() > 0)
{
for (int i = 0; i < children.getLength(); i++)
{
Node child = children.item(i);
if (PowerConstants.TAG_ESSENCE_MATRIX.equals(child.getNodeName()))
{
EssenceMatrix essence = essenceMatrixFromDomNode(child);
params.setDesignEssence(essence);
}
else if (PowerConstants.TAG_MATRIX.equals(child.getNodeName()))
{
// get the name of this matrix
String matrixName = null;
NamedNodeMap matrixAttrs = child.getAttributes();
Node name = matrixAttrs.getNamedItem(PowerConstants.ATTR_NAME);
if (name != null) matrixName = name.getNodeValue();
// if we have a valid name, parse and save the matrix to the linear model parameters
if (matrixName != null && !matrixName.isEmpty())
{
RealMatrix matrix = matrixFromDomNode(child);
if (PowerConstants.MATRIX_TYPE_BETA.equals(matrixName))
params.setBeta(matrix);
else if (PowerConstants.MATRIX_TYPE_DESIGN.equals(matrixName))
params.setDesign(matrix);
else if (PowerConstants.MATRIX_TYPE_THETA.equals(matrixName))
params.setTheta(matrix);
else if (PowerConstants.MATRIX_TYPE_WITHIN_CONTRAST.equals(matrixName))
params.setWithinSubjectContrast(matrix);
else if (PowerConstants.MATRIX_TYPE_BETWEEN_CONTRAST.equals(matrixName))
params.setBetweenSubjectContrast(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_ERROR.equals(matrixName))
params.setSigmaError(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_GAUSSIAN.equals(matrixName))
params.setSigmaGaussianRandom(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_OUTCOME.equals(matrixName))
params.setSigmaOutcome(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_OUTCOME_GAUSSIAN.equals(matrixName))
params.setSigmaOutcomeGaussianRandom(matrix);
else
PowerLogger.getInstance().warn("Ignoring Invalid matrix: " + matrixName);
}
else
{
PowerLogger.getInstance().warn("Ignoring unnamed matrix");
}
}
else
{
PowerLogger.getInstance().warn("Ignoring unknown tag while parsing parameters: " + child.getNodeName());
}
}
}
return params;
}
/**
* Parse an essence matrix from a DOM tree
*
* @param node root node of the DOM tree
* @return
* @throws IllegalArgumentException
*/
public static EssenceMatrix essenceMatrixFromDomNode(Node node)
throws ResourceException
{
EssenceMatrix essence = null;
RealMatrix matrix = null;
RowMetaData[] rmd = null;
ColumnMetaData[] cmd = null;
Node seed = null;
// parse the random seed value if specified
NamedNodeMap attrs = node.getAttributes();
if (attrs != null) seed = attrs.getNamedItem(PowerConstants.ATTR_RANDOM_SEED);
// parse the matrix data, row meta data, and column meta data
NodeList children = node.getChildNodes();
if (children != null && children.getLength() > 0)
{
for (int i = 0; i < children.getLength(); i++)
{
Node child = children.item(i);
if (PowerConstants.TAG_MATRIX.equals(child.getNodeName()))
{
matrix = ParameterResourceHelper.matrixFromDomNode(child);
}
else if (PowerConstants.TAG_ROW_META_DATA.equals(child.getNodeName()))
{
rmd = ParameterResourceHelper.rowMetaDataFromDomNode(child);
}
else if (PowerConstants.TAG_COLUMN_META_DATA.equals(child.getNodeName()))
{
cmd = ParameterResourceHelper.columnMetaDataFromDomNode(child);
}
else
{
PowerLogger.getInstance().warn("Ignoring unknown essence matrix child tag: " + child.getNodeName());
}
}
}
// now that we're done parsing, build the essence matrix object
if (matrix != null)
{
essence = new EssenceMatrix(matrix);
if (seed != null) essence.setRandomSeed(Integer.parseInt(seed.getNodeValue()));
if (cmd != null) essence.setColumnMetaData(cmd);
if (rmd != null) essence.setRowMetaData(rmd);
}
return essence;
}
/**
* Parse a row meta data object from a DOM node
*
* @param node
* @return array of RowMetaData objects
*/
public static RowMetaData[] rowMetaDataFromDomNode(Node node)
{
ArrayList<RowMetaData> metaDataList = new ArrayList<RowMetaData>();
NodeList children = node.getChildNodes();
if (children != null && children.getLength() > 0)
{
for (int i = 0; i < children.getLength(); i++)
{
RowMetaData rmd = new RowMetaData();
Node child = children.item(i);
if (PowerConstants.TAG_ROW.equals(child.getNodeName()))
{
NamedNodeMap attrs = child.getAttributes();
Node reps = attrs.getNamedItem(PowerConstants.ATTR_REPETITIONS);
if (reps != null) rmd.setRepetitions(Integer.parseInt(reps.getNodeValue()));
Node ratio = attrs.getNamedItem(PowerConstants.ATTR_RATIO);
if (ratio != null) rmd.setRatio(Integer.parseInt(ratio.getNodeValue()));
}
else
{
PowerLogger.getInstance().warn("Ignoring unknown tag while parsing row meta data: " + child.getNodeName());
}
metaDataList.add(rmd);
}
}
return (RowMetaData[]) metaDataList.toArray(new RowMetaData[metaDataList.size()]);
}
/**
* Parse an array of column meta data from a DOM tree
*
* @param node
* @return list of column meta data
*/
public static ColumnMetaData[] columnMetaDataFromDomNode(Node node)
{
ArrayList<ColumnMetaData> metaDataList = new ArrayList<ColumnMetaData>();
NodeList children = node.getChildNodes();
if (children != null && children.getLength() > 0)
{
for (int i = 0; i < children.getLength(); i++)
{
ColumnMetaData cmd = new ColumnMetaData();
Node child = children.item(i);
if (PowerConstants.TAG_COLUMN.equals(child.getNodeName()))
{
NamedNodeMap attrs = child.getAttributes();
Node predictorType = attrs.getNamedItem(PowerConstants.ATTR_TYPE);
if (predictorType != null)
{
// default is fixed, so only set if we see a random predictor specified
if (PowerConstants.COLUMN_TYPE_RANDOM.equals(predictorType.getNodeValue()))
{
cmd.setPredictorType(PredictorType.RANDOM);
}
}
Node mean = attrs.getNamedItem(PowerConstants.ATTR_MEAN);
if (mean != null) cmd.setMean(Double.parseDouble(mean.getNodeValue()));
Node variance = attrs.getNamedItem(PowerConstants.ATTR_VARIANCE);
if (variance != null) cmd.setVariance(Double.parseDouble(variance.getNodeValue()));
metaDataList.add(cmd);
}
else
{
PowerLogger.getInstance().warn("Ignoring unknown tag while parsing row meta data: " + child.getNodeName());
}
}
}
return (ColumnMetaData[]) metaDataList.toArray(new ColumnMetaData[metaDataList.size()]);
}
/**
* Parse a matrix from XML DOM. The matrix should be specified as follows:
* <p>
* <matrix type=(beta|theta|sigma|design|withinSubjectContrast|betweenSubjectContrast) >
* <br><row><col>number<col/>...</row>
* <br>...
* <br></matrix>
*
* @param node
* @return
* @throws ResourceException
*/
public static RealMatrix matrixFromDomNode(Node node) throws ResourceException
{
// make sure the root node is a matrix
if (!node.getNodeName().equals(PowerConstants.TAG_MATRIX))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid root node '" + node.getNodeName() + "' when parsing matrix object");
// parse the rows / columns from the attribute list
NamedNodeMap attrs = node.getAttributes();
Node numRowsStr = attrs.getNamedItem(PowerConstants.ATTR_ROWS);
int numRows = 0;
if (numRowsStr != null) numRows = Integer.parseInt(numRowsStr.getNodeValue());
Node numColsStr = attrs.getNamedItem(PowerConstants.ATTR_COLUMNS);
int numCols = 0;
if (numColsStr != null) numCols = Integer.parseInt(numColsStr.getNodeValue());
// make sure we got a reasonable value for rows/columns
if (numRows <= 0 || numCols <=0)
throw new IllegalArgumentException("Invalid matrix rows/columns specified - must be positive integer");
// create a placeholder matrix for storing the rows/columns
Array2DRowRealMatrix matrix = new Array2DRowRealMatrix(numRows, numCols);
// parse the children: should contain multiple row objects with col objects as children
NodeList rows = node.getChildNodes();
if (rows != null && rows.getLength() > 0)
{
for (int rowIndex = 0; rowIndex < rows.getLength() && rowIndex < numRows; rowIndex++)
{
Node row = rows.item(rowIndex);
if (!PowerConstants.TAG_ROW.equals(row.getNodeName()))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid row node '" + row.getNodeName() + "' when parsing matrix object");
// get all of the columns for the current row and insert into a matrix
NodeList columns = row.getChildNodes();
if (columns != null && columns.getLength() > 0)
{
for(int colIndex = 0; colIndex < columns.getLength() && colIndex < numCols; colIndex++)
{
Node colEntry = columns.item(colIndex);
String valStr = colEntry.getFirstChild().getNodeValue();
if (colEntry.hasChildNodes() && valStr != null && !valStr.isEmpty())
{
double val = Double.parseDouble(valStr);
matrix.setEntry(rowIndex, colIndex, val);
}
else
{
throw new IllegalArgumentException("Missing data in matrix [row=" + rowIndex + " col=" + colIndex + "]");
}
}
}
}
}
return matrix;
}
}
| true | true | public static LinearModelPowerSampleSizeParameters linearModelParamsFromDomNode(Node node) throws ResourceException
{
LinearModelPowerSampleSizeParameters params = new LinearModelPowerSampleSizeParameters();
// make sure the root node is a power parameters
if (!node.getNodeName().equals(PowerConstants.TAG_PARAMS))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid root node '" + node.getNodeName() + "' when parsing parameter object");
// get the parameter attributes
NamedNodeMap attrs = node.getAttributes();
if (attrs != null)
{
/* parse required attributes: alpha */
Node alpha = attrs.getNamedItem(PowerConstants.ATTR_ALPHA);
if (alpha != null) params.setAlpha(Double.parseDouble(alpha.getNodeValue()));
// TODO: extract this from design or essence matrix. It's silly to specify
Node sampleSize = attrs.getNamedItem(PowerConstants.ATTR_SAMPLESIZE);
if (sampleSize != null) params.setSampleSize(Integer.parseInt(sampleSize.getNodeValue()));
// parse desired power
Node power = attrs.getNamedItem(PowerConstants.ATTR_POWER);
if (power != null) params.setPower(Double.parseDouble(power.getNodeValue()));
/* parse the power method */
Node powerMethod = attrs.getNamedItem(PowerConstants.ATTR_POWER_METHOD);
if (powerMethod != null)
{
String powerMethodName = powerMethod.getNodeValue();
if (powerMethodName != null)
{
if (PowerConstants.POWER_METHOD_QUANTILE.equals(powerMethodName))
params.setPowerMethod(PowerMethod.QUANTILE_POWER);
else if (PowerConstants.POWER_METHOD_UNCONDITIONAL.equals(powerMethodName))
params.setPowerMethod(PowerMethod.UNCONDITIONAL_POWER);
else
params.setPowerMethod(PowerMethod.CONDITIONAL_POWER);
}
}
/* parse the quantile (if using quantile power) */
Node quantile = attrs.getNamedItem(PowerConstants.ATTR_QUANTILE);
if (quantile != null) params.setQuantile(Double.parseDouble(quantile.getNodeValue()));
/* parse the test statistic */
Node stat = attrs.getNamedItem(PowerConstants.ATTR_STATISTIC);
if (stat != null)
{
String statName = stat.getNodeValue();
if (statName != null)
{
if (PowerConstants.STATISTIC_UNIREP.equals(statName))
params.setTestStatistic(TestStatistic.UNIREP);
else if (PowerConstants.STATISTIC_HOTELLING_LAWLEY_TRACE.equals(statName))
params.setTestStatistic(TestStatistic.HOTELLING_LAWLEY_TRACE);
else if (PowerConstants.STATISTIC_PILLAU_BARTLETT_TRACE.equals(statName))
params.setTestStatistic(TestStatistic.PILLAU_BARTLETT_TRACE);
else if (PowerConstants.STATISTIC_WILKS_LAMBDA.equals(statName))
params.setTestStatistic(TestStatistic.WILKS_LAMBDA);
else
{
PowerLogger.getInstance().warn("Invalid statistic name '" + statName + "', defaulting to Hotelling-Lawley Trace");
}
}
}
}
// parse the matrix inputs: beta, design, theta, sigma, C-contrast, U-contrast
NodeList children = node.getChildNodes();
if (children != null && children.getLength() > 0)
{
for (int i = 0; i < children.getLength(); i++)
{
Node child = children.item(i);
if (PowerConstants.TAG_ESSENCE_MATRIX.equals(child.getNodeName()))
{
EssenceMatrix essence = essenceMatrixFromDomNode(child);
params.setDesignEssence(essence);
}
else if (PowerConstants.TAG_MATRIX.equals(child.getNodeName()))
{
// get the name of this matrix
String matrixName = null;
NamedNodeMap matrixAttrs = child.getAttributes();
Node name = matrixAttrs.getNamedItem(PowerConstants.ATTR_NAME);
if (name != null) matrixName = name.getNodeValue();
// if we have a valid name, parse and save the matrix to the linear model parameters
if (matrixName != null && !matrixName.isEmpty())
{
RealMatrix matrix = matrixFromDomNode(child);
if (PowerConstants.MATRIX_TYPE_BETA.equals(matrixName))
params.setBeta(matrix);
else if (PowerConstants.MATRIX_TYPE_DESIGN.equals(matrixName))
params.setDesign(matrix);
else if (PowerConstants.MATRIX_TYPE_THETA.equals(matrixName))
params.setTheta(matrix);
else if (PowerConstants.MATRIX_TYPE_WITHIN_CONTRAST.equals(matrixName))
params.setWithinSubjectContrast(matrix);
else if (PowerConstants.MATRIX_TYPE_BETWEEN_CONTRAST.equals(matrixName))
params.setBetweenSubjectContrast(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_ERROR.equals(matrixName))
params.setSigmaError(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_GAUSSIAN.equals(matrixName))
params.setSigmaGaussianRandom(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_OUTCOME.equals(matrixName))
params.setSigmaOutcome(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_OUTCOME_GAUSSIAN.equals(matrixName))
params.setSigmaOutcomeGaussianRandom(matrix);
else
PowerLogger.getInstance().warn("Ignoring Invalid matrix: " + matrixName);
}
else
{
PowerLogger.getInstance().warn("Ignoring unnamed matrix");
}
}
else
{
PowerLogger.getInstance().warn("Ignoring unknown tag while parsing parameters: " + child.getNodeName());
}
}
}
return params;
}
| public static LinearModelPowerSampleSizeParameters linearModelParamsFromDomNode(Node node) throws ResourceException
{
LinearModelPowerSampleSizeParameters params = new LinearModelPowerSampleSizeParameters();
// make sure the root node is a power parameters
if (!node.getNodeName().equals(PowerConstants.TAG_PARAMS))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid root node '" + node.getNodeName() + "' when parsing parameter object");
// get the parameter attributes
NamedNodeMap attrs = node.getAttributes();
if (attrs != null)
{
/* parse required attributes: alpha */
Node alpha = attrs.getNamedItem(PowerConstants.ATTR_ALPHA);
if (alpha != null) params.setAlpha(Double.parseDouble(alpha.getNodeValue()));
// TODO: extract this from design or essence matrix. It's silly to specify
Node sampleSize = attrs.getNamedItem(PowerConstants.ATTR_SAMPLESIZE);
if (sampleSize != null) params.setSampleSize(Integer.parseInt(sampleSize.getNodeValue()));
// parse desired power
Node power = attrs.getNamedItem(PowerConstants.ATTR_POWER);
if (power != null) params.setPower(Double.parseDouble(power.getNodeValue()));
/* parse the power method */
Node powerMethod = attrs.getNamedItem(PowerConstants.ATTR_POWER_METHOD);
if (powerMethod != null)
{
String powerMethodName = powerMethod.getNodeValue();
if (powerMethodName != null)
{
if (PowerConstants.POWER_METHOD_QUANTILE.equals(powerMethodName))
params.setPowerMethod(PowerMethod.QUANTILE_POWER);
else if (PowerConstants.POWER_METHOD_UNCONDITIONAL.equals(powerMethodName))
params.setPowerMethod(PowerMethod.UNCONDITIONAL_POWER);
else
params.setPowerMethod(PowerMethod.CONDITIONAL_POWER);
}
}
/* parse the quantile (if using quantile power) */
Node quantile = attrs.getNamedItem(PowerConstants.ATTR_QUANTILE);
if (quantile != null) params.setQuantile(Double.parseDouble(quantile.getNodeValue()));
/* parse the test statistic */
Node stat = attrs.getNamedItem(PowerConstants.ATTR_STATISTIC);
if (stat != null)
{
String statName = stat.getNodeValue();
if (statName != null)
{
if (PowerConstants.STATISTIC_UNIREP.equals(statName))
params.setTestStatistic(TestStatistic.UNIREP);
else if (PowerConstants.STATISTIC_HOTELLING_LAWLEY_TRACE.equals(statName))
params.setTestStatistic(TestStatistic.HOTELLING_LAWLEY_TRACE);
else if (PowerConstants.STATISTIC_PILLAU_BARTLETT_TRACE.equals(statName))
params.setTestStatistic(TestStatistic.PILLAI_BARTLETT_TRACE);
else if (PowerConstants.STATISTIC_WILKS_LAMBDA.equals(statName))
params.setTestStatistic(TestStatistic.WILKS_LAMBDA);
else
{
PowerLogger.getInstance().warn("Invalid statistic name '" + statName + "', defaulting to Hotelling-Lawley Trace");
}
}
}
}
// parse the matrix inputs: beta, design, theta, sigma, C-contrast, U-contrast
NodeList children = node.getChildNodes();
if (children != null && children.getLength() > 0)
{
for (int i = 0; i < children.getLength(); i++)
{
Node child = children.item(i);
if (PowerConstants.TAG_ESSENCE_MATRIX.equals(child.getNodeName()))
{
EssenceMatrix essence = essenceMatrixFromDomNode(child);
params.setDesignEssence(essence);
}
else if (PowerConstants.TAG_MATRIX.equals(child.getNodeName()))
{
// get the name of this matrix
String matrixName = null;
NamedNodeMap matrixAttrs = child.getAttributes();
Node name = matrixAttrs.getNamedItem(PowerConstants.ATTR_NAME);
if (name != null) matrixName = name.getNodeValue();
// if we have a valid name, parse and save the matrix to the linear model parameters
if (matrixName != null && !matrixName.isEmpty())
{
RealMatrix matrix = matrixFromDomNode(child);
if (PowerConstants.MATRIX_TYPE_BETA.equals(matrixName))
params.setBeta(matrix);
else if (PowerConstants.MATRIX_TYPE_DESIGN.equals(matrixName))
params.setDesign(matrix);
else if (PowerConstants.MATRIX_TYPE_THETA.equals(matrixName))
params.setTheta(matrix);
else if (PowerConstants.MATRIX_TYPE_WITHIN_CONTRAST.equals(matrixName))
params.setWithinSubjectContrast(matrix);
else if (PowerConstants.MATRIX_TYPE_BETWEEN_CONTRAST.equals(matrixName))
params.setBetweenSubjectContrast(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_ERROR.equals(matrixName))
params.setSigmaError(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_GAUSSIAN.equals(matrixName))
params.setSigmaGaussianRandom(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_OUTCOME.equals(matrixName))
params.setSigmaOutcome(matrix);
else if (PowerConstants.MATRIX_TYPE_SIGMA_OUTCOME_GAUSSIAN.equals(matrixName))
params.setSigmaOutcomeGaussianRandom(matrix);
else
PowerLogger.getInstance().warn("Ignoring Invalid matrix: " + matrixName);
}
else
{
PowerLogger.getInstance().warn("Ignoring unnamed matrix");
}
}
else
{
PowerLogger.getInstance().warn("Ignoring unknown tag while parsing parameters: " + child.getNodeName());
}
}
}
return params;
}
|
diff --git a/biz/src/main/java/org/huamuzhen/oa/biz/FeedbackManager.java b/biz/src/main/java/org/huamuzhen/oa/biz/FeedbackManager.java
index 50e82fe..e31a0b3 100644
--- a/biz/src/main/java/org/huamuzhen/oa/biz/FeedbackManager.java
+++ b/biz/src/main/java/org/huamuzhen/oa/biz/FeedbackManager.java
@@ -1,132 +1,129 @@
package org.huamuzhen.oa.biz;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.huamuzhen.oa.domain.dao.FeedbackDAO;
import org.huamuzhen.oa.domain.dao.ReportFormDAO;
import org.huamuzhen.oa.domain.entity.Feedback;
import org.huamuzhen.oa.domain.entity.OrgUnit;
import org.huamuzhen.oa.domain.entity.ReportForm;
import org.huamuzhen.oa.domain.entity.User;
import org.huamuzhen.oa.domain.enumeration.Privilege;
import org.huamuzhen.oa.domain.enumeration.ReportFormStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class FeedbackManager extends BaseManager<Feedback, String> {
@Resource
private ReportFormDAO reportFormDAO;
@Resource
private FeedbackDAO feedbackDAO;
@Resource
public void setDao(FeedbackDAO dao) {
super.setDao(dao);
}
@Transactional
public Feedback add(String reportFormId, String content, String signature,
String orgUnitId, String owner, User currentUser, boolean agree, String currentReceiverId, String leader2Id) {
Feedback feedback = new Feedback();
feedback.setContent(content);
feedback.setSignature(signature);
feedback.setFeedBackTime(new Timestamp(System.currentTimeMillis()));
feedback.setReportFormId(reportFormId);
feedback.setAgree(agree);
ReportForm reportForm = reportFormDAO.findOne(reportFormId);
if(currentUser.getPrivilege() == Privilege.DEPARTMENT && null != orgUnitId){
feedback.setOwner(currentUser.getOrgUnit().getName());
feedback.setResponseOrgUnitId(currentUser.getOrgUnit().getId());
Feedback savedFeedback= this.saveAndFlush(feedback);;
if(!agree){
reportForm.setStatus(ReportFormStatus.DENIED);
}else{
if(checkIfAllRequiredOrgUnitsSendPositiveFeedback(reportForm)){
reportForm.setStatus(ReportFormStatus.GOT_REPLY_FROM_UNITS);
}
}
reportFormDAO.save(reportForm);
return savedFeedback;
}else if(currentUser.getPrivilege() == Privilege.LEADER1 && null != currentReceiverId && null != leader2Id){
feedback.setOwner(Privilege.LEADER1.toString());
Feedback savedFeedback = this.save(feedback);
if(!agree){
reportForm.setStatus(ReportFormStatus.DENIED);
}else{
reportForm.setCurrentReceiverId(leader2Id);
reportForm.setStatus(ReportFormStatus.SENT_TO_LEADER2);
}
reportFormDAO.save(reportForm);
return savedFeedback;
}else if(currentUser.getPrivilege() == Privilege.LEADER2 && null != currentReceiverId){
feedback.setOwner(Privilege.LEADER2.toString());
Feedback savedFeedback = this.save(feedback);
if(!agree){
reportForm.setStatus(ReportFormStatus.DENIED);
}else{
reportForm.setStatus(ReportFormStatus.SENT_TO_OFFICE);
}
reportFormDAO.save(reportForm);
return savedFeedback;
}else if(currentUser.getPrivilege() == Privilege.OFFICE){
feedback.setOwner(Privilege.OFFICE.toString());
- Feedback savedFeedback = this.save(feedback);
- if(!agree){
- reportForm.setStatus(ReportFormStatus.DENIED);
- }else{
- reportForm.setStatus(ReportFormStatus.PASSED);
- }
+ feedback.setAgree(true);
+ Feedback savedFeedback = this.save(feedback);
+ reportForm.setStatus(ReportFormStatus.PASSED);
reportFormDAO.save(reportForm);
return savedFeedback;
}
return null;
}
@Transactional
private boolean checkIfAllRequiredOrgUnitsSendPositiveFeedback(ReportForm reportForm) {
Set<OrgUnit> requiredOrgUnits = reportForm.getReportFormType().getRequiredOrgUnits();
List<Feedback> feedbackList = feedbackDAO.findFeedbackByReportFormId(reportForm.getId());
List<String> requiredOrgUnitIdList = new ArrayList<String>();
for(OrgUnit requiredOrgUnit : requiredOrgUnits){
requiredOrgUnitIdList.add(requiredOrgUnit.getId());
}
for(OrgUnit requiredOrgUnit : requiredOrgUnits){
for(Feedback feedback : feedbackList){
if(!feedback.isAgree()){
return false;
}
if(feedback.getResponseOrgUnitId().equals(requiredOrgUnit.getId())){
requiredOrgUnitIdList.remove(feedback.getResponseOrgUnitId());
}
}
}
if(requiredOrgUnitIdList.size() == 0){
return true;
}
return false;
}
@Transactional
public boolean checkIfOrgUnitFeedbackIsAlreadyExists(OrgUnit orgUnit){
if(feedbackDAO.findFeedbackByResponseOrgUnitId(orgUnit.getId()).size() > 0){
return true;
}
return false;
}
}
| true | true | public Feedback add(String reportFormId, String content, String signature,
String orgUnitId, String owner, User currentUser, boolean agree, String currentReceiverId, String leader2Id) {
Feedback feedback = new Feedback();
feedback.setContent(content);
feedback.setSignature(signature);
feedback.setFeedBackTime(new Timestamp(System.currentTimeMillis()));
feedback.setReportFormId(reportFormId);
feedback.setAgree(agree);
ReportForm reportForm = reportFormDAO.findOne(reportFormId);
if(currentUser.getPrivilege() == Privilege.DEPARTMENT && null != orgUnitId){
feedback.setOwner(currentUser.getOrgUnit().getName());
feedback.setResponseOrgUnitId(currentUser.getOrgUnit().getId());
Feedback savedFeedback= this.saveAndFlush(feedback);;
if(!agree){
reportForm.setStatus(ReportFormStatus.DENIED);
}else{
if(checkIfAllRequiredOrgUnitsSendPositiveFeedback(reportForm)){
reportForm.setStatus(ReportFormStatus.GOT_REPLY_FROM_UNITS);
}
}
reportFormDAO.save(reportForm);
return savedFeedback;
}else if(currentUser.getPrivilege() == Privilege.LEADER1 && null != currentReceiverId && null != leader2Id){
feedback.setOwner(Privilege.LEADER1.toString());
Feedback savedFeedback = this.save(feedback);
if(!agree){
reportForm.setStatus(ReportFormStatus.DENIED);
}else{
reportForm.setCurrentReceiverId(leader2Id);
reportForm.setStatus(ReportFormStatus.SENT_TO_LEADER2);
}
reportFormDAO.save(reportForm);
return savedFeedback;
}else if(currentUser.getPrivilege() == Privilege.LEADER2 && null != currentReceiverId){
feedback.setOwner(Privilege.LEADER2.toString());
Feedback savedFeedback = this.save(feedback);
if(!agree){
reportForm.setStatus(ReportFormStatus.DENIED);
}else{
reportForm.setStatus(ReportFormStatus.SENT_TO_OFFICE);
}
reportFormDAO.save(reportForm);
return savedFeedback;
}else if(currentUser.getPrivilege() == Privilege.OFFICE){
feedback.setOwner(Privilege.OFFICE.toString());
Feedback savedFeedback = this.save(feedback);
if(!agree){
reportForm.setStatus(ReportFormStatus.DENIED);
}else{
reportForm.setStatus(ReportFormStatus.PASSED);
}
reportFormDAO.save(reportForm);
return savedFeedback;
}
return null;
}
| public Feedback add(String reportFormId, String content, String signature,
String orgUnitId, String owner, User currentUser, boolean agree, String currentReceiverId, String leader2Id) {
Feedback feedback = new Feedback();
feedback.setContent(content);
feedback.setSignature(signature);
feedback.setFeedBackTime(new Timestamp(System.currentTimeMillis()));
feedback.setReportFormId(reportFormId);
feedback.setAgree(agree);
ReportForm reportForm = reportFormDAO.findOne(reportFormId);
if(currentUser.getPrivilege() == Privilege.DEPARTMENT && null != orgUnitId){
feedback.setOwner(currentUser.getOrgUnit().getName());
feedback.setResponseOrgUnitId(currentUser.getOrgUnit().getId());
Feedback savedFeedback= this.saveAndFlush(feedback);;
if(!agree){
reportForm.setStatus(ReportFormStatus.DENIED);
}else{
if(checkIfAllRequiredOrgUnitsSendPositiveFeedback(reportForm)){
reportForm.setStatus(ReportFormStatus.GOT_REPLY_FROM_UNITS);
}
}
reportFormDAO.save(reportForm);
return savedFeedback;
}else if(currentUser.getPrivilege() == Privilege.LEADER1 && null != currentReceiverId && null != leader2Id){
feedback.setOwner(Privilege.LEADER1.toString());
Feedback savedFeedback = this.save(feedback);
if(!agree){
reportForm.setStatus(ReportFormStatus.DENIED);
}else{
reportForm.setCurrentReceiverId(leader2Id);
reportForm.setStatus(ReportFormStatus.SENT_TO_LEADER2);
}
reportFormDAO.save(reportForm);
return savedFeedback;
}else if(currentUser.getPrivilege() == Privilege.LEADER2 && null != currentReceiverId){
feedback.setOwner(Privilege.LEADER2.toString());
Feedback savedFeedback = this.save(feedback);
if(!agree){
reportForm.setStatus(ReportFormStatus.DENIED);
}else{
reportForm.setStatus(ReportFormStatus.SENT_TO_OFFICE);
}
reportFormDAO.save(reportForm);
return savedFeedback;
}else if(currentUser.getPrivilege() == Privilege.OFFICE){
feedback.setOwner(Privilege.OFFICE.toString());
feedback.setAgree(true);
Feedback savedFeedback = this.save(feedback);
reportForm.setStatus(ReportFormStatus.PASSED);
reportFormDAO.save(reportForm);
return savedFeedback;
}
return null;
}
|
diff --git a/modules/extension/xsd/xsd-gml3/src/main/java/org/geotools/gml3/bindings/ComplexSupportXSAnyTypeBinding.java b/modules/extension/xsd/xsd-gml3/src/main/java/org/geotools/gml3/bindings/ComplexSupportXSAnyTypeBinding.java
index 29c2577f6..dc3bffceb 100644
--- a/modules/extension/xsd/xsd-gml3/src/main/java/org/geotools/gml3/bindings/ComplexSupportXSAnyTypeBinding.java
+++ b/modules/extension/xsd/xsd-gml3/src/main/java/org/geotools/gml3/bindings/ComplexSupportXSAnyTypeBinding.java
@@ -1,267 +1,269 @@
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2004-2009, Open Source Geospatial Foundation (OSGeo)
*
* 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;
* version 2.1 of the License.
*
* 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.
*/
package org.geotools.gml3.bindings;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import org.eclipse.xsd.XSDElementDeclaration;
import org.eclipse.xsd.XSDFactory;
import org.eclipse.xsd.XSDParticle;
import org.eclipse.xsd.XSDTypeDefinition;
import org.geotools.feature.NameImpl;
import org.geotools.feature.type.FeatureTypeImpl;
import org.geotools.gml3.XSDIdRegistry;
import org.geotools.util.Converters;
import org.geotools.xlink.XLINK;
import org.geotools.xml.Schemas;
import org.geotools.xs.XS;
import org.geotools.xs.bindings.XSAnyTypeBinding;
import org.opengis.feature.Attribute;
import org.opengis.feature.ComplexAttribute;
import org.opengis.feature.Property;
import org.opengis.feature.type.Name;
import org.opengis.feature.type.PropertyDescriptor;
import org.opengis.filter.identity.Identifier;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
/**
* A replacement for {@link XSAnyTypeBinding} that adds support for {@link ComplexAttribute} and
* related behaviours.
*
* <p>
*
* This binding that searches the substitution group of XSD element children to find properties of a
* complex attribute. This is necessary to support the GML property type pattern, in which a
* property (a property-type type) contains a property that is a member of a substitution group.
* gml:AttributeType is the canonical example of the property type pattern.
*
* <p>
*
* gml:FeaturePropertyType is an example of the property type pattern that has an explicit binding
* {@link FeaturePropertyTypeBinding}, but because an application schema may define more property
* types whose names are not known at compile time, a binding like
* {@link FeaturePropertyTypeBinding} cannot be written. This class exists to handle these
* application-schema-defined property types.
*
* <p>
*
* This class supports the encoding of XML complexType with simpleContent through extraction of a
* simpleContent property, as well as encoding XML attributes stored in the UserData map.
*
* @author Ben Caradoc-Davies, CSIRO Earth Science and Resource Engineering
*/
public class ComplexSupportXSAnyTypeBinding extends XSAnyTypeBinding {
private XSDIdRegistry idSet;
public ComplexSupportXSAnyTypeBinding(XSDIdRegistry idRegistry) {
this.idSet = idRegistry;
}
/**
* @see org.geotools.xml.AbstractComplexBinding#getProperty(java.lang.Object,
* javax.xml.namespace.QName)
*/
@Override
public Object getProperty(Object object, QName name) throws Exception {
if (object instanceof ComplexAttribute) {
ComplexAttribute complex = (ComplexAttribute) object;
Property property = complex.getProperty(toTypeName(name));
if (property != null && !(property instanceof ComplexAttribute)) {
return property.getValue();
}
}
return null;
}
/**
* Convert a {@link QName} to a {@link Name}.
*
* @param name
* @return
*/
private static Name toTypeName(QName name) {
if (XMLConstants.NULL_NS_URI.equals(name.getNamespaceURI())) {
return new NameImpl(name.getLocalPart());
} else {
return new NameImpl(name.getNamespaceURI(), name.getLocalPart());
}
}
/**
* @see org.geotools.xml.AbstractComplexBinding#getProperties(java.lang.Object,
* org.eclipse.xsd.XSDElementDeclaration)
*/
@SuppressWarnings("unchecked")
@Override
public List getProperties(Object object, XSDElementDeclaration element) throws Exception {
List<Object[/* 2 */]> properties = new ArrayList<Object[/* 2 */]>();
XSDTypeDefinition typeDef = element.getTypeDefinition();
boolean isAnyType = typeDef.getName() != null && typeDef.getTargetNamespace() != null
&& typeDef.getName().equals(XS.ANYTYPE.getLocalPart())
&& typeDef.getTargetNamespace().equals(XS.NAMESPACE);
if (isAnyType) {
Collection complexAtts;
if (object instanceof Collection) {
// collection of features
complexAtts = (Collection) object;
} else if (object instanceof ComplexAttribute) {
// get collection of features from this attribute
complexAtts = ((ComplexAttribute) object).getProperties();
} else {
return null;
}
for (Object complex : complexAtts) {
if (complex instanceof ComplexAttribute) {
PropertyDescriptor descriptor = ((Attribute) complex).getDescriptor();
if (descriptor.getUserData() != null) {
Object propertyElement = descriptor.getUserData().get(
XSDElementDeclaration.class);
if (propertyElement != null
&& propertyElement instanceof XSDElementDeclaration) {
XSDParticle substitutedChildParticle = XSDFactory.eINSTANCE
.createXSDParticle();
substitutedChildParticle.setMaxOccurs(descriptor.getMaxOccurs());
substitutedChildParticle.setMinOccurs(descriptor.getMinOccurs());
XSDElementDeclaration wrapper = XSDFactory.eINSTANCE
.createXSDElementDeclaration();
wrapper
.setResolvedElementDeclaration((XSDElementDeclaration) propertyElement);
substitutedChildParticle.setContent(wrapper);
properties.add(new Object[] { substitutedChildParticle, complex });
}
}
}
}
return properties;
}
if (object instanceof ComplexAttribute) {
ComplexAttribute complex = (ComplexAttribute) object;
for (XSDParticle childParticle : (List<XSDParticle>) Schemas.getChildElementParticles(
element.getTypeDefinition(), true)) {
XSDElementDeclaration childElement = (XSDElementDeclaration) childParticle
.getContent();
if (childElement.isElementDeclarationReference()) {
childElement = childElement.getResolvedElementDeclaration();
}
for (XSDElementDeclaration e : (List<XSDElementDeclaration>) childElement
.getSubstitutionGroup()) {
Name name = new NameImpl(e.getTargetNamespace(), e.getName());
Collection<Property> nameProperties = complex.getProperties(name);
if (!nameProperties.isEmpty()) {
// Particle creation stolen from BindingPropertyExtractor.
// I do not know why a wrapper is required; monkey see, monkey do.
// Without the wrapper, get an NPE in BindingPropertyExtractor.
XSDParticle substitutedChildParticle = XSDFactory.eINSTANCE
.createXSDParticle();
substitutedChildParticle.setMaxOccurs(childParticle.getMaxOccurs());
substitutedChildParticle.setMinOccurs(childParticle.getMinOccurs());
XSDElementDeclaration wrapper = XSDFactory.eINSTANCE
.createXSDElementDeclaration();
wrapper.setResolvedElementDeclaration(e);
substitutedChildParticle.setContent(wrapper);
for (Property property : nameProperties) {
+ /*
+ * Note : Returning simple feature value is not necessary as it has been
+ * taken care in the 1st For Loop of BindingPropertyExtractor.java -
+ * List properties(Object, XSDElementDeclaration) method
+ */
if (property instanceof ComplexAttribute) {
properties.add(new Object[] { substitutedChildParticle, property });
- } else {
- properties.add(new Object[] { substitutedChildParticle,
- property.getValue() });
}
}
}
}
}
return properties;
}
return null;
}
/**
* Check if the complex attribute contains a feature which id is pre-existing in the document.
* If it's true, make sure it's only encoded as an xlink:href to the existing id.
*
* @param value
* The complex attribute value
* @param att
* The complex attribute itself
*/
private void checkXlinkHref(Object value, ComplexAttribute att) {
if (value != null && value instanceof ComplexAttribute) {
ComplexAttribute object = (ComplexAttribute) value;
// Only worry about features for now, as non feature types don't get ids encoded yet.
// See GEOS-3738. To encode xlink:href to an id that doesn't exist in the doc is wrong
if (!(object.getType() instanceof FeatureTypeImpl)) {
// we are checking the type, not the object as FeatureImpl, because they could still
// be non-features that are constructed as features for the purpose of feature
// chaining.
return;
}
Identifier ident = object.getIdentifier();
if (ident == null) {
return;
}
String id = Converters.convert(ident.getID(), String.class);
if (idSet.idExists(id)) {
// XSD type ids can only appear once in the same document, otherwise the document is
// not schema valid. Attributes of the same ids should be encoded as xlink:href to
// the existing attribute.
Object clientProperties = att.getUserData().get(Attributes.class);
Map<Name, Object> map = null;
if (clientProperties == null) {
map = new HashMap<Name, Object>();
att.getUserData().put(Attributes.class, map);
} else {
map = (Map<Name, Object>) clientProperties;
}
map.put(toTypeName(XLINK.HREF), "#" + id.toString());
// make sure the value is not encoded
att.setValue(Collections.emptyList());
}
}
return;
}
/**
* @see org.geotools.xml.AbstractComplexBinding#encode(java.lang.Object, org.w3c.dom.Document,
* org.w3c.dom.Element)
*/
@Override
public Element encode(Object object, Document document, Element value) throws Exception {
if (object instanceof ComplexAttribute) {
ComplexAttribute complex = (ComplexAttribute) object;
if (complex.getProperties().size() == 1) {
Property prop = complex.getProperties().iterator().next();
checkXlinkHref(prop, complex);
}
GML3EncodingUtils.encodeClientProperties(complex, value);
GML3EncodingUtils.encodeSimpleContent(complex, document, value);
}
return value;
}
}
| false | true | public List getProperties(Object object, XSDElementDeclaration element) throws Exception {
List<Object[/* 2 */]> properties = new ArrayList<Object[/* 2 */]>();
XSDTypeDefinition typeDef = element.getTypeDefinition();
boolean isAnyType = typeDef.getName() != null && typeDef.getTargetNamespace() != null
&& typeDef.getName().equals(XS.ANYTYPE.getLocalPart())
&& typeDef.getTargetNamespace().equals(XS.NAMESPACE);
if (isAnyType) {
Collection complexAtts;
if (object instanceof Collection) {
// collection of features
complexAtts = (Collection) object;
} else if (object instanceof ComplexAttribute) {
// get collection of features from this attribute
complexAtts = ((ComplexAttribute) object).getProperties();
} else {
return null;
}
for (Object complex : complexAtts) {
if (complex instanceof ComplexAttribute) {
PropertyDescriptor descriptor = ((Attribute) complex).getDescriptor();
if (descriptor.getUserData() != null) {
Object propertyElement = descriptor.getUserData().get(
XSDElementDeclaration.class);
if (propertyElement != null
&& propertyElement instanceof XSDElementDeclaration) {
XSDParticle substitutedChildParticle = XSDFactory.eINSTANCE
.createXSDParticle();
substitutedChildParticle.setMaxOccurs(descriptor.getMaxOccurs());
substitutedChildParticle.setMinOccurs(descriptor.getMinOccurs());
XSDElementDeclaration wrapper = XSDFactory.eINSTANCE
.createXSDElementDeclaration();
wrapper
.setResolvedElementDeclaration((XSDElementDeclaration) propertyElement);
substitutedChildParticle.setContent(wrapper);
properties.add(new Object[] { substitutedChildParticle, complex });
}
}
}
}
return properties;
}
if (object instanceof ComplexAttribute) {
ComplexAttribute complex = (ComplexAttribute) object;
for (XSDParticle childParticle : (List<XSDParticle>) Schemas.getChildElementParticles(
element.getTypeDefinition(), true)) {
XSDElementDeclaration childElement = (XSDElementDeclaration) childParticle
.getContent();
if (childElement.isElementDeclarationReference()) {
childElement = childElement.getResolvedElementDeclaration();
}
for (XSDElementDeclaration e : (List<XSDElementDeclaration>) childElement
.getSubstitutionGroup()) {
Name name = new NameImpl(e.getTargetNamespace(), e.getName());
Collection<Property> nameProperties = complex.getProperties(name);
if (!nameProperties.isEmpty()) {
// Particle creation stolen from BindingPropertyExtractor.
// I do not know why a wrapper is required; monkey see, monkey do.
// Without the wrapper, get an NPE in BindingPropertyExtractor.
XSDParticle substitutedChildParticle = XSDFactory.eINSTANCE
.createXSDParticle();
substitutedChildParticle.setMaxOccurs(childParticle.getMaxOccurs());
substitutedChildParticle.setMinOccurs(childParticle.getMinOccurs());
XSDElementDeclaration wrapper = XSDFactory.eINSTANCE
.createXSDElementDeclaration();
wrapper.setResolvedElementDeclaration(e);
substitutedChildParticle.setContent(wrapper);
for (Property property : nameProperties) {
if (property instanceof ComplexAttribute) {
properties.add(new Object[] { substitutedChildParticle, property });
} else {
properties.add(new Object[] { substitutedChildParticle,
property.getValue() });
}
}
}
}
}
return properties;
}
return null;
}
| public List getProperties(Object object, XSDElementDeclaration element) throws Exception {
List<Object[/* 2 */]> properties = new ArrayList<Object[/* 2 */]>();
XSDTypeDefinition typeDef = element.getTypeDefinition();
boolean isAnyType = typeDef.getName() != null && typeDef.getTargetNamespace() != null
&& typeDef.getName().equals(XS.ANYTYPE.getLocalPart())
&& typeDef.getTargetNamespace().equals(XS.NAMESPACE);
if (isAnyType) {
Collection complexAtts;
if (object instanceof Collection) {
// collection of features
complexAtts = (Collection) object;
} else if (object instanceof ComplexAttribute) {
// get collection of features from this attribute
complexAtts = ((ComplexAttribute) object).getProperties();
} else {
return null;
}
for (Object complex : complexAtts) {
if (complex instanceof ComplexAttribute) {
PropertyDescriptor descriptor = ((Attribute) complex).getDescriptor();
if (descriptor.getUserData() != null) {
Object propertyElement = descriptor.getUserData().get(
XSDElementDeclaration.class);
if (propertyElement != null
&& propertyElement instanceof XSDElementDeclaration) {
XSDParticle substitutedChildParticle = XSDFactory.eINSTANCE
.createXSDParticle();
substitutedChildParticle.setMaxOccurs(descriptor.getMaxOccurs());
substitutedChildParticle.setMinOccurs(descriptor.getMinOccurs());
XSDElementDeclaration wrapper = XSDFactory.eINSTANCE
.createXSDElementDeclaration();
wrapper
.setResolvedElementDeclaration((XSDElementDeclaration) propertyElement);
substitutedChildParticle.setContent(wrapper);
properties.add(new Object[] { substitutedChildParticle, complex });
}
}
}
}
return properties;
}
if (object instanceof ComplexAttribute) {
ComplexAttribute complex = (ComplexAttribute) object;
for (XSDParticle childParticle : (List<XSDParticle>) Schemas.getChildElementParticles(
element.getTypeDefinition(), true)) {
XSDElementDeclaration childElement = (XSDElementDeclaration) childParticle
.getContent();
if (childElement.isElementDeclarationReference()) {
childElement = childElement.getResolvedElementDeclaration();
}
for (XSDElementDeclaration e : (List<XSDElementDeclaration>) childElement
.getSubstitutionGroup()) {
Name name = new NameImpl(e.getTargetNamespace(), e.getName());
Collection<Property> nameProperties = complex.getProperties(name);
if (!nameProperties.isEmpty()) {
// Particle creation stolen from BindingPropertyExtractor.
// I do not know why a wrapper is required; monkey see, monkey do.
// Without the wrapper, get an NPE in BindingPropertyExtractor.
XSDParticle substitutedChildParticle = XSDFactory.eINSTANCE
.createXSDParticle();
substitutedChildParticle.setMaxOccurs(childParticle.getMaxOccurs());
substitutedChildParticle.setMinOccurs(childParticle.getMinOccurs());
XSDElementDeclaration wrapper = XSDFactory.eINSTANCE
.createXSDElementDeclaration();
wrapper.setResolvedElementDeclaration(e);
substitutedChildParticle.setContent(wrapper);
for (Property property : nameProperties) {
/*
* Note : Returning simple feature value is not necessary as it has been
* taken care in the 1st For Loop of BindingPropertyExtractor.java -
* List properties(Object, XSDElementDeclaration) method
*/
if (property instanceof ComplexAttribute) {
properties.add(new Object[] { substitutedChildParticle, property });
}
}
}
}
}
return properties;
}
return null;
}
|
diff --git a/src/testharness/TestCase.java b/src/testharness/TestCase.java
index ef2183a..017b7f4 100644
--- a/src/testharness/TestCase.java
+++ b/src/testharness/TestCase.java
@@ -1,18 +1,18 @@
/**
* Created: Mar 28, 2011 10:56:01 PM
*
*/
public class TestCase {
private org.apache.hadoop.util.Tool tool;
private String [] args;
- TestCase(org.apache.hadoop.util.Tool tool, String args) {
+ TestCase(org.apache.hadoop.util.Tool tool, String[] args) {
this.tool = tool;
this.args = args;
}
void runTest(PropertyCycle pc) throws Exception{
pc.run(tool, args);
}
}
| true | true | TestCase(org.apache.hadoop.util.Tool tool, String args) {
this.tool = tool;
this.args = args;
}
| TestCase(org.apache.hadoop.util.Tool tool, String[] args) {
this.tool = tool;
this.args = args;
}
|
diff --git a/servlet/src/test/java/io/undertow/servlet/test/multipart/MultiPartTestCase.java b/servlet/src/test/java/io/undertow/servlet/test/multipart/MultiPartTestCase.java
index ceabbfd27..0f901f48e 100644
--- a/servlet/src/test/java/io/undertow/servlet/test/multipart/MultiPartTestCase.java
+++ b/servlet/src/test/java/io/undertow/servlet/test/multipart/MultiPartTestCase.java
@@ -1,163 +1,163 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 io.undertow.servlet.test.multipart;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import javax.servlet.ServletException;
import io.undertow.servlet.test.util.DeploymentUtils;
import io.undertow.testutils.DefaultServer;
import io.undertow.testutils.HttpClientUtils;
import io.undertow.testutils.TestHttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import static io.undertow.servlet.Servlets.multipartConfig;
import static io.undertow.servlet.Servlets.servlet;
/**
* @author Stuart Douglas
*/
@RunWith(DefaultServer.class)
public class MultiPartTestCase {
@BeforeClass
public static void setup() throws ServletException {
DeploymentUtils.setupServlet(
servlet("mp0", MultiPartServlet.class)
.addMapping("/0"),
servlet("mp1", MultiPartServlet.class)
.addMapping("/1")
.setMultipartConfig(multipartConfig(null, 0, 0, 0)),
servlet("mp2", MultiPartServlet.class)
.addMapping("/2")
.setMultipartConfig(multipartConfig(null, 0, 3, 0)),
servlet("mp3", MultiPartServlet.class)
.addMapping("/3")
.setMultipartConfig(multipartConfig(null, 3, 0, 0)));
}
@Test
public void testMultiPartRequestWithNoMultipartConfig() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
String uri = DefaultServer.getDefaultServerURL() + "/servletContext/0";
HttpPost post = new HttpPost(uri);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("formValue", new StringBody("myValue", "text/plain", Charset.forName("UTF-8")));
entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));
post.setEntity(entity);
HttpResponse result = client.execute(post);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
final String response = HttpClientUtils.readResponse(result);
Assert.assertEquals("PARAMS:\n", response);
} finally {
client.getConnectionManager().shutdown();
}
}
@Test
public void testMultiPartRequest() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
String uri = DefaultServer.getDefaultServerURL() + "/servletContext/1";
HttpPost post = new HttpPost(uri);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("formValue", new StringBody("myValue", "text/plain", Charset.forName("UTF-8")));
entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));
post.setEntity(entity);
HttpResponse result = client.execute(post);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
final String response = HttpClientUtils.readResponse(result);
Assert.assertEquals("PARAMS:\n" +
"name: formValue\n" +
"filename: null\n" +
"content-type: null\n" +
"Content-Disposition: form-data; name=\"formValue\"\n" +
"size: 7\n" +
"content: myValue\n" +
"name: file\n" +
"filename: uploadfile.txt\n" +
"content-type: null\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n" +
- "size: 14\n" +
- "content: file contents\n\n", response);
+ "size: 13\n" +
+ "content: file contents\n", response);
} finally {
client.getConnectionManager().shutdown();
}
}
@Test
public void testMultiPartRequestToLarge() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
String uri = DefaultServer.getDefaultServerURL() + "/servletContext/2";
HttpPost post = new HttpPost(uri);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("formValue", new StringBody("myValue", "text/plain", Charset.forName("UTF-8")));
entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));
post.setEntity(entity);
HttpResponse result = client.execute(post);
Assert.assertEquals(500, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
} catch (IOException expected) {
//in some environments the forced close of the read side will cause a connection reset
}finally {
client.getConnectionManager().shutdown();
}
}
@Test
public void testMultiPartIndividualFileToLarge() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
String uri = DefaultServer.getDefaultServerURL() + "/servletContext/3";
HttpPost post = new HttpPost(uri);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("formValue", new StringBody("myValue", "text/plain", Charset.forName("UTF-8")));
entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));
post.setEntity(entity);
HttpResponse result = client.execute(post);
String response = HttpClientUtils.readResponse(result);
Assert.assertEquals("TEST FAILED: wrong response code\n" + response, 500, result.getStatusLine().getStatusCode());
} finally {
client.getConnectionManager().shutdown();
}
}
}
| true | true | public void testMultiPartRequest() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
String uri = DefaultServer.getDefaultServerURL() + "/servletContext/1";
HttpPost post = new HttpPost(uri);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("formValue", new StringBody("myValue", "text/plain", Charset.forName("UTF-8")));
entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));
post.setEntity(entity);
HttpResponse result = client.execute(post);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
final String response = HttpClientUtils.readResponse(result);
Assert.assertEquals("PARAMS:\n" +
"name: formValue\n" +
"filename: null\n" +
"content-type: null\n" +
"Content-Disposition: form-data; name=\"formValue\"\n" +
"size: 7\n" +
"content: myValue\n" +
"name: file\n" +
"filename: uploadfile.txt\n" +
"content-type: null\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n" +
"size: 14\n" +
"content: file contents\n\n", response);
} finally {
client.getConnectionManager().shutdown();
}
}
| public void testMultiPartRequest() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
String uri = DefaultServer.getDefaultServerURL() + "/servletContext/1";
HttpPost post = new HttpPost(uri);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("formValue", new StringBody("myValue", "text/plain", Charset.forName("UTF-8")));
entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));
post.setEntity(entity);
HttpResponse result = client.execute(post);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
final String response = HttpClientUtils.readResponse(result);
Assert.assertEquals("PARAMS:\n" +
"name: formValue\n" +
"filename: null\n" +
"content-type: null\n" +
"Content-Disposition: form-data; name=\"formValue\"\n" +
"size: 7\n" +
"content: myValue\n" +
"name: file\n" +
"filename: uploadfile.txt\n" +
"content-type: null\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n" +
"size: 13\n" +
"content: file contents\n", response);
} finally {
client.getConnectionManager().shutdown();
}
}
|
diff --git a/main/src/main/java/com/bloatit/web/html/pages/IdeasList.java b/main/src/main/java/com/bloatit/web/html/pages/IdeasList.java
index 0a39827d6..08711bfe6 100644
--- a/main/src/main/java/com/bloatit/web/html/pages/IdeasList.java
+++ b/main/src/main/java/com/bloatit/web/html/pages/IdeasList.java
@@ -1,229 +1,229 @@
/*
* Copyright (C) 2010 BloatIt. This file is part of BloatIt. BloatIt is free software: you
* can redistribute it and/or modify it under the terms of the GNU Affero General Public
* License as published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version. BloatIt is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details. You should have received a copy of the GNU Affero General
* Public License along with BloatIt. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bloatit.web.html.pages;
//import java.util.Random;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import com.bloatit.common.Image;
import com.bloatit.common.PageIterable;
import com.bloatit.framework.Demand;
import com.bloatit.framework.Translation;
import com.bloatit.framework.managers.DemandManager;
import com.bloatit.web.annotations.PageComponent;
import com.bloatit.web.annotations.ParamContainer;
import com.bloatit.web.exceptions.RedirectException;
import com.bloatit.web.html.HtmlNode;
import com.bloatit.web.html.components.custom.HtmlPagedList;
import com.bloatit.web.html.components.custom.HtmlProgressBar;
import com.bloatit.web.html.components.standard.HtmlDiv;
import com.bloatit.web.html.components.standard.HtmlGenericElement;
import com.bloatit.web.html.components.standard.HtmlImage;
import com.bloatit.web.html.components.standard.HtmlLink;
import com.bloatit.web.html.components.standard.HtmlParagraph;
import com.bloatit.web.html.components.standard.HtmlRenderer;
import com.bloatit.web.html.components.standard.HtmlTitleBlock;
import com.bloatit.web.html.pages.master.Page;
import com.bloatit.web.server.Context;
import com.bloatit.web.server.Session;
import com.bloatit.web.utils.i18n.CurrencyLocale;
import com.bloatit.web.utils.url.IdeaPageUrl;
import com.bloatit.web.utils.url.IdeasListUrl;
import com.bloatit.web.utils.url.OfferPageUrl;
@ParamContainer("ideas/list")
public class IdeasList extends Page {
@PageComponent
HtmlPagedList<Demand> pagedIdeaList;
private final IdeasListUrl url;
public IdeasList(final IdeasListUrl url) throws RedirectException {
super(url);
this.url = url;
generateContent();
}
private void generateContent() {
final HtmlTitleBlock pageTitle = new HtmlTitleBlock(Context.tr("Ideas list"), 1);
final PageIterable<Demand> ideaList = DemandManager.getDemands();
final HtmlRenderer<Demand> demandItemRenderer = new IdeasListItem();
final IdeasListUrl clonedUrl = url.clone();
pagedIdeaList = new HtmlPagedList<Demand>(demandItemRenderer, ideaList, clonedUrl, clonedUrl.getPagedIdeaListUrl());
pageTitle.add(pagedIdeaList);
add(pageTitle);
}
@Override
public String getTitle() {
return "View all ideas - search ideas";
}
@Override
public boolean isStable() {
return true;
}
@Override
protected String getCustomCss() {
return "ideas-list.css";
}
static class IdeasListItem implements HtmlRenderer<Demand> {
private Demand idea;
@Override
public HtmlNode generate(final Demand idea) {
this.idea = idea;
return generateContent();
}
private HtmlNode generateContent() {
final HtmlDiv ideaBlock = new HtmlDiv("idea_summary");
{
final HtmlDiv leftBlock = new HtmlDiv("idea_summary_left");
{
final HtmlDiv karmaBlock = new HtmlDiv("idea_karma");
karmaBlock.add(new HtmlParagraph("" + idea.getPopularity()));
leftBlock.add(karmaBlock);
}
// ideaLinkBlock.add(leftBlock);
ideaBlock.add(leftBlock);
final HtmlDiv centerBlock = new HtmlDiv("idea_summary_center");
{
HtmlGenericElement project = new HtmlGenericElement("span");
project.setCssClass("project");
project.addText("VLC");
final HtmlLink linkTitle = new IdeaPageUrl(idea).getHtmlLink("");
linkTitle.setCssClass("idea_link");
linkTitle.add(project);
linkTitle.addText(" - ");
linkTitle.addText(idea.getTitle());
final HtmlTitleBlock ideaTitle = new HtmlTitleBlock(linkTitle, 3);
{
final Session session = Context.getSession();
- final Locale defaultLocale = session.getLocale();
+ final Locale defaultLocale = Context.getLocalizator().getLocale();
final Translation translatedDescription = idea.getDescription().getTranslationOrDefault(defaultLocale);
String shortDescription = translatedDescription.getText();
if(shortDescription.length() > 144) {
shortDescription = shortDescription.substring(0, 143) + " ...";
}
final HtmlLink linkText = new IdeaPageUrl(idea).getHtmlLink(shortDescription);
linkText.setCssClass("idea_link_text");
ideaTitle.add(linkText);
float progressValue = (float) Math.floor(idea.getProgression());
float cappedProgressValue = progressValue;
if (cappedProgressValue > 100) {
cappedProgressValue = 100;
}
final HtmlProgressBar progressBar = new HtmlProgressBar(cappedProgressValue);
ideaTitle.add(progressBar);
if (idea.getCurrentOffer() == null) {
HtmlGenericElement amount = new HtmlGenericElement("span");
amount.setCssClass("important");
CurrencyLocale currency = new CurrencyLocale(idea.getContribution(), Context.getLocalizator().getLocale());
amount.addText(currency.getDefaultString());
final HtmlParagraph progressText = new HtmlParagraph();
progressText.setCssClass("idea_progress_text");
progressText.add(amount);
progressText.addText(Context.tr(" no offer ("));
progressText.add(new OfferPageUrl(idea).getHtmlLink(Context.tr("make an offer")));
progressText.addText(Context.tr(")"));
ideaTitle.add(progressText);
} else {
// Amount
CurrencyLocale amountCurrency = new CurrencyLocale(idea.getContribution(), Context.getLocalizator().getLocale());
HtmlGenericElement amount = new HtmlGenericElement("span");
amount.setCssClass("important");
amount.addText(amountCurrency.getDefaultString());
// Target
CurrencyLocale targetCurrency = new CurrencyLocale(idea.getCurrentOffer().getAmount() , Context.getLocalizator().getLocale());
HtmlGenericElement target = new HtmlGenericElement("span");
target.setCssClass("important");
target.addText(targetCurrency.getDefaultString());
// Progress
HtmlGenericElement progress = new HtmlGenericElement("span");
progress.setCssClass("important");
NumberFormat format = NumberFormat.getNumberInstance();
format.setMinimumFractionDigits(0);
progress.addText("" + format.format(progressValue) + " %");
final HtmlParagraph progressText = new HtmlParagraph();
progressText.setCssClass("idea_progress_text");
progressText.add(amount);
progressText.addText(Context.tr(" i.e. "));
progressText.add(progress);
progressText.addText(Context.tr(" of "));
progressText.add(target);
progressText.addText(Context.tr(" requested "));
ideaTitle.add(progressText);
}
}
centerBlock.add(ideaTitle);
}
// ideaLinkBlock.add(centerBlock);
ideaBlock.add(centerBlock);
final HtmlDiv rightBlock = new HtmlDiv("idea_summary_right");
{
rightBlock.add(new HtmlImage(new Image("/resources/img/idea.png", Image.ImageType.DISTANT)));
}
// ideaLinkBlock.add(rightBlock);
ideaBlock.add(rightBlock);
}
return ideaBlock;
}
};
}
| true | true | private HtmlNode generateContent() {
final HtmlDiv ideaBlock = new HtmlDiv("idea_summary");
{
final HtmlDiv leftBlock = new HtmlDiv("idea_summary_left");
{
final HtmlDiv karmaBlock = new HtmlDiv("idea_karma");
karmaBlock.add(new HtmlParagraph("" + idea.getPopularity()));
leftBlock.add(karmaBlock);
}
// ideaLinkBlock.add(leftBlock);
ideaBlock.add(leftBlock);
final HtmlDiv centerBlock = new HtmlDiv("idea_summary_center");
{
HtmlGenericElement project = new HtmlGenericElement("span");
project.setCssClass("project");
project.addText("VLC");
final HtmlLink linkTitle = new IdeaPageUrl(idea).getHtmlLink("");
linkTitle.setCssClass("idea_link");
linkTitle.add(project);
linkTitle.addText(" - ");
linkTitle.addText(idea.getTitle());
final HtmlTitleBlock ideaTitle = new HtmlTitleBlock(linkTitle, 3);
{
final Session session = Context.getSession();
final Locale defaultLocale = session.getLocale();
final Translation translatedDescription = idea.getDescription().getTranslationOrDefault(defaultLocale);
String shortDescription = translatedDescription.getText();
if(shortDescription.length() > 144) {
shortDescription = shortDescription.substring(0, 143) + " ...";
}
final HtmlLink linkText = new IdeaPageUrl(idea).getHtmlLink(shortDescription);
linkText.setCssClass("idea_link_text");
ideaTitle.add(linkText);
float progressValue = (float) Math.floor(idea.getProgression());
float cappedProgressValue = progressValue;
if (cappedProgressValue > 100) {
cappedProgressValue = 100;
}
final HtmlProgressBar progressBar = new HtmlProgressBar(cappedProgressValue);
ideaTitle.add(progressBar);
if (idea.getCurrentOffer() == null) {
HtmlGenericElement amount = new HtmlGenericElement("span");
amount.setCssClass("important");
CurrencyLocale currency = new CurrencyLocale(idea.getContribution(), Context.getLocalizator().getLocale());
amount.addText(currency.getDefaultString());
final HtmlParagraph progressText = new HtmlParagraph();
progressText.setCssClass("idea_progress_text");
progressText.add(amount);
progressText.addText(Context.tr(" no offer ("));
progressText.add(new OfferPageUrl(idea).getHtmlLink(Context.tr("make an offer")));
progressText.addText(Context.tr(")"));
ideaTitle.add(progressText);
} else {
// Amount
CurrencyLocale amountCurrency = new CurrencyLocale(idea.getContribution(), Context.getLocalizator().getLocale());
HtmlGenericElement amount = new HtmlGenericElement("span");
amount.setCssClass("important");
amount.addText(amountCurrency.getDefaultString());
// Target
CurrencyLocale targetCurrency = new CurrencyLocale(idea.getCurrentOffer().getAmount() , Context.getLocalizator().getLocale());
HtmlGenericElement target = new HtmlGenericElement("span");
target.setCssClass("important");
target.addText(targetCurrency.getDefaultString());
// Progress
HtmlGenericElement progress = new HtmlGenericElement("span");
progress.setCssClass("important");
NumberFormat format = NumberFormat.getNumberInstance();
format.setMinimumFractionDigits(0);
progress.addText("" + format.format(progressValue) + " %");
final HtmlParagraph progressText = new HtmlParagraph();
progressText.setCssClass("idea_progress_text");
progressText.add(amount);
progressText.addText(Context.tr(" i.e. "));
progressText.add(progress);
progressText.addText(Context.tr(" of "));
progressText.add(target);
progressText.addText(Context.tr(" requested "));
ideaTitle.add(progressText);
}
}
centerBlock.add(ideaTitle);
}
// ideaLinkBlock.add(centerBlock);
ideaBlock.add(centerBlock);
final HtmlDiv rightBlock = new HtmlDiv("idea_summary_right");
{
rightBlock.add(new HtmlImage(new Image("/resources/img/idea.png", Image.ImageType.DISTANT)));
}
// ideaLinkBlock.add(rightBlock);
ideaBlock.add(rightBlock);
}
return ideaBlock;
}
| private HtmlNode generateContent() {
final HtmlDiv ideaBlock = new HtmlDiv("idea_summary");
{
final HtmlDiv leftBlock = new HtmlDiv("idea_summary_left");
{
final HtmlDiv karmaBlock = new HtmlDiv("idea_karma");
karmaBlock.add(new HtmlParagraph("" + idea.getPopularity()));
leftBlock.add(karmaBlock);
}
// ideaLinkBlock.add(leftBlock);
ideaBlock.add(leftBlock);
final HtmlDiv centerBlock = new HtmlDiv("idea_summary_center");
{
HtmlGenericElement project = new HtmlGenericElement("span");
project.setCssClass("project");
project.addText("VLC");
final HtmlLink linkTitle = new IdeaPageUrl(idea).getHtmlLink("");
linkTitle.setCssClass("idea_link");
linkTitle.add(project);
linkTitle.addText(" - ");
linkTitle.addText(idea.getTitle());
final HtmlTitleBlock ideaTitle = new HtmlTitleBlock(linkTitle, 3);
{
final Session session = Context.getSession();
final Locale defaultLocale = Context.getLocalizator().getLocale();
final Translation translatedDescription = idea.getDescription().getTranslationOrDefault(defaultLocale);
String shortDescription = translatedDescription.getText();
if(shortDescription.length() > 144) {
shortDescription = shortDescription.substring(0, 143) + " ...";
}
final HtmlLink linkText = new IdeaPageUrl(idea).getHtmlLink(shortDescription);
linkText.setCssClass("idea_link_text");
ideaTitle.add(linkText);
float progressValue = (float) Math.floor(idea.getProgression());
float cappedProgressValue = progressValue;
if (cappedProgressValue > 100) {
cappedProgressValue = 100;
}
final HtmlProgressBar progressBar = new HtmlProgressBar(cappedProgressValue);
ideaTitle.add(progressBar);
if (idea.getCurrentOffer() == null) {
HtmlGenericElement amount = new HtmlGenericElement("span");
amount.setCssClass("important");
CurrencyLocale currency = new CurrencyLocale(idea.getContribution(), Context.getLocalizator().getLocale());
amount.addText(currency.getDefaultString());
final HtmlParagraph progressText = new HtmlParagraph();
progressText.setCssClass("idea_progress_text");
progressText.add(amount);
progressText.addText(Context.tr(" no offer ("));
progressText.add(new OfferPageUrl(idea).getHtmlLink(Context.tr("make an offer")));
progressText.addText(Context.tr(")"));
ideaTitle.add(progressText);
} else {
// Amount
CurrencyLocale amountCurrency = new CurrencyLocale(idea.getContribution(), Context.getLocalizator().getLocale());
HtmlGenericElement amount = new HtmlGenericElement("span");
amount.setCssClass("important");
amount.addText(amountCurrency.getDefaultString());
// Target
CurrencyLocale targetCurrency = new CurrencyLocale(idea.getCurrentOffer().getAmount() , Context.getLocalizator().getLocale());
HtmlGenericElement target = new HtmlGenericElement("span");
target.setCssClass("important");
target.addText(targetCurrency.getDefaultString());
// Progress
HtmlGenericElement progress = new HtmlGenericElement("span");
progress.setCssClass("important");
NumberFormat format = NumberFormat.getNumberInstance();
format.setMinimumFractionDigits(0);
progress.addText("" + format.format(progressValue) + " %");
final HtmlParagraph progressText = new HtmlParagraph();
progressText.setCssClass("idea_progress_text");
progressText.add(amount);
progressText.addText(Context.tr(" i.e. "));
progressText.add(progress);
progressText.addText(Context.tr(" of "));
progressText.add(target);
progressText.addText(Context.tr(" requested "));
ideaTitle.add(progressText);
}
}
centerBlock.add(ideaTitle);
}
// ideaLinkBlock.add(centerBlock);
ideaBlock.add(centerBlock);
final HtmlDiv rightBlock = new HtmlDiv("idea_summary_right");
{
rightBlock.add(new HtmlImage(new Image("/resources/img/idea.png", Image.ImageType.DISTANT)));
}
// ideaLinkBlock.add(rightBlock);
ideaBlock.add(rightBlock);
}
return ideaBlock;
}
|
diff --git a/src/main/java/com/theoryinpractise/clojure/ClojureSwankMojo.java b/src/main/java/com/theoryinpractise/clojure/ClojureSwankMojo.java
index bad65bd..fa1a911 100644
--- a/src/main/java/com/theoryinpractise/clojure/ClojureSwankMojo.java
+++ b/src/main/java/com/theoryinpractise/clojure/ClojureSwankMojo.java
@@ -1,94 +1,94 @@
/*
* Copyright (c) Mark Derricutt 2010.
*
* The use and distribution terms for this software are covered by the Eclipse Public License 1.0
* (http://opensource.org/licenses/eclipse-1.0.php) which can be found in the file epl-v10.html
* at the root of this distribution.
*
* By using this software in any fashion, you are agreeing to be bound by the terms of this license.
*
* You must not remove this notice, or any other, from this software.
*/
package com.theoryinpractise.clojure;
import org.apache.maven.plugin.MojoExecutionException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @goal swank
* @execute phase="test-compile"
* @requiresDependencyResolution test
*/
public class ClojureSwankMojo extends AbstractClojureCompilerMojo {
/**
* The clojure script to preceding the switch to the repl
*
* @parameter
*/
private String replScript;
/**
* @parameter expression="${clojure.swank.port}" default-value="4005"
*/
protected int port;
/**
* @parameter expression="${clojure.swank.protocolVersion}" default-value="2009-09-14"
*/
protected String protocolVersion;
/**
* @parameter expression="${clojure.swank.encoding}" default-value="iso-8859-1"
*/
protected String encoding;
/**
* @parameter expression="${clojure.swank.host}" default-value="localhost"
*/
protected String swankHost;
public void execute() throws MojoExecutionException {
File swankTempFile;
try {
swankTempFile = File.createTempFile("swank", ".port");
} catch (java.io.IOException e) {
throw new MojoExecutionException("could not create SWANK port file", e);
}
StringBuilder sb = new StringBuilder();
sb.append("(do ");
sb.append("(swank.swank/start-server \"");
- sb.append(swankTempFile.getAbsolutePath());
+ sb.append(swankTempFile.getAbsolutePath().replace("\\", "/"));
sb.append("\"");
sb.append(" :host \"").append(swankHost).append("\"");
sb.append(" :port ");
sb.append(Integer.toString(port));
sb.append(" :encoding \"").append(encoding).append("\"");
sb.append(" :dont-close true");
sb.append("))");
String swankLoader = sb.toString();
List<String> args = new ArrayList<String>();
if (replScript != null && new File(replScript).exists()) {
args.add("-i");
args.add(replScript);
}
args.add("-e");
args.add("(require (quote swank.swank))");
args.add("-e");
args.add(swankLoader);
callClojureWith(
getSourceDirectories(SourceDirectory.TEST, SourceDirectory.COMPILE),
outputDirectory, getRunWithClasspathElements(), "clojure.main",
args.toArray(new String[args.size()]));
}
}
| true | true | public void execute() throws MojoExecutionException {
File swankTempFile;
try {
swankTempFile = File.createTempFile("swank", ".port");
} catch (java.io.IOException e) {
throw new MojoExecutionException("could not create SWANK port file", e);
}
StringBuilder sb = new StringBuilder();
sb.append("(do ");
sb.append("(swank.swank/start-server \"");
sb.append(swankTempFile.getAbsolutePath());
sb.append("\"");
sb.append(" :host \"").append(swankHost).append("\"");
sb.append(" :port ");
sb.append(Integer.toString(port));
sb.append(" :encoding \"").append(encoding).append("\"");
sb.append(" :dont-close true");
sb.append("))");
String swankLoader = sb.toString();
List<String> args = new ArrayList<String>();
if (replScript != null && new File(replScript).exists()) {
args.add("-i");
args.add(replScript);
}
args.add("-e");
args.add("(require (quote swank.swank))");
args.add("-e");
args.add(swankLoader);
callClojureWith(
getSourceDirectories(SourceDirectory.TEST, SourceDirectory.COMPILE),
outputDirectory, getRunWithClasspathElements(), "clojure.main",
args.toArray(new String[args.size()]));
}
| public void execute() throws MojoExecutionException {
File swankTempFile;
try {
swankTempFile = File.createTempFile("swank", ".port");
} catch (java.io.IOException e) {
throw new MojoExecutionException("could not create SWANK port file", e);
}
StringBuilder sb = new StringBuilder();
sb.append("(do ");
sb.append("(swank.swank/start-server \"");
sb.append(swankTempFile.getAbsolutePath().replace("\\", "/"));
sb.append("\"");
sb.append(" :host \"").append(swankHost).append("\"");
sb.append(" :port ");
sb.append(Integer.toString(port));
sb.append(" :encoding \"").append(encoding).append("\"");
sb.append(" :dont-close true");
sb.append("))");
String swankLoader = sb.toString();
List<String> args = new ArrayList<String>();
if (replScript != null && new File(replScript).exists()) {
args.add("-i");
args.add(replScript);
}
args.add("-e");
args.add("(require (quote swank.swank))");
args.add("-e");
args.add(swankLoader);
callClojureWith(
getSourceDirectories(SourceDirectory.TEST, SourceDirectory.COMPILE),
outputDirectory, getRunWithClasspathElements(), "clojure.main",
args.toArray(new String[args.size()]));
}
|
diff --git a/src/java/com/android/internal/telephony/gsm/GsmConnection.java b/src/java/com/android/internal/telephony/gsm/GsmConnection.java
index ddfe082..21e52d8 100644
--- a/src/java/com/android/internal/telephony/gsm/GsmConnection.java
+++ b/src/java/com/android/internal/telephony/gsm/GsmConnection.java
@@ -1,768 +1,767 @@
/*
* 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.content.Context;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.Registrant;
import android.os.SystemClock;
import android.util.Log;
import android.telephony.PhoneNumberUtils;
import android.telephony.ServiceState;
import android.text.TextUtils;
import com.android.internal.telephony.*;
import com.android.internal.telephony.uicc.UiccController;
import com.android.internal.telephony.uicc.IccCardApplicationStatus.AppState;
/**
* {@hide}
*/
public class GsmConnection extends Connection {
static final String LOG_TAG = "GSM";
//***** Instance Variables
GsmCallTracker owner;
GsmCall parent;
String address; // MAY BE NULL!!!
String dialString; // outgoing calls only
String postDialString; // outgoing calls only
boolean isIncoming;
boolean disconnected;
int index; // index in GsmCallTracker.connections[], -1 if unassigned
// The GSM index is 1 + this
/*
* These time/timespan values are based on System.currentTimeMillis(),
* i.e., "wall clock" time.
*/
long createTime;
long connectTime;
long disconnectTime;
/*
* These time/timespan values are based on SystemClock.elapsedRealTime(),
* i.e., time since boot. They are appropriate for comparison and
* calculating deltas.
*/
long connectTimeReal;
long duration;
long holdingStartTime; // The time when the Connection last transitioned
// into HOLDING
int nextPostDialChar; // index into postDialString
DisconnectCause cause = DisconnectCause.NOT_DISCONNECTED;
PostDialState postDialState = PostDialState.NOT_STARTED;
int numberPresentation = PhoneConstants.PRESENTATION_ALLOWED;
UUSInfo uusInfo;
Handler h;
private PowerManager.WakeLock mPartialWakeLock;
//***** Event Constants
static final int EVENT_DTMF_DONE = 1;
static final int EVENT_PAUSE_DONE = 2;
static final int EVENT_NEXT_POST_DIAL = 3;
static final int EVENT_WAKE_LOCK_TIMEOUT = 4;
//***** Constants
static final int PAUSE_DELAY_FIRST_MILLIS = 100;
static final int PAUSE_DELAY_MILLIS = 3 * 1000;
static final int WAKE_LOCK_TIMEOUT_MILLIS = 60*1000;
//***** Inner Classes
class MyHandler extends Handler {
MyHandler(Looper l) {super(l);}
public void
handleMessage(Message msg) {
switch (msg.what) {
case EVENT_NEXT_POST_DIAL:
case EVENT_DTMF_DONE:
case EVENT_PAUSE_DONE:
processNextPostDialChar();
break;
case EVENT_WAKE_LOCK_TIMEOUT:
releaseWakeLock();
break;
}
}
}
//***** Constructors
/** This is probably an MT call that we first saw in a CLCC response */
/*package*/
GsmConnection (Context context, DriverCall dc, GsmCallTracker ct, int index) {
createWakeLock(context);
acquireWakeLock();
owner = ct;
h = new MyHandler(owner.getLooper());
address = dc.number;
isIncoming = dc.isMT;
createTime = System.currentTimeMillis();
cnapName = dc.name;
cnapNamePresentation = dc.namePresentation;
numberPresentation = dc.numberPresentation;
uusInfo = dc.uusInfo;
this.index = index;
parent = parentFromDCState (dc.state);
parent.attach(this, dc);
}
/** This is an MO call, created when dialing */
/*package*/
GsmConnection (Context context, String dialString, GsmCallTracker ct, GsmCall parent) {
createWakeLock(context);
acquireWakeLock();
owner = ct;
h = new MyHandler(owner.getLooper());
this.dialString = dialString;
this.address = PhoneNumberUtils.extractNetworkPortionAlt(dialString);
this.postDialString = PhoneNumberUtils.extractPostDialPortion(dialString);
index = -1;
isIncoming = false;
cnapName = null;
cnapNamePresentation = PhoneConstants.PRESENTATION_ALLOWED;
numberPresentation = PhoneConstants.PRESENTATION_ALLOWED;
createTime = System.currentTimeMillis();
this.parent = parent;
parent.attachFake(this, GsmCall.State.DIALING);
}
public void dispose() {
}
static boolean
equalsHandlesNulls (Object a, Object b) {
return (a == null) ? (b == null) : a.equals (b);
}
/*package*/ boolean
compareTo(DriverCall c) {
// On mobile originated (MO) calls, the phone number may have changed
// due to a SIM Toolkit call control modification.
//
// We assume we know when MO calls are created (since we created them)
// and therefore don't need to compare the phone number anyway.
if (! (isIncoming || c.isMT)) return true;
// ... but we can compare phone numbers on MT calls, and we have
// no control over when they begin, so we might as well
String cAddress = PhoneNumberUtils.stringFromStringAndTOA(c.number, c.TOA);
return isIncoming == c.isMT && equalsHandlesNulls(address, cAddress);
}
public String getAddress() {
return address;
}
public GsmCall getCall() {
return parent;
}
public long getCreateTime() {
return createTime;
}
public long getConnectTime() {
return connectTime;
}
public long getDisconnectTime() {
return disconnectTime;
}
public long getDurationMillis() {
if (connectTimeReal == 0) {
return 0;
} else if (duration == 0) {
return SystemClock.elapsedRealtime() - connectTimeReal;
} else {
return duration;
}
}
public long getHoldDurationMillis() {
if (getState() != GsmCall.State.HOLDING) {
// If not holding, return 0
return 0;
} else {
return SystemClock.elapsedRealtime() - holdingStartTime;
}
}
public DisconnectCause getDisconnectCause() {
return cause;
}
public boolean isIncoming() {
return isIncoming;
}
public GsmCall.State getState() {
if (disconnected) {
return GsmCall.State.DISCONNECTED;
} else {
return super.getState();
}
}
public void hangup() throws CallStateException {
if (!disconnected) {
owner.hangup(this);
} else {
throw new CallStateException ("disconnected");
}
}
public void separate() throws CallStateException {
if (!disconnected) {
owner.separate(this);
} else {
throw new CallStateException ("disconnected");
}
}
public PostDialState getPostDialState() {
return postDialState;
}
public void proceedAfterWaitChar() {
if (postDialState != PostDialState.WAIT) {
Log.w(LOG_TAG, "GsmConnection.proceedAfterWaitChar(): Expected "
+ "getPostDialState() to be WAIT but was " + postDialState);
return;
}
setPostDialState(PostDialState.STARTED);
processNextPostDialChar();
}
public void proceedAfterWildChar(String str) {
if (postDialState != PostDialState.WILD) {
Log.w(LOG_TAG, "GsmConnection.proceedAfterWaitChar(): Expected "
+ "getPostDialState() to be WILD but was " + postDialState);
return;
}
setPostDialState(PostDialState.STARTED);
if (false) {
boolean playedTone = false;
int len = (str != null ? str.length() : 0);
for (int i=0; i<len; i++) {
char c = str.charAt(i);
Message msg = null;
if (i == len-1) {
msg = h.obtainMessage(EVENT_DTMF_DONE);
}
if (PhoneNumberUtils.is12Key(c)) {
owner.cm.sendDtmf(c, msg);
playedTone = true;
}
}
if (!playedTone) {
processNextPostDialChar();
}
} else {
// make a new postDialString, with the wild char replacement string
// at the beginning, followed by the remaining postDialString.
StringBuilder buf = new StringBuilder(str);
buf.append(postDialString.substring(nextPostDialChar));
postDialString = buf.toString();
nextPostDialChar = 0;
if (Phone.DEBUG_PHONE) {
log("proceedAfterWildChar: new postDialString is " +
postDialString);
}
processNextPostDialChar();
}
}
public void cancelPostDial() {
setPostDialState(PostDialState.CANCELLED);
}
/**
* Called when this Connection is being hung up locally (eg, user pressed "end")
* Note that at this point, the hangup request has been dispatched to the radio
* but no response has yet been received so update() has not yet been called
*/
void
onHangupLocal() {
cause = DisconnectCause.LOCAL;
}
DisconnectCause
disconnectCauseFromCode(int causeCode) {
/**
* See 22.001 Annex F.4 for mapping of cause codes
* to local tones
*/
switch (causeCode) {
case CallFailCause.USER_BUSY:
return DisconnectCause.BUSY;
case CallFailCause.NO_CIRCUIT_AVAIL:
case CallFailCause.TEMPORARY_FAILURE:
case CallFailCause.SWITCHING_CONGESTION:
case CallFailCause.CHANNEL_NOT_AVAIL:
case CallFailCause.QOS_NOT_AVAIL:
case CallFailCause.BEARER_NOT_AVAIL:
return DisconnectCause.CONGESTION;
case CallFailCause.ACM_LIMIT_EXCEEDED:
return DisconnectCause.LIMIT_EXCEEDED;
case CallFailCause.CALL_BARRED:
return DisconnectCause.CALL_BARRED;
case CallFailCause.FDN_BLOCKED:
return DisconnectCause.FDN_BLOCKED;
case CallFailCause.UNOBTAINABLE_NUMBER:
return DisconnectCause.UNOBTAINABLE_NUMBER;
case CallFailCause.ERROR_UNSPECIFIED:
case CallFailCause.NORMAL_CLEARING:
default:
GSMPhone phone = owner.phone;
int serviceState = phone.getServiceState().getState();
- UiccCardApplication cardApp = UiccController
+ AppState uiccAppState = UiccController
.getInstance()
- .getUiccCardApplication(UiccController.APP_FAM_3GPP);
- AppState uiccAppState = (cardApp != null) ? cardApp.getState() :
- AppState.APPSTATE_UNKNOWN;
+ .getUiccCardApplication(UiccController.APP_FAM_3GPP)
+ .getState();
if (serviceState == ServiceState.STATE_POWER_OFF) {
return DisconnectCause.POWER_OFF;
} else if (serviceState == ServiceState.STATE_OUT_OF_SERVICE
|| serviceState == ServiceState.STATE_EMERGENCY_ONLY ) {
return DisconnectCause.OUT_OF_SERVICE;
} else if (uiccAppState != AppState.APPSTATE_READY) {
return DisconnectCause.ICC_ERROR;
} else if (causeCode == CallFailCause.ERROR_UNSPECIFIED) {
if (phone.mSST.mRestrictedState.isCsRestricted()) {
return DisconnectCause.CS_RESTRICTED;
} else if (phone.mSST.mRestrictedState.isCsEmergencyRestricted()) {
return DisconnectCause.CS_RESTRICTED_EMERGENCY;
} else if (phone.mSST.mRestrictedState.isCsNormalRestricted()) {
return DisconnectCause.CS_RESTRICTED_NORMAL;
} else {
return DisconnectCause.ERROR_UNSPECIFIED;
}
} else if (causeCode == CallFailCause.NORMAL_CLEARING) {
return DisconnectCause.NORMAL;
} else {
// If nothing else matches, report unknown call drop reason
// to app, not NORMAL call end.
return DisconnectCause.ERROR_UNSPECIFIED;
}
}
}
/*package*/ void
onRemoteDisconnect(int causeCode) {
onDisconnect(disconnectCauseFromCode(causeCode));
}
/** Called when the radio indicates the connection has been disconnected */
/*package*/ void
onDisconnect(DisconnectCause cause) {
this.cause = cause;
if (!disconnected) {
index = -1;
disconnectTime = System.currentTimeMillis();
duration = SystemClock.elapsedRealtime() - connectTimeReal;
disconnected = true;
if (false) Log.d(LOG_TAG,
"[GSMConn] onDisconnect: cause=" + cause);
owner.phone.notifyDisconnect(this);
if (parent != null) {
parent.connectionDisconnected(this);
}
}
releaseWakeLock();
}
// Returns true if state has changed, false if nothing changed
/*package*/ boolean
update (DriverCall dc) {
GsmCall newParent;
boolean changed = false;
boolean wasConnectingInOrOut = isConnectingInOrOut();
boolean wasHolding = (getState() == GsmCall.State.HOLDING);
newParent = parentFromDCState(dc.state);
if (!equalsHandlesNulls(address, dc.number)) {
if (Phone.DEBUG_PHONE) log("update: phone # changed!");
address = dc.number;
changed = true;
}
// A null cnapName should be the same as ""
if (TextUtils.isEmpty(dc.name)) {
if (!TextUtils.isEmpty(cnapName)) {
changed = true;
cnapName = "";
}
} else if (!dc.name.equals(cnapName)) {
changed = true;
cnapName = dc.name;
}
if (Phone.DEBUG_PHONE) log("--dssds----"+cnapName);
cnapNamePresentation = dc.namePresentation;
numberPresentation = dc.numberPresentation;
if (newParent != parent) {
if (parent != null) {
parent.detach(this);
}
newParent.attach(this, dc);
parent = newParent;
changed = true;
} else {
boolean parentStateChange;
parentStateChange = parent.update (this, dc);
changed = changed || parentStateChange;
}
/** Some state-transition events */
if (Phone.DEBUG_PHONE) log(
"update: parent=" + parent +
", hasNewParent=" + (newParent != parent) +
", wasConnectingInOrOut=" + wasConnectingInOrOut +
", wasHolding=" + wasHolding +
", isConnectingInOrOut=" + isConnectingInOrOut() +
", changed=" + changed);
if (wasConnectingInOrOut && !isConnectingInOrOut()) {
onConnectedInOrOut();
}
if (changed && !wasHolding && (getState() == GsmCall.State.HOLDING)) {
// We've transitioned into HOLDING
onStartedHolding();
}
return changed;
}
/**
* Called when this Connection is in the foregroundCall
* when a dial is initiated.
* We know we're ACTIVE, and we know we're going to end up
* HOLDING in the backgroundCall
*/
void
fakeHoldBeforeDial() {
if (parent != null) {
parent.detach(this);
}
parent = owner.backgroundCall;
parent.attachFake(this, GsmCall.State.HOLDING);
onStartedHolding();
}
/*package*/ int
getGSMIndex() throws CallStateException {
if (index >= 0) {
return index + 1;
} else {
throw new CallStateException ("GSM index not yet assigned");
}
}
/**
* An incoming or outgoing call has connected
*/
void
onConnectedInOrOut() {
connectTime = System.currentTimeMillis();
connectTimeReal = SystemClock.elapsedRealtime();
duration = 0;
// bug #678474: incoming call interpreted as missed call, even though
// it sounds like the user has picked up the call.
if (Phone.DEBUG_PHONE) {
log("onConnectedInOrOut: connectTime=" + connectTime);
}
if (!isIncoming) {
// outgoing calls only
processNextPostDialChar();
}
releaseWakeLock();
}
private void
onStartedHolding() {
holdingStartTime = SystemClock.elapsedRealtime();
}
/**
* Performs the appropriate action for a post-dial char, but does not
* notify application. returns false if the character is invalid and
* should be ignored
*/
private boolean
processPostDialChar(char c) {
if (PhoneNumberUtils.is12Key(c)) {
owner.cm.sendDtmf(c, h.obtainMessage(EVENT_DTMF_DONE));
} else if (c == PhoneNumberUtils.PAUSE) {
// From TS 22.101:
// "The first occurrence of the "DTMF Control Digits Separator"
// shall be used by the ME to distinguish between the addressing
// digits (i.e. the phone number) and the DTMF digits...."
if (nextPostDialChar == 1) {
// The first occurrence.
// We don't need to pause here, but wait for just a bit anyway
h.sendMessageDelayed(h.obtainMessage(EVENT_PAUSE_DONE),
PAUSE_DELAY_FIRST_MILLIS);
} else {
// It continues...
// "Upon subsequent occurrences of the separator, the UE shall
// pause again for 3 seconds (\u00B1 20 %) before sending any
// further DTMF digits."
h.sendMessageDelayed(h.obtainMessage(EVENT_PAUSE_DONE),
PAUSE_DELAY_MILLIS);
}
} else if (c == PhoneNumberUtils.WAIT) {
setPostDialState(PostDialState.WAIT);
} else if (c == PhoneNumberUtils.WILD) {
setPostDialState(PostDialState.WILD);
} else {
return false;
}
return true;
}
public String
getRemainingPostDialString() {
if (postDialState == PostDialState.CANCELLED
|| postDialState == PostDialState.COMPLETE
|| postDialString == null
|| postDialString.length() <= nextPostDialChar
) {
return "";
}
return postDialString.substring(nextPostDialChar);
}
@Override
protected void finalize()
{
/**
* It is understood that This finializer is not guaranteed
* to be called and the release lock call is here just in
* case there is some path that doesn't call onDisconnect
* and or onConnectedInOrOut.
*/
if (mPartialWakeLock.isHeld()) {
Log.e(LOG_TAG, "[GSMConn] UNEXPECTED; mPartialWakeLock is held when finalizing.");
}
releaseWakeLock();
}
private void
processNextPostDialChar() {
char c = 0;
Registrant postDialHandler;
if (postDialState == PostDialState.CANCELLED) {
//Log.v("GSM", "##### processNextPostDialChar: postDialState == CANCELLED, bail");
return;
}
if (postDialString == null ||
postDialString.length() <= nextPostDialChar) {
setPostDialState(PostDialState.COMPLETE);
// notifyMessage.arg1 is 0 on complete
c = 0;
} else {
boolean isValid;
setPostDialState(PostDialState.STARTED);
c = postDialString.charAt(nextPostDialChar++);
isValid = processPostDialChar(c);
if (!isValid) {
// Will call processNextPostDialChar
h.obtainMessage(EVENT_NEXT_POST_DIAL).sendToTarget();
// Don't notify application
Log.e("GSM", "processNextPostDialChar: c=" + c + " isn't valid!");
return;
}
}
postDialHandler = owner.phone.mPostDialHandler;
Message notifyMessage;
if (postDialHandler != null
&& (notifyMessage = postDialHandler.messageForRegistrant()) != null) {
// The AsyncResult.result is the Connection object
PostDialState state = postDialState;
AsyncResult ar = AsyncResult.forMessage(notifyMessage);
ar.result = this;
ar.userObj = state;
// arg1 is the character that was/is being processed
notifyMessage.arg1 = c;
//Log.v("GSM", "##### processNextPostDialChar: send msg to postDialHandler, arg1=" + c);
notifyMessage.sendToTarget();
}
}
/** "connecting" means "has never been ACTIVE" for both incoming
* and outgoing calls
*/
private boolean
isConnectingInOrOut() {
return parent == null || parent == owner.ringingCall
|| parent.state == GsmCall.State.DIALING
|| parent.state == GsmCall.State.ALERTING;
}
private GsmCall
parentFromDCState (DriverCall.State state) {
switch (state) {
case ACTIVE:
case DIALING:
case ALERTING:
return owner.foregroundCall;
//break;
case HOLDING:
return owner.backgroundCall;
//break;
case INCOMING:
case WAITING:
return owner.ringingCall;
//break;
default:
throw new RuntimeException("illegal call state: " + state);
}
}
/**
* Set post dial state and acquire wake lock while switching to "started"
* state, the wake lock will be released if state switches out of "started"
* state or after WAKE_LOCK_TIMEOUT_MILLIS.
* @param s new PostDialState
*/
private void setPostDialState(PostDialState s) {
if (postDialState != PostDialState.STARTED
&& s == PostDialState.STARTED) {
acquireWakeLock();
Message msg = h.obtainMessage(EVENT_WAKE_LOCK_TIMEOUT);
h.sendMessageDelayed(msg, WAKE_LOCK_TIMEOUT_MILLIS);
} else if (postDialState == PostDialState.STARTED
&& s != PostDialState.STARTED) {
h.removeMessages(EVENT_WAKE_LOCK_TIMEOUT);
releaseWakeLock();
}
postDialState = s;
}
private void
createWakeLock(Context context) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOG_TAG);
}
private void
acquireWakeLock() {
log("acquireWakeLock");
mPartialWakeLock.acquire();
}
private void
releaseWakeLock() {
synchronized(mPartialWakeLock) {
if (mPartialWakeLock.isHeld()) {
log("releaseWakeLock");
mPartialWakeLock.release();
}
}
}
private void log(String msg) {
Log.d(LOG_TAG, "[GSMConn] " + msg);
}
@Override
public int getNumberPresentation() {
return numberPresentation;
}
@Override
public UUSInfo getUUSInfo() {
return uusInfo;
}
}
| false | true | DisconnectCause
disconnectCauseFromCode(int causeCode) {
/**
* See 22.001 Annex F.4 for mapping of cause codes
* to local tones
*/
switch (causeCode) {
case CallFailCause.USER_BUSY:
return DisconnectCause.BUSY;
case CallFailCause.NO_CIRCUIT_AVAIL:
case CallFailCause.TEMPORARY_FAILURE:
case CallFailCause.SWITCHING_CONGESTION:
case CallFailCause.CHANNEL_NOT_AVAIL:
case CallFailCause.QOS_NOT_AVAIL:
case CallFailCause.BEARER_NOT_AVAIL:
return DisconnectCause.CONGESTION;
case CallFailCause.ACM_LIMIT_EXCEEDED:
return DisconnectCause.LIMIT_EXCEEDED;
case CallFailCause.CALL_BARRED:
return DisconnectCause.CALL_BARRED;
case CallFailCause.FDN_BLOCKED:
return DisconnectCause.FDN_BLOCKED;
case CallFailCause.UNOBTAINABLE_NUMBER:
return DisconnectCause.UNOBTAINABLE_NUMBER;
case CallFailCause.ERROR_UNSPECIFIED:
case CallFailCause.NORMAL_CLEARING:
default:
GSMPhone phone = owner.phone;
int serviceState = phone.getServiceState().getState();
UiccCardApplication cardApp = UiccController
.getInstance()
.getUiccCardApplication(UiccController.APP_FAM_3GPP);
AppState uiccAppState = (cardApp != null) ? cardApp.getState() :
AppState.APPSTATE_UNKNOWN;
if (serviceState == ServiceState.STATE_POWER_OFF) {
return DisconnectCause.POWER_OFF;
} else if (serviceState == ServiceState.STATE_OUT_OF_SERVICE
|| serviceState == ServiceState.STATE_EMERGENCY_ONLY ) {
return DisconnectCause.OUT_OF_SERVICE;
} else if (uiccAppState != AppState.APPSTATE_READY) {
return DisconnectCause.ICC_ERROR;
} else if (causeCode == CallFailCause.ERROR_UNSPECIFIED) {
if (phone.mSST.mRestrictedState.isCsRestricted()) {
return DisconnectCause.CS_RESTRICTED;
} else if (phone.mSST.mRestrictedState.isCsEmergencyRestricted()) {
return DisconnectCause.CS_RESTRICTED_EMERGENCY;
} else if (phone.mSST.mRestrictedState.isCsNormalRestricted()) {
return DisconnectCause.CS_RESTRICTED_NORMAL;
} else {
return DisconnectCause.ERROR_UNSPECIFIED;
}
} else if (causeCode == CallFailCause.NORMAL_CLEARING) {
return DisconnectCause.NORMAL;
} else {
// If nothing else matches, report unknown call drop reason
// to app, not NORMAL call end.
return DisconnectCause.ERROR_UNSPECIFIED;
}
}
}
| DisconnectCause
disconnectCauseFromCode(int causeCode) {
/**
* See 22.001 Annex F.4 for mapping of cause codes
* to local tones
*/
switch (causeCode) {
case CallFailCause.USER_BUSY:
return DisconnectCause.BUSY;
case CallFailCause.NO_CIRCUIT_AVAIL:
case CallFailCause.TEMPORARY_FAILURE:
case CallFailCause.SWITCHING_CONGESTION:
case CallFailCause.CHANNEL_NOT_AVAIL:
case CallFailCause.QOS_NOT_AVAIL:
case CallFailCause.BEARER_NOT_AVAIL:
return DisconnectCause.CONGESTION;
case CallFailCause.ACM_LIMIT_EXCEEDED:
return DisconnectCause.LIMIT_EXCEEDED;
case CallFailCause.CALL_BARRED:
return DisconnectCause.CALL_BARRED;
case CallFailCause.FDN_BLOCKED:
return DisconnectCause.FDN_BLOCKED;
case CallFailCause.UNOBTAINABLE_NUMBER:
return DisconnectCause.UNOBTAINABLE_NUMBER;
case CallFailCause.ERROR_UNSPECIFIED:
case CallFailCause.NORMAL_CLEARING:
default:
GSMPhone phone = owner.phone;
int serviceState = phone.getServiceState().getState();
AppState uiccAppState = UiccController
.getInstance()
.getUiccCardApplication(UiccController.APP_FAM_3GPP)
.getState();
if (serviceState == ServiceState.STATE_POWER_OFF) {
return DisconnectCause.POWER_OFF;
} else if (serviceState == ServiceState.STATE_OUT_OF_SERVICE
|| serviceState == ServiceState.STATE_EMERGENCY_ONLY ) {
return DisconnectCause.OUT_OF_SERVICE;
} else if (uiccAppState != AppState.APPSTATE_READY) {
return DisconnectCause.ICC_ERROR;
} else if (causeCode == CallFailCause.ERROR_UNSPECIFIED) {
if (phone.mSST.mRestrictedState.isCsRestricted()) {
return DisconnectCause.CS_RESTRICTED;
} else if (phone.mSST.mRestrictedState.isCsEmergencyRestricted()) {
return DisconnectCause.CS_RESTRICTED_EMERGENCY;
} else if (phone.mSST.mRestrictedState.isCsNormalRestricted()) {
return DisconnectCause.CS_RESTRICTED_NORMAL;
} else {
return DisconnectCause.ERROR_UNSPECIFIED;
}
} else if (causeCode == CallFailCause.NORMAL_CLEARING) {
return DisconnectCause.NORMAL;
} else {
// If nothing else matches, report unknown call drop reason
// to app, not NORMAL call end.
return DisconnectCause.ERROR_UNSPECIFIED;
}
}
}
|
diff --git a/src/eval/e9/E9v3.java b/src/eval/e9/E9v3.java
index 826b553..e8679c6 100644
--- a/src/eval/e9/E9v3.java
+++ b/src/eval/e9/E9v3.java
@@ -1,511 +1,511 @@
package eval.e9;
import state4.BitUtil;
import state4.Masks;
import state4.MoveEncoder;
import state4.State4;
import eval.Evaluator3;
import eval.PositionMasks;
import eval.ScoreEncoder;
import eval.e9.mobilityEval.MobilityEval;
import eval.e9.pawnEval.PawnEval;
public final class E9v3 implements Evaluator3{
private final static int[] kingDangerTable;
private final static int[] materialWeights = new int[7];
private final static int tempoWeight = S(14, 5);
private final static int bishopPairWeight = S(10, 42);
private final static int[] zeroi = new int[2];
private final int[] materialScore = new int[2];
/**
* gives bonus multiplier to the value of sliding pieces
* mobilitiy scores based on how cluttered the board is
* <p>
* sliding pieces with high movement on a clutterd board
* are more valuable
* <p>
* indexed [num-pawn-attacked-squares]
*/
private final static double[] clutterIndex;
/** margin for scaling scores from midgame to endgame
* <p> calculated by difference between midgame and endgame material*/
private final int scaleMargin;
private final int endMaterial;
/** stores score for non-pawn material*/
private final int[] nonPawnMaterial = new int[2];
/** stores attack mask for all pieces for each player, indexed [player][piece-type]*/
private final long[] attackMask = new long[2];
//cached values
/** stores total king distance from allied pawns*/
private final int[] kingPawnDist = new int[2];
private final PawnHash pawnHash;
final PawnHashEntry filler = new PawnHashEntry();
static{
//clutterIndex calculated by linear interpolation
clutterIndex = new double[64];
final double start = .8;
final double end = 1.2;
final double diff = end-start;
for(int a = 0; a < 64; a++){
clutterIndex[a] = start + diff*(a/63.);
}
kingDangerTable = new int[128];
final int maxSlope = 30;
final int maxDanger = 1280;
for(int x = 0, i = 0; i < kingDangerTable.length; i++){
x = Math.min(maxDanger, Math.min((int)(i*i*.4), x + maxSlope));
kingDangerTable[i] = S(-x, 0);
}
materialWeights[State4.PIECE_TYPE_QUEEN] = 900;
materialWeights[State4.PIECE_TYPE_ROOK] = 470;
materialWeights[State4.PIECE_TYPE_BISHOP] = 306;
materialWeights[State4.PIECE_TYPE_KNIGHT] = 301;
materialWeights[State4.PIECE_TYPE_PAWN] = 100;
}
public E9v3(){
this(16);
}
public E9v3(int pawnHashSize){
int startMaterial = (
materialWeights[State4.PIECE_TYPE_PAWN]*8
+ materialWeights[State4.PIECE_TYPE_KNIGHT]*2
+ materialWeights[State4.PIECE_TYPE_BISHOP]*2
+ materialWeights[State4.PIECE_TYPE_ROOK]*2
+ materialWeights[State4.PIECE_TYPE_QUEEN]
) * 2;
endMaterial = (
materialWeights[State4.PIECE_TYPE_ROOK]
+ materialWeights[State4.PIECE_TYPE_QUEEN]
) * 2;
scaleMargin = scaleMargin(startMaterial, endMaterial);
pawnHash = new PawnHash(pawnHashSize, 16);
}
/** build a weight scaling from passed start,end values*/
private static int S(int start, int end){
return Weight.encode(start, end);
}
/** build a constant, non-scaling weight*/
private static int S(final int v){
return Weight.encode(v);
}
/** calculates the scale margin to use in {@link #getScale(int, int, int)}*/
private static int scaleMargin(final int startMaterial, final int endMaterial){
return endMaterial-startMaterial;
}
/** gets the interpolatino factor for the weight*/
private static double getScale(final int totalMaterialScore, final int endMaterial, final int margin){
return Math.min(1-(endMaterial-totalMaterialScore)*1./margin, 1);
}
@Override
public int eval(final int player, final State4 s) {
return refine(player, s, -90000, 90000, 0);
}
@Override
public int eval(final int player, final State4 s, final int lowerBound, final int upperBound) {
return refine(player, s, lowerBound, upperBound, 0);
}
@Override
public int refine(final int player, final State4 s, final int lowerBound,
final int upperBound, final int scoreEncoding) {
int score = ScoreEncoder.getScore(scoreEncoding);
int margin = ScoreEncoder.getMargin(scoreEncoding);
int flags = ScoreEncoder.getFlags(scoreEncoding);
boolean isLowerBound = ScoreEncoder.isLowerBound(scoreEncoding);
- if((flags < 3 && ((score+margin <= lowerBound && isLowerBound) || (score+margin >= upperBound && !isLowerBound))) ||
+ if((flags != 0 && ((score+margin <= lowerBound && isLowerBound) || (score+margin >= upperBound && !isLowerBound))) ||
flags == 3){
return scoreEncoding;
}
final int totalMaterialScore = materialScore[0]+materialScore[1];
final double scale = getScale(totalMaterialScore, endMaterial, scaleMargin);
final int pawnType = State4.PIECE_TYPE_PAWN;
final int pawnWeight = materialWeights[pawnType];
nonPawnMaterial[0] = materialScore[0]-s.pieceCounts[0][pawnType]*pawnWeight;
nonPawnMaterial[1] = materialScore[1]-s.pieceCounts[1][pawnType]*pawnWeight;
final long alliedQueens = s.queens[player];
final long enemyQueens = s.queens[1-player];
final long queens = alliedQueens | enemyQueens;
if(flags == 0){
flags++;
//load hashed pawn values, if any
final long pawnZkey = s.pawnZkey();
final PawnHashEntry phEntry = pawnHash.get(pawnZkey);
final PawnHashEntry loader;
if(phEntry == null){
filler.passedPawns = 0;
filler.zkey = 0;
loader = filler;
} else{
loader = phEntry;
}
int stage1Score = S(materialScore[player] - materialScore[1-player]);
stage1Score += tempoWeight;
if(s.pieceCounts[player][State4.PIECE_TYPE_BISHOP] == 2){
stage1Score += bishopPairWeight;
}
if(s.pieceCounts[1-player][State4.PIECE_TYPE_BISHOP] == 2){
stage1Score += -bishopPairWeight;
}
stage1Score += PawnEval.scorePawns(player, s, loader, enemyQueens, nonPawnMaterial) -
PawnEval.scorePawns(1-player, s, loader, alliedQueens, nonPawnMaterial);
if(phEntry == null){ //store newly calculated pawn values
loader.zkey = pawnZkey;
pawnHash.put(pawnZkey, loader);
}
final int stage1MarginLower; //margin for a lower cutoff
final int stage1MarginUpper; //margin for an upper cutoff
if(alliedQueens != 0 && enemyQueens != 0){
//both sides have queen, apply even margin
stage1MarginLower = 82; //margin scores taken from profiled mean score diff, 1.7 std
stage1MarginUpper = -76;
} else if(alliedQueens != 0){
//score will be higher because allied queen, no enemy queen
stage1MarginLower = 120;
stage1MarginUpper = -96;
} else if(enemyQueens != 0){
//score will be lower because enemy queen, no allied queen
stage1MarginLower = 92;
stage1MarginUpper = -128;
} else{
stage1MarginLower = 142;
stage1MarginUpper = -141;
}
score = Weight.interpolate(stage1Score, scale) + Weight.interpolate(S((int)(Weight.egScore(stage1Score)*.1), 0), scale);
if(score+stage1MarginLower <= lowerBound){
return ScoreEncoder.encode(score, stage1MarginLower, flags, true);
}
if(score+stage1MarginUpper >= upperBound){
return ScoreEncoder.encode(score, stage1MarginUpper, flags, false);
}
}
boolean needsAttackMaskRecalc = true;
if(flags == 1){
flags++;
final long whitePawnAttacks = Masks.getRawPawnAttacks(0, s.pawns[0]);
final long blackPawnAttacks = Masks.getRawPawnAttacks(1, s.pawns[1]);
final long pawnAttacks = whitePawnAttacks | blackPawnAttacks;
final double clutterMult = clutterIndex[(int)BitUtil.getSetBits(pawnAttacks)];
final int stage2Score = MobilityEval.scoreMobility(player, s, clutterMult, nonPawnMaterial, attackMask) -
MobilityEval.scoreMobility(1-player, s, clutterMult, nonPawnMaterial, attackMask);
score += Weight.interpolate(stage2Score, scale) + Weight.interpolate(S((int)(Weight.egScore(stage2Score)*.1), 0), scale);
if(queens == 0){
flags++;
return ScoreEncoder.encode(score, 0, flags, true);
} else{
//stage 2 margin related to how much we expect the score to change
//maximally due to king safety
final int stage2MarginLower;
final int stage2MarginUpper;
if(alliedQueens != 0 && enemyQueens != 0){
//both sides have queen, apply even margin
stage2MarginLower = 3;
stage2MarginUpper = -3;
} else if(alliedQueens != 0){
//score will be higher because allied queen, no enemy queen
stage2MarginLower = 3;
stage2MarginUpper = -3;
} else if(enemyQueens != 0){
//score will be lower because enemy queen, no allied queen
stage2MarginLower = 2;
stage2MarginUpper = -4;
} else{
//both sides no queen, aplly even margin
stage2MarginLower = 0;
stage2MarginUpper = -0;
}
if(score+stage2MarginLower <= lowerBound){
return ScoreEncoder.encode(score, stage2MarginLower, flags, true);
} if(score+stage2MarginUpper >= upperBound){
return ScoreEncoder.encode(score, stage2MarginUpper, flags, false);
} else{
//margin cutoff failed, calculate king safety scores
//record that attack masks were just calculated in stage 2
needsAttackMaskRecalc = false;
}
}
}
if(flags == 2){
assert queens != 0; //should be caugt by stage 2 eval if queens == 0
flags++;
if(needsAttackMaskRecalc){
final long whitePawnAttacks = Masks.getRawPawnAttacks(0, s.pawns[0]);
final long blackPawnAttacks = Masks.getRawPawnAttacks(1, s.pawns[1]);
final long pawnAttacks = whitePawnAttacks | blackPawnAttacks;
final double clutterMult = clutterIndex[(int)BitUtil.getSetBits(pawnAttacks)];
//recalculate attack masks
MobilityEval.scoreMobility(player, s, clutterMult, nonPawnMaterial, attackMask);
MobilityEval.scoreMobility(1-player, s, clutterMult, nonPawnMaterial, attackMask);
}
final int stage3Score = evalKingSafety(player, s, alliedQueens, enemyQueens);
score += Weight.interpolate(stage3Score, scale) + Weight.interpolate(S((int)(Weight.egScore(stage3Score)*.1), 0), scale);
return ScoreEncoder.encode(score, 0, flags, true);
}
//evaluation should complete in one of the stages above
assert false;
return 0;
}
private int evalKingSafety(final int player, final State4 s, final long alliedQueens, final long enemyQueens){
int score = 0;
if(enemyQueens != 0){
final long king = s.kings[player];
final int kingIndex = BitUtil.lsbIndex(king);
score += evalKingPressure3(kingIndex, player, s, attackMask[player]);
}
if(alliedQueens != 0){
final long king = s.kings[1-player];
final int kingIndex = BitUtil.lsbIndex(king);
score -= evalKingPressure3(kingIndex, 1-player, s, attackMask[1-player]);
}
return score;
}
/**
* evaluates king pressure
* @param kingIndex index of the players king for whom pressure is to be evaluated
* @param player player owning the king for whom pressure is to be evaluated
* @param s
* @param alliedAttackMask attack mask for allied pieces, excluding the king;
* generated via {@link #scoreMobility(int, State4, double, int[], long[])}
* @return returns king pressure score
*/
private static int evalKingPressure3(final int kingIndex, final int player,
final State4 s, final long alliedAttackMask){
final long king = 1L << kingIndex;
final long allied = s.pieces[player];
final long enemy = s.pieces[1-player];
final long agg = allied | enemy;
int index = 0;
final long kingRing = Masks.getRawKingMoves(king);
final long undefended = kingRing & ~alliedAttackMask;
final long rookContactCheckMask = kingRing &
~(PositionMasks.pawnAttacks[0][kingIndex] | PositionMasks.pawnAttacks[1][kingIndex]);
final long bishopContactCheckMask = kingRing & ~rookContactCheckMask;
final int enemyPlayer = 1-player;
final long bishops = s.bishops[enemyPlayer];
final long rooks = s.rooks[enemyPlayer];
final long queens = s.queens[enemyPlayer];
final long pawns = s.pawns[enemyPlayer];
final long knights = s.knights[enemyPlayer];
//process enemy queen attacks
int supportedQueenAttacks = 0;
for(long tempQueens = queens; tempQueens != 0; tempQueens &= tempQueens-1){
final long q = tempQueens & -tempQueens;
final long qAgg = agg & ~q;
final long queenMoves = Masks.getRawQueenMoves(agg, q) & ~enemy & undefended;
for(long temp = queenMoves & ~alliedAttackMask; temp != 0; temp &= temp-1){
final long pos = temp & -temp;
if((pos & undefended) != 0){
final long aggPieces = qAgg | pos;
final long bishopAttacks = Masks.getRawBishopMoves(aggPieces, pos);
final long knightAttacks = Masks.getRawKnightMoves(pos);
final long rookAttacks = Masks.getRawRookMoves(aggPieces, pos);
final long pawnAttacks = Masks.getRawPawnAttacks(player, pawns);
if((bishops & bishopAttacks) != 0 |
(rooks & rookAttacks) != 0 |
(knights & knightAttacks) != 0 |
(pawns & pawnAttacks) != 0 |
(queens & ~q & (bishopAttacks|rookAttacks)) != 0){
supportedQueenAttacks++;
}
}
}
}
//index += supportedQueenAttacks*16;
index += supportedQueenAttacks*4;
//process enemy rook attacks
int supportedRookAttacks = 0;
int supportedRookContactChecks = 0;
for(long tempRooks = rooks; tempRooks != 0; tempRooks &= tempRooks-1){
final long r = tempRooks & -tempRooks;
final long rAgg = agg & ~r;
final long rookMoves = Masks.getRawRookMoves(agg, r) & ~enemy & undefended;
for(long temp = rookMoves & ~alliedAttackMask; temp != 0; temp &= temp-1){
final long pos = temp & -temp;
if((pos & undefended) != 0){
final long aggPieces = rAgg | pos;
final long bishopAttacks = Masks.getRawBishopMoves(aggPieces, pos);
final long knightAttacks = Masks.getRawKnightMoves(pos);
final long rookAttacks = Masks.getRawRookMoves(aggPieces, pos);
final long pawnAttacks = Masks.getRawPawnAttacks(player, pawns);
if((bishops & bishopAttacks) != 0 |
(rooks & ~r & rookAttacks) != 0 |
(knights & knightAttacks) != 0 |
(pawns & pawnAttacks) != 0 |
(queens & (bishopAttacks|rookAttacks)) != 0){
if((pos & rookContactCheckMask) != 0) supportedRookContactChecks++;
else supportedRookAttacks++;
}
}
}
}
index += supportedRookAttacks*1;
index += supportedRookContactChecks*2;
//process enemy bishop attacks
int supportedBishopAttacks = 0;
int supportedBishopContactChecks = 0;
for(long tempBishops = bishops; tempBishops != 0; tempBishops &= tempBishops-1){
final long b = tempBishops & -tempBishops;
final long bAgg = agg & ~b;
final long bishopMoves = Masks.getRawBishopMoves(agg, b) & ~enemy & undefended;
for(long temp = bishopMoves & ~alliedAttackMask; temp != 0; temp &= temp-1){
final long pos = temp & -temp;
if((pos & undefended) != 0){
final long aggPieces = bAgg | pos;
final long bishopAttacks = Masks.getRawBishopMoves(aggPieces, pos);
final long knightAttacks = Masks.getRawKnightMoves(pos);
final long rookAttacks = Masks.getRawRookMoves(aggPieces, pos);
final long pawnAttacks = Masks.getRawPawnAttacks(player, pawns);
if((bishops & ~b & bishopAttacks) != 0 |
(rooks & rookAttacks) != 0 |
(knights & knightAttacks) != 0 |
(pawns & pawnAttacks) != 0 |
(queens & (bishopAttacks|rookAttacks)) != 0){
if((pos & bishopContactCheckMask) != 0) supportedBishopContactChecks++;
else supportedBishopAttacks++;
}
}
}
}
index += supportedBishopAttacks*1;
index += supportedBishopContactChecks*2;
//process enemy knight attacks
int supportedKnightAttacks = 0;
for(long tempKnights = knights; tempKnights != 0; tempKnights &= tempKnights-1){
final long k = tempKnights & -tempKnights;
final long kAgg = agg & ~k;
final long knightMoves = Masks.getRawKnightMoves(k) & ~enemy & undefended;
for(long temp = knightMoves & ~alliedAttackMask; temp != 0; temp &= temp-1){
final long pos = temp & -temp;
if((pos & undefended) != 0){
final long aggPieces = kAgg | pos;
final long bishopAttacks = Masks.getRawBishopMoves(aggPieces, pos);
final long knightAttacks = Masks.getRawKnightMoves(pos);
final long rookAttacks = Masks.getRawRookMoves(aggPieces, pos);
final long pawnAttacks = Masks.getRawPawnAttacks(player, pawns);
if((bishops & bishopAttacks) != 0 |
(rooks & rookAttacks) != 0 |
(knights & ~k & knightAttacks) != 0 |
(pawns & pawnAttacks) != 0 |
(queens & (bishopAttacks|rookAttacks)) != 0){
supportedKnightAttacks++;
}
}
}
}
index += supportedKnightAttacks*1;
return kingDangerTable[index < 128? index: 127];
}
@Override
public void makeMove(final long encoding) {
update(encoding, 1);
}
@Override
public void undoMove(final long encoding) {
update(encoding, -1);
}
/** incrementally updates the score after a move, dir = undo? -1: 1*/
private void update(final long encoding, final int dir){
final int player = MoveEncoder.getPlayer(encoding);
final int taken = MoveEncoder.getTakenType(encoding);
if(taken != 0){
materialScore[1-player] -= dir*materialWeights[taken];
} else if(MoveEncoder.isEnPassanteTake(encoding) != 0){
materialScore[1-player] -= dir*materialWeights[State4.PIECE_TYPE_PAWN];
}
if(MoveEncoder.isPawnPromotion(encoding)){
materialScore[player] += dir*(materialWeights[State4.PIECE_TYPE_QUEEN]-
materialWeights[State4.PIECE_TYPE_PAWN]);
}
}
@Override
public void initialize(State4 s) {
System.arraycopy(zeroi, 0, materialScore, 0, 2);
System.arraycopy(zeroi, 0, kingPawnDist, 0, 2);
for(int a = 0; a < 2; a++){
final int b = State4.PIECE_TYPE_BISHOP;
materialScore[a] += s.pieceCounts[a][b] * materialWeights[b];
final int n = State4.PIECE_TYPE_KNIGHT;
materialScore[a] += s.pieceCounts[a][n] * materialWeights[n];
final int q = State4.PIECE_TYPE_QUEEN;
materialScore[a] += s.pieceCounts[a][q] * materialWeights[q];
final int r = State4.PIECE_TYPE_ROOK;
materialScore[a] += s.pieceCounts[a][r] * materialWeights[r];
final int p = State4.PIECE_TYPE_PAWN;
materialScore[a] += s.pieceCounts[a][p] * materialWeights[p];
}
}
@Override
public void reset(){}
}
| true | true | public int refine(final int player, final State4 s, final int lowerBound,
final int upperBound, final int scoreEncoding) {
int score = ScoreEncoder.getScore(scoreEncoding);
int margin = ScoreEncoder.getMargin(scoreEncoding);
int flags = ScoreEncoder.getFlags(scoreEncoding);
boolean isLowerBound = ScoreEncoder.isLowerBound(scoreEncoding);
if((flags < 3 && ((score+margin <= lowerBound && isLowerBound) || (score+margin >= upperBound && !isLowerBound))) ||
flags == 3){
return scoreEncoding;
}
final int totalMaterialScore = materialScore[0]+materialScore[1];
final double scale = getScale(totalMaterialScore, endMaterial, scaleMargin);
final int pawnType = State4.PIECE_TYPE_PAWN;
final int pawnWeight = materialWeights[pawnType];
nonPawnMaterial[0] = materialScore[0]-s.pieceCounts[0][pawnType]*pawnWeight;
nonPawnMaterial[1] = materialScore[1]-s.pieceCounts[1][pawnType]*pawnWeight;
final long alliedQueens = s.queens[player];
final long enemyQueens = s.queens[1-player];
final long queens = alliedQueens | enemyQueens;
if(flags == 0){
flags++;
//load hashed pawn values, if any
final long pawnZkey = s.pawnZkey();
final PawnHashEntry phEntry = pawnHash.get(pawnZkey);
final PawnHashEntry loader;
if(phEntry == null){
filler.passedPawns = 0;
filler.zkey = 0;
loader = filler;
} else{
loader = phEntry;
}
int stage1Score = S(materialScore[player] - materialScore[1-player]);
stage1Score += tempoWeight;
if(s.pieceCounts[player][State4.PIECE_TYPE_BISHOP] == 2){
stage1Score += bishopPairWeight;
}
if(s.pieceCounts[1-player][State4.PIECE_TYPE_BISHOP] == 2){
stage1Score += -bishopPairWeight;
}
stage1Score += PawnEval.scorePawns(player, s, loader, enemyQueens, nonPawnMaterial) -
PawnEval.scorePawns(1-player, s, loader, alliedQueens, nonPawnMaterial);
if(phEntry == null){ //store newly calculated pawn values
loader.zkey = pawnZkey;
pawnHash.put(pawnZkey, loader);
}
final int stage1MarginLower; //margin for a lower cutoff
final int stage1MarginUpper; //margin for an upper cutoff
if(alliedQueens != 0 && enemyQueens != 0){
//both sides have queen, apply even margin
stage1MarginLower = 82; //margin scores taken from profiled mean score diff, 1.7 std
stage1MarginUpper = -76;
} else if(alliedQueens != 0){
//score will be higher because allied queen, no enemy queen
stage1MarginLower = 120;
stage1MarginUpper = -96;
} else if(enemyQueens != 0){
//score will be lower because enemy queen, no allied queen
stage1MarginLower = 92;
stage1MarginUpper = -128;
} else{
stage1MarginLower = 142;
stage1MarginUpper = -141;
}
score = Weight.interpolate(stage1Score, scale) + Weight.interpolate(S((int)(Weight.egScore(stage1Score)*.1), 0), scale);
if(score+stage1MarginLower <= lowerBound){
return ScoreEncoder.encode(score, stage1MarginLower, flags, true);
}
if(score+stage1MarginUpper >= upperBound){
return ScoreEncoder.encode(score, stage1MarginUpper, flags, false);
}
}
boolean needsAttackMaskRecalc = true;
if(flags == 1){
flags++;
final long whitePawnAttacks = Masks.getRawPawnAttacks(0, s.pawns[0]);
final long blackPawnAttacks = Masks.getRawPawnAttacks(1, s.pawns[1]);
final long pawnAttacks = whitePawnAttacks | blackPawnAttacks;
final double clutterMult = clutterIndex[(int)BitUtil.getSetBits(pawnAttacks)];
final int stage2Score = MobilityEval.scoreMobility(player, s, clutterMult, nonPawnMaterial, attackMask) -
MobilityEval.scoreMobility(1-player, s, clutterMult, nonPawnMaterial, attackMask);
score += Weight.interpolate(stage2Score, scale) + Weight.interpolate(S((int)(Weight.egScore(stage2Score)*.1), 0), scale);
if(queens == 0){
flags++;
return ScoreEncoder.encode(score, 0, flags, true);
} else{
//stage 2 margin related to how much we expect the score to change
//maximally due to king safety
final int stage2MarginLower;
final int stage2MarginUpper;
if(alliedQueens != 0 && enemyQueens != 0){
//both sides have queen, apply even margin
stage2MarginLower = 3;
stage2MarginUpper = -3;
} else if(alliedQueens != 0){
//score will be higher because allied queen, no enemy queen
stage2MarginLower = 3;
stage2MarginUpper = -3;
} else if(enemyQueens != 0){
//score will be lower because enemy queen, no allied queen
stage2MarginLower = 2;
stage2MarginUpper = -4;
} else{
//both sides no queen, aplly even margin
stage2MarginLower = 0;
stage2MarginUpper = -0;
}
if(score+stage2MarginLower <= lowerBound){
return ScoreEncoder.encode(score, stage2MarginLower, flags, true);
} if(score+stage2MarginUpper >= upperBound){
return ScoreEncoder.encode(score, stage2MarginUpper, flags, false);
} else{
//margin cutoff failed, calculate king safety scores
//record that attack masks were just calculated in stage 2
needsAttackMaskRecalc = false;
}
}
}
if(flags == 2){
assert queens != 0; //should be caugt by stage 2 eval if queens == 0
flags++;
if(needsAttackMaskRecalc){
final long whitePawnAttacks = Masks.getRawPawnAttacks(0, s.pawns[0]);
final long blackPawnAttacks = Masks.getRawPawnAttacks(1, s.pawns[1]);
final long pawnAttacks = whitePawnAttacks | blackPawnAttacks;
final double clutterMult = clutterIndex[(int)BitUtil.getSetBits(pawnAttacks)];
//recalculate attack masks
MobilityEval.scoreMobility(player, s, clutterMult, nonPawnMaterial, attackMask);
MobilityEval.scoreMobility(1-player, s, clutterMult, nonPawnMaterial, attackMask);
}
final int stage3Score = evalKingSafety(player, s, alliedQueens, enemyQueens);
score += Weight.interpolate(stage3Score, scale) + Weight.interpolate(S((int)(Weight.egScore(stage3Score)*.1), 0), scale);
return ScoreEncoder.encode(score, 0, flags, true);
}
//evaluation should complete in one of the stages above
assert false;
return 0;
}
| public int refine(final int player, final State4 s, final int lowerBound,
final int upperBound, final int scoreEncoding) {
int score = ScoreEncoder.getScore(scoreEncoding);
int margin = ScoreEncoder.getMargin(scoreEncoding);
int flags = ScoreEncoder.getFlags(scoreEncoding);
boolean isLowerBound = ScoreEncoder.isLowerBound(scoreEncoding);
if((flags != 0 && ((score+margin <= lowerBound && isLowerBound) || (score+margin >= upperBound && !isLowerBound))) ||
flags == 3){
return scoreEncoding;
}
final int totalMaterialScore = materialScore[0]+materialScore[1];
final double scale = getScale(totalMaterialScore, endMaterial, scaleMargin);
final int pawnType = State4.PIECE_TYPE_PAWN;
final int pawnWeight = materialWeights[pawnType];
nonPawnMaterial[0] = materialScore[0]-s.pieceCounts[0][pawnType]*pawnWeight;
nonPawnMaterial[1] = materialScore[1]-s.pieceCounts[1][pawnType]*pawnWeight;
final long alliedQueens = s.queens[player];
final long enemyQueens = s.queens[1-player];
final long queens = alliedQueens | enemyQueens;
if(flags == 0){
flags++;
//load hashed pawn values, if any
final long pawnZkey = s.pawnZkey();
final PawnHashEntry phEntry = pawnHash.get(pawnZkey);
final PawnHashEntry loader;
if(phEntry == null){
filler.passedPawns = 0;
filler.zkey = 0;
loader = filler;
} else{
loader = phEntry;
}
int stage1Score = S(materialScore[player] - materialScore[1-player]);
stage1Score += tempoWeight;
if(s.pieceCounts[player][State4.PIECE_TYPE_BISHOP] == 2){
stage1Score += bishopPairWeight;
}
if(s.pieceCounts[1-player][State4.PIECE_TYPE_BISHOP] == 2){
stage1Score += -bishopPairWeight;
}
stage1Score += PawnEval.scorePawns(player, s, loader, enemyQueens, nonPawnMaterial) -
PawnEval.scorePawns(1-player, s, loader, alliedQueens, nonPawnMaterial);
if(phEntry == null){ //store newly calculated pawn values
loader.zkey = pawnZkey;
pawnHash.put(pawnZkey, loader);
}
final int stage1MarginLower; //margin for a lower cutoff
final int stage1MarginUpper; //margin for an upper cutoff
if(alliedQueens != 0 && enemyQueens != 0){
//both sides have queen, apply even margin
stage1MarginLower = 82; //margin scores taken from profiled mean score diff, 1.7 std
stage1MarginUpper = -76;
} else if(alliedQueens != 0){
//score will be higher because allied queen, no enemy queen
stage1MarginLower = 120;
stage1MarginUpper = -96;
} else if(enemyQueens != 0){
//score will be lower because enemy queen, no allied queen
stage1MarginLower = 92;
stage1MarginUpper = -128;
} else{
stage1MarginLower = 142;
stage1MarginUpper = -141;
}
score = Weight.interpolate(stage1Score, scale) + Weight.interpolate(S((int)(Weight.egScore(stage1Score)*.1), 0), scale);
if(score+stage1MarginLower <= lowerBound){
return ScoreEncoder.encode(score, stage1MarginLower, flags, true);
}
if(score+stage1MarginUpper >= upperBound){
return ScoreEncoder.encode(score, stage1MarginUpper, flags, false);
}
}
boolean needsAttackMaskRecalc = true;
if(flags == 1){
flags++;
final long whitePawnAttacks = Masks.getRawPawnAttacks(0, s.pawns[0]);
final long blackPawnAttacks = Masks.getRawPawnAttacks(1, s.pawns[1]);
final long pawnAttacks = whitePawnAttacks | blackPawnAttacks;
final double clutterMult = clutterIndex[(int)BitUtil.getSetBits(pawnAttacks)];
final int stage2Score = MobilityEval.scoreMobility(player, s, clutterMult, nonPawnMaterial, attackMask) -
MobilityEval.scoreMobility(1-player, s, clutterMult, nonPawnMaterial, attackMask);
score += Weight.interpolate(stage2Score, scale) + Weight.interpolate(S((int)(Weight.egScore(stage2Score)*.1), 0), scale);
if(queens == 0){
flags++;
return ScoreEncoder.encode(score, 0, flags, true);
} else{
//stage 2 margin related to how much we expect the score to change
//maximally due to king safety
final int stage2MarginLower;
final int stage2MarginUpper;
if(alliedQueens != 0 && enemyQueens != 0){
//both sides have queen, apply even margin
stage2MarginLower = 3;
stage2MarginUpper = -3;
} else if(alliedQueens != 0){
//score will be higher because allied queen, no enemy queen
stage2MarginLower = 3;
stage2MarginUpper = -3;
} else if(enemyQueens != 0){
//score will be lower because enemy queen, no allied queen
stage2MarginLower = 2;
stage2MarginUpper = -4;
} else{
//both sides no queen, aplly even margin
stage2MarginLower = 0;
stage2MarginUpper = -0;
}
if(score+stage2MarginLower <= lowerBound){
return ScoreEncoder.encode(score, stage2MarginLower, flags, true);
} if(score+stage2MarginUpper >= upperBound){
return ScoreEncoder.encode(score, stage2MarginUpper, flags, false);
} else{
//margin cutoff failed, calculate king safety scores
//record that attack masks were just calculated in stage 2
needsAttackMaskRecalc = false;
}
}
}
if(flags == 2){
assert queens != 0; //should be caugt by stage 2 eval if queens == 0
flags++;
if(needsAttackMaskRecalc){
final long whitePawnAttacks = Masks.getRawPawnAttacks(0, s.pawns[0]);
final long blackPawnAttacks = Masks.getRawPawnAttacks(1, s.pawns[1]);
final long pawnAttacks = whitePawnAttacks | blackPawnAttacks;
final double clutterMult = clutterIndex[(int)BitUtil.getSetBits(pawnAttacks)];
//recalculate attack masks
MobilityEval.scoreMobility(player, s, clutterMult, nonPawnMaterial, attackMask);
MobilityEval.scoreMobility(1-player, s, clutterMult, nonPawnMaterial, attackMask);
}
final int stage3Score = evalKingSafety(player, s, alliedQueens, enemyQueens);
score += Weight.interpolate(stage3Score, scale) + Weight.interpolate(S((int)(Weight.egScore(stage3Score)*.1), 0), scale);
return ScoreEncoder.encode(score, 0, flags, true);
}
//evaluation should complete in one of the stages above
assert false;
return 0;
}
|
diff --git a/WWIDesigner/src/main/com/wwidesigner/gui/WhistleStudyModel.java b/WWIDesigner/src/main/com/wwidesigner/gui/WhistleStudyModel.java
index 823e978..c0073d5 100644
--- a/WWIDesigner/src/main/com/wwidesigner/gui/WhistleStudyModel.java
+++ b/WWIDesigner/src/main/com/wwidesigner/gui/WhistleStudyModel.java
@@ -1,176 +1,176 @@
/**
*
*/
package com.wwidesigner.gui;
import java.util.prefs.Preferences;
import com.wwidesigner.geometry.Instrument;
import com.wwidesigner.modelling.BellNoteEvaluator;
import com.wwidesigner.modelling.EvaluatorInterface;
import com.wwidesigner.modelling.FmaxEvaluator;
import com.wwidesigner.modelling.FminEvaluator;
import com.wwidesigner.modelling.InstrumentCalculator;
import com.wwidesigner.modelling.InstrumentRangeTuner;
import com.wwidesigner.modelling.InstrumentTuner;
import com.wwidesigner.modelling.WhistleCalculator;
import com.wwidesigner.modelling.WhistleEvaluator;
import com.wwidesigner.note.Tuning;
import com.wwidesigner.optimization.BaseObjectiveFunction;
import com.wwidesigner.optimization.BetaObjectiveFunction;
import com.wwidesigner.optimization.HoleObjectiveFunction;
import com.wwidesigner.optimization.HolePositionObjectiveFunction;
import com.wwidesigner.optimization.HoleSizeObjectiveFunction;
import com.wwidesigner.optimization.LengthObjectiveFunction;
import com.wwidesigner.optimization.WindowHeightObjectiveFunction;
import com.wwidesigner.util.Constants.TemperatureType;
import com.wwidesigner.util.PhysicalParameters;
/**
* @author Burton Patkau
*
*/
public class WhistleStudyModel extends StudyModel
{
public static final String WINDOW_OPT_SUB_CATEGORY_ID = "1. Window Height Calibrator";
public static final String BETA_OPT_SUB_CATEGORY_ID = "2. Beta Calibrator";
public static final String LENGTH_OPT_SUB_CATEGORY_ID = "3. Length Optimizer";
public static final String HOLESIZE_OPT_SUB_CATEGORY_ID = "4. Hole Size Optimizer";
public static final String HOLESPACE_OPT_SUB_CATEGORY_ID = "5. Hole Spacing Optimizer";
public static final String HOLE_OPT_SUB_CATEGORY_ID = "6. Hole Size+Spacing Optimizer";
protected int blowingLevel;
public WhistleStudyModel()
{
super();
setLocalCategories();
blowingLevel = 5;
}
protected void setLocalCategories()
{
setParams(new PhysicalParameters(28.2, TemperatureType.C));
Category optimizers = new Category(OPTIMIZER_CATEGORY_ID);
optimizers.addSub(WINDOW_OPT_SUB_CATEGORY_ID, null);
optimizers.addSub(BETA_OPT_SUB_CATEGORY_ID, null);
optimizers.addSub(LENGTH_OPT_SUB_CATEGORY_ID, null);
optimizers.addSub(HOLESIZE_OPT_SUB_CATEGORY_ID, null);
optimizers.addSub(HOLESPACE_OPT_SUB_CATEGORY_ID, null);
optimizers.addSub(HOLE_OPT_SUB_CATEGORY_ID, null);
categories.add(optimizers);
}
/*
* (non-Javadoc)
*
* @see
* com.wwidesigner.gui.StudyModel#setPreferences(java.util.prefs.Preferences
* )
*/
@Override
public void setPreferences(Preferences newPreferences)
{
blowingLevel = newPreferences.getInt(
OptimizationPreferences.BLOWING_LEVEL_OPT, 5);
super.setPreferences(newPreferences);
}
@Override
protected InstrumentCalculator getCalculator()
{
InstrumentCalculator calculator = new WhistleCalculator();
calculator.setPhysicalParameters(params);
return calculator;
}
@Override
protected InstrumentTuner getInstrumentTuner()
{
InstrumentTuner tuner = new InstrumentRangeTuner(blowingLevel);
tuner.setParams(params);
return tuner;
}
@Override
protected BaseObjectiveFunction getObjectiveFunction() throws Exception
{
Category optimizerCategory = getCategory(OPTIMIZER_CATEGORY_ID);
String optimizer = optimizerCategory.getSelectedSub();
Instrument instrument = getInstrument();
Tuning tuning = getTuning();
WhistleCalculator calculator = new WhistleCalculator();
EvaluatorInterface evaluator;
calculator.setInstrument(instrument);
calculator.setPhysicalParameters(params);
BaseObjectiveFunction objective = null;
double[] lowerBound = null;
double[] upperBound = null;
switch (optimizer)
{
case WINDOW_OPT_SUB_CATEGORY_ID:
evaluator = new FmaxEvaluator(calculator);
objective = new WindowHeightObjectiveFunction(calculator,
tuning, evaluator);
lowerBound = new double[] { 0.000 };
upperBound = new double[] { 0.010 };
break;
case BETA_OPT_SUB_CATEGORY_ID:
evaluator = new FminEvaluator(calculator);
objective = new BetaObjectiveFunction(calculator, tuning,
evaluator);
lowerBound = new double[] { 0.2 };
upperBound = new double[] { 0.5 };
break;
case LENGTH_OPT_SUB_CATEGORY_ID:
evaluator = new BellNoteEvaluator(calculator);
objective = new LengthObjectiveFunction(calculator, tuning,
evaluator);
- lowerBound = new double[] { 0.350 };
+ lowerBound = new double[] { 0.200 };
upperBound = new double[] { 0.700 };
break;
case HOLESIZE_OPT_SUB_CATEGORY_ID:
evaluator = new WhistleEvaluator(calculator, blowingLevel);
objective = new HoleSizeObjectiveFunction(calculator, tuning,
evaluator);
// Bounds are diameters, expressed in meters.
lowerBound = new double[] { 0.004, 0.004, 0.004, 0.004, 0.004,
0.004 };
// upperBound = new double[] { 0.010, 0.010, 0.010, 0.010,
// 0.010, 0.010 };
upperBound = new double[] { 0.009, 0.009, 0.009, 0.009, 0.009,
0.009 };
break;
case HOLESPACE_OPT_SUB_CATEGORY_ID:
evaluator = new WhistleEvaluator(calculator, blowingLevel);
objective = new HolePositionObjectiveFunction(calculator,
tuning, evaluator);
// Bounds are expressed in meters.
lowerBound = new double[] { 0.200, 0.013, 0.013, 0.013, 0.013,
0.013, 0.013 };
upperBound = new double[] { 0.700, 0.050, 0.050, 0.050, 0.050,
0.050, 0.200 };
break;
case HOLE_OPT_SUB_CATEGORY_ID:
default:
evaluator = new WhistleEvaluator(calculator, blowingLevel);
objective = new HoleObjectiveFunction(calculator, tuning,
evaluator);
// Length bounds are expressed in meters, diameter bounds as
// ratios.
lowerBound = new double[] { 0.200, 0.012, 0.012, 0.012, 0.012,
0.012, 0.012, 0.004, 0.004, 0.004, 0.004, 0.004, 0.004 };
upperBound = new double[] { 0.700, 0.050, 0.050, 0.050, 0.050,
0.050, 0.200, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010 };
break;
}
objective.setLowerBounds(lowerBound);
objective.setUpperBounds(upperBound);
return objective;
}
}
| true | true | protected BaseObjectiveFunction getObjectiveFunction() throws Exception
{
Category optimizerCategory = getCategory(OPTIMIZER_CATEGORY_ID);
String optimizer = optimizerCategory.getSelectedSub();
Instrument instrument = getInstrument();
Tuning tuning = getTuning();
WhistleCalculator calculator = new WhistleCalculator();
EvaluatorInterface evaluator;
calculator.setInstrument(instrument);
calculator.setPhysicalParameters(params);
BaseObjectiveFunction objective = null;
double[] lowerBound = null;
double[] upperBound = null;
switch (optimizer)
{
case WINDOW_OPT_SUB_CATEGORY_ID:
evaluator = new FmaxEvaluator(calculator);
objective = new WindowHeightObjectiveFunction(calculator,
tuning, evaluator);
lowerBound = new double[] { 0.000 };
upperBound = new double[] { 0.010 };
break;
case BETA_OPT_SUB_CATEGORY_ID:
evaluator = new FminEvaluator(calculator);
objective = new BetaObjectiveFunction(calculator, tuning,
evaluator);
lowerBound = new double[] { 0.2 };
upperBound = new double[] { 0.5 };
break;
case LENGTH_OPT_SUB_CATEGORY_ID:
evaluator = new BellNoteEvaluator(calculator);
objective = new LengthObjectiveFunction(calculator, tuning,
evaluator);
lowerBound = new double[] { 0.350 };
upperBound = new double[] { 0.700 };
break;
case HOLESIZE_OPT_SUB_CATEGORY_ID:
evaluator = new WhistleEvaluator(calculator, blowingLevel);
objective = new HoleSizeObjectiveFunction(calculator, tuning,
evaluator);
// Bounds are diameters, expressed in meters.
lowerBound = new double[] { 0.004, 0.004, 0.004, 0.004, 0.004,
0.004 };
// upperBound = new double[] { 0.010, 0.010, 0.010, 0.010,
// 0.010, 0.010 };
upperBound = new double[] { 0.009, 0.009, 0.009, 0.009, 0.009,
0.009 };
break;
case HOLESPACE_OPT_SUB_CATEGORY_ID:
evaluator = new WhistleEvaluator(calculator, blowingLevel);
objective = new HolePositionObjectiveFunction(calculator,
tuning, evaluator);
// Bounds are expressed in meters.
lowerBound = new double[] { 0.200, 0.013, 0.013, 0.013, 0.013,
0.013, 0.013 };
upperBound = new double[] { 0.700, 0.050, 0.050, 0.050, 0.050,
0.050, 0.200 };
break;
case HOLE_OPT_SUB_CATEGORY_ID:
default:
evaluator = new WhistleEvaluator(calculator, blowingLevel);
objective = new HoleObjectiveFunction(calculator, tuning,
evaluator);
// Length bounds are expressed in meters, diameter bounds as
// ratios.
lowerBound = new double[] { 0.200, 0.012, 0.012, 0.012, 0.012,
0.012, 0.012, 0.004, 0.004, 0.004, 0.004, 0.004, 0.004 };
upperBound = new double[] { 0.700, 0.050, 0.050, 0.050, 0.050,
0.050, 0.200, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010 };
break;
}
objective.setLowerBounds(lowerBound);
objective.setUpperBounds(upperBound);
return objective;
}
| protected BaseObjectiveFunction getObjectiveFunction() throws Exception
{
Category optimizerCategory = getCategory(OPTIMIZER_CATEGORY_ID);
String optimizer = optimizerCategory.getSelectedSub();
Instrument instrument = getInstrument();
Tuning tuning = getTuning();
WhistleCalculator calculator = new WhistleCalculator();
EvaluatorInterface evaluator;
calculator.setInstrument(instrument);
calculator.setPhysicalParameters(params);
BaseObjectiveFunction objective = null;
double[] lowerBound = null;
double[] upperBound = null;
switch (optimizer)
{
case WINDOW_OPT_SUB_CATEGORY_ID:
evaluator = new FmaxEvaluator(calculator);
objective = new WindowHeightObjectiveFunction(calculator,
tuning, evaluator);
lowerBound = new double[] { 0.000 };
upperBound = new double[] { 0.010 };
break;
case BETA_OPT_SUB_CATEGORY_ID:
evaluator = new FminEvaluator(calculator);
objective = new BetaObjectiveFunction(calculator, tuning,
evaluator);
lowerBound = new double[] { 0.2 };
upperBound = new double[] { 0.5 };
break;
case LENGTH_OPT_SUB_CATEGORY_ID:
evaluator = new BellNoteEvaluator(calculator);
objective = new LengthObjectiveFunction(calculator, tuning,
evaluator);
lowerBound = new double[] { 0.200 };
upperBound = new double[] { 0.700 };
break;
case HOLESIZE_OPT_SUB_CATEGORY_ID:
evaluator = new WhistleEvaluator(calculator, blowingLevel);
objective = new HoleSizeObjectiveFunction(calculator, tuning,
evaluator);
// Bounds are diameters, expressed in meters.
lowerBound = new double[] { 0.004, 0.004, 0.004, 0.004, 0.004,
0.004 };
// upperBound = new double[] { 0.010, 0.010, 0.010, 0.010,
// 0.010, 0.010 };
upperBound = new double[] { 0.009, 0.009, 0.009, 0.009, 0.009,
0.009 };
break;
case HOLESPACE_OPT_SUB_CATEGORY_ID:
evaluator = new WhistleEvaluator(calculator, blowingLevel);
objective = new HolePositionObjectiveFunction(calculator,
tuning, evaluator);
// Bounds are expressed in meters.
lowerBound = new double[] { 0.200, 0.013, 0.013, 0.013, 0.013,
0.013, 0.013 };
upperBound = new double[] { 0.700, 0.050, 0.050, 0.050, 0.050,
0.050, 0.200 };
break;
case HOLE_OPT_SUB_CATEGORY_ID:
default:
evaluator = new WhistleEvaluator(calculator, blowingLevel);
objective = new HoleObjectiveFunction(calculator, tuning,
evaluator);
// Length bounds are expressed in meters, diameter bounds as
// ratios.
lowerBound = new double[] { 0.200, 0.012, 0.012, 0.012, 0.012,
0.012, 0.012, 0.004, 0.004, 0.004, 0.004, 0.004, 0.004 };
upperBound = new double[] { 0.700, 0.050, 0.050, 0.050, 0.050,
0.050, 0.200, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010 };
break;
}
objective.setLowerBounds(lowerBound);
objective.setUpperBounds(upperBound);
return objective;
}
|
diff --git a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/launching/StandardSourcePathProvider.java b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/launching/StandardSourcePathProvider.java
index 4742ee4e3..373591409 100644
--- a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/launching/StandardSourcePathProvider.java
+++ b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/launching/StandardSourcePathProvider.java
@@ -1,87 +1,89 @@
package org.eclipse.jdt.launching;
/*******************************************************************************
* Copyright (c) 2001, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.jdt.core.IJavaProject;
/**
* Default implementation of source lookup path computation and resolution.
* <p>
* This class may be subclassed.
* </p>
* @since 2.0
*/
public class StandardSourcePathProvider extends StandardClasspathProvider {
/**
* @see IRuntimeClasspathProvider#computeUnresolvedClasspath(ILaunchConfiguration)
*/
public IRuntimeClasspathEntry[] computeUnresolvedClasspath(ILaunchConfiguration configuration) throws CoreException {
boolean useDefault = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_SOURCE_PATH, true);
IRuntimeClasspathEntry[] entries = null;
if (useDefault) {
// the default source lookup path is the same as the classpath
entries = super.computeUnresolvedClasspath(configuration);
} else {
// recover persisted source path
entries = recoverRuntimePath(configuration, IJavaLaunchConfigurationConstants.ATTR_SOURCE_PATH);
}
return entries;
}
/**
* @see IRuntimeClasspathProvider#resolveClasspath(IRuntimeClasspathEntry[], ILaunchConfiguration)
*/
public IRuntimeClasspathEntry[] resolveClasspath(IRuntimeClasspathEntry[] entries, ILaunchConfiguration configuration) throws CoreException {
boolean includeJRE = false;
IJavaProject pro = JavaRuntime.getJavaProject(configuration);
includeJRE = pro == null;
// omit JRE from source lookup path if the runtime JRE is the same as the build JRE
// (so we retrieve source from the workspace, and not an external jar)
if (!includeJRE) {
IVMInstall buildVM = JavaRuntime.getVMInstall(pro);
IVMInstall runVM = JavaRuntime.computeVMInstall(configuration);
- includeJRE = !buildVM.equals(runVM);
+ if (buildVM != null) {
+ includeJRE = !buildVM.equals(runVM);
+ }
}
if (!includeJRE) {
// remove the JRE entry
List list = new ArrayList(entries.length);
for (int i = 0; i < entries.length; i++) {
switch (entries[i].getType()) {
case IRuntimeClasspathEntry.VARIABLE:
if (!entries[i].getVariableName().equals(JavaRuntime.JRELIB_VARIABLE)) {
list.add(entries[i]);
}
break;
case IRuntimeClasspathEntry.CONTAINER:
if (!entries[i].getVariableName().equals(JavaRuntime.JRE_CONTAINER)) {
list.add(entries[i]);
}
break;
default:
list.add(entries[i]);
break;
}
}
entries = (IRuntimeClasspathEntry[]) list.toArray(new IRuntimeClasspathEntry[list.size()]);
}
return super.resolveClasspath(entries, configuration);
}
}
| true | true | public IRuntimeClasspathEntry[] resolveClasspath(IRuntimeClasspathEntry[] entries, ILaunchConfiguration configuration) throws CoreException {
boolean includeJRE = false;
IJavaProject pro = JavaRuntime.getJavaProject(configuration);
includeJRE = pro == null;
// omit JRE from source lookup path if the runtime JRE is the same as the build JRE
// (so we retrieve source from the workspace, and not an external jar)
if (!includeJRE) {
IVMInstall buildVM = JavaRuntime.getVMInstall(pro);
IVMInstall runVM = JavaRuntime.computeVMInstall(configuration);
includeJRE = !buildVM.equals(runVM);
}
if (!includeJRE) {
// remove the JRE entry
List list = new ArrayList(entries.length);
for (int i = 0; i < entries.length; i++) {
switch (entries[i].getType()) {
case IRuntimeClasspathEntry.VARIABLE:
if (!entries[i].getVariableName().equals(JavaRuntime.JRELIB_VARIABLE)) {
list.add(entries[i]);
}
break;
case IRuntimeClasspathEntry.CONTAINER:
if (!entries[i].getVariableName().equals(JavaRuntime.JRE_CONTAINER)) {
list.add(entries[i]);
}
break;
default:
list.add(entries[i]);
break;
}
}
entries = (IRuntimeClasspathEntry[]) list.toArray(new IRuntimeClasspathEntry[list.size()]);
}
return super.resolveClasspath(entries, configuration);
}
| public IRuntimeClasspathEntry[] resolveClasspath(IRuntimeClasspathEntry[] entries, ILaunchConfiguration configuration) throws CoreException {
boolean includeJRE = false;
IJavaProject pro = JavaRuntime.getJavaProject(configuration);
includeJRE = pro == null;
// omit JRE from source lookup path if the runtime JRE is the same as the build JRE
// (so we retrieve source from the workspace, and not an external jar)
if (!includeJRE) {
IVMInstall buildVM = JavaRuntime.getVMInstall(pro);
IVMInstall runVM = JavaRuntime.computeVMInstall(configuration);
if (buildVM != null) {
includeJRE = !buildVM.equals(runVM);
}
}
if (!includeJRE) {
// remove the JRE entry
List list = new ArrayList(entries.length);
for (int i = 0; i < entries.length; i++) {
switch (entries[i].getType()) {
case IRuntimeClasspathEntry.VARIABLE:
if (!entries[i].getVariableName().equals(JavaRuntime.JRELIB_VARIABLE)) {
list.add(entries[i]);
}
break;
case IRuntimeClasspathEntry.CONTAINER:
if (!entries[i].getVariableName().equals(JavaRuntime.JRE_CONTAINER)) {
list.add(entries[i]);
}
break;
default:
list.add(entries[i]);
break;
}
}
entries = (IRuntimeClasspathEntry[]) list.toArray(new IRuntimeClasspathEntry[list.size()]);
}
return super.resolveClasspath(entries, configuration);
}
|
diff --git a/src/main/java/at/yawk/fimficiton/operation/GetStoryMetaOperation.java b/src/main/java/at/yawk/fimficiton/operation/GetStoryMetaOperation.java
index 6e9da02..36a5174 100644
--- a/src/main/java/at/yawk/fimficiton/operation/GetStoryMetaOperation.java
+++ b/src/main/java/at/yawk/fimficiton/operation/GetStoryMetaOperation.java
@@ -1,116 +1,116 @@
package at.yawk.fimficiton.operation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import lombok.AccessLevel;
import lombok.Cleanup;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.experimental.FieldDefaults;
import org.xml.sax.SAXException;
import at.yawk.fimficiton.FimFiction;
import at.yawk.fimficiton.Story;
import at.yawk.fimficiton.html.FullSearchParser;
import at.yawk.fimficiton.json.StoryParser;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* Request story metadata.
*
* @author Yawkat
*/
@Getter
@FieldDefaults(level = AccessLevel.PRIVATE)
@EqualsAndHashCode(callSuper = false)
@RequiredArgsConstructor
public class GetStoryMetaOperation extends AbstractRequest<Story> {
/**
* Story for which information should be requested. Right now, only the
* {@link Story#id} field is required but try to provide as accurate
* information as possible nonetheless.
*/
@NonNull final Story storyFor;
/**
* {@link RequestMethod} to use to get story metadata.
*/
@NonNull @Setter RequestMethod requestMethod = RequestMethod.JSON;
@Override
protected Story request(final FimFiction session) throws Exception {
switch (this.requestMethod) {
case JSON:
return this.requestJson();
case WEB:
return this.requestFull(session);
default:
throw new IllegalStateException();
}
}
/**
* Load story data using JSON request.
*/
private Story requestJson() throws IOException {
// prepare URL
final URL targeting = new URL("http://fimfiction.net/api/story.php?story=" + this.storyFor.getId());
// download and convert to JsonObject using Gson
final JsonObject returned;
final InputStream request = targeting.openStream();
try {
returned = new JsonParser().parse(new InputStreamReader(request)).getAsJsonObject();
} finally {
request.close();
}
// parse JSON data
final StoryParser parser = new StoryParser();
- return parser.parse(returned);
+ return parser.parse(returned.getAsJsonObject("story"));
}
private Story requestFull(final FimFiction session) throws IOException, SAXException {
// prepare URL
final URL targeting = new URL("http://fimfiction.net/story/" + this.storyFor.getId());
final URLConnection connection = targeting.openConnection();
connection.setRequestProperty("Cookie", Util.getCookies(session));
connection.connect();
@Cleanup final Reader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
return new FullSearchParser().parse(reader).get(0);
}
/**
* Request method to be used to download story metadata. Different methods
* may differ in speed, failure frequency and accuracy.
*/
public static enum RequestMethod {
/**
* Fast, accurate and pretty low exception rate. Uses
* {@link StoryParser}. Does not return sex/gore flags and characters or
* any user-related metadata such as favorite status.
*/
JSON,
/**
* Slow compared to {@link #JSON}, very likely to break with FimFiction
* updates. Try to avoid this if you don't need sex/gore flags,
* characters or account-specific information. Parses the story page and
* also returns data such as favorite status, read / unread chapters,
* like token etc.
*/
WEB;
}
}
| true | true | private Story requestJson() throws IOException {
// prepare URL
final URL targeting = new URL("http://fimfiction.net/api/story.php?story=" + this.storyFor.getId());
// download and convert to JsonObject using Gson
final JsonObject returned;
final InputStream request = targeting.openStream();
try {
returned = new JsonParser().parse(new InputStreamReader(request)).getAsJsonObject();
} finally {
request.close();
}
// parse JSON data
final StoryParser parser = new StoryParser();
return parser.parse(returned);
}
| private Story requestJson() throws IOException {
// prepare URL
final URL targeting = new URL("http://fimfiction.net/api/story.php?story=" + this.storyFor.getId());
// download and convert to JsonObject using Gson
final JsonObject returned;
final InputStream request = targeting.openStream();
try {
returned = new JsonParser().parse(new InputStreamReader(request)).getAsJsonObject();
} finally {
request.close();
}
// parse JSON data
final StoryParser parser = new StoryParser();
return parser.parse(returned.getAsJsonObject("story"));
}
|
diff --git a/codecs/src/test/java/com/github/t1/webresource/log/LoggingInterceptorTest.java b/codecs/src/test/java/com/github/t1/webresource/log/LoggingInterceptorTest.java
index 228fa18..0f2c73f 100644
--- a/codecs/src/test/java/com/github/t1/webresource/log/LoggingInterceptorTest.java
+++ b/codecs/src/test/java/com/github/t1/webresource/log/LoggingInterceptorTest.java
@@ -1,254 +1,254 @@
package com.github.t1.webresource.log;
import static com.github.t1.webresource.log.LogLevel.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.lang.reflect.Method;
import javax.interceptor.InvocationContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.*;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.slf4j.*;
@RunWith(MockitoJUnitRunner.class)
public class LoggingInterceptorTest {
@InjectMocks
LoggingInterceptor interceptor = new LoggingInterceptor() {
@Override
Logger getLogger(java.lang.Class<?> type) {
LoggingInterceptorTest.this.loggerType = type;
return logger;
};
};
@Mock
InvocationContext context;
@Mock
Logger logger;
Class<?> loggerType;
private void whenDebugEnabled() {
when(logger.isDebugEnabled()).thenReturn(true);
}
private void whenMethod(Method method, Object... args) throws ReflectiveOperationException {
when(context.getTarget()).thenReturn("dummy");
when(context.getMethod()).thenReturn(method);
when(context.getParameters()).thenReturn(args);
}
@Test
public void shouldLogALongMethodNameWithSpaces() throws Exception {
class Container {
@Logged
public void methodWithALongName() {}
}
whenDebugEnabled();
whenMethod(Container.class.getMethod("methodWithALongName"));
interceptor.aroundInvoke(context);
verify(logger).debug("method with a long name", new Object[0]);
}
@Test
public void shouldLogAnAnnotatedMethod() throws Exception {
class Container {
@Logged("bar")
public void foo() {}
}
whenDebugEnabled();
whenMethod(Container.class.getMethod("foo"));
interceptor.aroundInvoke(context);
verify(logger).debug("bar", new Object[0]);
}
@Test
public void shouldLogReturnValue() throws Exception {
class Container {
@Logged
public boolean methodWithReturnType() {
return true;
}
}
whenDebugEnabled();
whenMethod(Container.class.getMethod("methodWithReturnType"));
when(context.proceed()).thenReturn(true);
interceptor.aroundInvoke(context);
verify(logger).debug("returns {}", new Object[] { true });
}
@Test
public void shouldLogException() throws Exception {
class Container {
@Logged
public boolean methodThatMightFail() {
return true;
}
}
whenDebugEnabled();
whenMethod(Container.class.getMethod("methodThatMightFail"));
RuntimeException exception = new RuntimeException("foo");
when(context.proceed()).thenThrow(exception);
try {
interceptor.aroundInvoke(context);
fail("RuntimeException expected");
} catch (RuntimeException e) {
// that's okay
}
verify(logger).debug("failed", exception);
}
@Test
public void shouldNotLogVoidReturnValue() throws Exception {
class Container {
@Logged
public void voidReturnType() {}
}
whenDebugEnabled();
whenMethod(Container.class.getMethod("voidReturnType"));
interceptor.aroundInvoke(context);
verify(logger).debug("void return type", new Object[0]);
verify(logger, atLeast(0)).isDebugEnabled();
verifyNoMoreInteractions(logger);
}
@Test
public void shouldLogIntParameter() throws Exception {
class Container {
@Logged
public void methodWithIntArgument(int i) {}
}
whenDebugEnabled();
whenMethod(Container.class.getMethod("methodWithIntArgument", int.class), 3);
interceptor.aroundInvoke(context);
verify(logger).debug("method with int argument", new Object[] { 3 });
}
@Test
public void shouldLogIntegerParameter() throws Exception {
class Container {
@Logged
public void methodWithIntegerArgument(Integer i) {}
}
whenDebugEnabled();
whenMethod(Container.class.getMethod("methodWithIntegerArgument", Integer.class), 3);
interceptor.aroundInvoke(context);
verify(logger).debug("method with integer argument", new Object[] { 3 });
}
@Test
public void shouldLogTwoParameters() throws Exception {
class Container {
@Logged
public void methodWithTwoParameters(String one, String two) {}
}
whenDebugEnabled();
Method method = Container.class.getMethod("methodWithTwoParameters", String.class, String.class);
whenMethod(method, "foo", "bar");
interceptor.aroundInvoke(context);
verify(logger).debug("method with two parameters", new Object[] { "foo", "bar" });
}
@Test
public void shouldNotLogWhenOff() throws Exception {
class Container {
@Logged(level = OFF)
public void atOff() {}
}
whenDebugEnabled();
whenMethod(Container.class.getMethod("atOff"));
interceptor.aroundInvoke(context);
verifyNoMoreInteractions(logger);
}
@Test
public void shouldNotLogWhenDebugIsNotEnabled() throws Exception {
class Container {
@Logged(level = DEBUG)
public void atDebug() {}
}
whenMethod(Container.class.getMethod("atDebug"));
interceptor.aroundInvoke(context);
verify(logger, atLeast(0)).isDebugEnabled();
verifyNoMoreInteractions(logger);
}
@Test
public void shouldLogInfoWhenInfoIsEnabled() throws Exception {
class Container {
@Logged(level = INFO)
public void atInfo() {}
}
whenDebugEnabled();
when(logger.isInfoEnabled()).thenReturn(true);
whenMethod(Container.class.getMethod("atInfo"));
interceptor.aroundInvoke(context);
verify(logger).info("at info", new Object[0]);
}
@Test
public void shouldLogExplicitClass() throws Exception {
class Container {
@Logged(logger = Integer.class)
public void foo() {}
}
whenDebugEnabled();
whenMethod(Container.class.getMethod("foo"));
interceptor.aroundInvoke(context);
assertEquals(Integer.class, loggerType);
}
@Test
public void shouldLogLogContextParameter() throws Exception {
final String KEY = "user-id";
class Container {
@Logged
public void methodWithLogContextParameter(@LogContext(KEY) String one, String two) {}
}
whenDebugEnabled();
Method method = Container.class.getMethod("methodWithLogContextParameter", String.class, String.class);
whenMethod(method, "foo", "bar");
final String[] userId = new String[1];
when(context.proceed()).thenAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
userId[0] = MDC.get(KEY);
return null;
}
});
- assertNull(MDC.get(KEY));
+ MDC.put(KEY, "bar");
interceptor.aroundInvoke(context);
- assertNull(MDC.get(KEY));
+ assertEquals("bar", MDC.get(KEY));
verify(logger).debug("method with log context parameter", new Object[] { "foo", "bar" });
assertEquals("foo", userId[0]);
}
}
| false | true | public void shouldLogLogContextParameter() throws Exception {
final String KEY = "user-id";
class Container {
@Logged
public void methodWithLogContextParameter(@LogContext(KEY) String one, String two) {}
}
whenDebugEnabled();
Method method = Container.class.getMethod("methodWithLogContextParameter", String.class, String.class);
whenMethod(method, "foo", "bar");
final String[] userId = new String[1];
when(context.proceed()).thenAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
userId[0] = MDC.get(KEY);
return null;
}
});
assertNull(MDC.get(KEY));
interceptor.aroundInvoke(context);
assertNull(MDC.get(KEY));
verify(logger).debug("method with log context parameter", new Object[] { "foo", "bar" });
| public void shouldLogLogContextParameter() throws Exception {
final String KEY = "user-id";
class Container {
@Logged
public void methodWithLogContextParameter(@LogContext(KEY) String one, String two) {}
}
whenDebugEnabled();
Method method = Container.class.getMethod("methodWithLogContextParameter", String.class, String.class);
whenMethod(method, "foo", "bar");
final String[] userId = new String[1];
when(context.proceed()).thenAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
userId[0] = MDC.get(KEY);
return null;
}
});
MDC.put(KEY, "bar");
interceptor.aroundInvoke(context);
assertEquals("bar", MDC.get(KEY));
verify(logger).debug("method with log context parameter", new Object[] { "foo", "bar" });
|
diff --git a/src/com/nennig/life/wheel/MainActivity.java b/src/com/nennig/life/wheel/MainActivity.java
index 6de4fb0..c0ffd72 100644
--- a/src/com/nennig/life/wheel/MainActivity.java
+++ b/src/com/nennig/life/wheel/MainActivity.java
@@ -1,186 +1,189 @@
/* 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.nennig.life.wheel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.Toast;
import com.nennig.life.wheel.R;
import com.nennig.life.wheel.charting.PieChart;
public class MainActivity extends Activity {
private int itemCount = 0;
private static final String TAG = "lifewheel.MainActivity";
private String lifeType = "Sleeping";
private float scaleValue = 0;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
itemList.add(new Slice(lifeType, 3f));
// itemList.add(new Slice("Work", 4f/pieScale, res.getColor(R.color.yellow), res.getColor(R.color.yellow_light)));
// itemList.add(new Slice("Social", 5f/pieScale, res.getColor(R.color.blue), res.getColor(R.color.blue_light)));
// itemList.add(new Slice("Personal", 6f/pieScale, res.getColor(R.color.green), res.getColor(R.color.green_light)));
// itemList.add(new Slice("Health", 7f/pieScale, res.getColor(R.color.purple), res.getColor(R.color.purple_light)));
// itemList.add(new Slice("Eating", 8f/pieScale, res.getColor(R.color.black), res.getColor(R.color.black_light)));
//
// itemList.add(new Slice("Video Games", 3f/pieScale, res.getColor(R.color.red), res.getColor(R.color.red_light)));
// itemList.add(new Slice("Drinking", 4f/pieScale, res.getColor(R.color.yellow), res.getColor(R.color.yellow_light)));
// itemList.add(new Slice("Prayer", 5f/pieScale, res.getColor(R.color.blue), res.getColor(R.color.blue_light)));
// itemList.add(new Slice("TV", 6f/pieScale, res.getColor(R.color.green), res.getColor(R.color.green_light)));
// itemList.add(new Slice("Reading", 7f/pieScale, res.getColor(R.color.purple), res.getColor(R.color.purple_light)));
// itemList.add(new Slice("Tanning", 8f/pieScale, res.getColor(R.color.black), res.getColor(R.color.black_light)));
setContentView(R.layout.main);
final PieChart pie = (PieChart) this.findViewById(R.id.Pie);
Slice _slice;
_slice =itemList.get(itemCount);
pie.addItem(_slice.label,_slice.cPercent);
itemCount++;
// _slice =itemList.get(itemCount);
// pie.addItem(_slice.label,_slice.cPercent,_slice.sliceColor,_slice.itemColor);
// itemCount++;
//Add Button
((Button) findViewById(R.id.main_add_button)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d(TAG, "BEFORE>>List: " + itemList.toString());
Slice s = new Slice(lifeType, scaleValue);
if(itemList.contains(s)){
Log.d(TAG, "UPDATING!");
pie.updateItem(s.label, s.cPercent);
}
else
{
itemList.add(s);
if(itemCount < itemList.size())
{
Slice _slice;
_slice =itemList.get(itemCount);
pie.addItem(_slice.label,_slice.cPercent);
itemCount++;
}
}
Log.d(TAG, "AFTER>>List: " + itemList.toString());
}
});
//Delete Button
((Button) findViewById(R.id.main_delete_button)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Slice s = new Slice(lifeType, scaleValue);
if(itemList.contains(s)){
- pie.removeItem(s.label);
+ if(itemList.size() == 1)
+ Toast.makeText(MainActivity.this, "Cannot delete last slice of the wheel", Toast.LENGTH_SHORT).show();
+ else
+ pie.removeItem(s.label);
}
else
{
Toast.makeText(MainActivity.this, "Category: " + lifeType + " is not currently in your chart", Toast.LENGTH_SHORT).show();
}
//Code to Delete Last Label
// if((itemCount - 1) > 0)
// {
// Slice _slice;
// _slice =itemList.get(itemCount - 1);
// pie.removeItem(_slice.label);
// itemList.remove(itemCount - 1);
// itemCount--;
// }
}
});
((Spinner) findViewById(R.id.main_name_spinner)).setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
lifeType = adapter.getItemAtPosition(i).toString();
Log.d(TAG,"lifeType Changed to: " +lifeType);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {}
});
((Spinner) findViewById(R.id.main_scale_spinner)).setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
scaleValue = Float.parseFloat(adapter.getItemAtPosition(i).toString());
Log.d(TAG,"lifeType Changed to: " +lifeType);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {}
});
}
public static List<Slice> itemList = new ArrayList<Slice>();
//This is a simple slice class to manage the data that is changing by the user
private class Slice {
public String label; //Name of the slice
// public int itemColor; //item color that fills part of the slice
// public int sliceColor; //slice color that shows behind the item
public float cPercent; //
public Slice(String l, float p) {
label = l;
cPercent = p;
}
@Override
public boolean equals(Object obj){
if (obj == null) return false;
if (!(obj instanceof Slice))return false;
Slice s = (Slice) obj;
if(s.label.equals(label))
return true;
return false;
}
@Override
public String toString(){
return label + " <" + cPercent + ">";
}
// public Slice(String l, float p, int sColor, int iColor) {
// label = l;
// cPercent = p;
// sliceColor = sColor;
// itemColor = iColor;
// }
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
itemList.add(new Slice(lifeType, 3f));
// itemList.add(new Slice("Work", 4f/pieScale, res.getColor(R.color.yellow), res.getColor(R.color.yellow_light)));
// itemList.add(new Slice("Social", 5f/pieScale, res.getColor(R.color.blue), res.getColor(R.color.blue_light)));
// itemList.add(new Slice("Personal", 6f/pieScale, res.getColor(R.color.green), res.getColor(R.color.green_light)));
// itemList.add(new Slice("Health", 7f/pieScale, res.getColor(R.color.purple), res.getColor(R.color.purple_light)));
// itemList.add(new Slice("Eating", 8f/pieScale, res.getColor(R.color.black), res.getColor(R.color.black_light)));
//
// itemList.add(new Slice("Video Games", 3f/pieScale, res.getColor(R.color.red), res.getColor(R.color.red_light)));
// itemList.add(new Slice("Drinking", 4f/pieScale, res.getColor(R.color.yellow), res.getColor(R.color.yellow_light)));
// itemList.add(new Slice("Prayer", 5f/pieScale, res.getColor(R.color.blue), res.getColor(R.color.blue_light)));
// itemList.add(new Slice("TV", 6f/pieScale, res.getColor(R.color.green), res.getColor(R.color.green_light)));
// itemList.add(new Slice("Reading", 7f/pieScale, res.getColor(R.color.purple), res.getColor(R.color.purple_light)));
// itemList.add(new Slice("Tanning", 8f/pieScale, res.getColor(R.color.black), res.getColor(R.color.black_light)));
setContentView(R.layout.main);
final PieChart pie = (PieChart) this.findViewById(R.id.Pie);
Slice _slice;
_slice =itemList.get(itemCount);
pie.addItem(_slice.label,_slice.cPercent);
itemCount++;
// _slice =itemList.get(itemCount);
// pie.addItem(_slice.label,_slice.cPercent,_slice.sliceColor,_slice.itemColor);
// itemCount++;
//Add Button
((Button) findViewById(R.id.main_add_button)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d(TAG, "BEFORE>>List: " + itemList.toString());
Slice s = new Slice(lifeType, scaleValue);
if(itemList.contains(s)){
Log.d(TAG, "UPDATING!");
pie.updateItem(s.label, s.cPercent);
}
else
{
itemList.add(s);
if(itemCount < itemList.size())
{
Slice _slice;
_slice =itemList.get(itemCount);
pie.addItem(_slice.label,_slice.cPercent);
itemCount++;
}
}
Log.d(TAG, "AFTER>>List: " + itemList.toString());
}
});
//Delete Button
((Button) findViewById(R.id.main_delete_button)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Slice s = new Slice(lifeType, scaleValue);
if(itemList.contains(s)){
pie.removeItem(s.label);
}
else
{
Toast.makeText(MainActivity.this, "Category: " + lifeType + " is not currently in your chart", Toast.LENGTH_SHORT).show();
}
//Code to Delete Last Label
// if((itemCount - 1) > 0)
// {
// Slice _slice;
// _slice =itemList.get(itemCount - 1);
// pie.removeItem(_slice.label);
// itemList.remove(itemCount - 1);
// itemCount--;
// }
}
});
((Spinner) findViewById(R.id.main_name_spinner)).setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
lifeType = adapter.getItemAtPosition(i).toString();
Log.d(TAG,"lifeType Changed to: " +lifeType);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {}
});
((Spinner) findViewById(R.id.main_scale_spinner)).setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
scaleValue = Float.parseFloat(adapter.getItemAtPosition(i).toString());
Log.d(TAG,"lifeType Changed to: " +lifeType);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
itemList.add(new Slice(lifeType, 3f));
// itemList.add(new Slice("Work", 4f/pieScale, res.getColor(R.color.yellow), res.getColor(R.color.yellow_light)));
// itemList.add(new Slice("Social", 5f/pieScale, res.getColor(R.color.blue), res.getColor(R.color.blue_light)));
// itemList.add(new Slice("Personal", 6f/pieScale, res.getColor(R.color.green), res.getColor(R.color.green_light)));
// itemList.add(new Slice("Health", 7f/pieScale, res.getColor(R.color.purple), res.getColor(R.color.purple_light)));
// itemList.add(new Slice("Eating", 8f/pieScale, res.getColor(R.color.black), res.getColor(R.color.black_light)));
//
// itemList.add(new Slice("Video Games", 3f/pieScale, res.getColor(R.color.red), res.getColor(R.color.red_light)));
// itemList.add(new Slice("Drinking", 4f/pieScale, res.getColor(R.color.yellow), res.getColor(R.color.yellow_light)));
// itemList.add(new Slice("Prayer", 5f/pieScale, res.getColor(R.color.blue), res.getColor(R.color.blue_light)));
// itemList.add(new Slice("TV", 6f/pieScale, res.getColor(R.color.green), res.getColor(R.color.green_light)));
// itemList.add(new Slice("Reading", 7f/pieScale, res.getColor(R.color.purple), res.getColor(R.color.purple_light)));
// itemList.add(new Slice("Tanning", 8f/pieScale, res.getColor(R.color.black), res.getColor(R.color.black_light)));
setContentView(R.layout.main);
final PieChart pie = (PieChart) this.findViewById(R.id.Pie);
Slice _slice;
_slice =itemList.get(itemCount);
pie.addItem(_slice.label,_slice.cPercent);
itemCount++;
// _slice =itemList.get(itemCount);
// pie.addItem(_slice.label,_slice.cPercent,_slice.sliceColor,_slice.itemColor);
// itemCount++;
//Add Button
((Button) findViewById(R.id.main_add_button)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d(TAG, "BEFORE>>List: " + itemList.toString());
Slice s = new Slice(lifeType, scaleValue);
if(itemList.contains(s)){
Log.d(TAG, "UPDATING!");
pie.updateItem(s.label, s.cPercent);
}
else
{
itemList.add(s);
if(itemCount < itemList.size())
{
Slice _slice;
_slice =itemList.get(itemCount);
pie.addItem(_slice.label,_slice.cPercent);
itemCount++;
}
}
Log.d(TAG, "AFTER>>List: " + itemList.toString());
}
});
//Delete Button
((Button) findViewById(R.id.main_delete_button)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Slice s = new Slice(lifeType, scaleValue);
if(itemList.contains(s)){
if(itemList.size() == 1)
Toast.makeText(MainActivity.this, "Cannot delete last slice of the wheel", Toast.LENGTH_SHORT).show();
else
pie.removeItem(s.label);
}
else
{
Toast.makeText(MainActivity.this, "Category: " + lifeType + " is not currently in your chart", Toast.LENGTH_SHORT).show();
}
//Code to Delete Last Label
// if((itemCount - 1) > 0)
// {
// Slice _slice;
// _slice =itemList.get(itemCount - 1);
// pie.removeItem(_slice.label);
// itemList.remove(itemCount - 1);
// itemCount--;
// }
}
});
((Spinner) findViewById(R.id.main_name_spinner)).setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
lifeType = adapter.getItemAtPosition(i).toString();
Log.d(TAG,"lifeType Changed to: " +lifeType);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {}
});
((Spinner) findViewById(R.id.main_scale_spinner)).setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
scaleValue = Float.parseFloat(adapter.getItemAtPosition(i).toString());
Log.d(TAG,"lifeType Changed to: " +lifeType);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {}
});
}
|
diff --git a/src/info/micdm/munin_client/NodeActivity.java b/src/info/micdm/munin_client/NodeActivity.java
index 2f7824b..76f5cda 100644
--- a/src/info/micdm/munin_client/NodeActivity.java
+++ b/src/info/micdm/munin_client/NodeActivity.java
@@ -1,192 +1,191 @@
package info.micdm.munin_client;
import info.micdm.munin_client.events.Event;
import info.micdm.munin_client.events.EventDispatcher;
import info.micdm.munin_client.events.EventListener;
import info.micdm.munin_client.graph.GraphView;
import info.micdm.munin_client.models.Node;
import info.micdm.munin_client.models.Server;
import info.micdm.munin_client.models.ServerList;
import info.micdm.munin_client.reports.Report;
import info.micdm.munin_client.reports.ReportLoader;
import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* Экран с информацией о ноде.
* @author Mic, 2011
*
*/
public class NodeActivity extends Activity {
/**
* Отображаемый сервер.
*/
protected Server _server;
/**
* Отображаемая нода.
*/
protected Node _node;
/**
* Отображаемый тип отчетов.
*/
protected int _reportTypeIndex = 0;
/**
* Отображаемый период.
*/
protected Report.Period _reportPeriod = Report.Period.HOUR;
/**
* Запоминает сервер и ноду для отображения.
*/
protected void _setServerAndNode(Bundle bundle) {
String serverName = bundle.getString("server");
String nodeName = bundle.getString("node");
_server = ServerList.INSTANCE.get(serverName);
_node = _server.getNode(nodeName);
}
/**
* Загружает отчет.
*/
protected void _loadReport() {
Report.Type type = _node.getReportTypes().get(_reportTypeIndex);
ReportLoader.INSTANCE.load(_server, _node, type, _reportPeriod);
}
/**
* Загружает предыдущий доступный отчет.
*/
protected void _loadPreviousByType() {
if (_reportTypeIndex == 0) {
_reportTypeIndex = _node.getReportTypes().size() - 1;
} else {
_reportTypeIndex -= 1;
}
_loadReport();
}
/**
* Загружает следующий доступный отчет.
*/
protected void _loadNextByType() {
if (_reportTypeIndex >= _node.getReportTypes().size() - 1) {
_reportTypeIndex = 0;
} else {
_reportTypeIndex += 1;
}
_loadReport();
}
/**
* Загружает предыдущий доступный отчет.
*/
protected void _loadPreviousByPeriod() {
_reportPeriod = (_reportPeriod == Report.Period.HOUR) ? Report.Period.DAY : Report.Period.HOUR;
_loadReport();
}
/**
* Загружает следующий доступный отчет.
*/
protected void _loadNextByPeriod() {
_reportPeriod = (_reportPeriod == Report.Period.HOUR) ? Report.Period.DAY : Report.Period.HOUR;
_loadReport();
}
/**
* Выполняется при событии прокрутки.
*/
protected boolean _onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
- if (Math.abs(e1.getY() - e2.getY()) < 200) {
+ if (Math.abs(velocityX) > Math.abs(velocityY)) {
if (velocityX < 0) {
_loadNextByType();
return true;
}
if (velocityX > 0) {
_loadPreviousByType();
return true;
}
- }
- if (Math.abs(e1.getX() - e2.getX()) < 200) {
+ } else {
if (velocityY < 0) {
_loadNextByPeriod();
return true;
}
if (velocityY > 0) {
_loadPreviousByPeriod();
return true;
}
}
return false;
}
/**
* Слушает событие прокрутки, чтобы менять графики.
*/
protected void _listenToFling() {
final GestureDetector detector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return _onFling(e1, e2, velocityX, velocityY);
}
});
findViewById(R.id.graph).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
detector.onTouchEvent(event);
return true;
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.node);
_setServerAndNode(getIntent().getExtras());
_listenToFling();
}
/**
* Добавляет слушатели событий.
*/
protected void _addListeners() {
EventDispatcher.addListener(Event.Type.REPORT_AVAILABLE, new EventListener(this) {
@Override
public void notify(Event event) {
Object[] extra = event.getExtra();
Report report = (Report)extra[0];
GraphView view = (GraphView)findViewById(R.id.graph);
view.setReport(report);
}
});
}
@Override
public void onResume() {
super.onResume();
_addListeners();
_loadReport();
}
/**
* Удаляет все слушатели событий.
*/
protected void _removeListeners() {
EventDispatcher.removeAllListeners(this);
}
@Override
public void onPause() {
super.onPause();
_removeListeners();
}
}
| false | true | protected boolean _onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (Math.abs(e1.getY() - e2.getY()) < 200) {
if (velocityX < 0) {
_loadNextByType();
return true;
}
if (velocityX > 0) {
_loadPreviousByType();
return true;
}
}
if (Math.abs(e1.getX() - e2.getX()) < 200) {
if (velocityY < 0) {
_loadNextByPeriod();
return true;
}
if (velocityY > 0) {
_loadPreviousByPeriod();
return true;
}
}
return false;
}
| protected boolean _onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (Math.abs(velocityX) > Math.abs(velocityY)) {
if (velocityX < 0) {
_loadNextByType();
return true;
}
if (velocityX > 0) {
_loadPreviousByType();
return true;
}
} else {
if (velocityY < 0) {
_loadNextByPeriod();
return true;
}
if (velocityY > 0) {
_loadPreviousByPeriod();
return true;
}
}
return false;
}
|
diff --git a/src/main/java/org/werti/uima/ae/relevance/GenericRelevanceAnnotator.java b/src/main/java/org/werti/uima/ae/relevance/GenericRelevanceAnnotator.java
index 6721f91..dc54248 100644
--- a/src/main/java/org/werti/uima/ae/relevance/GenericRelevanceAnnotator.java
+++ b/src/main/java/org/werti/uima/ae/relevance/GenericRelevanceAnnotator.java
@@ -1,105 +1,105 @@
package org.werti.uima.ae.relevance;
import java.util.EmptyStackException;
import java.util.Iterator;
import java.util.Stack;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.FSIndex;
import org.apache.uima.jcas.JCas;
import org.werti.uima.types.annot.HTML;
import org.werti.uima.types.annot.RelevantText;
/**
* Generic relevance annotator.
*
* Looks at the HTML tags of a document and determines what would be suitable input
* for the PoS tagger and the input enhancer.
*
* Sometimes this will mark garbage. It might prove hard to actually fix this, though.
*
* Tha tags currently ignored are stored in the <tt>HTMLAnnotator</tt>'s code.
*
* @author Aleksandar Dimitrov
* @version 0.1
*/
public class GenericRelevanceAnnotator extends JCasAnnotator_ImplBase {
private static final Logger log =
Logger.getLogger(GenericRelevanceAnnotator.class);
private static final Pattern whiteSpacePattern = Pattern.compile("^\\s*$");
/**
* Searches for the document body, then goes on and tags everything it deems
* relevant as RelevantTag.
*
* The 'relevance'-notion is a primitive one. We just don't care about stuff that is
* enclosed in, say <i><script></i> tags. Whether or not a tag is relevant is
* determined by the <tt>HTMLAnnotator</tt>. We only look at an html tag's 'relevance'
* field here.
*
* @param cas The document's cas.
*/
@SuppressWarnings("unchecked")
public void process(JCas cas) throws AnalysisEngineProcessException {
log.info("Starting relevance annotation");
final Stack<String> tags = new Stack<String>();
final FSIndex tagIndex = cas.getAnnotationIndex(HTML.type);
final Iterator<HTML> tit = tagIndex.iterator();
HTML tag = tit.next();
if (tag == null) {
throw new AnalysisEngineProcessException(
new NullPointerException("No Html tags were found!"));
}
// skip ahead to the body
while (tit.hasNext()){
tag = tit.next();
- final String tname = tag.getTag_name();
+ final String tname = tag.getTag_name().toLowerCase();
if (tname.equals("/head")
|| tname.equals("body")) {
tags.push(tname);
break;
}
}
// read in all the natural language you can find
findreltxt: while (tit.hasNext()) {
- final String tname = tag.getTag_name();
+ final String tname = tag.getTag_name().toLowerCase();
tags.push(tname);
// weed out tags we don't need
if (tag.getIrrelevant()) {
tag = tit.next();
continue findreltxt;
}
// if it's a closing tag, we reduce the tag stack to find the matching opener
if (tag.getClosing()) {
try {
while (tags.pop().equals(tname)); // read: until not...
} catch (EmptyStackException ese) {
log.debug("Tag Stack broken. Tried to match " + tname);
}
}
final RelevantText rt = new RelevantText(cas);
rt.setBegin(tag.getEnd());
rt.setEnd((tag = tit.next()).getBegin());
if (whiteSpacePattern.matcher(rt.getCoveredText()).matches())
continue findreltxt;
rt.setEnclosing_tag(tname);
rt.addToIndexes();
}
log.info("Finished relevance annotation");
}
}
| false | true | public void process(JCas cas) throws AnalysisEngineProcessException {
log.info("Starting relevance annotation");
final Stack<String> tags = new Stack<String>();
final FSIndex tagIndex = cas.getAnnotationIndex(HTML.type);
final Iterator<HTML> tit = tagIndex.iterator();
HTML tag = tit.next();
if (tag == null) {
throw new AnalysisEngineProcessException(
new NullPointerException("No Html tags were found!"));
}
// skip ahead to the body
while (tit.hasNext()){
tag = tit.next();
final String tname = tag.getTag_name();
if (tname.equals("/head")
|| tname.equals("body")) {
tags.push(tname);
break;
}
}
// read in all the natural language you can find
findreltxt: while (tit.hasNext()) {
final String tname = tag.getTag_name();
tags.push(tname);
// weed out tags we don't need
if (tag.getIrrelevant()) {
tag = tit.next();
continue findreltxt;
}
// if it's a closing tag, we reduce the tag stack to find the matching opener
if (tag.getClosing()) {
try {
while (tags.pop().equals(tname)); // read: until not...
} catch (EmptyStackException ese) {
log.debug("Tag Stack broken. Tried to match " + tname);
}
}
final RelevantText rt = new RelevantText(cas);
rt.setBegin(tag.getEnd());
rt.setEnd((tag = tit.next()).getBegin());
if (whiteSpacePattern.matcher(rt.getCoveredText()).matches())
continue findreltxt;
rt.setEnclosing_tag(tname);
rt.addToIndexes();
}
log.info("Finished relevance annotation");
}
| public void process(JCas cas) throws AnalysisEngineProcessException {
log.info("Starting relevance annotation");
final Stack<String> tags = new Stack<String>();
final FSIndex tagIndex = cas.getAnnotationIndex(HTML.type);
final Iterator<HTML> tit = tagIndex.iterator();
HTML tag = tit.next();
if (tag == null) {
throw new AnalysisEngineProcessException(
new NullPointerException("No Html tags were found!"));
}
// skip ahead to the body
while (tit.hasNext()){
tag = tit.next();
final String tname = tag.getTag_name().toLowerCase();
if (tname.equals("/head")
|| tname.equals("body")) {
tags.push(tname);
break;
}
}
// read in all the natural language you can find
findreltxt: while (tit.hasNext()) {
final String tname = tag.getTag_name().toLowerCase();
tags.push(tname);
// weed out tags we don't need
if (tag.getIrrelevant()) {
tag = tit.next();
continue findreltxt;
}
// if it's a closing tag, we reduce the tag stack to find the matching opener
if (tag.getClosing()) {
try {
while (tags.pop().equals(tname)); // read: until not...
} catch (EmptyStackException ese) {
log.debug("Tag Stack broken. Tried to match " + tname);
}
}
final RelevantText rt = new RelevantText(cas);
rt.setBegin(tag.getEnd());
rt.setEnd((tag = tit.next()).getBegin());
if (whiteSpacePattern.matcher(rt.getCoveredText()).matches())
continue findreltxt;
rt.setEnclosing_tag(tname);
rt.addToIndexes();
}
log.info("Finished relevance annotation");
}
|
diff --git a/src/java/axiom/scripting/rhino/RhinoCore.java b/src/java/axiom/scripting/rhino/RhinoCore.java
index ac63d6c..cfeeea9 100755
--- a/src/java/axiom/scripting/rhino/RhinoCore.java
+++ b/src/java/axiom/scripting/rhino/RhinoCore.java
@@ -1,1284 +1,1284 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile: RhinoCore.java,v $
* $Author: hannes $
* $Revision: 1.90 $
* $Date: 2006/05/12 13:30:47 $
*/
/*
* Modified by:
*
* Axiom Software Inc., 11480 Commerce Park Drive, Third Floor, Reston, VA 20191 USA
* email: [email protected]
*/
package axiom.scripting.rhino;
import org.mozilla.javascript.*;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;
import axiom.framework.ErrorReporter;
import axiom.framework.core.*;
import axiom.framework.repository.Resource;
import axiom.objectmodel.*;
import axiom.objectmodel.db.DbMapping;
import axiom.objectmodel.db.DbSource;
import axiom.scripting.*;
import axiom.scripting.rhino.extensions.*;
import axiom.scripting.rhino.extensions.activex.ActiveX;
import axiom.util.CacheMap;
import axiom.util.ResourceProperties;
import axiom.util.SystemMap;
import axiom.util.TALTemplate;
import axiom.util.WeakCacheMap;
import axiom.util.WrappedMap;
import java.io.*;
import java.text.*;
import java.util.*;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
/**
* This is the implementation of ScriptingEnvironment for the Mozilla Rhino EcmaScript interpreter.
*/
public final class RhinoCore implements ScopeProvider {
// the application we're running in
public final Application app;
// the global object
GlobalObject global;
// caching table for JavaScript object wrappers
CacheMap wrappercache;
// table containing JavaScript prototypes
Hashtable prototypes;
// timestamp of last type update
volatile long lastUpdate = 0;
// the wrap factory
WrapFactory wrapper;
// the prototype for AxiomObject
ScriptableObject axiomObjectProto;
// the prototype for FileObject
ScriptableObject fileObjectProto;
// the prototype for ImageObject
ScriptableObject imageObjectProto;
// Any error that may have been found in global code
String globalError;
// dynamic portion of the type check sleep that grows
// as the app remains unchanged
long updateSnooze = 500;
// Prevent prototype resource checks from occuring
// upon every request, but rather, the resource update checks should occur by demand
private boolean isInitialized = false;
/* tal migration
*
*/
static HashMap templates = new HashMap();
private static HashMap cache = new HashMap();
protected static String DEBUGGER_PROPERTY = "rhino.debugger";
/**
* Create a Rhino evaluator for the given application and request evaluator.
*/
public RhinoCore(Application app) {
this.app = app;
wrappercache = new WeakCacheMap(500);
prototypes = new Hashtable();
Context context = Context.enter();
context.setLanguageVersion(170);
context.setCompileFunctionsWithDynamicScope(true);
context.setApplicationClassLoader(app.getClassLoader());
wrapper = new WrapMaker();
wrapper.setJavaPrimitiveWrap(false);
context.setWrapFactory(wrapper);
// Set default optimization level according to whether debugger is on
- int optLevel = "true".equals(app.getProperty(DEBUGGER_PROPERTY)) ? 0 : -1;
+ int optLevel = "true".equals(app.getProperty(DEBUGGER_PROPERTY)) ? -1 : 9;
String opt = app.getProperty("rhino.optlevel");
if (opt != null) {
try {
optLevel = Integer.parseInt(opt);
} catch (Exception ignore) {
app.logError(ErrorReporter.errorMsg(this.getClass(), "ctor")
+ "Invalid rhino optlevel: " + opt);
}
}
context.setOptimizationLevel(optLevel);
try {
// create global object
global = new GlobalObject(this, app, false);
// call the initStandardsObject in ImporterTopLevel so that
// importClass() and importPackage() are set up.
global.initStandardObjects(context, false);
global.init();
axiomObjectProto = AxiomObject.init(this);
fileObjectProto = FileObject.initFileProto(this);
imageObjectProto = ImageObject.initImageProto(this);
// Reference initialization
try {
new ReferenceObjCtor(this, Reference.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for Reference", x);
}
// MultiValue initialization
try {
new MultiValueCtor(this, MultiValue.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for MultiValue", x);
}
// use lazy loaded constructors for all extension objects that
// adhere to the ScriptableObject.defineClass() protocol
/*
* Changes made, namely:
*
* 1) Removed the File and Image objects in preference to the File/Image objects
* we built in house
* 2) Added the following objects to the Rhino scripting environment:
* LdapClient
* Filter (for specifying queries)
* Sort (for specifying the sort order of queries)
* DOMParser (for parsing xml into a dom object)
* XMLSerializer (for writing a dom object to an xml string)
*
*/
new LazilyLoadedCtor(global, "FtpClient",
"axiom.scripting.rhino.extensions.FtpObject", false);
new LazilyLoadedCtor(global, "LdapClient",
"axiom.scripting.rhino.extensions.LdapObject", false);
new LazilyLoadedCtor(global, "Filter",
"axiom.scripting.rhino.extensions.filter.FilterObject", false);
new LazilyLoadedCtor(global, "NativeFilter",
"axiom.scripting.rhino.extensions.filter.NativeFilterObject", false);
new LazilyLoadedCtor(global, "AndFilter",
"axiom.scripting.rhino.extensions.filter.AndFilterObject", false);
new LazilyLoadedCtor(global, "OrFilter",
"axiom.scripting.rhino.extensions.filter.OrFilterObject", false);
new LazilyLoadedCtor(global, "NotFilter",
"axiom.scripting.rhino.extensions.filter.NotFilterObject", false);
new LazilyLoadedCtor(global, "RangeFilter",
"axiom.scripting.rhino.extensions.filter.RangeFilterObject", false);
new LazilyLoadedCtor(global, "SearchFilter",
"axiom.scripting.rhino.extensions.filter.SearchFilterObject", false);
new LazilyLoadedCtor(global, "Sort",
"axiom.scripting.rhino.extensions.filter.SortObject", false);
ArrayList names = app.getDbNames();
for(int i = 0; i < names.size(); i++){
try{
String dbname = names.get(i).toString();
DbSource dbsource = app.getDbSource(dbname);
String hitsObject = dbsource.getProperty("hitsObject", null);
String hitsClass = dbsource.getProperty("hitsClass", null);
if(hitsObject != null && hitsClass != null){
new LazilyLoadedCtor(global, hitsObject,
hitsClass, false);
}
String filters = dbsource.getProperty("filters", null);
if(filters != null){
StringBuffer sb = new StringBuffer(filters);
int idx;
while ((idx = sb.indexOf("{")) > -1) {
sb.deleteCharAt(idx);
}
while ((idx = sb.indexOf("}")) > -1) {
sb.deleteCharAt(idx);
}
filters = sb.toString().trim();
String[] pairs = filters.split(",");
for (int j = 0; j < pairs.length; j++) {
String[] pair = pairs[j].split(":");
new LazilyLoadedCtor(global, pair[0].trim(),
pair[1].trim(), false);
}
}
}
catch(Exception e){
app.logError("Error during LazilyLoadedCtor initialization for external databases");
}
}
new LazilyLoadedCtor(global, "LuceneHits",
"axiom.scripting.rhino.extensions.LuceneHitsObject", false);
new LazilyLoadedCtor(global, "TopDocs",
"axiom.scripting.rhino.extensions.TopDocsObject", false);
new LazilyLoadedCtor(global, "DOMParser",
"axiom.scripting.rhino.extensions.DOMParser", false);
new LazilyLoadedCtor(global, "XMLSerializer",
"axiom.scripting.rhino.extensions.XMLSerializer", false);
if ("true".equalsIgnoreCase(app.getProperty(RhinoCore.DEBUGGER_PROPERTY))) {
new LazilyLoadedCtor(global, "Debug",
"axiom.scripting.rhino.debug.Debug", false);
}
MailObject.init(global, app.getProperties());
// defining the ActiveX scriptable object for exposure of its API in Axiom
ScriptableObject.defineClass(global, ActiveX.class);
// add some convenience functions to string, date and number prototypes
Scriptable stringProto = ScriptableObject.getClassPrototype(global, "String");
stringProto.put("trim", stringProto, new StringTrim());
Scriptable dateProto = ScriptableObject.getClassPrototype(global, "Date");
dateProto.put("format", dateProto, new DateFormat());
Scriptable numberProto = ScriptableObject.getClassPrototype(global, "Number");
numberProto.put("format", numberProto, new NumberFormat());
initialize();
loadTemplates(app);
} catch (Exception e) {
System.err.println("Cannot initialize interpreter");
System.err.println("Error: " + e);
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
Context.exit();
}
}
/**
* Initialize the evaluator, making sure the minimum type information
* necessary to bootstrap the rest is parsed.
*/
private synchronized void initialize() {
Collection protos = app.getPrototypes();
for (Iterator i = protos.iterator(); i.hasNext();) {
Prototype proto = (Prototype) i.next();
initPrototype(proto);
// getPrototype(proto.getName());
}
// always fully initialize global prototype, because
// we always need it and there's no chance to trigger
// creation on demand.
getPrototype("global");
}
/**
* Initialize a prototype info without compiling its script files.
*
* @param prototype the prototype to be created
*/
private synchronized void initPrototype(Prototype prototype) {
String name = prototype.getName();
String lowerCaseName = prototype.getLowerCaseName();
TypeInfo type = (TypeInfo) prototypes.get(lowerCaseName);
// check if the prototype info exists already
ScriptableObject op = (type == null) ? null : type.objProto;
// if prototype info doesn't exist (i.e. is a standard prototype
// built by AxiomExtension), create it.
if (op == null) {
if ("global".equals(lowerCaseName)) {
op = global;
} else if ("axiomobject".equals(lowerCaseName)) {
op = axiomObjectProto;
} else if ("file".equals(lowerCaseName)) {
op = fileObjectProto;
} else if ("image".equals(lowerCaseName)) {
op = imageObjectProto;
} else {
op = new AxiomObject(name, this);
}
registerPrototype(prototype, op);
}
// Register a constructor for all types except global.
// This will first create a new prototyped AxiomObject and then calls
// the actual (scripted) constructor on it.
if (!"global".equals(lowerCaseName)) {
if ("file".equals(lowerCaseName)) {
try {
new FileObjectCtor(this, op);
op.setParentScope(global);
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "initPrototype")
+ "Could not add ctor for " + name, x);
}
} else if ("image".equals(lowerCaseName)) {
try {
new ImageObjectCtor(this, op);
op.setParentScope(global);
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "initPrototype")
+ "Could not add ctor for " + name, x);
}
} else {
try {
new AxiomObjectCtor(name, this, op);
op.setParentScope(global);
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "initPrototype")
+ "Could not add ctor for " + name, x);
}
}
}
}
/**
* Set up a prototype, parsing and compiling all its script files.
*
* @param type the info, containing the object proto, last update time and
* the set of compiled functions properties
*/
private synchronized void evaluatePrototype(TypeInfo type) {
type.prepareCompilation();
Prototype prototype = type.frameworkProto;
// set the parent prototype in case it hasn't been done before
// or it has changed...
setParentPrototype(prototype, type);
type.error = null;
if ("global".equals(prototype.getLowerCaseName())) {
globalError = null;
}
// loop through the prototype's code elements and evaluate them
ArrayList code = prototype.getCodeResourceList();
final int size = code.size();
for (int i = 0; i < size; i++) {
evaluate(type, (Resource) code.get(i));
}
loadCompiledCode(type, prototype.getName());
type.commitCompilation();
}
private void loadTemplates(Application app) throws Exception {
HashMap templSources = getAllTemplateSources();
Iterator keys = templSources.keySet().iterator();
while (keys.hasNext()) {
String name = keys.next().toString();
retrieveDocument(app, name);
}
}
public Object retrieveDocument(Application app, String name)
throws Exception {
HashMap map = retrieveTemplatesForApp(app);
Object xml = null;
Resource templateSource = (Resource) findTemplateSource(name, app);
if (templateSource == null) {
// throw new Exception("ERROR in TAL(): Could not find the TAL template file indicated by '" + name + "'.");
return null;
}
TALTemplate template = null;
synchronized (map) {
if ((template = getTemplateByName(map, name)) != null && template.getLastModified() >= templateSource.lastModified()) {
xml = template.getDocument();
} else {
xml = ((Resource) templateSource).getContent().trim();
if (template != null) {
template.setDocument(xml);
template.setLastModified(templateSource.lastModified());
} else {
map.put(name, new TALTemplate(name, xml, templateSource.lastModified()));
}
}
}
return xml;
}
private static TALTemplate getTemplateByName(HashMap map, String name) {
return (TALTemplate) map.get(name);
}
private static HashMap retrieveTemplatesForApp(Application app) {
HashMap map = null;
synchronized (templates) {
Object ret = templates.get(app);
if (ret != null)
map = (HashMap) ret;
else {
map = new HashMap();
templates.put(app, map);
}
}
return map;
}
public static Object findTemplateSource(String name, Application app) throws Exception {
Resource resource = (Resource) cache.get(name);
if (resource == null || !resource.exists()) {
resource = null;
try {
int pos = name.indexOf(':');
Prototype prototype = app.getPrototypeByName(name.substring(0, pos));
name = name.substring(pos + 1) + ".tal";
if (prototype != null) {
resource = scanForResource(prototype, name);
}
} catch (Exception ex) {
throw new Exception("Unable to resolve source: " + name + " " + ex);
}
}
return resource;
}
private static Resource scanForResource(Prototype prototype, String name) throws Exception {
Resource resource = null;
// scan for resources with extension .tal:
Resource[] resources = prototype.getResources();
for (int i = 0; i < resources.length; i++) {
Resource res = resources[i];
if (res.exists() && res.getShortName().equals(name)) {
cache.put(name, res);
resource = res;
break;
}
}
return resource;
}
public HashMap getAllTemplateSources() throws Exception {
HashMap templSources = new HashMap();
ArrayList mylist = new ArrayList(app.getPrototypes());
final int size = mylist.size();
for (int i = 0; i < size; i++) {
Prototype prototype = (Prototype) mylist.get(i);
String proto = prototype.getName() + ":";
Resource[] resources = prototype.getResources();
final int length = resources.length;
for (int j = 0; j < length; j++) {
if (resources[j].exists() && resources[j].getShortName().endsWith(".tal")) {
templSources.put(proto + resources[j].getBaseName(), resources[j]);
}
}
}
return templSources;
}
/*
*
*
*
*
*
*/
/**
* Set the parent prototype on the ObjectPrototype.
*
* @param prototype the prototype spec
* @param type the prototype object info
*/
private void setParentPrototype(Prototype prototype, TypeInfo type) {
String name = prototype.getName();
String lowerCaseName = prototype.getLowerCaseName();
if (!"global".equals(lowerCaseName) && !"axiomobject".equals(lowerCaseName)) {
// get the prototype's prototype if possible and necessary
TypeInfo parentType = null;
Prototype parent = prototype.getParentPrototype();
if (parent != null) {
// see if parent prototype is already registered. if not, register it
parentType = getPrototypeInfo(parent.getName());
}
if (parentType == null && !app.isJavaPrototype(name)) {
// FIXME: does this ever occur?
parentType = getPrototypeInfo("axiomobject");
}
type.setParentType(parentType);
}
}
/**
* This method is called before an execution context is entered to let the
* engine know it should update its prototype information. The update policy
* here is to check for update those prototypes which already have been compiled
* before. Others will be updated/compiled on demand.
*/
public synchronized void updatePrototypes(boolean forceUpdate) throws IOException {
if ((System.currentTimeMillis() - lastUpdate) < 1000L + updateSnooze) {
return;
}
// We are no longer checking for prototype updates on a
// per request basis, but rather only when there is an explicit request to update
// the prototype resource mappings
if (!forceUpdate && this.isInitialized) {
return;
}
// init prototypes and/or update prototype checksums
app.typemgr.checkPrototypes();
// get a collection of all prototypes (code directories)
Collection protos = app.getPrototypes();
// in order to respect inter-prototype dependencies, we try to update
// the global prototype before all other prototypes, and parent
// prototypes before their descendants.
HashSet checked = new HashSet(protos.size() * 2);
TypeInfo type = (TypeInfo) prototypes.get("global");
if (type != null) {
updatePrototype(type, checked);
}
for (Iterator i = protos.iterator(); i.hasNext();) {
Prototype proto = (Prototype) i.next();
if (checked.contains(proto)) {
continue;
}
type = (TypeInfo) prototypes.get(proto.getLowerCaseName());
if (type == null) {
// a prototype we don't know anything about yet. Init local update info.
initPrototype(proto);
}
type = (TypeInfo) prototypes.get(proto.getLowerCaseName());
if (type != null && (type.lastUpdate > -1 || !this.isInitialized)) {
// only need to update prototype if it has already been initialized.
// otherwise, this will be done on demand.
updatePrototype(type, checked);
}
}
this.isInitialized = true;
//lastUpdate = System.currentTimeMillis();
// max updateSnooze is 4 seconds, reached after 66.6 idle minutes
//long newSnooze = (lastUpdate - app.typemgr.getLastCodeUpdate()) / 1000;
//updateSnooze = Math.min(4000, Math.max(0, newSnooze));
}
/**
* Check one prototype for updates. Used by <code>upatePrototypes()</code>.
*
* @param type the type info to check
* @param checked a set of prototypes that have already been checked
*/
private void updatePrototype(TypeInfo type, HashSet checked) {
// first, remember prototype as updated
checked.add(type.frameworkProto);
if (type.parentType != null &&
!checked.contains(type.parentType.frameworkProto)) {
updatePrototype(type.getParentType(), checked);
}
// let the prototype check if its resources have changed
type.frameworkProto.checkForUpdates();
// and re-evaluate if necessary
if (type.needsUpdate() || !this.isInitialized) {
evaluatePrototype(type);
}
}
/**
* A version of getPrototype() that retrieves a prototype and checks
* if it is valid, i.e. there were no errors when compiling it. If
* invalid, a ScriptingException is thrown.
*/
public Scriptable getValidPrototype(String protoName) {
if (globalError != null) {
throw new EvaluatorException(globalError);
}
TypeInfo type = getPrototypeInfo(protoName);
if (type != null) {
if (type.hasError()) {
throw new EvaluatorException(type.getError());
}
return type.objProto;
}
return null;
}
/**
* Get the object prototype for a prototype name and initialize/update it
* if necessary. The policy here is to update the prototype only if it
* hasn't been updated before, otherwise we assume it already was updated
* by updatePrototypes(), which is called for each request.
*/
public Scriptable getPrototype(String protoName) {
TypeInfo type = getPrototypeInfo(protoName);
return type == null ? null : type.objProto;
}
/**
* Get an array containing the property ids of all properties that were
* compiled from scripts for the given prototype.
*
* @param protoName the name of the prototype
* @return an array containing all compiled properties of the given prototype
*/
public Map getPrototypeProperties(String protoName) {
TypeInfo type = getPrototypeInfo(protoName);
SystemMap map = new SystemMap();
Iterator it = type.compiledProperties.iterator();
while(it.hasNext()) {
Object key = it.next();
if (key instanceof String)
map.put(key, type.objProto.get((String) key, type.objProto));
}
return map;
}
/**
* Private helper function that retrieves a prototype's TypeInfo
* and creates it if not yet created. This is used by getPrototype() and
* getValidPrototype().
*/
private TypeInfo getPrototypeInfo(String protoName) {
if (protoName == null) {
return null;
}
TypeInfo type = (TypeInfo) prototypes.get(protoName.toLowerCase());
// if type exists and hasn't been evaluated (used) yet, evaluate it now.
// otherwise, it has already been evaluated for this request by updatePrototypes(),
// which is called before a request is handled.
if ((type != null) && (type.lastUpdate == -1)) {
type.frameworkProto.checkForUpdates();
if (type.needsUpdate()) {
evaluatePrototype(type);
}
}
return type;
}
/**
* Register an object prototype for a prototype name.
*/
private TypeInfo registerPrototype(Prototype proto, ScriptableObject op) {
TypeInfo type = new TypeInfo(proto, op);
prototypes.put(proto.getLowerCaseName(), type);
return type;
}
/**
* Check if an object has a function property (public method if it
* is a java object) with that name.
*/
public boolean hasFunction(String protoname, String fname) {
// throws EvaluatorException if type has a syntax error
Scriptable op = getValidPrototype(protoname);
// if this is an untyped object return false
if (op == null) {
return false;
}
return ScriptableObject.getProperty(op, fname) instanceof Function;
}
/**
* Convert an input argument from Java to the scripting runtime
* representation.
*/
public Object processXmlRpcArgument (Object what) throws Exception {
if (what == null)
return null;
if (what instanceof Vector) {
Vector v = (Vector) what;
Object[] a = v.toArray();
for (int i=0; i<a.length; i++) {
a[i] = processXmlRpcArgument(a[i]);
}
return Context.getCurrentContext().newArray(global, a);
}
if (what instanceof Hashtable) {
Hashtable t = (Hashtable) what;
for (Enumeration e=t.keys(); e.hasMoreElements(); ) {
Object key = e.nextElement();
t.put(key, processXmlRpcArgument(t.get(key)));
}
return Context.toObject(new SystemMap(t), global);
}
if (what instanceof String)
return what;
if (what instanceof Number)
return what;
if (what instanceof Boolean)
return what;
if (what instanceof Date) {
Date d = (Date) what;
Object[] args = { new Long(d.getTime()) };
return Context.getCurrentContext().newObject(global, "Date", args);
}
return Context.toObject(what, global);
}
/**
* convert a JavaScript Object object to a generic Java object stucture.
*/
public Object processXmlRpcResponse (Object what) throws Exception {
// unwrap if argument is a Wrapper
if (what instanceof Wrapper) {
what = ((Wrapper) what).unwrap();
}
if (what instanceof NativeObject) {
NativeObject no = (NativeObject) what;
Object[] ids = no.getIds();
Hashtable ht = new Hashtable(ids.length*2);
for (int i=0; i<ids.length; i++) {
if (ids[i] instanceof String) {
String key = (String) ids[i];
Object o = no.get(key, no);
if (o != null) {
ht.put(key, processXmlRpcResponse(o));
}
}
}
what = ht;
} else if (what instanceof NativeArray) {
NativeArray na = (NativeArray) what;
Number n = (Number) na.get("length", na);
int l = n.intValue();
Vector retval = new Vector(l);
for (int i=0; i<l; i++) {
retval.add(i, processXmlRpcResponse(na.get(i, na)));
}
what = retval;
} else if (what instanceof Map) {
Map map = (Map) what;
Hashtable ht = new Hashtable(map.size()*2);
for (Iterator it=map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
ht.put(entry.getKey().toString(),
processXmlRpcResponse(entry.getValue()));
}
what = ht;
} else if (what instanceof Number) {
Number n = (Number) what;
if (what instanceof Float || what instanceof Long) {
what = new Double(n.doubleValue());
} else if (!(what instanceof Double)) {
what = new Integer(n.intValue());
}
} else if (what instanceof Scriptable) {
Scriptable s = (Scriptable) what;
if ("Date".equals(s.getClassName())) {
what = new Date((long) ScriptRuntime.toNumber(s));
}
}
return what;
}
/**
* Return the application we're running in
*/
public Application getApplication() {
return app;
}
/**
* Get a Script wrapper for any given object. If the object implements the IPathElement
* interface, the getPrototype method will be used to retrieve the name of the prototype
* to use. Otherwise, a Java-Class-to-Script-Prototype mapping is consulted.
*/
public Scriptable getElementWrapper(Object e) {
WeakReference ref = (WeakReference) wrappercache.get(e);
Scriptable wrapper = ref == null ? null : (Scriptable) ref.get();
if (wrapper == null) {
// Gotta find out the prototype name to use for this object...
String prototypeName = app.getPrototypeName(e);
Scriptable op = getPrototype(prototypeName);
if (op == null) {
// no prototype found, return an unscripted wrapper
wrapper = new NativeJavaObject(global, e, e.getClass());
} else {
wrapper = new JavaObject(global, e, prototypeName, op, this);
}
wrappercache.put(e, new WeakReference(wrapper));
}
return wrapper;
}
/**
* Get a script wrapper for an instance of axiom.objectmodel.INode
*/
public Scriptable getNodeWrapper(INode n) {
if (n == null) {
return null;
}
AxiomObject esn = (AxiomObject) wrappercache.get(n);
if (esn == null) {
String protoname = n.getPrototype();
Scriptable op = getValidPrototype(protoname);
// no prototype found for this node
if (op == null) {
// maybe this object has a prototype name that has been
// deleted, but the storage layer was able to set a
// DbMapping matching the relational table the object
// was fetched from.
DbMapping dbmap = n.getDbMapping();
if (dbmap != null && (protoname = dbmap.getTypeName()) != null) {
op = getValidPrototype(protoname);
}
// if not found, fall back to AxiomObject prototype
if (op == null) {
protoname = "AxiomObject";
op = getValidPrototype("AxiomObject");
}
}
if ("File".equals(protoname)) {
esn = new FileObject("File", this, n, op);
} else if ("Image".equals(protoname)) {
esn = new ImageObject("Image", this, n, op);
} else {
esn = new AxiomObject(protoname, this, n, op);
}
wrappercache.put(n, esn);
}
return esn;
}
protected String postProcessHref(Object obj, String protoName, String basicHref)
throws UnsupportedEncodingException, IOException {
// check if the app.properties specify a href-function to post-process the
// basic href.
String hrefFunction = app.getProperty("hrefFunction", null);
if (hrefFunction != null) {
Object handler = obj;
String proto = protoName;
while (handler != null) {
if (hasFunction(proto, hrefFunction)) {
// get the currently active rhino engine and invoke the function
Context cx = Context.getCurrentContext();
RhinoEngine engine = (RhinoEngine) cx.getThreadLocal("engine");
Object result;
try {
result = engine.invoke(handler, hrefFunction,
new Object[] { basicHref },
ScriptingEngine.ARGS_WRAP_DEFAULT,
false);
} catch (ScriptingException x) {
throw new EvaluatorException("Error in hrefFunction: " + x);
}
if (result == null) {
throw new EvaluatorException("hrefFunction " + hrefFunction +
" returned null");
}
basicHref = result.toString();
break;
}
handler = app.getParentElement(handler);
proto = app.getPrototypeName(handler);
}
}
return basicHref;
}
////////////////////////////////////////////////
// private evaluation/compilation methods
////////////////////////////////////////////////
private synchronized void loadCompiledCode(TypeInfo type, String protoname) {
// get the current context
Context cx = Context.getCurrentContext();
// unregister the per-thread scope while evaluating
Object threadScope = cx.getThreadLocal("threadscope");
cx.removeThreadLocal("threadscope");
try{
Script compiled = (Script) Class.forName("axiom.compiled."+protoname).newInstance();
compiled.exec(cx, type.objProto);
}catch(ClassNotFoundException e){
// no compiled code loaded, ignore
}catch(Exception e){
app.logError(ErrorReporter.errorMsg(this.getClass(), "loadCompiledCode")
+ "Error loading compiled js for prototype: " + protoname, e);
// mark prototype as broken
if (type.error == null) {
type.error = e.getMessage();
if (type.error == null || e instanceof EcmaError) {
type.error = e.toString();
}
if ("global".equals(type.frameworkProto.getLowerCaseName())) {
globalError = type.error;
}
wrappercache.clear();
}
}finally{
if (threadScope != null) {
cx.putThreadLocal("threadscope", threadScope);
}
}
}
private synchronized void evaluate (TypeInfo type, Resource code) {
// get the current context
Context cx = Context.getCurrentContext();
// unregister the per-thread scope while evaluating
Object threadScope = cx.getThreadLocal("threadscope");
cx.removeThreadLocal("threadscope");
String sourceName = code.getName();
Reader reader = null;
try {
Scriptable op = type.objProto;
// do the update, evaluating the file
if (sourceName.endsWith(".js")) {
reader = new InputStreamReader(code.getInputStream());
} else if (sourceName.endsWith(".tal")) {
reader = new StringReader(ResourceConverter.convertTal(code));
}
cx.evaluateReader(op, reader, sourceName, 1, null);
} catch (Exception e) {
app.logError(ErrorReporter.errorMsg(this.getClass(), "evaluate")
+ "Error parsing file " + sourceName, e);
// mark prototype as broken
if (type.error == null) {
type.error = e.getMessage();
if (type.error == null || e instanceof EcmaError) {
type.error = e.toString();
}
if ("global".equals(type.frameworkProto.getLowerCaseName())) {
globalError = type.error;
}
wrappercache.clear();
}
// e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {
}
}
if (threadScope != null) {
cx.putThreadLocal("threadscope", threadScope);
}
}
}
/**
* Return the global scope of this RhinoCore.
*/
public Scriptable getScope() {
return global;
}
public GlobalObject getGlobal(){
return global;
}
/**
* TypeInfo helper class
*/
class TypeInfo {
// the framework prototype object
Prototype frameworkProto;
// the JavaScript prototype for this type
ScriptableObject objProto;
// timestamp of last update. This is -1 so even an empty prototype directory
// (with lastUpdate == 0) gets evaluated at least once, which is necessary
// to get the prototype chain set.
long lastUpdate = -1;
// the parent prototype info
TypeInfo parentType;
// a set of property keys that were in script compilation.
// Used to decide which properties should be removed if not renewed.
Set compiledProperties;
// a set of property keys that were present before first script compilation
final Set predefinedProperties;
String error;
public TypeInfo(Prototype proto, ScriptableObject op) {
frameworkProto = proto;
objProto = op;
// remember properties already defined on this object prototype
compiledProperties = new HashSet();
predefinedProperties = new HashSet();
Object[] keys = op.getAllIds();
for (int i = 0; i < keys.length; i++) {
predefinedProperties.add(keys[i].toString());
}
}
/**
* If prototype implements PropertyRecorder tell it to start
* registering property puts.
*/
public void prepareCompilation() {
if (objProto instanceof PropertyRecorder) {
((PropertyRecorder) objProto).startRecording();
}
}
/**
* Compilation has been completed successfully - switch over to code
* from temporary prototype, removing properties that haven't been
* renewed.
*/
public void commitCompilation() {
// loop through properties defined on the prototype object
// and remove thos properties which haven't been renewed during
// this compilation/evaluation pass.
if (objProto instanceof PropertyRecorder) {
PropertyRecorder recorder = (PropertyRecorder) objProto;
recorder.stopRecording();
Set changedProperties = recorder.getChangeSet();
recorder.clearChangeSet();
// ignore all properties that were defined before we started
// compilation. We won't manage these properties, even
// if they were set during compilation.
changedProperties.removeAll(predefinedProperties);
// remove all renewed properties from the previously compiled
// property names so we can remove those properties that were not
// renewed in this compilation
compiledProperties.removeAll(changedProperties);
Iterator it = compiledProperties.iterator();
while (it.hasNext()) {
String key = (String) it.next();
try {
objProto.setAttributes(key, 0);
objProto.delete(key);
} catch (Exception px) {
System.err.println("Error unsetting property "+key+" on "+
frameworkProto.getName());
}
}
// update compiled properties
compiledProperties = changedProperties;
}
// mark this type as updated
lastUpdate = frameworkProto.lastCodeUpdate();
// If this prototype defines a postCompile() function, call it
Context cx = Context.getCurrentContext();
try {
Object fObj = ScriptableObject.getProperty(objProto,
"onCodeUpdate");
if (fObj instanceof Function) {
Object[] args = {frameworkProto.getName()};
((Function) fObj).call(cx, global, objProto, args);
}
} catch (Exception x) {
app.logError(ErrorReporter.errorMsg(this.getClass(), "commitCompilation")
+ "Exception in "+frameworkProto.getName()+
".onCodeUpdate(): " + x, x);
}
}
public boolean needsUpdate() {
return frameworkProto.lastCodeUpdate() > lastUpdate;
}
public void setParentType(TypeInfo type) {
parentType = type;
if (type == null) {
objProto.setPrototype(null);
} else {
objProto.setPrototype(type.objProto);
}
}
public TypeInfo getParentType() {
return parentType;
}
public boolean hasError() {
TypeInfo p = this;
while (p != null) {
if (p.error != null)
return true;
p = p.parentType;
}
return false;
}
public String getError() {
TypeInfo p = this;
while (p != null) {
if (p.error != null)
return p.error;
p = p.parentType;
}
return null;
}
public String toString() {
return ("TypeInfo[" + frameworkProto + "," + new Date(lastUpdate) + "]");
}
}
/**
* Object wrapper class
*/
class WrapMaker extends WrapFactory {
public Object wrap(Context cx, Scriptable scope, Object obj, Class staticType) {
// Wrap Nodes
if (obj instanceof INode) {
return getNodeWrapper((INode) obj);
}
// Masquerade SystemMap and WrappedMap as native JavaScript objects
if (obj instanceof SystemMap || obj instanceof WrappedMap) {
return new MapWrapper((Map) obj, RhinoCore.this);
}
// Convert java.util.Date objects to JavaScript Dates
if (obj instanceof Date) {
Object[] args = { new Long(((Date) obj).getTime()) };
try {
return cx.newObject(global, "Date", args);
} catch (JavaScriptException nafx) {
return obj;
}
}
// Wrap scripted Java objects
if (obj != null && app.getPrototypeName(obj) != null) {
return getElementWrapper(obj);
}
return super.wrap(cx, scope, obj, staticType);
}
public Scriptable wrapNewObject(Context cx, Scriptable scope, Object obj) {
// System.err.println ("N-Wrapping: "+obj);
if (obj instanceof INode) {
return getNodeWrapper((INode) obj);
}
if (obj != null && app.getPrototypeName(obj) != null) {
return getElementWrapper(obj);
}
return super.wrapNewObject(cx, scope, obj);
}
}
class StringTrim extends BaseFunction {
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
String str = thisObj.toString();
return str.trim();
}
}
class DateFormat extends BaseFunction {
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
Date date = new Date((long) ScriptRuntime.toNumber(thisObj));
SimpleDateFormat df;
if (args.length > 0 && args[0] != Undefined.instance && args[0] != null) {
if (args.length > 1 && args[1] instanceof NativeJavaObject) {
Object locale = ((NativeJavaObject) args[1]).unwrap();
if (locale instanceof Locale) {
df = new SimpleDateFormat(args[0].toString(), (Locale) locale);
} else {
throw new IllegalArgumentException("Second argument to Date.format() not a java.util.Locale: " +
locale.getClass());
}
} else {
df = new SimpleDateFormat(args[0].toString());
}
} else {
df = new SimpleDateFormat();
}
return df.format(date);
}
}
class NumberFormat extends BaseFunction {
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
DecimalFormat df;
if (args.length > 0 && args[0] != Undefined.instance) {
df = new DecimalFormat(args[0].toString());
} else {
df = new DecimalFormat("#,##0.00");
}
return df.format(ScriptRuntime.toNumber(thisObj));
}
}
}
| true | true | public RhinoCore(Application app) {
this.app = app;
wrappercache = new WeakCacheMap(500);
prototypes = new Hashtable();
Context context = Context.enter();
context.setLanguageVersion(170);
context.setCompileFunctionsWithDynamicScope(true);
context.setApplicationClassLoader(app.getClassLoader());
wrapper = new WrapMaker();
wrapper.setJavaPrimitiveWrap(false);
context.setWrapFactory(wrapper);
// Set default optimization level according to whether debugger is on
int optLevel = "true".equals(app.getProperty(DEBUGGER_PROPERTY)) ? 0 : -1;
String opt = app.getProperty("rhino.optlevel");
if (opt != null) {
try {
optLevel = Integer.parseInt(opt);
} catch (Exception ignore) {
app.logError(ErrorReporter.errorMsg(this.getClass(), "ctor")
+ "Invalid rhino optlevel: " + opt);
}
}
context.setOptimizationLevel(optLevel);
try {
// create global object
global = new GlobalObject(this, app, false);
// call the initStandardsObject in ImporterTopLevel so that
// importClass() and importPackage() are set up.
global.initStandardObjects(context, false);
global.init();
axiomObjectProto = AxiomObject.init(this);
fileObjectProto = FileObject.initFileProto(this);
imageObjectProto = ImageObject.initImageProto(this);
// Reference initialization
try {
new ReferenceObjCtor(this, Reference.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for Reference", x);
}
// MultiValue initialization
try {
new MultiValueCtor(this, MultiValue.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for MultiValue", x);
}
// use lazy loaded constructors for all extension objects that
// adhere to the ScriptableObject.defineClass() protocol
/*
* Changes made, namely:
*
* 1) Removed the File and Image objects in preference to the File/Image objects
* we built in house
* 2) Added the following objects to the Rhino scripting environment:
* LdapClient
* Filter (for specifying queries)
* Sort (for specifying the sort order of queries)
* DOMParser (for parsing xml into a dom object)
* XMLSerializer (for writing a dom object to an xml string)
*
*/
new LazilyLoadedCtor(global, "FtpClient",
"axiom.scripting.rhino.extensions.FtpObject", false);
new LazilyLoadedCtor(global, "LdapClient",
"axiom.scripting.rhino.extensions.LdapObject", false);
new LazilyLoadedCtor(global, "Filter",
"axiom.scripting.rhino.extensions.filter.FilterObject", false);
new LazilyLoadedCtor(global, "NativeFilter",
"axiom.scripting.rhino.extensions.filter.NativeFilterObject", false);
new LazilyLoadedCtor(global, "AndFilter",
"axiom.scripting.rhino.extensions.filter.AndFilterObject", false);
new LazilyLoadedCtor(global, "OrFilter",
"axiom.scripting.rhino.extensions.filter.OrFilterObject", false);
new LazilyLoadedCtor(global, "NotFilter",
"axiom.scripting.rhino.extensions.filter.NotFilterObject", false);
new LazilyLoadedCtor(global, "RangeFilter",
"axiom.scripting.rhino.extensions.filter.RangeFilterObject", false);
new LazilyLoadedCtor(global, "SearchFilter",
"axiom.scripting.rhino.extensions.filter.SearchFilterObject", false);
new LazilyLoadedCtor(global, "Sort",
"axiom.scripting.rhino.extensions.filter.SortObject", false);
ArrayList names = app.getDbNames();
for(int i = 0; i < names.size(); i++){
try{
String dbname = names.get(i).toString();
DbSource dbsource = app.getDbSource(dbname);
String hitsObject = dbsource.getProperty("hitsObject", null);
String hitsClass = dbsource.getProperty("hitsClass", null);
if(hitsObject != null && hitsClass != null){
new LazilyLoadedCtor(global, hitsObject,
hitsClass, false);
}
String filters = dbsource.getProperty("filters", null);
if(filters != null){
StringBuffer sb = new StringBuffer(filters);
int idx;
while ((idx = sb.indexOf("{")) > -1) {
sb.deleteCharAt(idx);
}
while ((idx = sb.indexOf("}")) > -1) {
sb.deleteCharAt(idx);
}
filters = sb.toString().trim();
String[] pairs = filters.split(",");
for (int j = 0; j < pairs.length; j++) {
String[] pair = pairs[j].split(":");
new LazilyLoadedCtor(global, pair[0].trim(),
pair[1].trim(), false);
}
}
}
catch(Exception e){
app.logError("Error during LazilyLoadedCtor initialization for external databases");
}
}
new LazilyLoadedCtor(global, "LuceneHits",
"axiom.scripting.rhino.extensions.LuceneHitsObject", false);
new LazilyLoadedCtor(global, "TopDocs",
"axiom.scripting.rhino.extensions.TopDocsObject", false);
new LazilyLoadedCtor(global, "DOMParser",
"axiom.scripting.rhino.extensions.DOMParser", false);
new LazilyLoadedCtor(global, "XMLSerializer",
"axiom.scripting.rhino.extensions.XMLSerializer", false);
if ("true".equalsIgnoreCase(app.getProperty(RhinoCore.DEBUGGER_PROPERTY))) {
new LazilyLoadedCtor(global, "Debug",
"axiom.scripting.rhino.debug.Debug", false);
}
MailObject.init(global, app.getProperties());
// defining the ActiveX scriptable object for exposure of its API in Axiom
ScriptableObject.defineClass(global, ActiveX.class);
// add some convenience functions to string, date and number prototypes
Scriptable stringProto = ScriptableObject.getClassPrototype(global, "String");
stringProto.put("trim", stringProto, new StringTrim());
Scriptable dateProto = ScriptableObject.getClassPrototype(global, "Date");
dateProto.put("format", dateProto, new DateFormat());
Scriptable numberProto = ScriptableObject.getClassPrototype(global, "Number");
numberProto.put("format", numberProto, new NumberFormat());
initialize();
loadTemplates(app);
} catch (Exception e) {
System.err.println("Cannot initialize interpreter");
System.err.println("Error: " + e);
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
Context.exit();
}
}
| public RhinoCore(Application app) {
this.app = app;
wrappercache = new WeakCacheMap(500);
prototypes = new Hashtable();
Context context = Context.enter();
context.setLanguageVersion(170);
context.setCompileFunctionsWithDynamicScope(true);
context.setApplicationClassLoader(app.getClassLoader());
wrapper = new WrapMaker();
wrapper.setJavaPrimitiveWrap(false);
context.setWrapFactory(wrapper);
// Set default optimization level according to whether debugger is on
int optLevel = "true".equals(app.getProperty(DEBUGGER_PROPERTY)) ? -1 : 9;
String opt = app.getProperty("rhino.optlevel");
if (opt != null) {
try {
optLevel = Integer.parseInt(opt);
} catch (Exception ignore) {
app.logError(ErrorReporter.errorMsg(this.getClass(), "ctor")
+ "Invalid rhino optlevel: " + opt);
}
}
context.setOptimizationLevel(optLevel);
try {
// create global object
global = new GlobalObject(this, app, false);
// call the initStandardsObject in ImporterTopLevel so that
// importClass() and importPackage() are set up.
global.initStandardObjects(context, false);
global.init();
axiomObjectProto = AxiomObject.init(this);
fileObjectProto = FileObject.initFileProto(this);
imageObjectProto = ImageObject.initImageProto(this);
// Reference initialization
try {
new ReferenceObjCtor(this, Reference.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for Reference", x);
}
// MultiValue initialization
try {
new MultiValueCtor(this, MultiValue.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for MultiValue", x);
}
// use lazy loaded constructors for all extension objects that
// adhere to the ScriptableObject.defineClass() protocol
/*
* Changes made, namely:
*
* 1) Removed the File and Image objects in preference to the File/Image objects
* we built in house
* 2) Added the following objects to the Rhino scripting environment:
* LdapClient
* Filter (for specifying queries)
* Sort (for specifying the sort order of queries)
* DOMParser (for parsing xml into a dom object)
* XMLSerializer (for writing a dom object to an xml string)
*
*/
new LazilyLoadedCtor(global, "FtpClient",
"axiom.scripting.rhino.extensions.FtpObject", false);
new LazilyLoadedCtor(global, "LdapClient",
"axiom.scripting.rhino.extensions.LdapObject", false);
new LazilyLoadedCtor(global, "Filter",
"axiom.scripting.rhino.extensions.filter.FilterObject", false);
new LazilyLoadedCtor(global, "NativeFilter",
"axiom.scripting.rhino.extensions.filter.NativeFilterObject", false);
new LazilyLoadedCtor(global, "AndFilter",
"axiom.scripting.rhino.extensions.filter.AndFilterObject", false);
new LazilyLoadedCtor(global, "OrFilter",
"axiom.scripting.rhino.extensions.filter.OrFilterObject", false);
new LazilyLoadedCtor(global, "NotFilter",
"axiom.scripting.rhino.extensions.filter.NotFilterObject", false);
new LazilyLoadedCtor(global, "RangeFilter",
"axiom.scripting.rhino.extensions.filter.RangeFilterObject", false);
new LazilyLoadedCtor(global, "SearchFilter",
"axiom.scripting.rhino.extensions.filter.SearchFilterObject", false);
new LazilyLoadedCtor(global, "Sort",
"axiom.scripting.rhino.extensions.filter.SortObject", false);
ArrayList names = app.getDbNames();
for(int i = 0; i < names.size(); i++){
try{
String dbname = names.get(i).toString();
DbSource dbsource = app.getDbSource(dbname);
String hitsObject = dbsource.getProperty("hitsObject", null);
String hitsClass = dbsource.getProperty("hitsClass", null);
if(hitsObject != null && hitsClass != null){
new LazilyLoadedCtor(global, hitsObject,
hitsClass, false);
}
String filters = dbsource.getProperty("filters", null);
if(filters != null){
StringBuffer sb = new StringBuffer(filters);
int idx;
while ((idx = sb.indexOf("{")) > -1) {
sb.deleteCharAt(idx);
}
while ((idx = sb.indexOf("}")) > -1) {
sb.deleteCharAt(idx);
}
filters = sb.toString().trim();
String[] pairs = filters.split(",");
for (int j = 0; j < pairs.length; j++) {
String[] pair = pairs[j].split(":");
new LazilyLoadedCtor(global, pair[0].trim(),
pair[1].trim(), false);
}
}
}
catch(Exception e){
app.logError("Error during LazilyLoadedCtor initialization for external databases");
}
}
new LazilyLoadedCtor(global, "LuceneHits",
"axiom.scripting.rhino.extensions.LuceneHitsObject", false);
new LazilyLoadedCtor(global, "TopDocs",
"axiom.scripting.rhino.extensions.TopDocsObject", false);
new LazilyLoadedCtor(global, "DOMParser",
"axiom.scripting.rhino.extensions.DOMParser", false);
new LazilyLoadedCtor(global, "XMLSerializer",
"axiom.scripting.rhino.extensions.XMLSerializer", false);
if ("true".equalsIgnoreCase(app.getProperty(RhinoCore.DEBUGGER_PROPERTY))) {
new LazilyLoadedCtor(global, "Debug",
"axiom.scripting.rhino.debug.Debug", false);
}
MailObject.init(global, app.getProperties());
// defining the ActiveX scriptable object for exposure of its API in Axiom
ScriptableObject.defineClass(global, ActiveX.class);
// add some convenience functions to string, date and number prototypes
Scriptable stringProto = ScriptableObject.getClassPrototype(global, "String");
stringProto.put("trim", stringProto, new StringTrim());
Scriptable dateProto = ScriptableObject.getClassPrototype(global, "Date");
dateProto.put("format", dateProto, new DateFormat());
Scriptable numberProto = ScriptableObject.getClassPrototype(global, "Number");
numberProto.put("format", numberProto, new NumberFormat());
initialize();
loadTemplates(app);
} catch (Exception e) {
System.err.println("Cannot initialize interpreter");
System.err.println("Error: " + e);
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
Context.exit();
}
}
|
diff --git a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/StateImpl.java b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/StateImpl.java
index 6841f4d9..7c6c6cc4 100644
--- a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/StateImpl.java
+++ b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/StateImpl.java
@@ -1,690 +1,690 @@
/*******************************************************************************
* Copyright (c) 2003, 2006 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.osgi.internal.resolver;
import java.util.*;
import org.eclipse.osgi.framework.debug.Debug;
import org.eclipse.osgi.framework.debug.FrameworkDebugOptions;
import org.eclipse.osgi.framework.internal.core.*;
import org.eclipse.osgi.framework.util.KeyedElement;
import org.eclipse.osgi.framework.util.KeyedHashSet;
import org.eclipse.osgi.internal.baseadaptor.StateManager;
import org.eclipse.osgi.service.resolver.*;
import org.eclipse.osgi.util.ManifestElement;
import org.osgi.framework.BundleException;
import org.osgi.framework.Version;
public abstract class StateImpl implements State {
public static final String[] PROPS = {"osgi.os", "osgi.ws", "osgi.nl", "osgi.arch", Constants.OSGI_FRAMEWORK_SYSTEM_PACKAGES, Constants.OSGI_RESOLVER_MODE, Constants.FRAMEWORK_EXECUTIONENVIRONMENT, "osgi.resolveOptional", "osgi.genericAliases"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
transient private Resolver resolver;
transient private StateDeltaImpl changes;
transient private boolean resolving = false;
transient private HashSet removalPendings = new HashSet();
private boolean resolved = true;
private long timeStamp = System.currentTimeMillis();
private KeyedHashSet bundleDescriptions = new KeyedHashSet(false);
private HashMap resolverErrors = new HashMap();
private StateObjectFactory factory;
private KeyedHashSet resolvedBundles = new KeyedHashSet();
boolean fullyLoaded = false;
private boolean dynamicCacheChanged = false;
// only used for lazy loading of BundleDescriptions
private StateReader reader;
private Dictionary[] platformProperties = {new Hashtable(PROPS.length)}; // Dictionary here because of Filter API
private static long cumulativeTime;
protected StateImpl() {
// to prevent extra-package instantiation
}
public boolean addBundle(BundleDescription description) {
if (!basicAddBundle(description))
return false;
resolved = false;
getDelta().recordBundleAdded((BundleDescriptionImpl) description);
if (Constants.getInternalSymbolicName().equals(description.getSymbolicName()))
resetSystemExports();
if (resolver != null)
resolver.bundleAdded(description);
return true;
}
public boolean updateBundle(BundleDescription newDescription) {
BundleDescriptionImpl existing = (BundleDescriptionImpl) bundleDescriptions.get((BundleDescriptionImpl) newDescription);
if (existing == null)
return false;
if (!bundleDescriptions.remove(existing))
return false;
resolvedBundles.remove(existing);
existing.setStateBit(BundleDescriptionImpl.REMOVAL_PENDING, true);
if (!basicAddBundle(newDescription))
return false;
resolved = false;
getDelta().recordBundleUpdated((BundleDescriptionImpl) newDescription);
if (Constants.getInternalSymbolicName().equals(newDescription.getSymbolicName()))
resetSystemExports();
if (resolver != null) {
boolean pending = existing.getDependents().length > 0;
resolver.bundleUpdated(newDescription, existing, pending);
if (pending) {
getDelta().recordBundleRemovalPending(existing);
removalPendings.add(existing);
} else {
// an existing bundle has been updated with no dependents it can safely be unresolved now
synchronized (this) {
try {
resolving = true;
resolverErrors.remove(existing);
resolveBundle(existing, false, null, null, null, null);
} finally {
resolving = false;
}
}
}
}
return true;
}
public BundleDescription removeBundle(long bundleId) {
BundleDescription toRemove = getBundle(bundleId);
if (toRemove == null || !removeBundle(toRemove))
return null;
return toRemove;
}
public boolean removeBundle(BundleDescription toRemove) {
if (!bundleDescriptions.remove((KeyedElement) toRemove))
return false;
resolvedBundles.remove((KeyedElement) toRemove);
resolved = false;
getDelta().recordBundleRemoved((BundleDescriptionImpl) toRemove);
((BundleDescriptionImpl) toRemove).setStateBit(BundleDescriptionImpl.REMOVAL_PENDING, true);
if (resolver != null) {
boolean pending = toRemove.getDependents().length > 0;
resolver.bundleRemoved(toRemove, pending);
if (pending) {
getDelta().recordBundleRemovalPending((BundleDescriptionImpl) toRemove);
removalPendings.add(toRemove);
} else {
// a bundle has been removed with no dependents it can safely be unresolved now
synchronized (this) {
try {
resolving = true;
resolverErrors.remove(toRemove);
resolveBundle(toRemove, false, null, null, null, null);
} finally {
resolving = false;
}
}
}
}
return true;
}
public StateDelta getChanges() {
return getDelta();
}
private StateDeltaImpl getDelta() {
if (changes == null)
changes = new StateDeltaImpl(this);
return changes;
}
public BundleDescription[] getBundles(final String symbolicName) {
final List bundles = new ArrayList();
for (Iterator iter = bundleDescriptions.iterator(); iter.hasNext();) {
BundleDescription bundle = (BundleDescription) iter.next();
if (symbolicName.equals(bundle.getSymbolicName()))
bundles.add(bundle);
}
return (BundleDescription[]) bundles.toArray(new BundleDescription[bundles.size()]);
}
public BundleDescription[] getBundles() {
return (BundleDescription[]) bundleDescriptions.elements(new BundleDescription[bundleDescriptions.size()]);
}
public BundleDescription getBundle(long id) {
BundleDescription result = (BundleDescription) bundleDescriptions.getByKey(new Long(id));
if (result != null)
return result;
// need to look in removal pending bundles;
for (Iterator iter = removalPendings.iterator(); iter.hasNext();) {
BundleDescription removedBundle = (BundleDescription) iter.next();
if (removedBundle.getBundleId() == id) // just return the first matching id
return removedBundle;
}
return null;
}
public BundleDescription getBundle(String name, Version version) {
BundleDescription[] allBundles = getBundles(name);
if (allBundles.length == 1)
return version == null || allBundles[0].getVersion().equals(version) ? allBundles[0] : null;
if (allBundles.length == 0)
return null;
BundleDescription unresolvedFound = null;
BundleDescription resolvedFound = null;
for (int i = 0; i < allBundles.length; i++) {
BundleDescription current = allBundles[i];
BundleDescription base;
if (current.isResolved())
base = resolvedFound;
else
base = unresolvedFound;
if (version == null || current.getVersion().equals(version)) {
if (base != null && (base.getVersion().compareTo(current.getVersion()) <= 0 || base.getBundleId() > current.getBundleId())) {
if (base == resolvedFound)
resolvedFound = current;
else
unresolvedFound = current;
} else {
if (current.isResolved())
resolvedFound = current;
else
unresolvedFound = current;
}
}
}
if (resolvedFound != null)
return resolvedFound;
return unresolvedFound;
}
public long getTimeStamp() {
return timeStamp;
}
public boolean isResolved() {
return resolved || isEmpty();
}
public void resolveConstraint(VersionConstraint constraint, BaseDescription supplier) {
((VersionConstraintImpl) constraint).setSupplier(supplier);
}
public synchronized void resolveBundle(BundleDescription bundle, boolean status, BundleDescription[] hosts, ExportPackageDescription[] selectedExports, BundleDescription[] resolvedRequires, ExportPackageDescription[] resolvedImports) {
if (!resolving)
throw new IllegalStateException(); // TODO need error message here!
BundleDescriptionImpl modifiable = (BundleDescriptionImpl) bundle;
// must record the change before setting the resolve state to
// accurately record if a change has happened.
getDelta().recordBundleResolved(modifiable, status);
// force the new resolution data to stay in memory; we will not read this from disk anymore
modifiable.setLazyLoaded(false);
modifiable.setStateBit(BundleDescriptionImpl.RESOLVED, status);
if (status) {
resolverErrors.remove(modifiable);
resolveConstraints(modifiable, hosts, selectedExports, resolvedRequires, resolvedImports);
resolvedBundles.add(modifiable);
} else {
// ensures no links are left
unresolveConstraints(modifiable);
// remove the bundle from the resolved pool
resolvedBundles.remove(modifiable);
}
}
public synchronized void removeBundleComplete(BundleDescription bundle) {
if (!resolving)
throw new IllegalStateException(); // TODO need error message here!
getDelta().recordBundleRemovalComplete((BundleDescriptionImpl) bundle);
removalPendings.remove(bundle);
}
private void resolveConstraints(BundleDescriptionImpl bundle, BundleDescription[] hosts, ExportPackageDescription[] selectedExports, BundleDescription[] resolvedRequires, ExportPackageDescription[] resolvedImports) {
HostSpecificationImpl hostSpec = (HostSpecificationImpl) bundle.getHost();
if (hostSpec != null) {
if (hosts != null) {
hostSpec.setHosts(hosts);
for (int i = 0; i < hosts.length; i++)
((BundleDescriptionImpl) hosts[i]).addDependency(bundle);
}
}
bundle.setSelectedExports(selectedExports);
bundle.setResolvedRequires(resolvedRequires);
bundle.setResolvedImports(resolvedImports);
bundle.addDependencies(hosts);
bundle.addDependencies(resolvedRequires);
bundle.addDependencies(resolvedImports);
// add dependecies for generics
GenericSpecification[] genericRequires = bundle.getGenericRequires();
if (genericRequires.length > 0) {
ArrayList genericSuppliers = new ArrayList(genericRequires.length);
for (int i = 0; i < genericRequires.length; i++)
if (genericRequires[i].getSupplier() != null)
genericSuppliers.add(genericRequires[i].getSupplier());
bundle.addDependencies((BaseDescription[]) genericSuppliers.toArray(new BaseDescription[genericSuppliers.size()]));
}
}
private void unresolveConstraints(BundleDescriptionImpl bundle) {
HostSpecificationImpl host = (HostSpecificationImpl) bundle.getHost();
if (host != null)
host.setHosts(null);
bundle.setSelectedExports(null);
bundle.setResolvedImports(null);
bundle.setResolvedRequires(null);
bundle.removeDependencies();
}
private synchronized StateDelta resolve(boolean incremental, BundleDescription[] reResolve) {
try {
resolving = true;
if (resolver == null)
throw new IllegalStateException("no resolver set"); //$NON-NLS-1$
fullyLoad();
long start = 0;
if (StateManager.DEBUG_PLATFORM_ADMIN_RESOLVER)
start = System.currentTimeMillis();
if (!incremental) {
resolved = false;
reResolve = getBundles();
// need to get any removal pendings before flushing
if (removalPendings.size() > 0) {
BundleDescription[] removed = getRemovalPendings();
reResolve = mergeBundles(reResolve, removed);
}
flush(reResolve);
}
if (resolved && reResolve == null)
return new StateDeltaImpl(this);
if (removalPendings.size() > 0) {
BundleDescription[] removed = getRemovalPendings();
reResolve = mergeBundles(reResolve, removed);
}
resolver.resolve(reResolve, platformProperties);
- resolved = true;
+ resolved = removalPendings.size() == 0;
StateDelta savedChanges = changes == null ? new StateDeltaImpl(this) : changes;
changes = new StateDeltaImpl(this);
if (StateManager.DEBUG_PLATFORM_ADMIN_RESOLVER) {
long time = System.currentTimeMillis() - start;
Debug.println("Time spent resolving: " + time); //$NON-NLS-1$
cumulativeTime = cumulativeTime + time;
FrameworkDebugOptions.getDefault().setOption("org.eclipse.core.runtime.adaptor/resolver/timing/value", Long.toString(cumulativeTime)); //$NON-NLS-1$
}
return savedChanges;
} finally {
resolving = false;
}
}
private BundleDescription[] mergeBundles(BundleDescription[] reResolve, BundleDescription[] removed) {
if (reResolve == null)
return removed; // just return all the removed bundles
if (reResolve.length == 0)
return reResolve; // if reResolve length==0 then we want to prevent pending removal
// merge in all removal pending bundles that are not already in the list
ArrayList result = new ArrayList(reResolve.length + removed.length);
for (int i = 0; i < reResolve.length; i++)
result.add(reResolve[i]);
for (int i = 0; i < removed.length; i++) {
boolean found = false;
for (int j = 0; j < reResolve.length; j++) {
if (removed[i] == reResolve[j]) {
found = true;
break;
}
}
if (!found)
result.add(removed[i]);
}
return (BundleDescription[]) result.toArray(new BundleDescription[result.size()]);
}
private void flush(BundleDescription[] bundles) {
resolver.flush();
resolved = false;
resolverErrors.clear();
if (resolvedBundles.isEmpty())
return;
for (int i = 0; i < bundles.length; i++) {
resolveBundle(bundles[i], false, null, null, null, null);
}
resolvedBundles.clear();
}
public StateDelta resolve() {
return resolve(true, null);
}
public StateDelta resolve(boolean incremental) {
return resolve(incremental, null);
}
public StateDelta resolve(BundleDescription[] reResolve) {
return resolve(true, reResolve);
}
public void setOverrides(Object value) {
throw new UnsupportedOperationException();
}
public BundleDescription[] getResolvedBundles() {
return (BundleDescription[]) resolvedBundles.elements(new BundleDescription[resolvedBundles.size()]);
}
public boolean isEmpty() {
return bundleDescriptions.isEmpty();
}
void setResolved(boolean resolved) {
this.resolved = resolved;
}
boolean basicAddBundle(BundleDescription description) {
((BundleDescriptionImpl) description).setContainingState(this);
((BundleDescriptionImpl) description).setStateBit(BundleDescriptionImpl.REMOVAL_PENDING, false);
return bundleDescriptions.add((BundleDescriptionImpl) description);
}
void addResolvedBundle(BundleDescriptionImpl resolvedBundle) {
resolvedBundles.add(resolvedBundle);
}
public ExportPackageDescription[] getExportedPackages() {
fullyLoad();
final List allExportedPackages = new ArrayList();
for (Iterator iter = resolvedBundles.iterator(); iter.hasNext();) {
BundleDescription bundle = (BundleDescription) iter.next();
ExportPackageDescription[] bundlePackages = bundle.getSelectedExports();
if (bundlePackages == null)
continue;
for (int i = 0; i < bundlePackages.length; i++)
allExportedPackages.add(bundlePackages[i]);
}
for (Iterator iter = removalPendings.iterator(); iter.hasNext();) {
BundleDescription bundle = (BundleDescription) iter.next();
ExportPackageDescription[] bundlePackages = bundle.getSelectedExports();
if (bundlePackages == null)
continue;
for (int i = 0; i < bundlePackages.length; i++)
allExportedPackages.add(bundlePackages[i]);
}
return (ExportPackageDescription[]) allExportedPackages.toArray(new ExportPackageDescription[allExportedPackages.size()]);
}
BundleDescription[] getFragments(final BundleDescription host) {
final List fragments = new ArrayList();
for (Iterator iter = bundleDescriptions.iterator(); iter.hasNext();) {
BundleDescription bundle = (BundleDescription) iter.next();
HostSpecification hostSpec = bundle.getHost();
if (hostSpec != null) {
BundleDescription[] hosts = hostSpec.getHosts();
if (hosts != null)
for (int i = 0; i < hosts.length; i++)
if (hosts[i] == host) {
fragments.add(bundle);
break;
}
}
}
return (BundleDescription[]) fragments.toArray(new BundleDescription[fragments.size()]);
}
public void setTimeStamp(long newTimeStamp) {
timeStamp = newTimeStamp;
}
public StateObjectFactory getFactory() {
return factory;
}
void setFactory(StateObjectFactory factory) {
this.factory = factory;
}
public BundleDescription getBundleByLocation(String location) {
for (Iterator i = bundleDescriptions.iterator(); i.hasNext();) {
BundleDescription current = (BundleDescription) i.next();
if (location.equals(current.getLocation()))
return current;
}
return null;
}
public Resolver getResolver() {
return resolver;
}
public void setResolver(Resolver newResolver) {
if (resolver == newResolver)
return;
if (resolver != null) {
Resolver oldResolver = resolver;
resolver = null;
oldResolver.setState(null);
}
resolver = newResolver;
if (resolver == null)
return;
resolver.setState(this);
}
public boolean setPlatformProperties(Dictionary platformProperties) {
return setPlatformProperties(new Dictionary[] {platformProperties});
}
public boolean setPlatformProperties(Dictionary[] platformProperties) {
return setPlatformProperties(platformProperties, true);
}
synchronized boolean setPlatformProperties(Dictionary[] platformProperties, boolean resetSystemExports) {
if (platformProperties.length == 0)
throw new IllegalArgumentException();
if (this.platformProperties.length != platformProperties.length) {
this.platformProperties = new Dictionary[platformProperties.length];
for (int i = 0; i < platformProperties.length; i++)
this.platformProperties[i] = new Hashtable(PROPS.length);
}
boolean result = false;
for (int i = 0; i < platformProperties.length; i++)
result |= setProps(this.platformProperties[i], platformProperties[i]);
if (resetSystemExports && result)
resetSystemExports();
return result;
}
private void resetSystemExports() {
BundleDescription[] systemBundles = getBundles(Constants.getInternalSymbolicName());
if (systemBundles.length > 0) {
BundleDescriptionImpl systemBundle = (BundleDescriptionImpl) systemBundles[0];
ExportPackageDescription[] exports = systemBundle.getExportPackages();
ArrayList newExports = new ArrayList(exports.length);
for (int i = 0; i < exports.length; i++)
if (((Integer) exports[i].getDirective(ExportPackageDescriptionImpl.EQUINOX_EE)).intValue() < 0)
newExports.add(exports[i]);
addSystemExports(newExports);
systemBundle.setExportPackages((ExportPackageDescription[]) newExports.toArray(new ExportPackageDescription[newExports.size()]));
}
}
private void addSystemExports(ArrayList exports) {
for (int i = 0; i < platformProperties.length; i++)
try {
ManifestElement[] elements = ManifestElement.parseHeader(Constants.EXPORT_PACKAGE, (String) platformProperties[i].get(Constants.OSGI_FRAMEWORK_SYSTEM_PACKAGES));
if (elements == null)
continue;
// we can pass false for strict mode here because we never want to mark the system exports as internal.
ExportPackageDescription[] systemExports = StateBuilder.createExportPackages(elements, null, null, null, 2, false);
Integer profInx = new Integer(i);
for (int j = 0; j < systemExports.length; j++) {
((ExportPackageDescriptionImpl) systemExports[j]).setDirective(ExportPackageDescriptionImpl.EQUINOX_EE, profInx);
exports.add(systemExports[j]);
}
} catch (BundleException e) {
// TODO consider throwing this...
}
}
public Dictionary[] getPlatformProperties() {
return platformProperties;
}
private boolean checkProp(Object origObj, Object newObj) {
if ((origObj == null && newObj != null) || (origObj != null && newObj == null))
return true;
if (origObj == null)
return false;
if (origObj.getClass() != newObj.getClass())
return true;
if (origObj instanceof String)
return !origObj.equals(newObj);
String[] origProps = (String[]) origObj;
String[] newProps = (String[]) newObj;
if (origProps.length != newProps.length)
return true;
for (int i = 0; i < origProps.length; i++) {
if (!origProps[i].equals(newProps[i]))
return true;
}
return false;
}
private boolean setProps(Dictionary origProps, Dictionary newProps) {
boolean changed = false;
for (int i = 0; i < PROPS.length; i++) {
Object origProp = origProps.get(PROPS[i]);
Object newProp = newProps.get(PROPS[i]);
if (checkProp(origProp, newProp)) {
changed = true;
if (newProp == null)
origProps.remove(PROPS[i]);
else
origProps.put(PROPS[i], newProp);
}
}
return changed;
}
public BundleDescription[] getRemovalPendings() {
return (BundleDescription[]) removalPendings.toArray(new BundleDescription[removalPendings.size()]);
}
public synchronized ExportPackageDescription linkDynamicImport(BundleDescription importingBundle, String requestedPackage) {
if (resolver == null)
throw new IllegalStateException("no resolver set"); //$NON-NLS-1$
BundleDescriptionImpl importer = (BundleDescriptionImpl) importingBundle;
if (importer.getDynamicStamp(requestedPackage) == getTimeStamp())
return null;
fullyLoad();
// ask the resolver to resolve our dynamic import
ExportPackageDescriptionImpl result = (ExportPackageDescriptionImpl) resolver.resolveDynamicImport(importingBundle, requestedPackage);
if (result == null)
importer.setDynamicStamp(requestedPackage, new Long(getTimeStamp()));
else {
importer.setDynamicStamp(requestedPackage, null); // remove any cached timestamp
// need to add the result to the list of resolved imports
importer.addDynamicResolvedImport(result);
}
setDynamicCacheChanged(true);
return result;
}
void setReader(StateReader reader) {
this.reader = reader;
}
StateReader getReader() {
return reader;
}
public void fullyLoad() {
if (fullyLoaded == true)
return;
if (reader != null && reader.isLazyLoaded())
reader.fullyLoad();
fullyLoaded = true;
}
public void unloadLazyData(long expireTime) {
// make sure no other thread is trying to unload or load
synchronized (reader) {
if (reader.getAccessedFlag()) {
reader.setAccessedFlag(false); // reset accessed flag
return;
}
BundleDescription[] bundles = getBundles();
for (int i = 0; i < bundles.length; i++)
((BundleDescriptionImpl) bundles[i]).unload();
}
}
public ExportPackageDescription[] getSystemPackages() {
ArrayList result = new ArrayList();
BundleDescription[] systemBundles = getBundles(Constants.getInternalSymbolicName());
if (systemBundles.length > 0) {
BundleDescriptionImpl systemBundle = (BundleDescriptionImpl) systemBundles[0];
ExportPackageDescription[] exports = systemBundle.getExportPackages();
for (int i = 0; i < exports.length; i++)
if (((Integer) exports[i].getDirective(ExportPackageDescriptionImpl.EQUINOX_EE)).intValue() >= 0)
result.add(exports[i]);
}
return (ExportPackageDescription[]) result.toArray(new ExportPackageDescription[result.size()]);
}
boolean inStrictMode() {
return Constants.STRICT_MODE.equals(getPlatformProperties()[0].get(Constants.OSGI_RESOLVER_MODE));
}
public synchronized ResolverError[] getResolverErrors(BundleDescription bundle) {
if (bundle.isResolved())
return new ResolverError[0];
ArrayList result = (ArrayList) resolverErrors.get(bundle);
return result == null ? new ResolverError[0] : (ResolverError[]) result.toArray(new ResolverError[result.size()]);
}
public synchronized void addResolverError(BundleDescription bundle, int type, String data, VersionConstraint unsatisfied) {
if (!resolving)
throw new IllegalStateException(); // TODO need error message here!
ArrayList errors = (ArrayList) resolverErrors.get(bundle);
if (errors == null) {
errors = new ArrayList(1);
resolverErrors.put(bundle, errors);
}
errors.add(new ResolverErrorImpl((BundleDescriptionImpl) bundle, type, data, unsatisfied));
}
public synchronized void removeResolverErrors(BundleDescription bundle) {
if (!resolving)
throw new IllegalStateException(); // TODO need error message here!
resolverErrors.remove(bundle);
}
public boolean dynamicCacheChanged() {
return dynamicCacheChanged;
}
void setDynamicCacheChanged(boolean dynamicCacheChanged) {
this.dynamicCacheChanged = dynamicCacheChanged;
}
public StateHelper getStateHelper() {
return StateHelperImpl.getInstance();
}
}
| true | true | private synchronized StateDelta resolve(boolean incremental, BundleDescription[] reResolve) {
try {
resolving = true;
if (resolver == null)
throw new IllegalStateException("no resolver set"); //$NON-NLS-1$
fullyLoad();
long start = 0;
if (StateManager.DEBUG_PLATFORM_ADMIN_RESOLVER)
start = System.currentTimeMillis();
if (!incremental) {
resolved = false;
reResolve = getBundles();
// need to get any removal pendings before flushing
if (removalPendings.size() > 0) {
BundleDescription[] removed = getRemovalPendings();
reResolve = mergeBundles(reResolve, removed);
}
flush(reResolve);
}
if (resolved && reResolve == null)
return new StateDeltaImpl(this);
if (removalPendings.size() > 0) {
BundleDescription[] removed = getRemovalPendings();
reResolve = mergeBundles(reResolve, removed);
}
resolver.resolve(reResolve, platformProperties);
resolved = true;
StateDelta savedChanges = changes == null ? new StateDeltaImpl(this) : changes;
changes = new StateDeltaImpl(this);
if (StateManager.DEBUG_PLATFORM_ADMIN_RESOLVER) {
long time = System.currentTimeMillis() - start;
Debug.println("Time spent resolving: " + time); //$NON-NLS-1$
cumulativeTime = cumulativeTime + time;
FrameworkDebugOptions.getDefault().setOption("org.eclipse.core.runtime.adaptor/resolver/timing/value", Long.toString(cumulativeTime)); //$NON-NLS-1$
}
return savedChanges;
} finally {
resolving = false;
}
}
| private synchronized StateDelta resolve(boolean incremental, BundleDescription[] reResolve) {
try {
resolving = true;
if (resolver == null)
throw new IllegalStateException("no resolver set"); //$NON-NLS-1$
fullyLoad();
long start = 0;
if (StateManager.DEBUG_PLATFORM_ADMIN_RESOLVER)
start = System.currentTimeMillis();
if (!incremental) {
resolved = false;
reResolve = getBundles();
// need to get any removal pendings before flushing
if (removalPendings.size() > 0) {
BundleDescription[] removed = getRemovalPendings();
reResolve = mergeBundles(reResolve, removed);
}
flush(reResolve);
}
if (resolved && reResolve == null)
return new StateDeltaImpl(this);
if (removalPendings.size() > 0) {
BundleDescription[] removed = getRemovalPendings();
reResolve = mergeBundles(reResolve, removed);
}
resolver.resolve(reResolve, platformProperties);
resolved = removalPendings.size() == 0;
StateDelta savedChanges = changes == null ? new StateDeltaImpl(this) : changes;
changes = new StateDeltaImpl(this);
if (StateManager.DEBUG_PLATFORM_ADMIN_RESOLVER) {
long time = System.currentTimeMillis() - start;
Debug.println("Time spent resolving: " + time); //$NON-NLS-1$
cumulativeTime = cumulativeTime + time;
FrameworkDebugOptions.getDefault().setOption("org.eclipse.core.runtime.adaptor/resolver/timing/value", Long.toString(cumulativeTime)); //$NON-NLS-1$
}
return savedChanges;
} finally {
resolving = false;
}
}
|
diff --git a/src/whitehole/StrictThreadGroup.java b/src/whitehole/StrictThreadGroup.java
index 19f1fac..f551d1e 100644
--- a/src/whitehole/StrictThreadGroup.java
+++ b/src/whitehole/StrictThreadGroup.java
@@ -1,65 +1,65 @@
/*
Copyright 2012 The Whitehole team
This file is part of Whitehole.
Whitehole 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.
Whitehole 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 Whitehole. If not, see http://www.gnu.org/licenses/.
*/
package whitehole;
import java.io.File;
import java.io.PrintStream;
import javax.swing.JOptionPane;
public class StrictThreadGroup extends ThreadGroup
{
public StrictThreadGroup()
{
super("StrictThreadGroup");
}
@Override
public void uncaughtException(Thread t, Throwable e)
{
if (e.getMessage().contains("Method 'gl") && e.getMessage().contains("' not available"))
{
JOptionPane.showMessageDialog(null,
e.getMessage() + "\n\n"
+ "This error is likely caused by an outdated video driver. Update it if possible.",
Whitehole.name, JOptionPane.ERROR_MESSAGE);
return;
}
JOptionPane.showMessageDialog(null,
"An unhandled exception has occured: " + e.getMessage() + "\n"
+ "Whitehole may be unstable. It is recommended that you close it now. You can try to save your unsaved work before doing so, but at your own risks.\n\n"
- + "You should report this crash at Kuribo64 ("+Whitehole.websiteURL+"), providing the detailed report found in whiteholeCrash.txt.",
+ + "You should report this crash at Kuribo64 ("+Whitehole.crashReportURL+"), providing the detailed report found in whiteholeCrash.txt.",
Whitehole.name, JOptionPane.ERROR_MESSAGE);
try
{
File report = new File("whiteholeCrash.txt");
if (report.exists()) report.delete();
report.createNewFile();
PrintStream ps = new PrintStream(report);
ps.append(Whitehole.fullName + " crash report\r\n");
ps.append("Please report this at Kuribo64 ("+Whitehole.websiteURL+") with all the details below\r\n");
ps.append("--------------------------------------------------------------------------------\r\n\r\n");
e.printStackTrace(ps);
ps.close();
}
catch (Exception ex) {}
}
}
| true | true | public void uncaughtException(Thread t, Throwable e)
{
if (e.getMessage().contains("Method 'gl") && e.getMessage().contains("' not available"))
{
JOptionPane.showMessageDialog(null,
e.getMessage() + "\n\n"
+ "This error is likely caused by an outdated video driver. Update it if possible.",
Whitehole.name, JOptionPane.ERROR_MESSAGE);
return;
}
JOptionPane.showMessageDialog(null,
"An unhandled exception has occured: " + e.getMessage() + "\n"
+ "Whitehole may be unstable. It is recommended that you close it now. You can try to save your unsaved work before doing so, but at your own risks.\n\n"
+ "You should report this crash at Kuribo64 ("+Whitehole.websiteURL+"), providing the detailed report found in whiteholeCrash.txt.",
Whitehole.name, JOptionPane.ERROR_MESSAGE);
try
{
File report = new File("whiteholeCrash.txt");
if (report.exists()) report.delete();
report.createNewFile();
PrintStream ps = new PrintStream(report);
ps.append(Whitehole.fullName + " crash report\r\n");
ps.append("Please report this at Kuribo64 ("+Whitehole.websiteURL+") with all the details below\r\n");
ps.append("--------------------------------------------------------------------------------\r\n\r\n");
e.printStackTrace(ps);
ps.close();
}
catch (Exception ex) {}
}
| public void uncaughtException(Thread t, Throwable e)
{
if (e.getMessage().contains("Method 'gl") && e.getMessage().contains("' not available"))
{
JOptionPane.showMessageDialog(null,
e.getMessage() + "\n\n"
+ "This error is likely caused by an outdated video driver. Update it if possible.",
Whitehole.name, JOptionPane.ERROR_MESSAGE);
return;
}
JOptionPane.showMessageDialog(null,
"An unhandled exception has occured: " + e.getMessage() + "\n"
+ "Whitehole may be unstable. It is recommended that you close it now. You can try to save your unsaved work before doing so, but at your own risks.\n\n"
+ "You should report this crash at Kuribo64 ("+Whitehole.crashReportURL+"), providing the detailed report found in whiteholeCrash.txt.",
Whitehole.name, JOptionPane.ERROR_MESSAGE);
try
{
File report = new File("whiteholeCrash.txt");
if (report.exists()) report.delete();
report.createNewFile();
PrintStream ps = new PrintStream(report);
ps.append(Whitehole.fullName + " crash report\r\n");
ps.append("Please report this at Kuribo64 ("+Whitehole.websiteURL+") with all the details below\r\n");
ps.append("--------------------------------------------------------------------------------\r\n\r\n");
e.printStackTrace(ps);
ps.close();
}
catch (Exception ex) {}
}
|
diff --git a/src/main/java/com/bergerkiller/bukkit/mw/Portal.java b/src/main/java/com/bergerkiller/bukkit/mw/Portal.java
index f442bf6..b6616b5 100644
--- a/src/main/java/com/bergerkiller/bukkit/mw/Portal.java
+++ b/src/main/java/com/bergerkiller/bukkit/mw/Portal.java
@@ -1,322 +1,321 @@
package com.bergerkiller.bukkit.mw;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Entity;
import org.bukkit.material.Directional;
import org.bukkit.material.MaterialData;
import com.bergerkiller.bukkit.common.bases.IntVector3;
import com.bergerkiller.bukkit.common.utils.CommonUtil;
import com.bergerkiller.bukkit.common.utils.EntityUtil;
import com.bergerkiller.bukkit.common.utils.FaceUtil;
import com.bergerkiller.bukkit.common.utils.LogicUtil;
import com.bergerkiller.bukkit.common.utils.StringUtil;
import com.bergerkiller.bukkit.common.utils.WorldUtil;
public class Portal extends PortalStore {
public static final double SEARCH_RADIUS = 5.0;
private String name;
private String destination;
private String destdisplayname;
private Location location;
/**
* Gets the identifier name of this Portal
*
* @return Portal identifier name
*/
public String getName() {
return this.name;
}
/**
* Gets the Location of this Portal
*
* @return Portal location
*/
public Location getLocation() {
return this.location;
}
/**
* Gets the destination name of this Portal
*
* @return Portal destination name
*/
public String getDestinationName() {
if (this.destination == null) {
return null;
} else {
return this.destination.substring(this.destination.indexOf('.') + 1);
}
}
/**
* Gets the destination display name of this Portal
*
* @return Portal destination display name
*/
public String getDestinationDisplayName() {
return this.destdisplayname;
}
/**
* Gets the destination location of this Portal
*
* @return Portal destination
*/
public Location getDestination() {
Location loc = getPortalLocation(this.destination, location.getWorld().getName(), true);
if (loc == null) {
String portalname = WorldManager.matchWorld(this.destination);
World w = WorldManager.getWorld(portalname);
if (w != null) {
loc = WorldManager.getSpawnLocation(w);
}
}
return loc;
}
/**
* Checks if this Portal has an available destination
*
* @return True if it has a destination, False if not
*/
public boolean hasDestination() {
if (this.destination == null || this.destination.trim().isEmpty()) {
return false;
}
return getDestination() != null;
}
/**
* Teleports an Entity to the location of this Portal
*
* @param entity to teleport
* @return True if successful, False if not
*/
public boolean teleportSelf(Entity entity) {
MWPermissionListener.lastSelfPortal = this;
boolean rval = EntityUtil.teleport(entity, Util.spawnOffset(this.getLocation()));
MWPermissionListener.lastSelfPortal = null;
return rval;
}
/**
* Teleports an Entity to the destination of this Portal in the next tick
*
* @param entity to teleport
*/
public void teleportNextTick(final Entity entity) {
CommonUtil.nextTick(new Runnable() {
public void run() {
if (Portal.this.hasDestination()) {
Portal.this.teleport(entity);
} else {
CommonUtil.sendMessage(entity, Localization.PORTAL_NODESTINATION.get());
}
}
});
}
/**
* Teleports an Entity to the destination of this Portal
*
* @param entity to teleport
* @return True if successful, False if not
*/
public boolean teleport(Entity entity) {
Location dest = this.getDestination();
if (dest != null && entity != null) {
MWPermissionListener.lastPortal = this;
boolean rval = EntityUtil.teleport(entity, dest);
MWPermissionListener.lastPortal = null;
return rval;
}
return false;
}
/**
* Adds this Portal to the internal mapping
*/
public void add() {
getPortalLocations(location.getWorld().getName()).put(name, new Position(location));
}
/**
* Removes this Portal from the internal mapping
*
* @return True if successful, False if not
*/
public boolean remove() {
return remove(this.name, this.location.getWorld().getName());
}
/**
* Checks if this Portal is added to the internal mapping
*
* @return True if it is added, False if not
*/
public boolean isAdded() {
return getPortalLocations(this.location.getWorld().getName()).containsKey(this.getName());
}
public static boolean exists(String world, String portalname) {
return getPortalLocations(world).containsKey(portalname);
}
public static boolean remove(String name, String world) {
return getPortalLocations(world).remove(name) != null;
}
/**
* Gets the nearest portal (sign) near a given point using the SEARCH_RADIUS as radius
*
* @param middle point of the sphere to look in
* @return Nearest portal, or null if none are found
*/
public static Portal getNear(Location middle) {
return getNear(middle, SEARCH_RADIUS);
}
/**
* Gets the nearest portal (sign) in a given spherical area
*
* @param middle point of the sphere to look in
* @param radius of the sphere to look in
* @return Nearest portal, or null if none are found
*/
public static Portal getNear(Location middle, double radius) {
Portal p = null;
HashMap<String, Position> positions = getPortalLocations(middle.getWorld().getName());
for (Map.Entry<String, Position> pos : positions.entrySet()) {
Location ploc = Util.getLocation(pos.getValue());
String portalname = pos.getKey();
if (ploc != null && ploc.getWorld() == middle.getWorld()) {
double distance = ploc.distance(middle);
if (distance <= radius) {
Portal newp = Portal.get(ploc);
if (newp != null) {
p = newp;
radius = distance;
} else if (ploc.getWorld().isChunkLoaded(ploc.getBlockX() >> 4, ploc.getBlockZ() >> 4)) {
//In loaded chunk and NOT found!
//Remove it
positions.remove(portalname);
MyWorlds.plugin.log(Level.WARNING, "Removed portal '" + portalname + "' because it is no longer there!");
//End the loop and call the function again
return getNear(middle, radius);
}
}
}
}
return p;
}
public static Portal get(String name) {
return get(getPortalLocation(name, null));
}
public static Portal get(Location signloc) {
if (signloc == null) return null;
return get(signloc.getBlock(), false);
}
public static Portal get(Block signblock, boolean loadchunk) {
if (loadchunk) {
signblock.getChunk();
} else if (!WorldUtil.isLoaded(signblock)) {
return null;
}
if (signblock.getState() instanceof Sign) {
return get(signblock, ((Sign) signblock.getState()).getLines());
}
return null;
}
public static Portal get(Block signblock, String[] lines) {
if (signblock.getState() instanceof Sign && lines[0].equalsIgnoreCase("[portal]")) {
String name = lines[1];
if (LogicUtil.nullOrEmpty(name)) {
name = StringUtil.blockToString(signblock);
}
Portal p = new Portal();
p.name = name.replace("\"", "").replace("'", "");
p.destination = lines[2].replace("\"", "").replace("'", "");
if (lines[3].isEmpty()) {
p.destdisplayname = p.getDestinationName();
} else {
p.destdisplayname = lines[3];
}
p.location = signblock.getLocation();
MaterialData data = signblock.getState().getData();
float yaw = 0;
if (data instanceof Directional) {
yaw = FaceUtil.faceToYaw(((Directional) data).getFacing()) + 90;
}
p.location.setYaw(yaw);
return p;
}
return null;
}
/**
* Handles an entity entering a certain portal block
*
* @param e that entered
* @param portalMaterial of the block that was used as portal
* @return True if a teleport was performed, False if not
*/
public static boolean handlePortalEnter(Entity e, Material portalMaterial) {
Portal portal = getNear(e.getLocation());
if (portal == null) {
// Default portals
String def = null;
if (portalMaterial == Material.PORTAL) {
def = WorldConfig.get(e).getNetherPortal();
} else if (portalMaterial == Material.ENDER_PORTAL) {
def = WorldConfig.get(e).getEndPortal();
}
if (def != null) {
portal = get(getPortalLocation(def, e.getWorld().getName()));
if (portal == null) {
// Is it a world spawn?
World w = WorldManager.getWorld(def);
if (w != null) {
final Location dest;
if (MyWorlds.allowPersonalPortals) {
// Find out what location to teleport to
// Use source block as the location to search from
double blockRatio = w.getEnvironment() == Environment.NORMAL ? 8 : 0.125;
- Location entityLoc = e.getLocation();
- IntVector3 blockPos = new IntVector3(blockRatio * entityLoc.getX(), entityLoc.getY(), blockRatio * entityLoc.getZ());
- dest = WorldUtil.findSpawnLocation(new Location(w, blockPos.x + 0.5, blockPos.y + 0.5, blockPos.z + 0.5));
+ Location start = e.getLocation();
+ dest = WorldUtil.findSpawnLocation(new Location(w, blockRatio * start.getX(), start.getY(), blockRatio * start.getZ())).add(0.5, 0.0, 0.5);
} else {
// Fall-back to the main world spawn
dest = WorldManager.getSpawnLocation(w);
}
if (dest != null) {
EntityUtil.teleportNextTick(e, dest);
return true;
}
}
}
}
}
// If a portal was found, teleport using it
if (portal != null) {
portal.teleportNextTick(e);
return true;
}
return false;
}
}
| true | true | public static boolean handlePortalEnter(Entity e, Material portalMaterial) {
Portal portal = getNear(e.getLocation());
if (portal == null) {
// Default portals
String def = null;
if (portalMaterial == Material.PORTAL) {
def = WorldConfig.get(e).getNetherPortal();
} else if (portalMaterial == Material.ENDER_PORTAL) {
def = WorldConfig.get(e).getEndPortal();
}
if (def != null) {
portal = get(getPortalLocation(def, e.getWorld().getName()));
if (portal == null) {
// Is it a world spawn?
World w = WorldManager.getWorld(def);
if (w != null) {
final Location dest;
if (MyWorlds.allowPersonalPortals) {
// Find out what location to teleport to
// Use source block as the location to search from
double blockRatio = w.getEnvironment() == Environment.NORMAL ? 8 : 0.125;
Location entityLoc = e.getLocation();
IntVector3 blockPos = new IntVector3(blockRatio * entityLoc.getX(), entityLoc.getY(), blockRatio * entityLoc.getZ());
dest = WorldUtil.findSpawnLocation(new Location(w, blockPos.x + 0.5, blockPos.y + 0.5, blockPos.z + 0.5));
} else {
// Fall-back to the main world spawn
dest = WorldManager.getSpawnLocation(w);
}
if (dest != null) {
EntityUtil.teleportNextTick(e, dest);
return true;
}
}
}
}
}
// If a portal was found, teleport using it
if (portal != null) {
portal.teleportNextTick(e);
return true;
}
return false;
}
| public static boolean handlePortalEnter(Entity e, Material portalMaterial) {
Portal portal = getNear(e.getLocation());
if (portal == null) {
// Default portals
String def = null;
if (portalMaterial == Material.PORTAL) {
def = WorldConfig.get(e).getNetherPortal();
} else if (portalMaterial == Material.ENDER_PORTAL) {
def = WorldConfig.get(e).getEndPortal();
}
if (def != null) {
portal = get(getPortalLocation(def, e.getWorld().getName()));
if (portal == null) {
// Is it a world spawn?
World w = WorldManager.getWorld(def);
if (w != null) {
final Location dest;
if (MyWorlds.allowPersonalPortals) {
// Find out what location to teleport to
// Use source block as the location to search from
double blockRatio = w.getEnvironment() == Environment.NORMAL ? 8 : 0.125;
Location start = e.getLocation();
dest = WorldUtil.findSpawnLocation(new Location(w, blockRatio * start.getX(), start.getY(), blockRatio * start.getZ())).add(0.5, 0.0, 0.5);
} else {
// Fall-back to the main world spawn
dest = WorldManager.getSpawnLocation(w);
}
if (dest != null) {
EntityUtil.teleportNextTick(e, dest);
return true;
}
}
}
}
}
// If a portal was found, teleport using it
if (portal != null) {
portal.teleportNextTick(e);
return true;
}
return false;
}
|
diff --git a/motech-omod/src/main/java/org/motech/openmrs/module/web/controller/MotherController.java b/motech-omod/src/main/java/org/motech/openmrs/module/web/controller/MotherController.java
index 98afb1ca..9e5f7452 100755
--- a/motech-omod/src/main/java/org/motech/openmrs/module/web/controller/MotherController.java
+++ b/motech-omod/src/main/java/org/motech/openmrs/module/web/controller/MotherController.java
@@ -1,217 +1,217 @@
package org.motech.openmrs.module.web.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.motech.openmrs.module.ContextService;
import org.motech.openmrs.module.web.model.WebModelConverter;
import org.motech.openmrs.module.web.model.WebPatient;
import org.motech.svc.RegistrarBean;
import org.openmrs.Location;
import org.openmrs.Patient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
@Controller
@RequestMapping("/module/motechmodule/mother")
@SessionAttributes("mother")
public class MotherController {
private static Log log = LogFactory.getLog(MotherController.class);
private WebModelConverter webModelConverter;
@Autowired
@Qualifier("registrarBean")
private RegistrarBean registrarBean;
private ContextService contextService;
@Autowired
public void setContextService(ContextService contextService) {
this.contextService = contextService;
}
public void setRegistrarBean(RegistrarBean registrarBean) {
this.registrarBean = registrarBean;
}
@Autowired
public void setWebModelConverter(WebModelConverter webModelConverter) {
this.webModelConverter = webModelConverter;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
String datePattern = "dd/MM/yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, true, datePattern.length()));
binder
.registerCustomEditor(String.class, new StringTrimmerEditor(
true));
}
@ModelAttribute("regions")
public List<Location> getRegions() {
return contextService.getMotechService().getAllRegions();
}
@ModelAttribute("districts")
public List<Location> getDistricts() {
return contextService.getMotechService().getAllDistricts();
}
@ModelAttribute("communities")
public List<Location> getCommunities() {
return contextService.getMotechService().getAllCommunities();
}
@ModelAttribute("clinics")
public List<Location> getClinics() {
return contextService.getMotechService().getAllClinics();
}
@RequestMapping(method = RequestMethod.GET)
public void viewForm(@RequestParam(required = false) Integer id,
ModelMap model) {
}
@ModelAttribute("mother")
public WebPatient getWebMother(@RequestParam(required = false) Integer id) {
WebPatient result = new WebPatient();
if (id != null) {
Patient patient = contextService.getPatientService().getPatient(id);
if (patient != null) {
webModelConverter.patientToWeb(patient, result);
}
}
return result;
}
@RequestMapping(method = RequestMethod.POST)
public String submitForm(@ModelAttribute("mother") WebPatient mother,
Errors errors, ModelMap model, SessionStatus status) {
log.debug("Register Pregnant Mother");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName",
"motechmodule.firstName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName",
"motechmodule.lastName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthDate",
"motechmodule.birthDate.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthDateEst",
"motechmodule.birthDateEst.required");
if (!Boolean.TRUE.equals(mother.getRegisteredGHS())) {
errors.rejectValue("registeredGHS",
"motechmodule.registeredGHS.required");
} else {
ValidationUtils.rejectIfEmpty(errors, "regNumberGHS",
"motechmodule.regNumberGHS.required");
if (mother.getRegNumberGHS() != null
&& registrarBean.getPatientBySerial(mother
.getRegNumberGHS()) != null) {
errors.rejectValue("regNumberGHS",
"motechmodule.regNumberGHS.nonunique");
}
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "insured",
"motechmodule.insured.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "region",
"motechmodule.region.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "district",
"motechmodule.district.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "community",
"motechmodule.community.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address",
"motechmodule.address.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "clinic",
"motechmodule.clinic.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dueDate",
"motechmodule.dueDate.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dueDateConfirmed",
"motechmodule.dueDateConfirmed.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gravida",
"motechmodule.gravida.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "parity",
"motechmodule.parity.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "hivStatus",
"motechmodule.hivStatus.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"registerPregProgram",
"motechmodule.registerPregProgram.required");
if (Boolean.TRUE.equals(mother.getRegisterPregProgram())) {
if (!Boolean.TRUE.equals(mother.getTermsConsent())) {
errors.rejectValue("termsConsent",
"motechmodule.termsConsent.required");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "primaryPhone",
"motechmodule.primaryPhone.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"primaryPhoneType",
"motechmodule.primaryPhoneType.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "mediaTypeInfo",
"motechmodule.mediaTypeInfo.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"mediaTypeReminder",
"motechmodule.mediaTypeReminder.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "languageVoice",
"motechmodule.languageVoice.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "languageText",
"motechmodule.languageText.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "whoRegistered",
"motechmodule.whoRegistered.required");
}
if (!errors.hasErrors()) {
registrarBean.registerPregnantMother(mother.getFirstName(), mother
.getMiddleName(), mother.getLastName(), mother
.getPrefName(), mother.getBirthDate(), mother
.getBirthDateEst(), mother.getRegisteredGHS(), mother
.getRegNumberGHS(), mother.getInsured(), mother.getNhis(),
mother.getNhisExpDate(), mother.getRegion(), mother
.getDistrict(), mother.getCommunity(), mother
.getAddress(), mother.getClinic(), mother
.getDueDate(), mother.getDueDateConfirmed(), mother
- .getGravida(), mother.getGravida(), mother
+ .getGravida(), mother.getParity(), mother
.getHivStatus(), mother.getRegisterPregProgram(),
mother.getPrimaryPhone(), mother.getPrimaryPhoneType(),
mother.getSecondaryPhone(), mother.getSecondaryPhoneType(),
mother.getMediaTypeInfo(), mother.getMediaTypeReminder(),
mother.getLanguageVoice(), mother.getLanguageText(), mother
.getWhoRegistered(), mother.getReligion(), mother
.getOccupation());
model.addAttribute("successMsg",
"motechmodule.Mother.register.success");
status.setComplete();
return "redirect:/module/motechmodule/viewdata.form";
}
return "/module/motechmodule/mother";
}
}
| true | true | public String submitForm(@ModelAttribute("mother") WebPatient mother,
Errors errors, ModelMap model, SessionStatus status) {
log.debug("Register Pregnant Mother");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName",
"motechmodule.firstName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName",
"motechmodule.lastName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthDate",
"motechmodule.birthDate.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthDateEst",
"motechmodule.birthDateEst.required");
if (!Boolean.TRUE.equals(mother.getRegisteredGHS())) {
errors.rejectValue("registeredGHS",
"motechmodule.registeredGHS.required");
} else {
ValidationUtils.rejectIfEmpty(errors, "regNumberGHS",
"motechmodule.regNumberGHS.required");
if (mother.getRegNumberGHS() != null
&& registrarBean.getPatientBySerial(mother
.getRegNumberGHS()) != null) {
errors.rejectValue("regNumberGHS",
"motechmodule.regNumberGHS.nonunique");
}
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "insured",
"motechmodule.insured.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "region",
"motechmodule.region.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "district",
"motechmodule.district.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "community",
"motechmodule.community.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address",
"motechmodule.address.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "clinic",
"motechmodule.clinic.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dueDate",
"motechmodule.dueDate.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dueDateConfirmed",
"motechmodule.dueDateConfirmed.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gravida",
"motechmodule.gravida.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "parity",
"motechmodule.parity.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "hivStatus",
"motechmodule.hivStatus.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"registerPregProgram",
"motechmodule.registerPregProgram.required");
if (Boolean.TRUE.equals(mother.getRegisterPregProgram())) {
if (!Boolean.TRUE.equals(mother.getTermsConsent())) {
errors.rejectValue("termsConsent",
"motechmodule.termsConsent.required");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "primaryPhone",
"motechmodule.primaryPhone.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"primaryPhoneType",
"motechmodule.primaryPhoneType.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "mediaTypeInfo",
"motechmodule.mediaTypeInfo.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"mediaTypeReminder",
"motechmodule.mediaTypeReminder.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "languageVoice",
"motechmodule.languageVoice.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "languageText",
"motechmodule.languageText.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "whoRegistered",
"motechmodule.whoRegistered.required");
}
if (!errors.hasErrors()) {
registrarBean.registerPregnantMother(mother.getFirstName(), mother
.getMiddleName(), mother.getLastName(), mother
.getPrefName(), mother.getBirthDate(), mother
.getBirthDateEst(), mother.getRegisteredGHS(), mother
.getRegNumberGHS(), mother.getInsured(), mother.getNhis(),
mother.getNhisExpDate(), mother.getRegion(), mother
.getDistrict(), mother.getCommunity(), mother
.getAddress(), mother.getClinic(), mother
.getDueDate(), mother.getDueDateConfirmed(), mother
.getGravida(), mother.getGravida(), mother
.getHivStatus(), mother.getRegisterPregProgram(),
mother.getPrimaryPhone(), mother.getPrimaryPhoneType(),
mother.getSecondaryPhone(), mother.getSecondaryPhoneType(),
mother.getMediaTypeInfo(), mother.getMediaTypeReminder(),
mother.getLanguageVoice(), mother.getLanguageText(), mother
.getWhoRegistered(), mother.getReligion(), mother
.getOccupation());
model.addAttribute("successMsg",
"motechmodule.Mother.register.success");
status.setComplete();
return "redirect:/module/motechmodule/viewdata.form";
}
return "/module/motechmodule/mother";
}
| public String submitForm(@ModelAttribute("mother") WebPatient mother,
Errors errors, ModelMap model, SessionStatus status) {
log.debug("Register Pregnant Mother");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName",
"motechmodule.firstName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName",
"motechmodule.lastName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthDate",
"motechmodule.birthDate.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthDateEst",
"motechmodule.birthDateEst.required");
if (!Boolean.TRUE.equals(mother.getRegisteredGHS())) {
errors.rejectValue("registeredGHS",
"motechmodule.registeredGHS.required");
} else {
ValidationUtils.rejectIfEmpty(errors, "regNumberGHS",
"motechmodule.regNumberGHS.required");
if (mother.getRegNumberGHS() != null
&& registrarBean.getPatientBySerial(mother
.getRegNumberGHS()) != null) {
errors.rejectValue("regNumberGHS",
"motechmodule.regNumberGHS.nonunique");
}
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "insured",
"motechmodule.insured.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "region",
"motechmodule.region.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "district",
"motechmodule.district.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "community",
"motechmodule.community.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address",
"motechmodule.address.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "clinic",
"motechmodule.clinic.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dueDate",
"motechmodule.dueDate.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dueDateConfirmed",
"motechmodule.dueDateConfirmed.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gravida",
"motechmodule.gravida.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "parity",
"motechmodule.parity.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "hivStatus",
"motechmodule.hivStatus.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"registerPregProgram",
"motechmodule.registerPregProgram.required");
if (Boolean.TRUE.equals(mother.getRegisterPregProgram())) {
if (!Boolean.TRUE.equals(mother.getTermsConsent())) {
errors.rejectValue("termsConsent",
"motechmodule.termsConsent.required");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "primaryPhone",
"motechmodule.primaryPhone.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"primaryPhoneType",
"motechmodule.primaryPhoneType.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "mediaTypeInfo",
"motechmodule.mediaTypeInfo.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"mediaTypeReminder",
"motechmodule.mediaTypeReminder.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "languageVoice",
"motechmodule.languageVoice.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "languageText",
"motechmodule.languageText.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "whoRegistered",
"motechmodule.whoRegistered.required");
}
if (!errors.hasErrors()) {
registrarBean.registerPregnantMother(mother.getFirstName(), mother
.getMiddleName(), mother.getLastName(), mother
.getPrefName(), mother.getBirthDate(), mother
.getBirthDateEst(), mother.getRegisteredGHS(), mother
.getRegNumberGHS(), mother.getInsured(), mother.getNhis(),
mother.getNhisExpDate(), mother.getRegion(), mother
.getDistrict(), mother.getCommunity(), mother
.getAddress(), mother.getClinic(), mother
.getDueDate(), mother.getDueDateConfirmed(), mother
.getGravida(), mother.getParity(), mother
.getHivStatus(), mother.getRegisterPregProgram(),
mother.getPrimaryPhone(), mother.getPrimaryPhoneType(),
mother.getSecondaryPhone(), mother.getSecondaryPhoneType(),
mother.getMediaTypeInfo(), mother.getMediaTypeReminder(),
mother.getLanguageVoice(), mother.getLanguageText(), mother
.getWhoRegistered(), mother.getReligion(), mother
.getOccupation());
model.addAttribute("successMsg",
"motechmodule.Mother.register.success");
status.setComplete();
return "redirect:/module/motechmodule/viewdata.form";
}
return "/module/motechmodule/mother";
}
|
diff --git a/src/com/djdch/bukkit/onehundredgenerator/mc100/GenLayer.java b/src/com/djdch/bukkit/onehundredgenerator/mc100/GenLayer.java
index 37ed5ab..8399220 100644
--- a/src/com/djdch/bukkit/onehundredgenerator/mc100/GenLayer.java
+++ b/src/com/djdch/bukkit/onehundredgenerator/mc100/GenLayer.java
@@ -1,117 +1,117 @@
package com.djdch.bukkit.onehundredgenerator.mc100;
public abstract class GenLayer {
private long b;
protected GenLayer a;
private long c;
private long d;
public static GenLayer[] a(long paramLong) {
Object localObject1 = new LayerIsland(1L);
localObject1 = new GenLayerZoomFuzzy(2000L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(1L, (GenLayer) localObject1);
localObject1 = new GenLayerZoom(2001L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(2L, (GenLayer) localObject1);
localObject1 = new GenLayerIcePlains(2L, (GenLayer) localObject1);
localObject1 = new GenLayerZoom(2002L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(3L, (GenLayer) localObject1);
localObject1 = new GenLayerZoom(2003L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(4L, (GenLayer) localObject1);
localObject1 = new GenLayerMushroomIsland(5L, (GenLayer) localObject1);
int i = 4;
Object localObject2 = localObject1;
localObject2 = GenLayerZoom.a(1000L, (GenLayer) localObject2, 0);
localObject2 = new GenLayerRiverInit(100L, (GenLayer) localObject2);
localObject2 = GenLayerZoom.a(1000L, (GenLayer) localObject2, i + 2);
localObject2 = new GenLayerRiver(1L, (GenLayer) localObject2);
localObject2 = new GenLayerSmooth(1000L, (GenLayer) localObject2);
Object localObject3 = localObject1;
localObject3 = GenLayerZoom.a(1000L, (GenLayer) localObject3, 0);
localObject3 = new GenLayerBiome(200L, (GenLayer) localObject3);
localObject3 = GenLayerZoom.a(1000L, (GenLayer) localObject3, 2);
Object localObject4 = new GenLayerTemperature((GenLayer) localObject3);
Object localObject5 = new GenLayerDownfall((GenLayer) localObject3);
for (int j = 0; j < i; j++) {
localObject3 = new GenLayerZoom(1000 + j, (GenLayer) localObject3);
if (j == 0)
localObject3 = new GenLayerIsland(3L, (GenLayer) localObject3);
if (j == 0) {
localObject3 = new GenLayerMushroomShore(1000L, (GenLayer) localObject3);
}
localObject4 = new GenLayerSmoothZoom(1000 + j, (GenLayer) localObject4);
localObject4 = new GenLayerTemperatureMix((GenLayer) localObject4, (GenLayer) localObject3, j);
localObject5 = new GenLayerSmoothZoom(1000 + j, (GenLayer) localObject5);
localObject5 = new GenLayerDownfallMix((GenLayer) localObject5, (GenLayer) localObject3, j);
}
localObject3 = new GenLayerSmooth(1000L, (GenLayer) localObject3);
localObject3 = new GenLayerRiverMix(100L, (GenLayer) localObject3, (GenLayer) localObject2);
Object localObject6 = localObject3;
localObject4 = GenLayerSmoothZoom.a(1000L, (GenLayer) localObject4, 2);
localObject5 = GenLayerSmoothZoom.a(1000L, (GenLayer) localObject5, 2);
GenLayerZoomVoronoi localGenLayerZoomVoronoi = new GenLayerZoomVoronoi(10L, (GenLayer) localObject3);
((GenLayer) localObject3).b(paramLong);
((GenLayer) localObject4).b(paramLong);
((GenLayer) localObject5).b(paramLong);
localGenLayerZoomVoronoi.b(paramLong);
- return (GenLayer) (GenLayer) (GenLayer) (GenLayer) (GenLayer) new GenLayer[] { localObject3, localGenLayerZoomVoronoi, localObject4, localObject5, localObject6 };
+ return (new GenLayer[] { (GenLayer) localObject3, localGenLayerZoomVoronoi, (GenLayer) localObject4, (GenLayer) localObject5, (GenLayer) localObject6 });
}
public GenLayer(long paramLong) {
this.d = paramLong;
this.d *= (this.d * 6364136223846793005L + 1442695040888963407L);
this.d += paramLong;
this.d *= (this.d * 6364136223846793005L + 1442695040888963407L);
this.d += paramLong;
this.d *= (this.d * 6364136223846793005L + 1442695040888963407L);
this.d += paramLong;
}
public void b(long paramLong) {
this.b = paramLong;
if (this.a != null)
this.a.b(paramLong);
this.b *= (this.b * 6364136223846793005L + 1442695040888963407L);
this.b += this.d;
this.b *= (this.b * 6364136223846793005L + 1442695040888963407L);
this.b += this.d;
this.b *= (this.b * 6364136223846793005L + 1442695040888963407L);
this.b += this.d;
}
public void a(long paramLong1, long paramLong2) {
this.c = this.b;
this.c *= (this.c * 6364136223846793005L + 1442695040888963407L);
this.c += paramLong1;
this.c *= (this.c * 6364136223846793005L + 1442695040888963407L);
this.c += paramLong2;
this.c *= (this.c * 6364136223846793005L + 1442695040888963407L);
this.c += paramLong1;
this.c *= (this.c * 6364136223846793005L + 1442695040888963407L);
this.c += paramLong2;
}
protected int a(int paramInt) {
int i = (int) ((this.c >> 24) % paramInt);
if (i < 0)
i += paramInt;
this.c *= (this.c * 6364136223846793005L + 1442695040888963407L);
this.c += this.b;
return i;
}
public abstract int[] a(int paramInt1, int paramInt2, int paramInt3, int paramInt4);
}
| true | true | public static GenLayer[] a(long paramLong) {
Object localObject1 = new LayerIsland(1L);
localObject1 = new GenLayerZoomFuzzy(2000L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(1L, (GenLayer) localObject1);
localObject1 = new GenLayerZoom(2001L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(2L, (GenLayer) localObject1);
localObject1 = new GenLayerIcePlains(2L, (GenLayer) localObject1);
localObject1 = new GenLayerZoom(2002L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(3L, (GenLayer) localObject1);
localObject1 = new GenLayerZoom(2003L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(4L, (GenLayer) localObject1);
localObject1 = new GenLayerMushroomIsland(5L, (GenLayer) localObject1);
int i = 4;
Object localObject2 = localObject1;
localObject2 = GenLayerZoom.a(1000L, (GenLayer) localObject2, 0);
localObject2 = new GenLayerRiverInit(100L, (GenLayer) localObject2);
localObject2 = GenLayerZoom.a(1000L, (GenLayer) localObject2, i + 2);
localObject2 = new GenLayerRiver(1L, (GenLayer) localObject2);
localObject2 = new GenLayerSmooth(1000L, (GenLayer) localObject2);
Object localObject3 = localObject1;
localObject3 = GenLayerZoom.a(1000L, (GenLayer) localObject3, 0);
localObject3 = new GenLayerBiome(200L, (GenLayer) localObject3);
localObject3 = GenLayerZoom.a(1000L, (GenLayer) localObject3, 2);
Object localObject4 = new GenLayerTemperature((GenLayer) localObject3);
Object localObject5 = new GenLayerDownfall((GenLayer) localObject3);
for (int j = 0; j < i; j++) {
localObject3 = new GenLayerZoom(1000 + j, (GenLayer) localObject3);
if (j == 0)
localObject3 = new GenLayerIsland(3L, (GenLayer) localObject3);
if (j == 0) {
localObject3 = new GenLayerMushroomShore(1000L, (GenLayer) localObject3);
}
localObject4 = new GenLayerSmoothZoom(1000 + j, (GenLayer) localObject4);
localObject4 = new GenLayerTemperatureMix((GenLayer) localObject4, (GenLayer) localObject3, j);
localObject5 = new GenLayerSmoothZoom(1000 + j, (GenLayer) localObject5);
localObject5 = new GenLayerDownfallMix((GenLayer) localObject5, (GenLayer) localObject3, j);
}
localObject3 = new GenLayerSmooth(1000L, (GenLayer) localObject3);
localObject3 = new GenLayerRiverMix(100L, (GenLayer) localObject3, (GenLayer) localObject2);
Object localObject6 = localObject3;
localObject4 = GenLayerSmoothZoom.a(1000L, (GenLayer) localObject4, 2);
localObject5 = GenLayerSmoothZoom.a(1000L, (GenLayer) localObject5, 2);
GenLayerZoomVoronoi localGenLayerZoomVoronoi = new GenLayerZoomVoronoi(10L, (GenLayer) localObject3);
((GenLayer) localObject3).b(paramLong);
((GenLayer) localObject4).b(paramLong);
((GenLayer) localObject5).b(paramLong);
localGenLayerZoomVoronoi.b(paramLong);
return (GenLayer) (GenLayer) (GenLayer) (GenLayer) (GenLayer) new GenLayer[] { localObject3, localGenLayerZoomVoronoi, localObject4, localObject5, localObject6 };
}
| public static GenLayer[] a(long paramLong) {
Object localObject1 = new LayerIsland(1L);
localObject1 = new GenLayerZoomFuzzy(2000L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(1L, (GenLayer) localObject1);
localObject1 = new GenLayerZoom(2001L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(2L, (GenLayer) localObject1);
localObject1 = new GenLayerIcePlains(2L, (GenLayer) localObject1);
localObject1 = new GenLayerZoom(2002L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(3L, (GenLayer) localObject1);
localObject1 = new GenLayerZoom(2003L, (GenLayer) localObject1);
localObject1 = new GenLayerIsland(4L, (GenLayer) localObject1);
localObject1 = new GenLayerMushroomIsland(5L, (GenLayer) localObject1);
int i = 4;
Object localObject2 = localObject1;
localObject2 = GenLayerZoom.a(1000L, (GenLayer) localObject2, 0);
localObject2 = new GenLayerRiverInit(100L, (GenLayer) localObject2);
localObject2 = GenLayerZoom.a(1000L, (GenLayer) localObject2, i + 2);
localObject2 = new GenLayerRiver(1L, (GenLayer) localObject2);
localObject2 = new GenLayerSmooth(1000L, (GenLayer) localObject2);
Object localObject3 = localObject1;
localObject3 = GenLayerZoom.a(1000L, (GenLayer) localObject3, 0);
localObject3 = new GenLayerBiome(200L, (GenLayer) localObject3);
localObject3 = GenLayerZoom.a(1000L, (GenLayer) localObject3, 2);
Object localObject4 = new GenLayerTemperature((GenLayer) localObject3);
Object localObject5 = new GenLayerDownfall((GenLayer) localObject3);
for (int j = 0; j < i; j++) {
localObject3 = new GenLayerZoom(1000 + j, (GenLayer) localObject3);
if (j == 0)
localObject3 = new GenLayerIsland(3L, (GenLayer) localObject3);
if (j == 0) {
localObject3 = new GenLayerMushroomShore(1000L, (GenLayer) localObject3);
}
localObject4 = new GenLayerSmoothZoom(1000 + j, (GenLayer) localObject4);
localObject4 = new GenLayerTemperatureMix((GenLayer) localObject4, (GenLayer) localObject3, j);
localObject5 = new GenLayerSmoothZoom(1000 + j, (GenLayer) localObject5);
localObject5 = new GenLayerDownfallMix((GenLayer) localObject5, (GenLayer) localObject3, j);
}
localObject3 = new GenLayerSmooth(1000L, (GenLayer) localObject3);
localObject3 = new GenLayerRiverMix(100L, (GenLayer) localObject3, (GenLayer) localObject2);
Object localObject6 = localObject3;
localObject4 = GenLayerSmoothZoom.a(1000L, (GenLayer) localObject4, 2);
localObject5 = GenLayerSmoothZoom.a(1000L, (GenLayer) localObject5, 2);
GenLayerZoomVoronoi localGenLayerZoomVoronoi = new GenLayerZoomVoronoi(10L, (GenLayer) localObject3);
((GenLayer) localObject3).b(paramLong);
((GenLayer) localObject4).b(paramLong);
((GenLayer) localObject5).b(paramLong);
localGenLayerZoomVoronoi.b(paramLong);
return (new GenLayer[] { (GenLayer) localObject3, localGenLayerZoomVoronoi, (GenLayer) localObject4, (GenLayer) localObject5, (GenLayer) localObject6 });
}
|
diff --git a/app/extensions/ObjectExtensions.java b/app/extensions/ObjectExtensions.java
index a89f174..0fe86b6 100644
--- a/app/extensions/ObjectExtensions.java
+++ b/app/extensions/ObjectExtensions.java
@@ -1,21 +1,21 @@
package extensions;
import org.apache.commons.lang.StringUtils;
import play.templates.JavaExtensions;
/**
* Created by IntelliJ IDEA.
*
* @author neteller
* @created: Nov 26, 2010
*/
public class ObjectExtensions extends JavaExtensions {
public static String toWords(Object object) {
- final String s = object.toString();
+ final String s = object.toString().replaceAll("_", " ");
return StringUtils.capitalize(s.toLowerCase());
}
}
| true | true | public static String toWords(Object object) {
final String s = object.toString();
return StringUtils.capitalize(s.toLowerCase());
}
| public static String toWords(Object object) {
final String s = object.toString().replaceAll("_", " ");
return StringUtils.capitalize(s.toLowerCase());
}
|
diff --git a/mmstudio/src/org/micromanager/conf/PeripheralDevicesPreInitializationPropertiesPage.java b/mmstudio/src/org/micromanager/conf/PeripheralDevicesPreInitializationPropertiesPage.java
index 97285b5e5..3a9fa31c6 100644
--- a/mmstudio/src/org/micromanager/conf/PeripheralDevicesPreInitializationPropertiesPage.java
+++ b/mmstudio/src/org/micromanager/conf/PeripheralDevicesPreInitializationPropertiesPage.java
@@ -1,177 +1,167 @@
///////////////////////////////////////////////////////////////////////////////
//FILE: PeripheralDevicesPreInitializationPropertiesPage.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//-----------------------------------------------------------------------------
//
// AUTHOR: Karl Hoover January 2011
//
//
// COPYRIGHT: University of California, San Francisco, 2006
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// CVS: $Id: PeripheralDevicesPreInitializationPropertiesPage.java 6968 2011-04-13 19:30:09Z karlh $
//
package org.micromanager.conf;
import java.util.prefs.Preferences;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableColumn;
import org.micromanager.utils.GUIUtils;
import mmcorej.MMCoreJ;
import org.micromanager.utils.PropertyItem;
import org.micromanager.utils.PropertyNameCellRenderer;
import org.micromanager.utils.PropertyValueCellEditor;
import org.micromanager.utils.PropertyValueCellRenderer;
import org.micromanager.utils.ReportingUtils;
/**
* Wizard page to set device properties.
*
*/
public class PeripheralDevicesPreInitializationPropertiesPage extends PagePanel {
private static final long serialVersionUID = 1L;
private JTable propTable_;
private JScrollPane scrollPane_;
private static final String HELP_FILE_NAME = "conf_preinit_page.html";
/**
* Create the panel
*/
public PeripheralDevicesPreInitializationPropertiesPage(Preferences prefs) {
super();
title_ = "Edit peripheral device pre-initialization settings";
helpText_ = "The list of device properties which must be defined prior to initialization is shown above. ";
setLayout(null);
prefs_ = prefs;
setHelpFileName(HELP_FILE_NAME);
scrollPane_ = new JScrollPane();
scrollPane_.setBounds(10, 9, 421, 262);
add(scrollPane_);
propTable_ = new JTable();
propTable_.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
propTable_.setAutoCreateColumnsFromModel(false);
scrollPane_.setViewportView(propTable_);
final PeripheralDevicesPreInitializationPropertiesPage thisPage = this;
}
private void rebuildTable() {
PropertyTableModel tm = new PropertyTableModel(this, model_, PropertyTableModel.PREINIT);
propTable_.setModel(tm);
PropertyValueCellEditor propValueEditor = new PropertyValueCellEditor();
PropertyValueCellRenderer propValueRenderer = new PropertyValueCellRenderer();
PropertyNameCellRenderer propNameRenderer = new PropertyNameCellRenderer();
if (propTable_.getColumnCount() == 0) {
TableColumn column;
column = new TableColumn(0, 200, propNameRenderer, null);
propTable_.addColumn(column);
column = new TableColumn(1, 200, propNameRenderer, null);
propTable_.addColumn(column);
column = new TableColumn(2, 200, propValueRenderer, propValueEditor);
propTable_.addColumn(column);
}
tm.fireTableStructureChanged();
tm.fireTableDataChanged();
boolean any = false;
Device devices[] = model_.getPeripheralDevices();
// build list of devices to look for on the serial ports
for (int i = 0; i < devices.length; i++) {
for (int j = 0; j < devices[i].getNumberOfProperties(); j++) {
PropertyItem p = devices[i].getProperty(j);
if (p.name.compareTo(MMCoreJ.getG_Keyword_Port()) == 0) {
any = true;
break;
}
}
if (any) {
break;
}
}
propTable_.repaint();
}
public boolean enterPage(boolean fromNextPage) {
if (fromNextPage) {
return true;
}
rebuildTable();
return true;
}
public boolean exitPage(boolean toNextPage) {
try {
if (toNextPage) {
- // set the properties of only the 'peripheral' devices!!
- Device devices[] = model_.getPeripheralDevices();
+ // set all pre-initialization properties
PropertyTableModel ptm = (PropertyTableModel) propTable_.getModel();
for (int i = 0; i < ptm.getRowCount(); i++) {
Setting s = ptm.getSetting(i);
- boolean found = false;
- for (Device d : devices) {
- if (s.deviceName_.equals(d.getName())) {
- found = true;
- break;
- }
- }
- if (found) {
- core_.setProperty(s.deviceName_, s.propertyName_, s.propertyValue_);
- Device dev = model_.findDevice(s.deviceName_);
- PropertyItem prop = dev.findSetupProperty(s.propertyName_);
- if (prop == null) {
- model_.addSetupProperty(s.deviceName_, new PropertyItem(s.propertyName_, s.propertyValue_, true));
- }
- model_.setDeviceSetupProperty(s.deviceName_, s.propertyName_, s.propertyValue_);
+ core_.setProperty(s.deviceName_, s.propertyName_, s.propertyValue_);
+ Device dev = model_.findDevice(s.deviceName_);
+ PropertyItem prop = dev.findSetupProperty(s.propertyName_);
+ if (prop == null) {
+ model_.addSetupProperty(s.deviceName_, new PropertyItem(s.propertyName_, s.propertyValue_, true));
}
+ model_.setDeviceSetupProperty(s.deviceName_, s.propertyName_, s.propertyValue_);
}
try {
core_.initializeAllDevices();
// create the post-initialization properties
model_.loadDeviceDataFromHardware(core_);
model_.loadStateLabelsFromHardware(core_);
} catch (Exception ex) {
- ReportingUtils.logError(ex);
+ ReportingUtils.showError(ex);
}
} else {
GUIUtils.preventDisplayAdapterChangeExceptions();
}
} catch (Exception e) {
handleException(e);
if (toNextPage) {
return false;
}
}
return true;
}
public void refresh() {
rebuildTable();
}
public void loadSettings() {
}
public void saveSettings() {
}
public JTable GetPropertyTable() {
return propTable_;
}
}
| false | true | public boolean exitPage(boolean toNextPage) {
try {
if (toNextPage) {
// set the properties of only the 'peripheral' devices!!
Device devices[] = model_.getPeripheralDevices();
PropertyTableModel ptm = (PropertyTableModel) propTable_.getModel();
for (int i = 0; i < ptm.getRowCount(); i++) {
Setting s = ptm.getSetting(i);
boolean found = false;
for (Device d : devices) {
if (s.deviceName_.equals(d.getName())) {
found = true;
break;
}
}
if (found) {
core_.setProperty(s.deviceName_, s.propertyName_, s.propertyValue_);
Device dev = model_.findDevice(s.deviceName_);
PropertyItem prop = dev.findSetupProperty(s.propertyName_);
if (prop == null) {
model_.addSetupProperty(s.deviceName_, new PropertyItem(s.propertyName_, s.propertyValue_, true));
}
model_.setDeviceSetupProperty(s.deviceName_, s.propertyName_, s.propertyValue_);
}
}
try {
core_.initializeAllDevices();
// create the post-initialization properties
model_.loadDeviceDataFromHardware(core_);
model_.loadStateLabelsFromHardware(core_);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
} else {
GUIUtils.preventDisplayAdapterChangeExceptions();
}
} catch (Exception e) {
handleException(e);
if (toNextPage) {
return false;
}
}
return true;
}
| public boolean exitPage(boolean toNextPage) {
try {
if (toNextPage) {
// set all pre-initialization properties
PropertyTableModel ptm = (PropertyTableModel) propTable_.getModel();
for (int i = 0; i < ptm.getRowCount(); i++) {
Setting s = ptm.getSetting(i);
core_.setProperty(s.deviceName_, s.propertyName_, s.propertyValue_);
Device dev = model_.findDevice(s.deviceName_);
PropertyItem prop = dev.findSetupProperty(s.propertyName_);
if (prop == null) {
model_.addSetupProperty(s.deviceName_, new PropertyItem(s.propertyName_, s.propertyValue_, true));
}
model_.setDeviceSetupProperty(s.deviceName_, s.propertyName_, s.propertyValue_);
}
try {
core_.initializeAllDevices();
// create the post-initialization properties
model_.loadDeviceDataFromHardware(core_);
model_.loadStateLabelsFromHardware(core_);
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
} else {
GUIUtils.preventDisplayAdapterChangeExceptions();
}
} catch (Exception e) {
handleException(e);
if (toNextPage) {
return false;
}
}
return true;
}
|
diff --git a/src/main/org/deidentifier/arx/algorithm/FLASHAlgorithm.java b/src/main/org/deidentifier/arx/algorithm/FLASHAlgorithm.java
index 043a7b729..d9dbec9fa 100644
--- a/src/main/org/deidentifier/arx/algorithm/FLASHAlgorithm.java
+++ b/src/main/org/deidentifier/arx/algorithm/FLASHAlgorithm.java
@@ -1,402 +1,403 @@
/*
* ARX: Efficient, Stable and Optimal Data Anonymization
* Copyright (C) 2012 - 2013 Florian Kohlmayer, Fabian Prasser
*
* 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.deidentifier.arx.algorithm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Stack;
import org.deidentifier.arx.criteria.KAnonymity;
import org.deidentifier.arx.framework.check.INodeChecker;
import org.deidentifier.arx.framework.check.history.History;
import org.deidentifier.arx.framework.check.history.History.PruningStrategy;
import org.deidentifier.arx.framework.lattice.Lattice;
import org.deidentifier.arx.framework.lattice.Node;
/**
* This class provides a reference implementation of the ARX algorithm.
*
* @author Prasser, Kohlmayer
*/
public class FLASHAlgorithm extends AbstractAlgorithm {
/** Potential traverse types */
private static enum TraverseType {
FIRST_PHASE_ONLY,
FIRST_AND_SECOND_PHASE,
SECOND_PHASE_ONLY
}
/** The stack. */
private final Stack<Node> stack;
/** The heap. */
private final PriorityQueue<Node> pqueue;
/** The current path. */
private final ArrayList<Node> path;
/** Are the pointers for a node with id 'index' already sorted?. */
private final boolean[] sorted;
/** The strategy. */
private final FLASHStrategy strategy;
/** Traverse type of 2PF */
private TraverseType traverseType;
/** The history*/
private History history;
/**
* Creates a new instance of the ARX algorithm.
*
* @param lattice
* The lattice
* @param history
* The history
* @param checker
* The checker
* @param metric
* The metric
*/
public FLASHAlgorithm(final Lattice lattice,
final INodeChecker checker,
final FLASHStrategy metric) {
super(lattice, checker);
strategy = metric;
pqueue = new PriorityQueue<Node>(11, strategy);
sorted = new boolean[lattice.getSize()];
path = new ArrayList<Node>();
stack = new Stack<Node>();
this.history = checker.getHistory();
// NOTE: If we assume practical monotonicity then we assume
// monotonicity for both criterion AND metric!
// NOTE: We assume monotonicity for criterion with 0% suppression
if ((checker.getConfiguration().getAbsoluteMaxOutliers() == 0) ||
(checker.getConfiguration().isCriterionMonotonic() && checker.getMetric()
.isMonotonic()) ||
(checker.getConfiguration().isPracticalMonotonicity())) {
traverseType = TraverseType.FIRST_PHASE_ONLY;
history.setPruningStrategy(PruningStrategy.ANONYMOUS);
} else {
if (checker.getConfiguration().getMinimalGroupSize() != Integer.MAX_VALUE) {
traverseType = TraverseType.FIRST_AND_SECOND_PHASE;
history.setPruningStrategy(PruningStrategy.K_ANONYMOUS);
} else {
traverseType = TraverseType.SECOND_PHASE_ONLY;
history.setPruningStrategy(PruningStrategy.CHECKED);
}
}
}
/**
* Check a node during the first phase
*
* @param node
*/
protected void checkNode1(final Node node) {
checker.check(node);
// NOTE: SECOND_PHASE_ONLY not needed, as in this case
// checkNode1 would never been called
switch (traverseType) {
case FIRST_PHASE_ONLY:
lattice.tagAnonymous(node, node.isAnonymous());
break;
case FIRST_AND_SECOND_PHASE:
lattice.tagKAnonymous(node, node.isKAnonymous());
break;
default:
throw new RuntimeException("Not implemented!");
}
}
/**
* Check a node during the second phase
*
* @param node
*/
protected void checkNode2(final Node node) {
if (!node.isChecked()) {
// TODO: Rethink var1 & var2
final boolean var1 = !checker.getMetric().isMonotonic() &&
checker.getConfiguration()
.isCriterionMonotonic();
final boolean var2 = !checker.getMetric().isMonotonic() &&
!checker.getConfiguration()
.isCriterionMonotonic() &&
checker.getConfiguration()
.isPracticalMonotonicity();
// NOTE: Might return non-anonymous result as optimum, when
// 1. the criterion is not monotonic, and
// 2. practical monotonicity is assumed, and
// 3. the metric is non-monotonic BUT independent.
// -> Such a metric does currently not exist
if (checker.getMetric().isIndependent() && (var1 || var2)) {
checker.getMetric().evaluate(node, null);
} else {
checker.check(node);
}
}
// In case metric is monotone it can be tagged if the node is anonymous
if (checker.getMetric().isMonotonic() && node.isAnonymous()) {
lattice.tagAnonymous(node, node.isAnonymous());
} else {
node.setTagged();
lattice.untaggedCount[node.getLevel()]--;
}
}
/**
* Checks a path binary.
*
* @param path
* The path
*/
private final Node checkPathBinary(final List<Node> path) {
int low = 0;
int high = path.size() - 1;
Node lastAnonymousNode = null;
while (low <= high) {
final int mid = (low + high) >>> 1;
final Node node = path.get(mid);
if (!node.isTagged()) {
checkNode1(node);
if (!isNodeAnonymous(node)) { // put only non-anonymous nodes in
// pqueue, as potetnially a
// snaphsot is avaliable
for (final Node up : node.getSuccessors()) {
if (!up.isTagged()) { // only unknown nodes are
// nesessary
pqueue.add(up);
}
}
}
}
if (isNodeAnonymous(node)) {
lastAnonymousNode = node;
high = mid - 1;
} else {
low = mid + 1;
}
}
return lastAnonymousNode;
}
/**
* Checks a path sequentially.
*
* @param path
* The path
*/
private final void checkPathExhaustive(final List<Node> path) {
for (final Node node : path) {
if (!node.isTagged()) {
checkNode2(node);
// Put all untagged nodes on the stack
for (final Node up : node.getSuccessors()) {
if (!up.isTagged()) {
stack.push(up);
}
}
}
}
}
/**
* Greedy find path.
*
* @param current
* The current
* @return the list
*/
private final List<Node> findPath(Node current) {
path.clear();
path.add(current);
boolean found = true;
while (found) {
found = false;
this.sort(current);
for (final Node candidate : current.getSuccessors()) {
if (!candidate.isTagged()) {
current = candidate;
path.add(candidate);
found = true;
break;
}
}
}
return path;
}
/**
* Is the node anonymous according to the first run of the algorithm
*
* @param node
* @param traverseType
* @return
*/
private boolean isNodeAnonymous(final Node node) {
// SECOND_PHASE_ONLY not needed, as isNodeAnonymous is only used during the first phase
switch (traverseType) {
case FIRST_PHASE_ONLY:
return node.isAnonymous();
case FIRST_AND_SECOND_PHASE:
return node.isKAnonymous();
default:
throw new RuntimeException("Not implemented!");
}
}
/**
* Sorts a level.
*
* @param level
* The level
* @return the node[]
*/
private final Node[] sort(final int level) {
final Node[] result = new Node[lattice.getUntaggedCount(level)];
if (result.length == 0) { return result; }
int index = 0;
final Node[] nlevel = lattice.getLevels()[level];
for (final Node n : nlevel) {
if (!n.isTagged()) {
result[index++] = n;
}
}
this.sort(result);
return result;
}
/**
* Sorts upwards pointers of a node.
*
* @param current
* The current
*/
private final void sort(final Node current) {
if (!sorted[current.id]) {
this.sort(current.getSuccessors());
sorted[current.id] = true;
}
}
/**
* Sorts a node array.
*
* @param array
* The array
*/
protected final void sort(final Node[] array) {
Arrays.sort(array, strategy);
}
/*
* (non-Javadoc)
*
* @see org.deidentifier.ARX.algorithm.AbstractAlgorithm#traverse()
*/
@Override
public void traverse() {
pqueue.clear();
stack.clear();
// check first node
for (final Node[] level : lattice.getLevels()) {
if (level.length != 0) {
if (level.length == 1) {
checker.check(level[0]);
break;
} else {
throw new RuntimeException("Multiple bottom nodes!");
}
}
}
// For each node
final int length = lattice.getLevels().length;
for (int i = 0; i < length; i++) {
Node[] level;
level = this.sort(i);
for (final Node node : level) {
if (!node.isTagged()) {
pqueue.add(node);
while (!pqueue.isEmpty()) {
Node head = pqueue.poll();
// if anonymity is unknown
if (!head.isTagged()) {
// If first phase is needed
if (traverseType == TraverseType.FIRST_PHASE_ONLY ||
traverseType == TraverseType.FIRST_AND_SECOND_PHASE) {
findPath(head);
head = checkPathBinary(path);
}
// if second phase needed, process path
if (head != null &&
(traverseType == TraverseType.FIRST_AND_SECOND_PHASE || traverseType == TraverseType.SECOND_PHASE_ONLY)) {
// Change strategy
final PruningStrategy pruning = history.getPruningStrategy();
history.setPruningStrategy(PruningStrategy.CHECKED);
- // Untag all nodes above first anonymous node if they have already been tagged by first phase;
- // They will all be tagged again by StackFlash
+ // Untag all nodes above first anonymous node if they have
+ // already been tagged in first phase.
+ // They will all be tagged again in the second phase
if (traverseType == TraverseType.FIRST_AND_SECOND_PHASE) {
lattice.doUnTagUpwards(head);
}
stack.push(head);
while (!stack.isEmpty()) {
final Node start = stack.pop();
if (!start.isTagged()) {
findPath(start);
checkPathExhaustive(path);
}
}
// Switch back to previous strategy
history.setPruningStrategy(pruning);
}
}
}
}
}
}
}
}
| true | true | public void traverse() {
pqueue.clear();
stack.clear();
// check first node
for (final Node[] level : lattice.getLevels()) {
if (level.length != 0) {
if (level.length == 1) {
checker.check(level[0]);
break;
} else {
throw new RuntimeException("Multiple bottom nodes!");
}
}
}
// For each node
final int length = lattice.getLevels().length;
for (int i = 0; i < length; i++) {
Node[] level;
level = this.sort(i);
for (final Node node : level) {
if (!node.isTagged()) {
pqueue.add(node);
while (!pqueue.isEmpty()) {
Node head = pqueue.poll();
// if anonymity is unknown
if (!head.isTagged()) {
// If first phase is needed
if (traverseType == TraverseType.FIRST_PHASE_ONLY ||
traverseType == TraverseType.FIRST_AND_SECOND_PHASE) {
findPath(head);
head = checkPathBinary(path);
}
// if second phase needed, process path
if (head != null &&
(traverseType == TraverseType.FIRST_AND_SECOND_PHASE || traverseType == TraverseType.SECOND_PHASE_ONLY)) {
// Change strategy
final PruningStrategy pruning = history.getPruningStrategy();
history.setPruningStrategy(PruningStrategy.CHECKED);
// Untag all nodes above first anonymous node if they have already been tagged by first phase;
// They will all be tagged again by StackFlash
if (traverseType == TraverseType.FIRST_AND_SECOND_PHASE) {
lattice.doUnTagUpwards(head);
}
stack.push(head);
while (!stack.isEmpty()) {
final Node start = stack.pop();
if (!start.isTagged()) {
findPath(start);
checkPathExhaustive(path);
}
}
// Switch back to previous strategy
history.setPruningStrategy(pruning);
}
}
}
}
}
}
}
| public void traverse() {
pqueue.clear();
stack.clear();
// check first node
for (final Node[] level : lattice.getLevels()) {
if (level.length != 0) {
if (level.length == 1) {
checker.check(level[0]);
break;
} else {
throw new RuntimeException("Multiple bottom nodes!");
}
}
}
// For each node
final int length = lattice.getLevels().length;
for (int i = 0; i < length; i++) {
Node[] level;
level = this.sort(i);
for (final Node node : level) {
if (!node.isTagged()) {
pqueue.add(node);
while (!pqueue.isEmpty()) {
Node head = pqueue.poll();
// if anonymity is unknown
if (!head.isTagged()) {
// If first phase is needed
if (traverseType == TraverseType.FIRST_PHASE_ONLY ||
traverseType == TraverseType.FIRST_AND_SECOND_PHASE) {
findPath(head);
head = checkPathBinary(path);
}
// if second phase needed, process path
if (head != null &&
(traverseType == TraverseType.FIRST_AND_SECOND_PHASE || traverseType == TraverseType.SECOND_PHASE_ONLY)) {
// Change strategy
final PruningStrategy pruning = history.getPruningStrategy();
history.setPruningStrategy(PruningStrategy.CHECKED);
// Untag all nodes above first anonymous node if they have
// already been tagged in first phase.
// They will all be tagged again in the second phase
if (traverseType == TraverseType.FIRST_AND_SECOND_PHASE) {
lattice.doUnTagUpwards(head);
}
stack.push(head);
while (!stack.isEmpty()) {
final Node start = stack.pop();
if (!start.isTagged()) {
findPath(start);
checkPathExhaustive(path);
}
}
// Switch back to previous strategy
history.setPruningStrategy(pruning);
}
}
}
}
}
}
}
|
diff --git a/logging/src/com/dmdirc/addons/logging/LoggingPlugin.java b/logging/src/com/dmdirc/addons/logging/LoggingPlugin.java
index f201f3b8..bc2849ac 100644
--- a/logging/src/com/dmdirc/addons/logging/LoggingPlugin.java
+++ b/logging/src/com/dmdirc/addons/logging/LoggingPlugin.java
@@ -1,60 +1,60 @@
/*
* Copyright (c) 2006-2015 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.logging;
import com.dmdirc.plugins.PluginInfo;
import com.dmdirc.plugins.implementations.BaseCommandPlugin;
import dagger.ObjectGraph;
/**
* Adds logging facility to client.
*/
public class LoggingPlugin extends BaseCommandPlugin {
/** The manager in use. */
private LoggingManager manager;
@Override
public void load(final PluginInfo pluginInfo, final ObjectGraph graph) {
super.load(pluginInfo, graph);
- setObjectGraph(graph.plus(new LoggingModule(pluginInfo.getDomain())));
+ setObjectGraph(graph.plus(new LoggingModule(pluginInfo)));
manager = getObjectGraph().get(LoggingManager.class);
registerCommand(LoggingCommand.class, LoggingCommand.INFO);
}
@Override
public void onLoad() {
super.onLoad();
manager.load();
}
@Override
public void onUnload() {
super.onUnload();
manager.unload();
}
}
| true | true | public void load(final PluginInfo pluginInfo, final ObjectGraph graph) {
super.load(pluginInfo, graph);
setObjectGraph(graph.plus(new LoggingModule(pluginInfo.getDomain())));
manager = getObjectGraph().get(LoggingManager.class);
registerCommand(LoggingCommand.class, LoggingCommand.INFO);
}
| public void load(final PluginInfo pluginInfo, final ObjectGraph graph) {
super.load(pluginInfo, graph);
setObjectGraph(graph.plus(new LoggingModule(pluginInfo)));
manager = getObjectGraph().get(LoggingManager.class);
registerCommand(LoggingCommand.class, LoggingCommand.INFO);
}
|
diff --git a/logwatcher-logback-appender/src/main/java/com/farpost/logwatcher/logback/LogWatcherAppender.java b/logwatcher-logback-appender/src/main/java/com/farpost/logwatcher/logback/LogWatcherAppender.java
index d9bc74e..d055e84 100644
--- a/logwatcher-logback-appender/src/main/java/com/farpost/logwatcher/logback/LogWatcherAppender.java
+++ b/logwatcher-logback-appender/src/main/java/com/farpost/logwatcher/logback/LogWatcherAppender.java
@@ -1,135 +1,135 @@
package com.farpost.logwatcher.logback;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.farpost.logwatcher.Cause;
import com.farpost.logwatcher.LogEntry;
import com.farpost.logwatcher.LogEntryImpl;
import com.farpost.logwatcher.Severity;
import com.farpost.logwatcher.marshalling.Jaxb2Marshaller;
import com.farpost.logwatcher.marshalling.Marshaller;
import com.farpost.timepoint.DateTime;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.*;
import java.util.HashMap;
import static java.lang.Integer.parseInt;
public class LogWatcherAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
private static final int DEFAULT_PORT = 6578;
private InetAddress address;
private int port;
private String applicationId;
private DatagramSocket socket;
private final Marshaller marshaller;
private final Object socketLock = new Object();
public LogWatcherAppender() {
marshaller = new Jaxb2Marshaller();
}
@Override
protected void append(ILoggingEvent event) {
try {
DateTime time = new DateTime(event.getTimeStamp());
Severity severity = severity(event.getLevel());
ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy();
Cause cause = throwableProxy != null
? constructCause(throwableProxy.getThrowable())
: null;
- LogEntry entry = new LogEntryImpl(time, event.getLoggerName(), event.getFormattedMessage(), severity, null, applicationId,
+ LogEntry entry = new LogEntryImpl(time, event.getLoggerName(), event.getFormattedMessage(), severity, "", applicationId,
new HashMap<String, String>(), cause);
byte[] data = marshaller.marshall(entry);
DatagramPacket packet = new DatagramPacket(data, data.length);
synchronized (socketLock) {
if (socket == null) {
return;
}
socket.send(packet);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Cause constructCause(Throwable t) {
StringWriter buffer = new StringWriter();
t.printStackTrace(new PrintWriter(buffer));
Cause cause = t.getCause() == null
? null
: constructCause(t.getCause());
return new Cause(t.getClass().getSimpleName(), t.getMessage(), buffer.toString(), cause);
}
private Severity severity(Level level) {
switch (level.levelInt) {
case Level.ERROR_INT:
return Severity.error;
case Level.DEBUG_INT:
return Severity.debug;
case Level.INFO_INT:
return Severity.info;
case Level.WARN_INT:
return Severity.warning;
case Level.TRACE_INT:
return Severity.trace;
default:
return Severity.error;
}
}
@Override
public void start() {
synchronized (socketLock) {
if (!isStarted()) {
try {
socket = new DatagramSocket();
socket.connect(address, port);
} catch (SocketException e) {
throw new RuntimeException(e);
}
super.start();
}
}
}
@Override
public void stop() {
synchronized (socketLock) {
if (isStarted()) {
socket.close();
socket = null;
super.stop();
}
}
}
public void setAddress(String address) {
try {
String parts[] = address.split(":");
this.address = InetAddress.getByName(parts[0]);
this.port = parts.length > 1
? parseInt(parts[1])
: DEFAULT_PORT;
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public void setApplicationId(String applicationId) {
if (applicationId == null || applicationId.isEmpty()) {
throw new IllegalArgumentException("Empty application id is given");
}
this.applicationId = applicationId;
}
}
| true | true | protected void append(ILoggingEvent event) {
try {
DateTime time = new DateTime(event.getTimeStamp());
Severity severity = severity(event.getLevel());
ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy();
Cause cause = throwableProxy != null
? constructCause(throwableProxy.getThrowable())
: null;
LogEntry entry = new LogEntryImpl(time, event.getLoggerName(), event.getFormattedMessage(), severity, null, applicationId,
new HashMap<String, String>(), cause);
byte[] data = marshaller.marshall(entry);
DatagramPacket packet = new DatagramPacket(data, data.length);
synchronized (socketLock) {
if (socket == null) {
return;
}
socket.send(packet);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
| protected void append(ILoggingEvent event) {
try {
DateTime time = new DateTime(event.getTimeStamp());
Severity severity = severity(event.getLevel());
ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy();
Cause cause = throwableProxy != null
? constructCause(throwableProxy.getThrowable())
: null;
LogEntry entry = new LogEntryImpl(time, event.getLoggerName(), event.getFormattedMessage(), severity, "", applicationId,
new HashMap<String, String>(), cause);
byte[] data = marshaller.marshall(entry);
DatagramPacket packet = new DatagramPacket(data, data.length);
synchronized (socketLock) {
if (socket == null) {
return;
}
socket.send(packet);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/FocusManager.java b/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/FocusManager.java
index 109f23c2f..a8ef9117e 100644
--- a/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/FocusManager.java
+++ b/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/ui/ridgets/swt/FocusManager.java
@@ -1,248 +1,248 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 compeople AG 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:
* compeople AG - initial API and implementation
*******************************************************************************/
package org.eclipse.riena.ui.ridgets.swt;
import org.eclipse.core.runtime.Assert;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
import org.eclipse.riena.ui.ridgets.IMarkableRidget;
import org.eclipse.riena.ui.swt.ChoiceComposite;
import org.eclipse.riena.ui.swt.CompletionCombo;
import org.eclipse.riena.ui.swt.UIConstants;
import org.eclipse.riena.ui.swt.utils.SWTBindingPropertyLocator;
import org.eclipse.riena.ui.swt.utils.SwtUtilities;
/**
* Focus listener that also prevents the widget corresponding to this ridget
* from getting the UI focus when the ridget is not focusable or output only.
* <p>
* The algorithm is as follows:
* <ul>
* <li>if the widget is non-focusable, select the next focusable widget</li>
* <li>if the widget is output only, select the next focusable widget</li>
* <li>if the widget is output only and was clicked, accept focus</li>
* <li>in any other case, accept focus</li>
* </ul>
* Implementation note: SWT will invoke the focusGained, focusLost methods
* before the mouseDown method.
*
* @see AbstractSWTRidget#setFocusable(boolean).
*
* @since 3.0
*/
public final class FocusManager extends MouseAdapter implements FocusListener {
private final AbstractSWTRidget ridget;
private boolean clickToFocus;
/**
* Create a new instance.
*
* @param ridget
* a ridget instance; never null.
*/
FocusManager(final AbstractSWTRidget ridget) {
Assert.isNotNull(ridget);
this.ridget = ridget;
}
/**
* Add the required listeners for operation of the focus manager to the
* given control.
*
* @param control
* a control instance; never null
*/
public void addListeners(final Control control) {
control.addFocusListener(this);
control.addMouseListener(this);
}
public void focusGained(final FocusEvent e) {
if (isFocusable()) {
// trace("## focus gained: %s %d", e.widget, e.widget.hashCode());
ridget.fireFocusGained();
} else {
Control target = findFocusTarget((Control) e.widget);
if (target != null) {
// trace("## %s %d -> %s %d", e.widget, e.widget.hashCode(), target, target.hashCode());
target.setFocus();
} else {
// no suitable control found, start searching from the top of the view
final Composite topControl = findTopContentComposite((Control) e.widget);
target = findFocusTarget(null, topControl);
if (target != null) {
// trace("## %s %d -> %s %d (from top)", e.widget, e.widget.hashCode(), target, target.hashCode());
target.setFocus();
}
}
if (target == null) {
// trace("!! %s %d -> NO TARGET", e.widget, e.widget.hashCode());
}
}
}
/**
* Returns: (a) the topmost Composite of the current View in the workarea,
* or as a fallback: (b) the topmost Shell.
*
* @return a Composite instance
*/
private Composite findTopContentComposite(final Control startControl) {
Composite result = null;
Composite start = (startControl instanceof Composite) ? (Composite) startControl : startControl.getParent();
while (start != null && result == null) {
if (start.getData(UIConstants.DATA_KEY_CONTENT_COMPOSITE) != null) {
result = start;
}
start = start.getParent();
}
if (result == null) {
result = startControl.getShell();
}
return result;
}
public boolean isClickToFocus() {
return clickToFocus;
}
public void focusLost(final FocusEvent e) {
if (isFocusable()) {
clickToFocus = false;
ridget.fireFocusLost();
}
}
@Override
public void mouseDown(final MouseEvent e) {
if (ridget.isFocusable() && ridget.isOutputOnly()) {
// trace("## mouse DOWN: %s %d", e.widget, e.widget.hashCode());
clickToFocus = true;
((Control) e.widget).setFocus();
}
}
/**
* Remove the required listeners for operation of the focus manager from the
* given control.
*
* @param control
* a control instance; never null
*/
public void removeListeners(final Control control) {
if (!control.isDisposed()) {
control.removeFocusListener(this);
control.removeMouseListener(this);
}
}
// helping methods
//////////////////
/**
* Tests whether the given control can get the focus or cannot.
*
* @param control
* UI control
* @return {@code true} if control can get the focus; otherwise
* {@code false}.
*/
private boolean canGetFocus(final Control control) {
// skip disabled or hidden
if (!control.isEnabled() || !control.isVisible()) {
return false;
}
// skip read-only
if (SwtUtilities.hasStyle(control, SWT.READ_ONLY)) {
return false;
}
if (control instanceof Text && !((Text) control).getEditable()) {
return false;
}
if (control instanceof ChoiceComposite && !((ChoiceComposite) control).getEditable()) {
return false;
}
if (control instanceof CompletionCombo && !((CompletionCombo) control).getEditable()) {
return false;
}
// skip IMarkableRidgets that are not focusable or output only
final String bindingId = SWTBindingPropertyLocator.getInstance().locateBindingProperty(control);
if (bindingId != null) {
final Object controlsRidget = ridget.getController().getRidget(bindingId);
if (controlsRidget instanceof IMarkableRidget) {
final IMarkableRidget markableRidget = (IMarkableRidget) controlsRidget;
return markableRidget.isFocusable() && !markableRidget.isOutputOnly();
}
// skip IRidgets that are not focusable
- if (controlsRidget instanceof AbstractSWTWidgetRidget) {
+ if (controlsRidget instanceof AbstractSWTRidget) {
return isFocusable((AbstractSWTRidget) controlsRidget);
}
}
// skip Composites that have no children that can get focus
if (control instanceof Composite) {
return findFocusTarget(null, (Composite) control) != null;
}
return true;
}
private Control findFocusTarget(final Control startControl) {
Control result = null;
Control start = startControl;
while (start.getParent() != null && result == null) {
final Composite parent = start.getParent();
result = findFocusTarget(start, parent);
start = parent;
}
return result;
}
private Control findFocusTarget(final Control start, final Composite parent) {
Control result = null;
final Control[] siblings = parent.getTabList();
int myIndex = -1;
// find index for control
for (int i = 0; myIndex == -1 && i < siblings.length; i++) {
if (siblings[i] == start) {
myIndex = i;
}
}
// find next possible control
for (int i = myIndex + 1; result == null && i < siblings.length; i++) {
final Control candidate = siblings[i];
if (canGetFocus(candidate)) {
result = candidate;
}
}
return result;
}
private boolean isFocusable() {
return isFocusable(ridget);
}
private boolean isFocusable(final AbstractSWTRidget ridget) {
return (ridget.isFocusable() && !ridget.isOutputOnly()) || ridget.getFocusManager().isClickToFocus();
}
@SuppressWarnings("unused")
private void trace(final String format, final Object... args) {
System.out.println(String.format(format, args));
}
}
| true | true | private boolean canGetFocus(final Control control) {
// skip disabled or hidden
if (!control.isEnabled() || !control.isVisible()) {
return false;
}
// skip read-only
if (SwtUtilities.hasStyle(control, SWT.READ_ONLY)) {
return false;
}
if (control instanceof Text && !((Text) control).getEditable()) {
return false;
}
if (control instanceof ChoiceComposite && !((ChoiceComposite) control).getEditable()) {
return false;
}
if (control instanceof CompletionCombo && !((CompletionCombo) control).getEditable()) {
return false;
}
// skip IMarkableRidgets that are not focusable or output only
final String bindingId = SWTBindingPropertyLocator.getInstance().locateBindingProperty(control);
if (bindingId != null) {
final Object controlsRidget = ridget.getController().getRidget(bindingId);
if (controlsRidget instanceof IMarkableRidget) {
final IMarkableRidget markableRidget = (IMarkableRidget) controlsRidget;
return markableRidget.isFocusable() && !markableRidget.isOutputOnly();
}
// skip IRidgets that are not focusable
if (controlsRidget instanceof AbstractSWTWidgetRidget) {
return isFocusable((AbstractSWTRidget) controlsRidget);
}
}
// skip Composites that have no children that can get focus
if (control instanceof Composite) {
return findFocusTarget(null, (Composite) control) != null;
}
return true;
}
| private boolean canGetFocus(final Control control) {
// skip disabled or hidden
if (!control.isEnabled() || !control.isVisible()) {
return false;
}
// skip read-only
if (SwtUtilities.hasStyle(control, SWT.READ_ONLY)) {
return false;
}
if (control instanceof Text && !((Text) control).getEditable()) {
return false;
}
if (control instanceof ChoiceComposite && !((ChoiceComposite) control).getEditable()) {
return false;
}
if (control instanceof CompletionCombo && !((CompletionCombo) control).getEditable()) {
return false;
}
// skip IMarkableRidgets that are not focusable or output only
final String bindingId = SWTBindingPropertyLocator.getInstance().locateBindingProperty(control);
if (bindingId != null) {
final Object controlsRidget = ridget.getController().getRidget(bindingId);
if (controlsRidget instanceof IMarkableRidget) {
final IMarkableRidget markableRidget = (IMarkableRidget) controlsRidget;
return markableRidget.isFocusable() && !markableRidget.isOutputOnly();
}
// skip IRidgets that are not focusable
if (controlsRidget instanceof AbstractSWTRidget) {
return isFocusable((AbstractSWTRidget) controlsRidget);
}
}
// skip Composites that have no children that can get focus
if (control instanceof Composite) {
return findFocusTarget(null, (Composite) control) != null;
}
return true;
}
|
diff --git a/CubicTestPlugin/src/main/java/org/cubictest/model/PageElement.java b/CubicTestPlugin/src/main/java/org/cubictest/model/PageElement.java
index 8fd8314f..dae8a69d 100644
--- a/CubicTestPlugin/src/main/java/org/cubictest/model/PageElement.java
+++ b/CubicTestPlugin/src/main/java/org/cubictest/model/PageElement.java
@@ -1,211 +1,211 @@
/*
* Created on Apr 20, 2005
*
* This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE
* Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html
*/
package org.cubictest.model;
import static org.cubictest.model.IdentifierType.LABEL;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
/**
* Base class for elements on a page.
*
* @author skyttere
* @author chr_schwarz
*
*/
public abstract class PageElement extends PropertyAwareObject
implements Cloneable, IActionElement, IDescription {
public static final String DIRECT_EDIT_IDENTIFIER = "directEditIdentifier";
private String description = "";
private List<Identifier> identifiers;
private Identifier directEditIdentifier;
private boolean not;
public String toString() {
return getType() + ": " + getDescription() + " = " + getText();
}
/**
* Get the user interaction types that is possible on this page elemenent.
*/
public List<ActionType> getActionTypes() {
List<ActionType> actions = new ArrayList<ActionType>();
actions.add(ActionType.CLICK);
actions.add(ActionType.MOUSE_OVER);
actions.add(ActionType.MOUSE_OUT);
actions.add(ActionType.DBLCLICK);
return actions;
}
@Override
public void resetStatus() {
setStatus(TestPartStatus.UNKNOWN);
}
@Override
public PageElement clone() throws CloneNotSupportedException {
PageElement clone = (PageElement) super.clone();
clone.setDescription(description);
List<Identifier> clonedIdentifiers = new ArrayList<Identifier>();
for(Identifier id : identifiers){
Identifier idClone = id.clone();
clonedIdentifiers.add(idClone);
if (idClone.equals(directEditIdentifier))
clone.directEditIdentifier = idClone;
}
clone.setIdentifiers(clonedIdentifiers);
return clone;
}
/**
* Get the text that is shown in the CubicTest GUI for the page element.
* @return the text that is shown in the CubicTest GUI for the page element.
*/
public String getDescription() {
if (description == null)
return "";
return description;
}
/**
* Set the text that is shown in the CubicTest GUI for the page element.
* @param text The text that is shown in the CubicTest GUI for the page element.
*/
public void setDescription(String desc) {
String oldDesc = this.description;
this.description = desc;
firePropertyChange(PropertyAwareObject.NAME, oldDesc, desc);
}
public String getText() {
return getDirectEditIdentifier().getValue();
}
/**
* Set the text used to identify the element in the HTML page.
* Can be e.g. text in label, ID or name, according to type in setIdentifierType().
*/
public void setText(String text) {
String oldText = getText();
getDirectEditIdentifier().setValue(text);
firePropertyChange(PropertyAwareObject.NAME, oldText, text);
}
/**
* Get the user friendly type-name of this page element.
*/
public abstract String getType();
/**
* Get the default action for user interaction with this page element.
*/
public ActionType getDefaultAction(){
return getActionTypes().get(0);
}
public void setIdentifiers(List<Identifier> identifiers) {
this.identifiers = identifiers;
}
public List<Identifier> getIdentifiers() {
if(identifiers == null){
identifiers = new ArrayList<Identifier>();
for(IdentifierType type : getIdentifierTypes()){
Identifier identifier = new Identifier();
identifier.setType(type);
identifiers.add(identifier);
}
if(identifiers.size() > 0)
identifiers.get(0).setProbability(Identifier.MAX_PROBABILITY);
}
return identifiers;
}
/**
* Set the identifier types that this page elements supports.
*/
public void addIdentifier(Identifier identifier) {
identifiers.add(identifier);
firePropertyChange(PropertyAwareObject.NAME, null, identifier);
}
/**
* Get the identifier types that this page elements supports.
* @return the identifier types that this page elements supports.
*/
public List<IdentifierType> getIdentifierTypes() {
List<IdentifierType> list = new ArrayList<IdentifierType>();
list.add(LABEL);
return list;
}
public void setDirectEditIdentifier(Identifier directEditIdentifier) {
Identifier oldDirectEditIdentifier = this.directEditIdentifier;
this.directEditIdentifier = directEditIdentifier;
firePropertyChange(DIRECT_EDIT_IDENTIFIER, oldDirectEditIdentifier, directEditIdentifier);
}
public Identifier getDirectEditIdentifier() {
if(directEditIdentifier == null){
directEditIdentifier = getIdentifiers().get(0);
}
return directEditIdentifier;
}
public boolean isNot(){
return not;
}
public void setNot(boolean not){
boolean oldNot = this.not;
this.not = not;
firePropertyChange(PropertyAwareObject.NOT, oldNot, not);
}
/**
* Gets the Identifier with the highest probability (must be greater than "indifferent").
* If more than one has the same probability, returns the first.
*/
public Identifier getMostSignificantIdentifier() {
int highestProbability = 0;
Identifier result = null;
for (Identifier identifier : getIdentifiers()) {
if (identifier.getProbability() > highestProbability) {
result = identifier;
highestProbability = identifier.getProbability();
}
else if (identifier.getProbability() == highestProbability) {
//direct edit has precedence:
if (getDirectEditIdentifier().equals(identifier)) {
result = identifier;
highestProbability = identifier.getProbability();
}
- else if (StringUtils.isNotBlank(identifier.getValue()) && StringUtils.isBlank(result.getValue())) {
+ else if (StringUtils.isNotBlank(identifier.getValue()) && (result == null || StringUtils.isBlank(result.getValue()))) {
//the ID with a non-null value has precedence:
result = identifier;
highestProbability = identifier.getProbability();
}
}
}
return result;
}
public Identifier getIdentifier(IdentifierType idType) {
for (Identifier identifier : getIdentifiers()) {
if (identifier.getType().equals(idType)) {
return identifier;
}
}
return null;
}
}
| true | true | public Identifier getMostSignificantIdentifier() {
int highestProbability = 0;
Identifier result = null;
for (Identifier identifier : getIdentifiers()) {
if (identifier.getProbability() > highestProbability) {
result = identifier;
highestProbability = identifier.getProbability();
}
else if (identifier.getProbability() == highestProbability) {
//direct edit has precedence:
if (getDirectEditIdentifier().equals(identifier)) {
result = identifier;
highestProbability = identifier.getProbability();
}
else if (StringUtils.isNotBlank(identifier.getValue()) && StringUtils.isBlank(result.getValue())) {
//the ID with a non-null value has precedence:
result = identifier;
highestProbability = identifier.getProbability();
}
}
}
return result;
}
| public Identifier getMostSignificantIdentifier() {
int highestProbability = 0;
Identifier result = null;
for (Identifier identifier : getIdentifiers()) {
if (identifier.getProbability() > highestProbability) {
result = identifier;
highestProbability = identifier.getProbability();
}
else if (identifier.getProbability() == highestProbability) {
//direct edit has precedence:
if (getDirectEditIdentifier().equals(identifier)) {
result = identifier;
highestProbability = identifier.getProbability();
}
else if (StringUtils.isNotBlank(identifier.getValue()) && (result == null || StringUtils.isBlank(result.getValue()))) {
//the ID with a non-null value has precedence:
result = identifier;
highestProbability = identifier.getProbability();
}
}
}
return result;
}
|
diff --git a/core/src/main/java/cucumber/runtime/arquillian/DefaultObjectFactoryExtension.java b/core/src/main/java/cucumber/runtime/arquillian/DefaultObjectFactoryExtension.java
index 74e1f81..b5b4853 100644
--- a/core/src/main/java/cucumber/runtime/arquillian/DefaultObjectFactoryExtension.java
+++ b/core/src/main/java/cucumber/runtime/arquillian/DefaultObjectFactoryExtension.java
@@ -1,46 +1,46 @@
package cucumber.runtime.arquillian;
import static cucumber.runtime.arquillian.TestEnricherProvider.getTestEnrichers;
import static java.lang.String.format;
import java.util.HashMap;
import java.util.Map;
import cucumber.runtime.CucumberException;
import org.jboss.arquillian.test.spi.TestEnricher;
public class DefaultObjectFactoryExtension implements ObjectFactoryExtension {
private final Map<Class<?>, Object> instances;
public DefaultObjectFactoryExtension() {
instances = new HashMap<Class<?>, Object>();
}
public void addClass(Class<?> clazz) {
// intentionally empty
}
@Override
public <T> T getInstance(Class<T> type) {
if (!instances.containsKey(type)) {
try {
T instance = type.getConstructor().newInstance();
for (TestEnricher testEnricher : getTestEnrichers()) {
testEnricher.enrich(instance);
}
instances.put(type, instance);
- } catch (ReflectiveOperationException exception) {
+ } catch (Exception exception) {
throw new CucumberException(format("Failed to instantiate %s", type), exception);
}
}
return (T) instances.get(type);
}
public void start() {
// intentionally empty
}
@Override
public void stop() {
instances.clear();
}
}
| true | true | public <T> T getInstance(Class<T> type) {
if (!instances.containsKey(type)) {
try {
T instance = type.getConstructor().newInstance();
for (TestEnricher testEnricher : getTestEnrichers()) {
testEnricher.enrich(instance);
}
instances.put(type, instance);
} catch (ReflectiveOperationException exception) {
throw new CucumberException(format("Failed to instantiate %s", type), exception);
}
}
return (T) instances.get(type);
}
| public <T> T getInstance(Class<T> type) {
if (!instances.containsKey(type)) {
try {
T instance = type.getConstructor().newInstance();
for (TestEnricher testEnricher : getTestEnrichers()) {
testEnricher.enrich(instance);
}
instances.put(type, instance);
} catch (Exception exception) {
throw new CucumberException(format("Failed to instantiate %s", type), exception);
}
}
return (T) instances.get(type);
}
|
diff --git a/ini/trakem2/display/DisplayCanvas.java b/ini/trakem2/display/DisplayCanvas.java
index 06f830d2..994989e6 100644
--- a/ini/trakem2/display/DisplayCanvas.java
+++ b/ini/trakem2/display/DisplayCanvas.java
@@ -1,3151 +1,3151 @@
/**
TrakEM2 plugin for ImageJ(C).
Copyright (C) 2005-2009 Albert Cardona and Rodney Douglas.
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 (http://www.gnu.org/licenses/gpl.txt )
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
You may contact Albert Cardona at acardona at ini.phys.ethz.ch
Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
**/
package ini.trakem2.display;
import ij.IJ;
import ij.ImagePlus;
import ij.Prefs;
import ij.WindowManager;
import ij.gui.ImageCanvas;
import ij.gui.Roi;
import ij.gui.Toolbar;
import ij.measure.Calibration;
import ij.process.ByteProcessor;
import ij.process.ColorProcessor;
import ini.trakem2.Project;
import ini.trakem2.display.graphics.GraphicsSource;
import ini.trakem2.imaging.Segmentation;
import ini.trakem2.persistence.Loader;
import ini.trakem2.utils.Bureaucrat;
import ini.trakem2.utils.IJError;
import ini.trakem2.utils.Lock;
import ini.trakem2.utils.ProjectToolbar;
import ini.trakem2.utils.Search;
import ini.trakem2.utils.Utils;
import ini.trakem2.utils.Worker;
import java.awt.AWTException;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Composite;
import java.awt.Cursor;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Robot;
import java.awt.Stroke;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.awt.image.VolatileImage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.vecmath.Point2f;
import javax.vecmath.Vector2f;
import javax.vecmath.Vector3d;
public final class DisplayCanvas extends ImageCanvas implements KeyListener/*, FocusListener*/, MouseWheelListener {
private Display display;
private boolean update_graphics = false;
private BufferedImage offscreen = null;
private final HashSet<BufferedImage> to_flush = new HashSet<BufferedImage>();
private ArrayList<Displayable> al_top = new ArrayList<Displayable>();
private final Lock lock_paint = new Lock();
private Rectangle box = null; // the bounding box of the active
private FakeImageWindow fake_win;
private FreeHandProfile freehandProfile = null;
private Robot r;// used for setting the mouse pointer
private final Object offscreen_lock = new Object();
private Cursor noCursor;
private boolean snapping = false;
private boolean dragging = false;
private boolean input_disabled = false;
private boolean input_disabled2 = false;
/** Store a copy of whatever data as each Class may define it, one such data object per class.
* Private to the package. */
static private Hashtable<Class,Object> copy_buffer = new Hashtable<Class,Object>();
static void setCopyBuffer(final Class c, final Object ob) { copy_buffer.put(c, ob); }
static Object getCopyBuffer(final Class c) { return copy_buffer.get(c); }
static private boolean openglEnabled = false;
static private boolean quartzEnabled = false;
static private boolean ddscaleEnabled = false;
// Private to the display package:
static final RenderingHints rhints;
/** Adapted code from Wayne Meissner, for gstreamer-java org.gstreamer.swing.GstVideoComponent; */
static {
final Map<RenderingHints.Key, Object> hints = new HashMap<RenderingHints.Key, Object>();
try {
String openglProperty = System.getProperty("sun.java2d.opengl");
openglEnabled = openglProperty != null && Boolean.parseBoolean(openglProperty);
} catch (Exception ex) { }
try {
String quartzProperty = System.getProperty("apple.awt.graphics.UseQuartz");
quartzEnabled = Boolean.parseBoolean(quartzProperty);
} catch (Exception ex) { }
try {
String ddscaleProperty = System.getProperty("sun.java2d.ddscale");
String d3dProperty = System.getProperty("sun.java2d.d3d");
ddscaleEnabled = Boolean.parseBoolean(ddscaleProperty) && Boolean.parseBoolean(d3dProperty);
} catch (Exception ex) { }
if (openglEnabled) {
// Bilinear interpolation can be accelerated by the OpenGL pipeline
hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
} else if (quartzEnabled) {
//hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
} else if (ddscaleEnabled) {
hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
}
rhints = new RenderingHints(hints);
}
private VolatileImage volatileImage;
private Object volatile_lock = new Object();
//private javax.swing.Timer resourceTimer = new javax.swing.Timer(10000, resourceReaper);
//private boolean frameRendered = false;
private boolean invalid_volatile = false;
/** Adapted code from Wayne Meissner, for gstreamer-java org.gstreamer.swing.GstVideoComponent.
* MUST be called within a "synchronized (volatile_lock) { ... }" block. */
private void renderVolatileImage(final GraphicsConfiguration gc, final BufferedImage offscreen, final ArrayList<Displayable> top, final Displayable active, final Layer active_layer, final int c_alphas, final AffineTransform at, Rectangle clipRect) {
do {
// Recreate volatileImage ONLY if necessary: when null, when incompatible, or when dimensions have changed
// Otherwise, just paint on top of it
final int w = getWidth(), h = getHeight();
if (null == volatileImage || volatileImage.getWidth() != w
|| volatileImage.getHeight() != h || volatileImage.validate(gc) == VolatileImage.IMAGE_INCOMPATIBLE) {
if (null != volatileImage) volatileImage.flush();
volatileImage = gc.createCompatibleVolatileImage(w, h);
volatileImage.setAccelerationPriority(1.0f);
invalid_volatile = false;
clipRect = null; // paint all
}
//
// Now paint the BufferedImage into the accelerated image
//
final Graphics2D g = volatileImage.createGraphics();
// 0 - set clipRect
if (null != clipRect) g.setClip(clipRect);
// 1 - Erase any background
g.setColor(Color.black);
if (null == clipRect) g.fillRect(0, 0, w, h);
else g.fillRect(clipRect.x, clipRect.y, clipRect.width, clipRect.height);
// 2 - Paint offscreen image
if (null != offscreen) g.drawImage(offscreen, 0, 0, null);
// 3 - Paint the active Displayable and all cached on top
//Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
//Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
if (null != active_layer) {
g.setTransform(at);
g.setStroke(this.stroke); // AFTER setting the transform
// Active has to be painted wherever it is, within al_top, if it's not an image
//if (null != active && active.getClass() != Patch.class && !active.isOutOfRepaintingClip(magnification, srcRect, clipRect)) active.paint(g, magnification, true, c_alphas, active_layer);
final boolean must_paint_active = null != active && active.isVisible() && !ImageData.class.isAssignableFrom(active.getClass());
boolean active_painted = !must_paint_active;
if (null != top) {
final Rectangle tmp = null != clipRect ? new Rectangle() : null;
final Rectangle clip = null != clipRect ? new Rectangle((int)(clipRect.x * magnification) - srcRect.x, (int)(clipRect.y * magnification) - srcRect.y, (int)(clipRect.width * magnification), (int)(clipRect.height * magnification)) : null;
for (final Displayable d : top) {
if (null != clipRect && !d.getBoundingBox(tmp).intersects(clip)) continue;
d.paint(g, srcRect, magnification, d == active, c_alphas, active_layer);
if (active_painted) continue;
else active_painted = d == active;
}
if (must_paint_active && !active_painted) {
// Active may not have been part of top array if it was added new and the offscreen image was not updated,
// which is the case for any non-image object
active.paint(g, srcRect, magnification, true, c_alphas, active_layer);
}
}
}
display.getMode().getGraphicsSource().paintOnTop(g, display, srcRect, magnification);
if (null != active_layer.getOverlay2())
active_layer.getOverlay2().paint(g, srcRect, magnification);
if (null != active_layer.getParent().getOverlay2())
active_layer.getParent().getOverlay2().paint(g, srcRect, magnification);
if (null != display.gridoverlay) display.gridoverlay.paint(g);
/* // debug: paint the ZDisplayable's bucket in this layer
if (null != active_layer.getParent().lbucks) {
active_layer.getParent().lbucks.get(active_layer).root.paint(g, srcRect, magnification, Color.red);
}
*/
g.dispose();
} while (volatileImage.contentsLost());
}
/** Adapted code from Wayne Meissner, for gstreamer-java org.gstreamer.swing.GstVideoComponent;
* Paints (and re-renders, if necessary) the volatile image onto the given Graphics object, which
* is that of the DisplayCanvas as provided to the paint(Graphics g) method.
*
* Expects clipRect in screen coordinates
*/
private void render(final Graphics g, final Displayable active, final Layer active_layer, final int c_alphas, final AffineTransform at, Rectangle clipRect) {
final Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHints(rhints);
do {
final ArrayList<Displayable> top;
final BufferedImage offscreen;
synchronized (offscreen_lock) {
offscreen = this.offscreen;
top = this.al_top; // will never be cleared, but may be swapped
}
final GraphicsConfiguration gc = getGraphicsConfiguration();
display.getProject().getLoader().releaseToFit(getWidth() * getHeight() * 4 * 5); // 5 images
// Protect volatile image while rendering it
synchronized (volatile_lock) {
if (invalid_volatile || null == volatileImage
|| volatileImage.validate(gc) != VolatileImage.IMAGE_OK)
{
// clear clip, remade in full
clipRect = null;
renderVolatileImage(gc, offscreen, top, active, active_layer, c_alphas, at, clipRect);
}
if (null != clipRect) g2d.setClip(clipRect);
g2d.drawImage(volatileImage, 0, 0, null);
}
} while (volatileImage.contentsLost());
g2d.dispose();
// Flush all old offscreen images
synchronized (offscreen_lock) {
for (final BufferedImage bi : to_flush) {
bi.flush();
}
to_flush.clear();
}
}
protected void invalidateVolatile() {
synchronized (volatile_lock) {
this.invalid_volatile = true;
}
}
/////////////////
public DisplayCanvas(Display display, int width, int height) {
super(new FakeImagePlus(width, height, display));
fake_win = new FakeImageWindow(imp, this, display);
this.display = display;
this.imageWidth = width;
this.imageHeight = height;
removeKeyListener(IJ.getInstance());
addKeyListener(this);
addMouseWheelListener(this);
}
public Display getDisplay() { return display; }
/** Used to constrain magnification so that only snapshots are used for painting when opening a new, large and filled Display. */
protected void setInitialMagnification(double mag) { // calling this method 'setMagnification' would conflict with the super class homonimous method.
this.magnification = mag; // don't save in the database. This value is overriden when reopening from the database by calling the setup method.
}
/** Used for restoring properties from the database. */
public void setup(double mag, Rectangle srcRect) {
this.magnification = mag;
this.srcRect = (Rectangle)srcRect.clone(); // just in case
super.setDrawingSize((int)Math.ceil(srcRect.width * mag), (int)Math.ceil(srcRect.height * mag));
setMagnification(mag);
//no longer needed//display.pack(); // TODO should be run via invokeLater ... need to check many potential locks of invokeLater calling each other.
}
/** Does not repaint. */
public void setDimensions(double width, double height) {
this.imageWidth = (int)Math.ceil(width);
this.imageHeight = (int)Math.ceil(height);
((FakeImagePlus)imp).setDimensions(imageWidth, imageHeight);
}
/** Overriding to disable it. */
public void handlePopupMenu() {}
public final void update(final Graphics g) {
// overriding to avoid default behaviour in java.awt.Canvas which consists in first repainting the entire drawable area with the background color, and then calling method paint.
this.paint(g);
}
/** Handles repaint event requests and the generation of offscreen threads. */
private final AbstractRepaintThread RT = new AbstractRepaintThread(this, "T2-Canvas-Repainter", new OffscreenThread()) {
protected void handleUpdateGraphics(final Component target, final Rectangle clipRect) {
this.off.setProperties(new RepaintProperties(clipRect, display.getLayer(), target.getWidth(), target.getHeight(), srcRect, magnification, display.getActive(), display.getDisplayChannelAlphas(), display.getMode().getGraphicsSource()));
}
};
/*
private final void setRenderingHints(final Graphics2D g) {
// so slow!! Particularly the first one.
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
//g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
//g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
//g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}
*/
public void setMagnification(double mag) {
if (mag < 0.00000001) mag = 0.00000001;
// ensure a stroke of thickness 1.0 regardless of magnification
this.stroke = new BasicStroke((float)(1.0/mag), BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
// FIXES MAG TO ImageCanvas.zoomLevel LIMITS!!
//super.setMagnification(mag);
// So, manually:
this.magnification = mag;
imp.setTitle(imp.getTitle());
display.getMode().magnificationUpdated(srcRect, mag);
}
/** Paint lines always with a thickness of 1 pixel. This stroke is modified when the magnification is changed, to compensate. */
private BasicStroke stroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
/** The affine transform representing the srcRect displacement and the magnification. */
private final AffineTransform atc = new AffineTransform();
public void paint(final Graphics g) {
if (null == g) return;
try {
synchronized (lock_paint) {
lock_paint.lock();
}
// ensure proper positioning
g.translate(0, 0); // ints!
final Rectangle clipRect = g.getClipBounds();
final Displayable active = display.getActive();
final int c_alphas = display.getDisplayChannelAlphas();
final Layer active_layer = display.getLayer();
final Graphics2D g2d = (Graphics2D)g;
// prepare the canvas for the srcRect and magnification
final AffineTransform at_original = g2d.getTransform();
atc.setToIdentity();
atc.scale(magnification, magnification);
atc.translate(-srcRect.x, -srcRect.y);
at_original.preConcatenate(atc);
if (null != offscreen && dragging) invalidateVolatile(); // to update the active at least
render(g, active, active_layer, c_alphas, at_original, clipRect);
g2d.setTransform(at_original);
g2d.setStroke(this.stroke);
// debug buckets
//if (null != display.getLayer().root) display.getLayer().root.paint(g2d, srcRect, magnification, Color.red);
//if (null != display.getLayer().getParent().lbucks.get(display.getLayer()).root) display.getLayer().getParent().lbucks.get(display.getLayer()).root.paint(g2d, srcRect, magnification, Color.blue);
// reset to identity
g2d.setTransform(new AffineTransform());
// reset to 1.0 thickness
g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
// paint brush outline for AreaList, or fast-marching area
if (mouse_in && null != active && AreaContainer.class.isInstance(active)) {
switch (ProjectToolbar.getToolId()) {
case ProjectToolbar.BRUSH:
int brushSize = ProjectToolbar.getBrushSize();
g.setColor(active.getColor());
g.drawOval((int)((xMouse -srcRect.x -brushSize/2)*magnification), (int)((yMouse - srcRect.y -brushSize/2)*magnification), (int)(brushSize * magnification), (int)(brushSize * magnification));
break;
case ProjectToolbar.PENCIL:
Composite co = g2d.getComposite();
if (IJ.isWindows()) g2d.setColor(Color.yellow);
else g2d.setXORMode(Color.yellow); // XOR on yellow for best contrast
g2d.drawRect((int)((xMouse -srcRect.x -Segmentation.fmp.width/2) * magnification),
(int)((yMouse -srcRect.y -Segmentation.fmp.height/2) * magnification),
(int)(Segmentation.fmp.width * magnification),
(int)(Segmentation.fmp.height * magnification));
g2d.setComposite(co); // undo XOR mode
break;
}
}
final Roi roi = imp.getRoi();
if (null != roi) {
roi.draw(g);
}
// Mathias code:
if (null != freehandProfile) {
freehandProfile.paint(g, magnification, srcRect, true);
if(noCursor == null)
noCursor = Toolkit.getDefaultToolkit().createCustomCursor(new BufferedImage(1,1,BufferedImage.TYPE_BYTE_BINARY), new Point(0,0), "noCursor");
}
} catch (Exception e) {
Utils.log2("DisplayCanvas.paint(Graphics) Error: " + e);
//IJError.print(e);
} finally {
synchronized (lock_paint) {
lock_paint.unlock();
}
}
}
public void waitForRepaint() {
// wait for all offscreen methods to finish painting
RT.waitForOffs();
// wait for the paint method to finish painting
synchronized (lock_paint) {
lock_paint.lock();
lock_paint.unlock();
}
}
/** Paints a handle on the screen coords. Adapted from ij.gui.Roi class. */
static public void drawHandle(final Graphics g, final int x, final int y, final double magnification) {
final int width5 = (int)(5 / magnification + 0.5);
final int width3 = (int)(3 / magnification + 0.5);
final int corr2 = (int)(2 / magnification + 0.5);
final int corr1 = (int)(1 / magnification + 0.5);
g.setColor(Color.white);
g.drawRect(x - corr2, y - corr2, width5, width5);
g.setColor(Color.black);
g.drawRect(x - corr1, y - corr1, width3, width3);
g.setColor(Color.white);
g.fillRect(x, y, corr1, corr1);
}
/** Paints a handle at x,y screen coords. */
static public void drawScreenHandle(final Graphics g, final int x, final int y) {
g.setColor(Color.orange);
g.drawRect(x - 2, y - 2, 5, 5);
g.setColor(Color.black);
g.drawRect(x - 1, y - 1, 3, 3);
g.setColor(Color.orange);
g.fillRect(x, y, 1, 1);
}
/** Paints a handle on the offscreen x,y. Adapted from ij.gui.Roi class. */
/*
private void drawHandle(Graphics g, double x, double y) {
g.setColor(Color.black);
g.fillRect((int) ((x - srcRect.x) * magnification) - 1, (int) ((y - srcRect.y) * magnification) - 1, 3, 3);
g.setColor(Color.white);
g.drawRect((int) ((x - srcRect.x) * magnification) - 2, (int) ((y - srcRect.y) * magnification) - 2, 5, 5);
}
*/
static protected BasicStroke DEFAULT_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
static protected AffineTransform DEFAULT_AFFINE = new AffineTransform();
static public void drawHandle(Graphics2D g, double x, double y, Rectangle srcRect, double magnification) {
AffineTransform original = g.getTransform();
g.setTransform(DEFAULT_AFFINE);
Stroke st = g.getStroke();
g.setStroke(DEFAULT_STROKE);
g.setColor(Color.black);
g.fillRect((int) ((x - srcRect.x) * magnification) - 1, (int) ((y - srcRect.y) * magnification) - 1, 3, 3);
g.setColor(Color.white);
g.drawRect((int) ((x - srcRect.x) * magnification) - 2, (int) ((y - srcRect.y) * magnification) - 2, 5, 5);
g.setStroke(st);
g.setTransform(original);
}
protected void setDrawingColor(int ox, int oy, boolean setBackground) {
super.setDrawingColor(ox, oy, setBackground);
}
/** As offscreen. */
private int x_p, y_p, x_d, y_d, x_d_old, y_d_old;
private boolean popup = false;
private boolean locked = false;
private int tmp_tool = -1;
/** In world coordinates. */
protected Point last_popup = null;
protected Point consumeLastPopupPoint() {
Point p = last_popup;
last_popup = null;
return p;
}
public void mousePressed(MouseEvent me) {
super.flags = me.getModifiers();
x_p = x_d = srcRect.x + (int) (me.getX() / magnification); // offScreenX(me.getX());
y_p = y_d = srcRect.y + (int) (me.getY() / magnification); // offScreenY(me.getY());
this.xMouse = x_p;
this.yMouse = y_p;
// ban if beyond bounds:
if (x_p < srcRect.x || y_p < srcRect.y || x_p > srcRect.x + srcRect.width || y_p > srcRect.y + srcRect.height) {
return;
}
// Popup:
popup = false; // not reset properly in macosx
if (Utils.isPopupTrigger(me)) {
popup = true;
last_popup = new Point(x_p, y_p);
display.getPopupMenu().show(this, me.getX(), me.getY());
return;
}
// reset
snapping = false;
int tool = ProjectToolbar.getToolId();
// pan with middle mouse like in inkscape
/* // works, but can't use it: the alt button then is useless (so no erasing with areas, and so on)
if (0 != (flags & InputEvent.BUTTON2_MASK))
*/
if (me.getButton() == MouseEvent.BUTTON2) {
tmp_tool = tool;
ProjectToolbar.setTool(Toolbar.HAND);
tool = Toolbar.HAND;
}
//Utils.log2("button: " + me.getButton() + " BUTTON2: " + MouseEvent.BUTTON2);
if (!zoom_and_pan) {
// stop animations when clicking (and on pushing ESC)
cancelAnimations();
}
switch (tool) {
case Toolbar.MAGNIFIER:
if (me.isAltDown()) zoomOut(me.getX(), me.getY());
else zoomIn(me.getX(), me.getY());
return;
case Toolbar.HAND:
super.setupScroll(x_p, y_p); // offscreen coords.
return;
}
if (input_disabled) {
input_disabled2 = true;
Utils.showMessage("Please wait while completing the task.\nOnly the glass and hand tool are enabled.");
return; // only zoom and pan are allowed
}
Displayable active = display.getActive();
if (isTransforming() && ProjectToolbar.SELECT != tool) {
Utils.logAll("Notice: the 'Select' tool is not active!\n Activate the 'Select' tool to operate transformation modes.");
}
switch (tool) {
case Toolbar.WAND:
if (null != active && active instanceof Patch) {
me.translatePoint(-(int) active.getX(), -(int) active.getY());
super.mousePressed(me);
repaint();
// TODO should use LayerStack virtualization ... then scale back the ROI
}
return;
case ProjectToolbar.PENCIL:
if (null != active && active.isVisible() && active.getClass() == Profile.class) {
Profile prof = (Profile) active;
this.freehandProfile = new FreeHandProfile(prof);
freehandProfile.mousePressed(x_p, y_p);
return;
}
break;
case Toolbar.RECTANGLE:
case Toolbar.OVAL:
case Toolbar.POLYGON:
case Toolbar.FREEROI:
case Toolbar.LINE:
case Toolbar.POLYLINE:
case Toolbar.FREELINE:
case Toolbar.ANGLE:
case Toolbar.POINT:
// pass the mouse event to superclass ImageCanvas.
super.mousePressed(me);
repaint();
return;
case Toolbar.DROPPER:
// The color dropper
setDrawingColor(x_p, y_p, me.isAltDown());
return;
}
// check:
if (display.isReadOnly()) return;
switch (tool) {
case Toolbar.TEXT:
if (!isTransforming()) {
// edit a label, or add a new one
if (null == active || !active.contains(x_p, y_p)) {
// find a Displayable to activate, if any
display.choose(me.getX(), me.getY(), x_p, y_p, DLabel.class);
active = display.getActive();
}
if (null != active && active.isVisible() && active instanceof DLabel) {
// edit
((DLabel) active).edit();
} else {
// new
DLabel label = new DLabel(display.getProject(), " ", x_p, y_p);
display.getLayer().add(label);
label.edit();
}
}
return;
}
// SPECIFIC for SELECT and above tools
// no ROIs allowed past this point
if (tool >= ProjectToolbar.SELECT) imp.killRoi();
else return;
Selection selection = display.getSelection();
if (isTransforming()) {
box = display.getMode().getRepaintBounds();
display.getMode().mousePressed(me, x_p, y_p, magnification);
return;
}
// select or deselect another active Displayable, or add it to the selection group:
if (ProjectToolbar.SELECT == tool) {
display.choose(me.getX(), me.getY(), x_p, y_p, me.isShiftDown(), null);
}
active = display.getActive();
selection = display.getSelection();
if (null == active || !active.isVisible()) return;
switch (tool) {
case ProjectToolbar.SELECT:
// gather initial box (for repainting purposes)
box = display.getMode().getRepaintBounds();
// check if the active is usable:
// check if the selection contains locked objects
if (selection.isLocked()) {
locked = true;
return;
}
display.getMode().mousePressed(me, x_p, y_p, magnification);
break;
default: // the PEN and PENCIL tools, and any other custom tool
display.getLayerSet().addPreDataEditStep(active);
box = active.getBoundingBox();
active.mousePressed(me, display.getLayer(), x_p, y_p, magnification);
invalidateVolatile();
break;
}
}
public void mouseDragged(MouseEvent me) {
super.flags = me.getModifiers();
if (popup) return;
// ban if beyond bounds:
if (x_p < srcRect.x || y_p < srcRect.y || x_p > srcRect.x + srcRect.width || y_p > srcRect.y + srcRect.height) {
return;
}
Selection selection = display.getSelection();
if (ProjectToolbar.SELECT == ProjectToolbar.getToolId() && locked) {
Utils.log2("Selection is locked.");
return;
}
dragging = true;
x_d_old = x_d;
y_d_old = y_d;
x_d = srcRect.x + (int) (me.getX() / magnification); // offscreen
y_d = srcRect.y + (int) (me.getY() / magnification);
this.xMouse = x_d;
this.yMouse = y_d;
// protection:
int me_x = me.getX();
int me_y = me.getY();
if (me_x < 0 || me_x > this.getWidth() || me_y < 0 || me_y > this.getHeight()) {
x_d = x_d_old;
y_d = y_d_old;
return;
}
int tool = ProjectToolbar.getToolId();
// pan with middle mouse like in inkscape
/* // works, but can't use it: the alt button then is useless (so no erasing with areas, and so on)
if (0 != (flags & InputEvent.BUTTON2_MASK)) {
tool = Toolbar.HAND;
}
*/ // so the above has been implemented as a temporary switch to the HAND tool at the mousePressed function.
switch (tool) {
case Toolbar.MAGNIFIER: // TODO : create a zooms-area tool
return;
case Toolbar.HAND:
int srx = srcRect.x,
sry = srcRect.y;
scroll(me.getX(), me.getY());
if (0 != srx - srcRect.x || 0 != sry - srcRect.y) {
update_graphics = true; // update the offscreen images.
display.getNavigator().repaint(false);
repaint(true);
}
return;
}
if (input_disabled2) return;
//debug:
//Utils.log2("x_d,y_d : " + x_d + "," + y_d + " x_d_old, y_d_old : " + x_d_old + "," + y_d_old + " dx, dy : " + (x_d_old - x_d) + "," + (y_d_old - y_d));
// Code for Matthias' FreehandProfile (TODO this should be done on mousePressed, not on mouseDragged)
Displayable active = display.getActive();
if (null != active && active.getClass() == Profile.class) {
try {
if (r == null) {
r = new Robot(this.getGraphicsConfiguration().getDevice());
}
} catch (AWTException e) {
e.printStackTrace();
}
}
switch (tool) {
case ProjectToolbar.PENCIL:
if (null != active && active.isVisible() && active.getClass() == Profile.class) {
if (freehandProfile == null)
return; // starting painting out of the DisplayCanvas border
double dx = x_d - x_d_old;
double dy = y_d - y_d_old;
freehandProfile.mouseDragged(me, x_d, y_d, dx, dy);
repaint();
// Point screenLocation = getLocationOnScreen();
// mousePos[0] += screenLocation.x;
// mousePos[1] += screenLocation.y;
// r.mouseMove( mousePos[0], mousePos[1]);
return;
}
break;
case Toolbar.RECTANGLE:
case Toolbar.OVAL:
case Toolbar.POLYGON:
case Toolbar.FREEROI:
case Toolbar.LINE:
case Toolbar.POLYLINE:
case Toolbar.FREELINE:
case Toolbar.ANGLE:
case Toolbar.POINT:
// pass the mouse event to superclass ImageCanvas.
super.mouseDragged(me);
repaint(false);
return;
}
// no ROIs beyond this point
if (tool >= ProjectToolbar.SELECT) imp.killRoi();
else return;
// check:
if (display.isReadOnly()) return;
if (null != active && active.isVisible()) {
// prevent dragging beyond the layer limits
if (display.getLayer().contains(x_d, y_d, 1)) {
Rectangle box2;
switch (tool) {
case ProjectToolbar.SELECT:
display.getMode().mouseDragged(me, x_p, y_p, x_d, y_d, x_d_old, y_d_old);
box2 = display.getMode().getRepaintBounds();
box.add(box2);
// repaint all Displays (where it was and where it is now, hence the sum of both boxes):
Display.repaint(display.getLayer(), Selection.PADDING, box, false, active.isLinked() || active.getClass() == Patch.class);
// box for next mouse dragged iteration
box = box2;
break;
default:
active.mouseDragged(me, display.getLayer(), x_p, y_p, x_d, y_d, x_d_old, y_d_old);
// the line above must repaint on its own
break;
}
} else {
//beyond_srcRect = true;
Utils.log("DisplayCanvas.mouseDragged: preventing drag beyond layer limits.");
}
} else if (display.getMode() instanceof ManualAlignMode) {
if (display.getLayer().contains(x_d, y_d, 1)) {
if (tool >= ProjectToolbar.SELECT) {
display.getMode().mouseDragged(me, x_p, y_p, x_d, y_d, x_d_old, y_d_old);
}
}
}
}
public void mouseReleased(MouseEvent me) {
super.flags = me.getModifiers();
boolean dragging2 = dragging;
dragging = false;
boolean locked2 = locked;
locked = false;
if (popup) {
popup = false;
return;
}
// ban if beyond bounds:
if (x_p < srcRect.x || y_p < srcRect.y || x_p > srcRect.x + srcRect.width || y_p > srcRect.y + srcRect.height) {
return;
}
int tool = ProjectToolbar.getToolId();
// pan with middle mouse like in inkscape
/* // works, but can't use it: the alt button then is useless (so no erasing with areas, and so on)
if (0 != (flags & InputEvent.BUTTON2_MASK)) {
tool = Toolbar.HAND;
}
*/
switch (tool) {
case Toolbar.MAGNIFIER:
// display.updateInDatabase("srcRect"); // TODO if the display.frame
// is shrinked, the pack() in the zoom methods will also call the
// updateInDatabase("srcRect") (so it's going to be done twice)
display.updateFrameTitle();
return;
case Toolbar.HAND:
display.updateInDatabase("srcRect");
if (-1 != tmp_tool) {
ProjectToolbar.setTool(tmp_tool);
tmp_tool = -1;
}
if (!dragging2) repaint(true); // TEMPORARY just to allow fixing bad screen when simply cliking with the hand
display.getMode().srcRectUpdated(srcRect, magnification);
return;
}
if (input_disabled2) {
input_disabled2 = false; // reset
return;
}
if (locked2) {
if (ProjectToolbar.SELECT == tool) {
if (dragging2) {
Utils.showMessage("Selection is locked!");
}
return;
}
}
// pan with middle mouse like in inkscape
/* // works, but can't use it: the alt button then is useless (so no erasing with areas, and so on)
if (0 != (flags & InputEvent.BUTTON2_MASK)) {
tool = Toolbar.HAND;
}
*/
super.flags &= ~InputEvent.BUTTON1_MASK; // make sure button 1 bit is not set
super.flags &= ~InputEvent.BUTTON2_MASK; // make sure button 2 bit is not set
super.flags &= ~InputEvent.BUTTON3_MASK; // make sure button 3 bit is not set
int x_r = srcRect.x + (int)(me.getX() / magnification);
int y_r = srcRect.y + (int)(me.getY() / magnification);
/*
if (beyond_srcRect) {
// Artificial release on the last dragged point
x_r = x_d;
y_r = y_d;
}
*/
this.xMouse = x_r;
this.yMouse = y_r;
Displayable active = display.getActive();
switch (tool) {
case ProjectToolbar.PENCIL:
if (null != active && active.isVisible() && active.getClass() == Profile.class) {
if (freehandProfile == null)
return; // starting painting out of the DisplayCanvas boarder
freehandProfile.mouseReleased(me, x_p, y_p, x_d, y_d, x_r, y_r);
freehandProfile = null;
//repaint(true);
Selection selection = display.getSelection();
selection.updateTransform(display.getActive());
Display.repaint(display.getLayer(), selection.getBox(), Selection.PADDING); // repaints the navigator as well
return;
}
break;
case Toolbar.RECTANGLE:
case Toolbar.OVAL:
case Toolbar.POLYGON:
case Toolbar.FREEROI:
case Toolbar.LINE:
case Toolbar.POLYLINE:
case Toolbar.FREELINE:
case Toolbar.ANGLE:
case Toolbar.POINT:
// pass the mouse event to superclass ImageCanvas.
super.mouseReleased(me);
repaint();
// return; // replaced by #SET_ROI
}
final Roi roi = imp.getRoi();
// check:
if (display.isReadOnly()) return;
if (tool >= ProjectToolbar.SELECT) {
if (null != roi) imp.killRoi();
} else return; // #SET_ROI
Selection selection = display.getSelection();
if (snapping) {
// finish dragging
display.getMode().mouseReleased(me, x_p, y_p, x_d, y_d, x_r, y_r);
box.add(display.getMode().getRepaintBounds());
Display.repaint(display.getLayer(), box, Selection.PADDING); // repaints the navigator as well
Display.snap((Patch)active);
// reset:
snapping = false;
return;
}
if (null != active && active.isVisible()) {
switch(tool) {
case ProjectToolbar.SELECT:
display.getMode().mouseReleased(me, x_p, y_p, x_d, y_d, x_r, y_r);
box.add(display.getMode().getRepaintBounds());
Display.repaint(display.getLayer(), Selection.PADDING, box, !isTransforming(), active.isLinked() || active.getClass() == Patch.class); // does not repaint the navigator
break;
case ProjectToolbar.PENCIL:
case ProjectToolbar.PEN:
case ProjectToolbar.BRUSH:
active.mouseReleased(me, display.getLayer(), x_p, y_p, x_d, y_d, x_r, y_r); // active, not selection (Selection only handles transforms, not active's data editions)
// update active's bounding box
selection.updateTransform(active);
box.add(selection.getBox());
Display.repaint(display.getLayer(), Selection.PADDING, box, !isTransforming(), active.isLinked() || active.getClass() == Patch.class); // does not repaint the navigator
//if (!active.getClass().equals(AreaList.class)) Display.repaint(display.getLayer(), box, Selection.PADDING); // repaints the navigator as well
// TODO: this last repaint call is unnecessary, if the box was properly repainted on mouse drag for Profile etc.
//else
if (null != old_brush_box) {
repaint(old_brush_box, 0, false);
old_brush_box = null; // from mouseMoved
}
// The current state:
display.getLayerSet().addDataEditStep(active);
break;
}
}
}
private boolean mouse_in = false;
public void mouseEntered(MouseEvent me) {
mouse_in = true;
// try to catch focus if the JFrame is front most
if (display.isActiveWindow() && !this.hasFocus()) {
this.requestFocus();
}
// bring dragged point to mouse pointer
// TODO doesn't work as expected.
/*
Displayable active = display.getActive();
int x = offScreenX(me.getX());
int y = offScreenY(me.getY());
if (null != active) {
active.snapTo(x, y, x_p, y_p);
x_p = x_d = x_d_old = x;
y_p = y_d = y_d_old = y;
}
*/
//Utils.log2("mouseEntered x,y: " + offScreenX(me.getX()) + "," + offScreenY(me.getY()));
}
public void mouseExited(MouseEvent me) {
mouse_in = false;
// paint away the circular brush if any
if (ProjectToolbar.getToolId() == ProjectToolbar.BRUSH) {
Displayable active = display.getActive();
if (null != active && active.isVisible() && AreaContainer.class.isInstance(active)) {
if (null != old_brush_box) {
this.repaint(old_brush_box, 0);
old_brush_box = null;
}
}
}
}
/** Sets the cursor based on the current tool and cursor location. */
public void setCursor(int sx, int sy, int ox, int oy) {
// copy of ImageCanvas.setCursor without the win==null
xMouse = ox;
yMouse = oy;
Roi roi = imp.getRoi();
/*
* ImageWindow win = imp.getWindow(); if (win==null) return;
*/
if (IJ.spaceBarDown()) {
setCursor(handCursor);
return;
}
switch (Toolbar.getToolId()) {
case Toolbar.MAGNIFIER:
if (IJ.isMacintosh())
setCursor(defaultCursor);
else
setCursor(moveCursor);
break;
case Toolbar.HAND:
setCursor(handCursor);
break;
case ProjectToolbar.SELECT:
case ProjectToolbar.PENCIL:
setCursor(defaultCursor);
break;
default: // selection tool
if (roi != null && roi.getState() != Roi.CONSTRUCTING && roi.isHandle(sx, sy) >= 0)
setCursor(handCursor);
else if (Prefs.usePointerCursor || (roi != null && roi.getState() != Roi.CONSTRUCTING && roi.contains(ox, oy)))
setCursor(defaultCursor);
else
setCursor(crosshairCursor);
break;
}
}
/** Set the srcRect - used by the DisplayNavigator. */
protected void setSrcRect(int x, int y, int width, int height) {
if (width < 1) width = 1;
if (height < 1) height = 1;
this.srcRect.setRect(x, y, width, height);
display.updateInDatabase("srcRect");
display.getMode().srcRectUpdated(srcRect, magnification);
}
public void setDrawingSize(int new_width, int new_height,
boolean adjust_srcRect) {
// adjust srcRect!
if (adjust_srcRect) {
double mag = super.getMagnification();
// This method is very important! Make it fit perfectly.
if (srcRect.width * mag < new_width) {
// expand
if (new_width > imageWidth * mag) {
// too large, limit
srcRect.x = 0;
srcRect.width = imageWidth;
} else {
srcRect.width = (int) Math.ceil(new_width / mag);
if (srcRect.x + srcRect.width > imageWidth) {
srcRect.x = imageWidth - srcRect.width;
}
}
} else {
// shrink
srcRect.width = (int) Math.ceil(new_width / mag);
}
if (srcRect.height * mag < new_height) {
// expand
if (new_height > imageHeight * mag) {
// too large, limit
srcRect.y = 0;
srcRect.height = imageHeight;
} else {
srcRect.height = (int) Math.ceil(new_height / mag);
if (srcRect.y + srcRect.height > imageHeight) {
srcRect.y = imageHeight - srcRect.height;
}
}
} else {
// shrink
srcRect.height = (int) Math.ceil(new_height / mag);
}
}
super.setDrawingSize(new_width, new_height);
}
private void zoomIn2(int x, int y) {
// copy of ImageCanvas.zoomIn except for the canEnlarge is different and
// there's no call to the non-existing ImageWindow
if (magnification >= 32)
return;
double newMag = getHigherZoomLevel2(magnification);
// zoom at point: correct mag drift
int cx = getWidth() / 2;
int cy = getHeight() / 2;
int dx = (int)(((x - cx) * magnification) / newMag);
int dy = (int)(((y - cy) * magnification) / newMag);
x -= dx;
y -= dy;
// Adjust the srcRect to the new dimensions
int w = (int) Math.round(dstWidth / newMag);
if (w * newMag < dstWidth)
w++;
if (w > imageWidth)
w = imageWidth;
int h = (int) Math.round(dstHeight / newMag);
if (h * newMag < dstHeight)
h++;
if (h > imageHeight)
h = imageHeight;
x = offScreenX(x);
y = offScreenY(y);
final Rectangle r = new Rectangle(x - w / 2, y - h / 2, w, h);
if (r.x < 0)
r.x = 0;
if (r.y < 0)
r.y = 0;
if (r.x + w > imageWidth)
r.x = imageWidth - w;
if (r.y + h > imageHeight)
r.y = imageHeight - h;
srcRect = r;
//display.pack();
setMagnification(newMag);
display.updateInDatabase("srcRect");
display.repaintAll2(); // this repaint includes this canvas's repaint as well, but also the navigator, etc. // repaint();
}
private void zoomOut2(int x, int y) {
//if (magnification <= 0.03125)
// return;
double newMag = getLowerZoomLevel2(magnification);
// zoom at point: correct mag drift
int cx = getWidth() / 2;
int cy = getHeight() / 2;
int dx = (int)(((x - cx) * magnification) / newMag);
int dy = (int)(((y - cy) * magnification) / newMag);
x -= dx;
y -= dy;
if (imageWidth * newMag > dstWidth || imageHeight * newMag > dstHeight) {
int w = (int) Math.round(dstWidth / newMag);
if (w * newMag < dstWidth)
w++;
int h = (int) Math.round(dstHeight / newMag);
if (h * newMag < dstHeight)
h++;
x = offScreenX(x);
y = offScreenY(y);
Rectangle r = new Rectangle(x - w / 2, y - h / 2, w, h);
if (r.x < 0)
r.x = 0;
if (r.y < 0)
r.y = 0;
if (r.x + w > imageWidth)
r.x = imageWidth - w;
if (r.y + h > imageHeight)
r.y = imageHeight - h;
srcRect = r;
} else {
// Shrink srcRect, but NOT the dstWidth,dstHeight of the canvas, which remain the same:
srcRect = new Rectangle(0, 0, imageWidth, imageHeight);
}
setMagnification(newMag);
display.repaintAll2(); // this repaint includes this canvas's repaint
// as well, but also the navigator, etc.
// repaint();
display.updateInDatabase("srcRect");
}
/** The minimum amout of pixels allowed for width or height when zooming out. */
static private final int MIN_DIMENSION = 10; // pixels
/** Enable zooming out up to the point where the display becomes 10 pixels in width or height. */
protected double getLowerZoomLevel2(final double currentMag) {
// if it is 1/72 or lower, then:
if (Math.abs(currentMag - 1/72.0) < 0.00000001 || currentMag < 1/72.0) { // lowest zoomLevel in ImageCanvas is 1/72.0
// find nearest power of two under currentMag
// start at level 7, which is 1/128
int level = 7;
double scale = currentMag;
while (scale * srcRect.width > MIN_DIMENSION && scale * srcRect.height > MIN_DIMENSION) {
scale = 1 / Math.pow(2, level);
// if not equal and actually smaller, break:
if (Math.abs(scale - currentMag) != 0.00000001 && scale < currentMag) break;
level++;
}
return scale;
} else {
return ImageCanvas.getLowerZoomLevel(currentMag);
}
}
protected double getHigherZoomLevel2(final double currentMag) {
// if it is not 1/72 and its lower, then:
if (Math.abs(currentMag - 1/72.0) > 0.00000001 && currentMag < 1/72.0) { // lowest zoomLevel in ImageCanvas is 1/72.0
// find nearest power of two above currentMag
// start at level 14, which is 0.00006103515625 (0.006 %)
int level = 14; // this value may be increased in the future
double scale = currentMag;
while (level >= 0) {
scale = 1 / Math.pow(2, level);
if (scale > currentMag) break;
level--;
}
return scale;
} else {
return ImageCanvas.getHigherZoomLevel(currentMag);
}
}
/*
* // OBSOLETE: modified ij.gui.ImageCanvas directly
public void mouseMoved(MouseEvent e) { if (IJ.getInstance()==null) return; int sx =
* e.getX(); int sy = e.getY(); int ox = offScreenX(sx); int oy =
* offScreenY(sy); flags = e.getModifiers(); setCursor(sx, sy, ox, oy);
* IJ.setInputEvent(e); Roi roi = imp.getRoi(); if (roi!=null &&
* (roi.getType()==Roi.POLYGON || roi.getType()==Roi.POLYLINE ||
* roi.getType()==Roi.ANGLE) && roi.getState()==roi.CONSTRUCTING) {
* PolygonRoi pRoi = (PolygonRoi)roi; pRoi.handleMouseMove(ox, oy); } else {
* if (ox<imageWidth && oy<imageHeight) { //ImageWindow win =
* imp.getWindow(); //if (win!=null) win.mouseMoved(ox, oy);
* imp.mouseMoved(ox, oy); } else IJ.showStatus(""); } }
*/
private Rectangle old_brush_box = null;
private MouseMovedThread mouse_moved = new MouseMovedThread();
private class MouseMovedThread extends Thread {
private volatile MouseEvent me = null;
MouseMovedThread() {
super("T2-mouseMoved");
setDaemon(true);
setPriority(Thread.NORM_PRIORITY);
start();
}
void dispatch(MouseEvent me) {
//Utils.log2("before");
synchronized (this) {
//Utils.log2("in");
this.me = me;
notify();
}
}
void quit() {
interrupt();
synchronized (this) { notify(); }
}
public void run() {
while (!isInterrupted()) {
MouseEvent me = this.me;
if (null != me) {
try { mouseMoved(me); } catch (Exception e) { IJError.print(e); }
}
// Wait only if the event has not changed
synchronized (this) {
if (me == this.me) {
// Release the pointer
me = null;
this.me = null;
// Wait until there is a new event
try { wait(); } catch (Exception e) {}
}
}
}
}
private void mouseMoved(MouseEvent me) {
if (null == me) return;
if (input_disabled || display.getMode().isDragging()) return;
xMouse = (int)(me.getX() / magnification) + srcRect.x;
yMouse = (int)(me.getY() / magnification) + srcRect.y;
final Displayable active = display.getActive();
// only when no mouse buttons are down
final int flags = DisplayCanvas.super.flags;
if (0 == (flags & InputEvent.BUTTON1_MASK)
/* && 0 == (flags & InputEvent.BUTTON2_MASK) */ // this is the alt key down ..
&& 0 == (flags & InputEvent.BUTTON3_MASK)
//if (me.getButton() == MouseEvent.NOBUTTON
&& null != active && active.isVisible() && AreaContainer.class.isInstance(active)) {
final int tool = ProjectToolbar.getToolId();
Rectangle r = null;
if (ProjectToolbar.BRUSH == tool) {
// repaint area where the brush circle is
int brushSize = ProjectToolbar.getBrushSize() +2; // +2 padding
r = new Rectangle( xMouse - brushSize/2,
yMouse - brushSize/2,
brushSize+1,
brushSize+1 );
} else if (ProjectToolbar.PENCIL == tool) {
// repaint area where the fast-marching box is
r = new Rectangle( xMouse - Segmentation.fmp.width/2 - 2,
yMouse - Segmentation.fmp.height/2 - 2,
Segmentation.fmp.width + 4,
Segmentation.fmp.height + 4 );
}
if (null != r) {
Rectangle copy = (Rectangle)r.clone();
if (null != old_brush_box) r.add(old_brush_box);
old_brush_box = copy;
repaint(r, 1); // padding because of painting rounding which would live dirty trails
}
}
if (me.isShiftDown()) {
// Print a comma-separated list of objects under the mouse pointer
final Layer layer = DisplayCanvas.this.display.getLayer();
final int x_p = offScreenX(me.getX()),
y_p = offScreenY(me.getY());
final ArrayList<Displayable> al = new ArrayList<Displayable>(layer.getParent().findZDisplayables(layer, x_p, y_p, true));
final ArrayList<Displayable> al2 = new ArrayList<Displayable>(layer.find(x_p, y_p, true));
Collections.reverse(al2); // text labels first
al.addAll(al2);
if (0 == al.size()) {
Utils.showStatus("", false);
return;
}
final StringBuilder sb = new StringBuilder();
final Project pr = layer.getProject();
for (Displayable d : al) sb.append(pr.getShortMeaningfulTitle(d)).append(", ");
sb.setLength(sb.length()-2);
Utils.showStatus(sb.toString(), false);
}
}
}
public boolean isDragging() {
return display.getMode().isDragging();
}
public void mouseMoved(final MouseEvent me) {
super.flags = me.getModifiers();
mouse_moved.dispatch(me);
if (!me.isShiftDown())
DisplayCanvas.super.mouseMoved(me);
}
/** Zoom in using the current mouse position, or the center if the mouse is out. */
public void zoomIn() {
if (xMouse < 0 || screenX(xMouse) > dstWidth || yMouse < 0 || screenY(yMouse) > dstHeight) {
zoomIn(dstWidth/2, dstHeight/2);
} else {
zoomIn(screenX(xMouse), screenY(yMouse));
}
}
/** Overriding to repaint the DisplayNavigator as well. */
public void zoomIn(int x, int y) {
update_graphics = true; // update the offscreen images.
zoomIn2(x, y);
}
/** Zoom out using the current mouse position, or the center if the mouse is out. */
public void zoomOut() {
if (xMouse < 0 || screenX(xMouse) > dstWidth || yMouse < 0 || screenY(yMouse) > dstHeight) {
zoomOut(dstWidth/2, dstHeight/2);
} else zoomOut(screenX(xMouse), screenY(yMouse));
}
/** Overriding to repaint the DisplayNavigator as well. */
public void zoomOut(int x, int y) {
update_graphics = true; // update the offscreen images.
zoomOut2(x, y);
}
/** Center the srcRect around the given object(s) bounding box, zooming if necessary,
* so that the given r becomes a rectangle centered in the srcRect and zoomed out by a factor of 2. */
public void showCentered(Rectangle r) {
// multiply bounding box dimensions by two
r.x -= r.width / 2;
r.y -= r.height / 2;
r.width += r.width;
r.height += r.height;
// compute target magnification
double magn = getWidth() / (double)(r.width > r.height ? r.width : r.height);
center(r, magn);
}
/** Show the given r as the srcRect (or as much of it as possible) at the given magnification. */
public void center(Rectangle r, double magn) {
// bring bounds within limits of the layer and the canvas' drawing size
double lw = display.getLayer().getLayerWidth();
double lh = display.getLayer().getLayerHeight();
int cw = (int) (getWidth() / magn); // canvas dimensions in offscreen coords
int ch = (int) (getHeight() / magn);
// 2nd attempt:
// fit to canvas drawing size:
r.y += (r.height - ch) / 2;
r.width = cw;
r.height = ch;
// place within layer bounds
if (r.x < 0) r.x = 0;
if (r.y < 0) r.y = 0;
if (r.width > lw) {
r.x = 0;
r.width = (int)lw;
}
if (r.height > lh) {
r.y = 0;
r.height = (int)lh;
}
if (r.x + r.width > lw) r.x = (int)(lw - cw);
if (r.y + r.height > lh) r.y = (int)(lh - ch);
// compute magn again, since the desired width may have changed:
magn = getWidth() / (double)r.width;
// set magnification and srcRect
setup(magn, r);
try { Thread.sleep(200); } catch (Exception e) {} // swing ... waiting for the display.pack()
update_graphics = true;
RT.paint(null, update_graphics);
display.updateInDatabase("srcRect");
display.updateFrameTitle();
display.getNavigator().repaint(false);
}
/** Repaint as much as the bounding box around the given Displayable. If the Displayable is null, the entire canvas is repainted, remaking the offscreen images. */
public void repaint(Displayable d) {
repaint(d, 0);
}
/**
* Repaint as much as the bounding box around the given Displayable plus the
* extra padding. If the Displayable is null, the entire canvas is
* repainted, remaking the offscreen images.
*/
public void repaint(Displayable displ, int extra) {
repaint(displ, extra, update_graphics);
}
public void repaint(Displayable displ, int extra, boolean update_graphics) {
if (null != displ) {
Rectangle r = displ.getBoundingBox();
r.x = (int) ((r.x - srcRect.x) * magnification) - extra;
r.y = (int) ((r.y - srcRect.y) * magnification) - extra;
r.width = (int) Math.ceil(r.width * magnification) + extra + extra;
r.height = (int) Math.ceil(r.height * magnification) + extra + extra;
invalidateVolatile();
RT.paint(r, update_graphics);
} else {
// everything
repaint(true);
}
}
/**
* Repaint the clip corresponding to the sum of all boundingboxes of
* Displayable objects in the hashset.
*/
// it is assumed that the linked objects are close to each other, otherwise
// the clip rectangle grows enormously.
public void repaint(final HashSet<Displayable> hs) {
if (null == hs) return;
Rectangle r = null;
final Layer dl = display.getLayer();
for (final Displayable d : hs) {
if (d.getLayer() == dl) {
if (null == r) r = d.getBoundingBox();
else r.add(d.getBoundingBox());
}
}
if (null != r) {
//repaint(r.x, r.y, r.width, r.height);
invalidateVolatile();
RT.paint(r, update_graphics);
}
}
/**
* Repaint the given offscreen Rectangle after transforming its data on the fly to the
* srcRect and magnification of this DisplayCanvas. The Rectangle is not
* modified.
*/
public void repaint(final Rectangle r, final int extra) {
invalidateVolatile();
if (null == r) {
//Utils.log2("DisplayCanvas.repaint(Rectangle, int) warning: null r");
RT.paint(null, update_graphics);
return;
}
// repaint((int) ((r.x - srcRect.x) * magnification) - extra, (int) ((r.y - srcRect.y) * magnification) - extra, (int) Math .ceil(r.width * magnification) + extra + extra, (int) Math.ceil(r.height * magnification) + extra + extra);
RT.paint(new Rectangle((int) ((r.x - srcRect.x) * magnification) - extra, (int) ((r.y - srcRect.y) * magnification) - extra, (int) Math.ceil(r.width * magnification) + extra + extra, (int) Math.ceil(r.height * magnification) + extra + extra), update_graphics);
}
/**
* Repaint the given Rectangle after transforming its data on the fly to the
* srcRect and magnification of this DisplayCanvas. The Rectangle is not
* modified.
* @param box The rectangle to repaint
* @param extra The extra outbound padding to add to the rectangle
* @param update_graphics Whether to recreate the offscreen images or not
*/
public void repaint(Rectangle box, int extra, boolean update_graphics) {
this.update_graphics = update_graphics;
repaint(box, extra);
}
/** Repaint everything, updating offscreen graphics if so specified. */
public void repaint(final boolean update_graphics) {
this.update_graphics = update_graphics | this.update_graphics;
invalidateVolatile();
RT.paint(null, this.update_graphics);
}
/** Overridden to multithread. This method is here basically to enable calls to the FakeImagePlus.draw from the HAND and other tools to repaint properly.*/
public void repaint() {
//Utils.log2("issuing thread");
invalidateVolatile();
RT.paint(null, update_graphics);
}
/** Overridden to multithread. */
/* // saved as unoveridden to make sure there are no infinite thread loops when calling super in buggy JVMs
public void repaint(long ms, int x, int y, int width, int height) {
RT.paint(new Rectangle(x, y, width, height), update_graphics);
}
*/
/** Overridden to multithread. */
public void repaint(int x, int y, int width, int height) {
invalidateVolatile();
RT.paint(new Rectangle(x, y, width, height), update_graphics);
}
public void setUpdateGraphics(boolean b) {
update_graphics = b;
}
/** Release offscreen images and stop threads. */
public void flush() {
// cleanup update graphics thread if any
RT.quit();
synchronized (offscreen_lock) {
if (null != offscreen) {
offscreen.flush();
offscreen = null;
}
update_graphics = true;
for (final BufferedImage bi : to_flush) bi.flush();
to_flush.clear();
}
mouse_moved.quit();
try {
synchronized (this) { if (null != animator) animator.shutdownNow(); }
cancelAnimations();
} catch (Exception e) {}
animator = null;
}
public void destroy() {
flush();
WindowManager.setTempCurrentImage(imp); // the FakeImagePlus
WindowManager.removeWindow(fake_win); // the FakeImageWindow
}
public boolean applyTransform() {
boolean b = display.getMode().apply();
if (b) {
display.setMode(new DefaultMode(display));
Display.repaint();
}
return b;
}
public boolean isTransforming() {
// TODO this may have to change if modes start getting used for a task other than transformation.
// Perhaps "isTransforming" will have to broaden its meaning to "isNotDefaultMode"
return display.getMode().getClass() != DefaultMode.class;
}
public void cancelTransform() {
display.getMode().cancel();
display.setMode(new DefaultMode(display));
repaint(true);
}
private int last_keyCode = KeyEvent.VK_ESCAPE;
private boolean tagging = false;
public void keyPressed(KeyEvent ke) {
Displayable active = display.getActive();
if (null != freehandProfile
&& ProjectToolbar.getToolId() == ProjectToolbar.PENCIL
&& ke.getKeyCode() == KeyEvent.VK_ESCAPE
&& null != freehandProfile)
{
freehandProfile.abort();
ke.consume();
return;
}
final int keyCode = ke.getKeyCode();
try {
// Enable tagging system for any alphanumeric key:
if (!input_disabled && null != active && active instanceof Tree && ProjectToolbar.isDataEditTool(ProjectToolbar.getToolId())) {
if (tagging) {
if (KeyEvent.VK_0 == keyCode && KeyEvent.VK_0 != last_keyCode) {
// do nothing: keep tagging as true
} else {
// last step of tagging: a char after t or after t and a number (and the char itself can be a number)
tagging = false;
}
active.keyPressed(ke);
return;
} else if (KeyEvent.VK_T == keyCode) {
tagging = true;
active.keyPressed(ke);
return;
}
}
} finally {
last_keyCode = keyCode;
}
tagging = false;
if (ke.isConsumed()) return;
/*
* TODO screen editor ... TEMPORARY if (active instanceof DLabel) {
* active.keyPressed(ke); ke.consume(); return; }
*/
if (!zoom_and_pan) {
if (KeyEvent.VK_ESCAPE == keyCode) {
cancelAnimations();
}
return;
}
final int keyChar = ke.getKeyChar();
boolean used = false;
switch (keyChar) {
case '+':
case '=':
zoomIn();
used = true;
break;
case '-':
case '_':
zoomOut();
used = true;
break;
default:
break;
}
if (used) {
ke.consume(); // otherwise ImageJ would use it!
return;
}
if (input_disabled) {
if (KeyEvent.VK_ESCAPE == keyCode) {
// cancel last job if any
if (Utils.checkYN("Really cancel job?")) {
display.getProject().getLoader().quitJob(null);
display.repairGUI();
}
}
ke.consume();
return; // only zoom is enabled, above
}
if (KeyEvent.VK_W == keyCode) {
display.remove(false); // will call back the canvas.flush()
ke.consume();
return;
} else if (KeyEvent.VK_S == keyCode && 0 == ke.getModifiers() && display.getProject().getLoader().isAsynchronous()) {
display.getProject().getLoader().save(display.getProject());
ke.consume();
return;
} else if (KeyEvent.VK_F == keyCode && Utils.isControlDown(ke)) {
new Search();
ke.consume();
return;
}
// if display is not read-only, check for other keys:
switch (keyChar) {
case '<':
case ',': // select next Layer up
display.previousLayer(ke.getModifiers()); // repaints as well
ke.consume();
return;
case '>':
case '.': // select next Layer down
display.nextLayer(ke.getModifiers());
ke.consume();
return;
}
if (null == active && null != imp.getRoi() && KeyEvent.VK_A != keyCode) { // control+a and a roi should select under roi
IJ.getInstance().keyPressed(ke);
return;
}
// end here if display is read-only
if (display.isReadOnly()) {
ke.consume();
display.repaintAll();
return;
}
if (KeyEvent.VK_ENTER == keyCode) {
if (isTransforming()) {
applyTransform();
ke.consume();
return;
} else {
IJ.getInstance().toFront();
ke.consume();
return;
}
}
// check preconditions (or the keys are meaningless). Allow 'enter' to
// bring forward the ImageJ window, and 'v' to paste a patch.
/*if (null == active && KeyEvent.VK_ENTER != keyCode && KeyEvent.VK_V != keyCode && KeyEvent) {
return;
}*/
Layer layer = display.getLayer();
final int mod = ke.getModifiers();
switch (keyCode) {
case KeyEvent.VK_COMMA:
case 0xbc: // select next Layer up
display.nextLayer(ke.getModifiers());
break;
case KeyEvent.VK_PERIOD:
case 0xbe: // select next Layer down
display.previousLayer(ke.getModifiers());
break;
case KeyEvent.VK_Z:
// UNDO: shift+z or ctrl+z
if (0 == (mod ^ Event.SHIFT_MASK) || 0 == (mod ^ Utils.getControlModifier())) {
Bureaucrat.createAndStart(new Worker.Task("Undo") { public void exec() {
if (isTransforming()) display.getMode().undoOneStep();
else display.getLayerSet().undoOneStep();
Display.repaint(display.getLayerSet());
}}, display.getProject());
ke.consume();
// REDO: alt+z or ctrl+shift+z
} else if (0 == (mod ^ Event.ALT_MASK) || 0 == (mod ^ (Event.SHIFT_MASK | Utils.getControlModifier())) ) {
Bureaucrat.createAndStart(new Worker.Task("Redo") { public void exec() {
if (isTransforming()) display.getMode().redoOneStep();
else display.getLayerSet().redoOneStep();
Display.repaint(display.getLayerSet());
}}, display.getProject());
ke.consume();
}
// else, the 'z' command restores the image using ImageJ internal undo
break;
case KeyEvent.VK_T:
if (null != active && !isTransforming() && ProjectToolbar.getToolId() <= ProjectToolbar.SELECT) {
if (0 == ke.getModifiers()) {
display.setMode(new AffineTransformMode(display));
} else if (Event.SHIFT_MASK == ke.getModifiers()) {
for (final Displayable d : display.getSelection().getSelected()) {
if (d.isLinked()) {
Utils.showMessage("Can't enter manual non-linear transformation mode:\nat least one image is linked.");
return;
}
}
display.setMode(new NonLinearTransformMode(display));
}
ke.consume();
}
// else, let ImageJ grab the ROI into the Manager, if any
break;
case KeyEvent.VK_A:
if (0 == (ke.getModifiers() ^ Utils.getControlModifier())) {
Roi roi = getFakeImagePlus().getRoi();
if (null != roi) display.getSelection().selectAll(roi, true);
else display.getSelection().selectAllVisible();
Display.repaint(display.getLayer(), display.getSelection().getBox(), 0);
ke.consume();
break; // INSIDE the 'if' block, so that it can bleed to the default block which forwards to active!
} else if (null != active) {
active.keyPressed(ke);
if (ke.isConsumed()) break;
// TODO this is just a hack really. Should just fall back to default switch option.
// The whole keyPressed method needs revision: should not break from it when not using the key.
}
case KeyEvent.VK_ESCAPE: // cancel transformation
if (isTransforming()) cancelTransform();
else {
display.select(null); // deselect
// repaint out the brush if present
if (ProjectToolbar.BRUSH == ProjectToolbar.getToolId()) {
repaint(old_brush_box, 0);
}
}
ke.consume();
break;
case KeyEvent.VK_SPACE:
if (0 == ke.getModifiers()) {
if (null != active) {
invalidateVolatile();
if (Math.abs(active.getAlpha() - 0.5f) > 0.001f) active.setAlpha(0.5f);
else active.setAlpha(1.0f);
display.setTransparencySlider(active.getAlpha());
ke.consume();
}
} else {
// ;)
int kem = ke.getModifiers();
if (0 != (kem & KeyEvent.SHIFT_MASK)
&& 0 != (kem & KeyEvent.ALT_MASK)
&& 0 != (kem & KeyEvent.CTRL_MASK)) {
Utils.showMessage("A mathematician, like a painter or poet,\nis a maker of patterns.\nIf his patterns are more permanent than theirs,\nit is because they are made with ideas\n \nG. H. Hardy.");
ke.consume();
}
}
break;
case KeyEvent.VK_S:
if (ke.isAltDown()) {
snapping = true;
ke.consume();
} else if (dragging) {
// ignore improper 's' that open ImageJ's save dialog (linux problem ... in macosx, a single dialog opens with lots of 'ssss...' in the text field)
ke.consume();
}
break;
case KeyEvent.VK_H:
handleHide(ke);
ke.consume();
break;
case KeyEvent.VK_F1:
case KeyEvent.VK_F2:
case KeyEvent.VK_F3:
case KeyEvent.VK_F4:
case KeyEvent.VK_F5:
case KeyEvent.VK_F6:
case KeyEvent.VK_F7:
case KeyEvent.VK_F8:
case KeyEvent.VK_F9:
case KeyEvent.VK_F10:
case KeyEvent.VK_F11:
case KeyEvent.VK_F12:
ProjectToolbar.keyPressed(ke);
ke.consume();
break;
}
if (ke.isConsumed()) return;
if (null != active) {
active.keyPressed(ke);
if (ke.isConsumed()) return;
}
// Else:
switch (keyCode) {
case KeyEvent.VK_G:
if (browseToNodeLayer(ke.isShiftDown())) {
ke.consume();
}
break;
case KeyEvent.VK_I:
if (ke.isAltDown()) {
if (ke.isShiftDown()) display.importImage();
else display.importNextImage();
ke.consume();
}
break;
case KeyEvent.VK_PAGE_UP: // as in Inkscape
if (null != active) {
update_graphics = true;
layer.getParent().move(LayerSet.UP, active);
Display.repaint(layer, active, 5);
Display.updatePanelIndex(layer, active);
ke.consume();
}
break;
case KeyEvent.VK_PAGE_DOWN: // as in Inkscape
if (null != active) {
update_graphics = true;
layer.getParent().move(LayerSet.DOWN, active);
Display.repaint(layer, active, 5);
Display.updatePanelIndex(layer, active);
ke.consume();
}
break;
case KeyEvent.VK_HOME: // as in Inkscape
if (null != active) {
update_graphics = true;
layer.getParent().move(LayerSet.TOP, active);
Display.repaint(layer, active, 5);
Display.updatePanelIndex(layer, active);
ke.consume();
}
break;
case KeyEvent.VK_END: // as in Inkscape
if (null != active) {
update_graphics = true;
layer.getParent().move(LayerSet.BOTTOM, active);
Display.repaint(layer, active, 5);
Display.updatePanelIndex(layer, active);
ke.consume();
}
break;
case KeyEvent.VK_V:
if (0 == ke.getModifiers()) {
if (null == active || active.getClass() == Patch.class) {
// paste a new image
ImagePlus clipboard = ImagePlus.getClipboard();
if (null != clipboard) {
ImagePlus imp = new ImagePlus(clipboard.getTitle() + "_" + System.currentTimeMillis(), clipboard.getProcessor().crop());
Object info = clipboard.getProperty("Info");
if (null != info) imp.setProperty("Info", (String)info);
double x = srcRect.x + srcRect.width/2 - imp.getWidth()/2;
double y = srcRect.y + srcRect.height/2 - imp.getHeight()/2;
// save the image somewhere:
Patch pa = display.getProject().getLoader().addNewImage(imp, x, y);
display.getLayer().add(pa);
ke.consume();
} // TODO there isn't much ImageJ integration in the pasting. Can't paste to a selected image, for example.
} else {
// Each type may know how to paste data from the copy buffer into itself:
active.keyPressed(ke);
ke.consume();
}
}
break;
case KeyEvent.VK_P:
if (0 == ke.getModifiers()) {
display.getLayerSet().color_cues = !display.getLayerSet().color_cues;
Display.repaint(display.getLayerSet());
ke.consume();
}
break;
case KeyEvent.VK_F:
if (0 == (ke.getModifiers() ^ KeyEvent.SHIFT_MASK)) {
// toggle visibility of edge arrows
display.getLayerSet().paint_arrows = !display.getLayerSet().paint_arrows;
Display.repaint();
ke.consume();
} else if (0 == ke.getModifiers()) {
// toggle visibility of edge confidence boxes
display.getLayerSet().paint_edge_confidence_boxes = !display.getLayerSet().paint_edge_confidence_boxes;
Display.repaint();
ke.consume();
}
break;
case KeyEvent.VK_DELETE:
if (0 == ke.getModifiers()) {
display.getSelection().deleteAll();
}
break;
case KeyEvent.VK_B:
if (0 == ke.getModifiers() && null != active && active.getClass() == Profile.class) {
display.duplicateLinkAndSendTo(active, 0, active.getLayer().getParent().previous(layer));
ke.consume();
}
break;
case KeyEvent.VK_N:
if (0 == ke.getModifiers() && null != active && active.getClass() == Profile.class) {
display.duplicateLinkAndSendTo(active, 1, active.getLayer().getParent().next(layer));
ke.consume();
}
break;
case KeyEvent.VK_1:
case KeyEvent.VK_2:
case KeyEvent.VK_3:
case KeyEvent.VK_4:
case KeyEvent.VK_5:
case KeyEvent.VK_6:
case KeyEvent.VK_7:
case KeyEvent.VK_8:
case KeyEvent.VK_9:
// run a plugin, if any
if (null != Utils.launchTPlugIn(ke, "Display", display.getProject(), display.getActive())) {
ke.consume();
break;
}
}
if ( !(keyCode == KeyEvent.VK_UNDEFINED || keyChar == KeyEvent.CHAR_UNDEFINED) && !ke.isConsumed() && null != active && active instanceof Patch) {
// TODO should allow forwarding for all, not just Patch
// forward to ImageJ for a final try
IJ.getInstance().keyPressed(ke);
repaint(active, 5);
ke.consume();
}
//Utils.log2("keyCode, keyChar: " + keyCode + ", " + keyChar + " ref: " + KeyEvent.VK_UNDEFINED + ", " + KeyEvent.CHAR_UNDEFINED);
}
public void keyTyped(KeyEvent ke) {}
public void keyReleased(KeyEvent ke) {}
public void zoomToFit() {
double magw = (double) getWidth() / imageWidth;
double magh = (double) getHeight() / imageHeight;
this.magnification = magw < magh ? magw : magh;
this.srcRect.setRect(0, 0, imageWidth, imageHeight);
setMagnification(magnification);
display.updateInDatabase("srcRect"); // includes magnification
}
public void setReceivesInput(boolean b) {
this.input_disabled = !b;
}
public boolean isInputEnabled() {
return !input_disabled;
}
public void exportXML(final StringBuilder sb_body, final String indent, final Object any) {
sb_body.append("<canvas magnification=\"").append(magnification).append("\" srcrect_x=\"").append(srcRect.x).append("\" srcrect_y=\"").append(srcRect.y).append("\" srcrect_width=\"").append(srcRect.width).append("\" srcrect_height=\"").append(srcRect.height).append("\">\n");
}
/** CAREFUL: the ImageProcessor of the returned ImagePlus is fake, that is, a 4x4 byte array; but the dimensions that it returns are those of the host LayerSet. Used to retrieve ROIs for example.*/
public ImagePlus getFakeImagePlus() {
return this.imp;
}
/** Key/Mouse bindings like:
* - ij.gui.StackWindow: wheel to scroll slices (in this case Layers)
* - Inkscape: control+wheel to zoom (apple+wheel in macosx, since control+wheel zooms desktop)
*/
public void mouseWheelMoved(MouseWheelEvent mwe) {
if (dragging) return; // prevent unexpected mouse wheel movements
final int modifiers = mwe.getModifiers();
final int rotation = mwe.getWheelRotation();
final int tool = ProjectToolbar.getToolId();
if (0 != (modifiers & Utils.getControlModifier())) {
if (!zoom_and_pan) return;
// scroll zoom under pointer
int x = mwe.getX();
int y = mwe.getY();
if (x < 0 || y < 0 || x >= getWidth() || y >= getHeight()) {
x = getWidth()/2;
y = getHeight()/2;
}
// Current mouse point in world coords
final double xx = x/magnification + srcRect.x;
final double yy = y/magnification + srcRect.y;
// Delta of view, in screen pixels:
final int px_inc;
if ( 0 != (modifiers & MouseWheelEvent.SHIFT_MASK)) {
if (0 != (modifiers & MouseWheelEvent.ALT_MASK)) px_inc = 1;
else px_inc = 5;
} else px_inc = 20;
final double inc = px_inc/magnification;
final Rectangle r = new Rectangle();
if (rotation > 0) {
// zoom out
r.width = srcRect.width + (int)(inc+0.5);
r.height = srcRect.height + (int)(inc+0.5);
r.x = (int)(xx - ((xx - srcRect.x)/srcRect.width) * r.width + 0.5);
r.y = (int)(yy - ((yy - srcRect.y)/srcRect.height) * r.height + 0.5);
// check boundaries
if (r.width * magnification < getWidth()
|| r.height * magnification < getHeight()) {
// Can't zoom at point: would chage field of view's flow or would have to shift the canvas position!
Utils.showStatus("To zoom more, use -/+ keys");
return;
}
} else {
//zoom in
r.width = srcRect.width - (int)(inc+0.5);
r.height = srcRect.height - (int)(inc+0.5);
if (r.width < 1 || r.height < 1) {
return;
}
r.x = (int)(xx - ((xx - srcRect.x)/srcRect.width) * r.width + 0.5);
r.y = (int)(yy - ((yy - srcRect.y)/srcRect.height) * r.height + 0.5);
}
final double newMag = magnification * (srcRect.width / (double)r.width);
// correct floating-point-induced erroneous drift: the int-precision offscreen point under the mouse shoud remain the same
r.x -= (int)((x/newMag + r.x) - xx);
r.y -= (int)((y/newMag + r.y) - yy);
// adjust bounds
int w = (int) Math.round(dstWidth / newMag);
if (w * newMag < dstWidth) w++;
if (w > imageWidth) w = imageWidth;
int h = (int) Math.round(dstHeight / newMag);
if (h * newMag < dstHeight) h++;
if (h > imageHeight) h = imageHeight;
if (r.x < 0) r.x = 0;
if (r.y < 0) r.y = 0;
if (r.x + w > imageWidth) r.x = imageWidth - w;
if (r.y + h > imageHeight) r.y = imageHeight - h; //imageWidth and imageHeight are the LayerSet's width,height, ie. the world's 2D dimensions.
// set!
this.setMagnification(newMag);
this.setSrcRect(r.x, r.y, w, h);
display.repaintAll2();
} else if (0 == (modifiers ^ InputEvent.SHIFT_MASK) && null != display.getActive() && ProjectToolbar.PEN != tool && AreaContainer.class.isInstance(display.getActive())) {
final int sign = rotation > 0 ? 1 : -1;
if (ProjectToolbar.BRUSH == tool) {
int brushSize_old = ProjectToolbar.getBrushSize();
// resize brush for AreaList/AreaTree painting
int brushSize = ProjectToolbar.setBrushSize((int)(5 * sign / magnification)); // the getWheelRotation provides the sign
if (brushSize_old > brushSize) brushSize = brushSize_old; // for repainting purposes alone
int extra = (int)(10 / magnification);
if (extra < 2) extra = 2;
extra += 4; // for good measure
this.repaint(new Rectangle((int)(mwe.getX() / magnification) + srcRect.x - brushSize/2 - extra, (int)(mwe.getY() / magnification) + srcRect.y - brushSize/2 - extra, brushSize+extra, brushSize+extra), 0);
} else if (ProjectToolbar.PENCIL == tool) {
// resize area to consider for fast-marching
int w = Segmentation.fmp.width;
int h = Segmentation.fmp.height;
Segmentation.fmp.resizeArea(sign, magnification);
w = Math.max(w, Segmentation.fmp.width);
h = Math.max(h, Segmentation.fmp.height);
this.repaint(new Rectangle((int)(mwe.getX() / magnification) + srcRect.x - w/2 + 2,
(int)(mwe.getY() / magnification) + srcRect.y - h/2 + 2,
w + 4, h + 4), 0);
}
} else if (0 == modifiers) {
// scroll layers
if (rotation > 0) display.nextLayer(modifiers);
else display.previousLayer(modifiers);
} else if (null != display.getActive()) {
// forward to active
display.getActive().mouseWheelMoved(mwe);
}
}
protected class RepaintProperties implements AbstractOffscreenThread.RepaintProperties {
final private Layer layer;
final private int g_width;
final private int g_height;
final private Rectangle srcRect;
final private double magnification;
final private Displayable active;
final private int c_alphas;
final private Rectangle clipRect;
final private int mode;
final private HashMap<Color,Layer> hm;
final private ArrayList<LayerPanel> blending_list;
final private GraphicsSource graphics_source;
RepaintProperties(final Rectangle clipRect, final Layer layer, final int g_width, final int g_height, final Rectangle srcRect, final double magnification, final Displayable active, final int c_alphas, final GraphicsSource graphics_source) {
this.clipRect = clipRect;
this.layer = layer;
this.g_width = g_width;
this.g_height = g_height;
this.srcRect = srcRect;
this.magnification = magnification;
this.active = active;
this.c_alphas = c_alphas;
// query the display for repainting mode
this.hm = new HashMap<Color,Layer>();
this.blending_list = new ArrayList<LayerPanel>();
this.mode = display.getPaintMode(hm, blending_list);
this.graphics_source = graphics_source;
}
}
private final class OffscreenThread extends AbstractOffscreenThread {
OffscreenThread() {
super("T2-Canvas-Offscreen");
}
public void paint() {
final Layer layer;
final int g_width;
final int g_height;
final Rectangle srcRect;
final double magnification;
final Displayable active;
final int c_alphas;
final Rectangle clipRect;
final Loader loader;
final HashMap<Color,Layer> hm;
final ArrayList<LayerPanel> blending_list;
final int mode;
final GraphicsSource graphics_source;
synchronized (this) {
final DisplayCanvas.RepaintProperties rp = (DisplayCanvas.RepaintProperties) this.rp;
layer = rp.layer;
g_width = rp.g_width;
g_height = rp.g_height;
srcRect = rp.srcRect;
magnification = rp.magnification;
active = rp.active;
c_alphas = rp.c_alphas;
clipRect = rp.clipRect;
loader = layer.getProject().getLoader();
mode = rp.mode;
hm = rp.hm;
blending_list = rp.blending_list;
graphics_source = rp.graphics_source;
}
BufferedImage target = null;
final ArrayList<Displayable> al_top = new ArrayList<Displayable>();
// Check if the image is cached
Screenshot sc = null;
try {
if (display.getMode().getClass() == DefaultMode.class) {
sc = layer.getParent().getScreenshot(new ScreenshotProperties(layer, srcRect, magnification, g_width, g_height, c_alphas, graphics_source));
if (null != sc) {
//Utils.log2("Using cached screenshot " + sc + " with srcRect " + sc.srcRect);
target = (BufferedImage) loader.getCachedAWT(sc.sid, 0);
if (null == target) layer.getParent().removeFromOffscreens(sc); // the image was thrown out of the cache
else if ( (sc.al_top.size() > 0 && sc.al_top.get(0) != display.getActive())
|| (0 == sc.al_top.size() && null != display.getActive()) ) {
// Can't accept: different active object
Utils.log2("rejecting: different active object");
target = null;
} else al_top.addAll(sc.al_top);
}
}
} catch (Throwable t) {
IJError.print(t);
}
//Utils.log2("Found target " + target + "\n with al_top.size() = " + al_top.size());
if (null == target) {
target = paintOffscreen(layer, g_width, g_height, srcRect, magnification, active, c_alphas, clipRect, loader, hm, blending_list, mode, graphics_source, layer.getParent().prepaint, al_top, true);
// Store it:
/* CAN'T, may have prePaint in it
if (null != sc && display.getProject().getProperty("look_ahead_cache", 0) > 0) {
sc.assoc(target);
layer.getParent().storeScreenshot(sc);
}
*/
}
synchronized (offscreen_lock) {
// only on success:
if (null != offscreen) to_flush.add(offscreen);
offscreen = target;
update_graphics = false;
DisplayCanvas.this.al_top = al_top;
}
// Outside, otherwise could deadlock
invalidateVolatile();
// Send repaint event, without offscreen graphics
RT.paint(clipRect, false);
}
}
/** Looks into the layer and its LayerSet and finds out what needs to be painted, putting it into the three lists.
* @return the index of the first non-image object. */
private final int gatherDisplayables(final Layer layer, final Rectangle srcRect, final Displayable active, final ArrayList<Displayable> al_paint, final ArrayList<Displayable> al_top, final boolean preload_patches) {
layer.getParent().checkBuckets();
layer.checkBuckets();
final Iterator<Displayable> ital = layer.find(srcRect, true).iterator();
final Collection<Displayable> zdal;
final LayerSet layer_set = layer.getParent();
// Which layers to color cue, if any?
if (layer_set.color_cues) {
final Collection<Displayable> atlayer = layer_set.roughlyFindZDisplayables(layer, srcRect, true);
final Set<Displayable> others = new HashSet<Displayable>();
for (final Layer la : layer_set.getColorCueLayerRange(layer)) {
if (la == layer) continue;
others.addAll(layer_set.roughlyFindZDisplayables(la, srcRect, true));
}
others.removeAll(atlayer);
zdal = new ArrayList<Displayable>(others); // in whatever order, to paint under
zdal.addAll(atlayer); // in proper stack-index order
} else {
zdal = layer_set.roughlyFindZDisplayables(layer, srcRect, true);
}
final Iterator<Displayable> itzd = zdal.iterator();
// Assumes the Layer has its objects in order:
// 1 - Patches
// 2 - Profiles, Balls
// 3 - Pipes and ZDisplayables (from the parent LayerSet)
// 4 - DLabels
Displayable tmp = null;
boolean top = false;
final ArrayList<Patch> al_patches = preload_patches ? new ArrayList<Patch>() : null;
int first_non_patch = 0;
while (ital.hasNext()) {
final Displayable d = ital.next();
final Class c = d.getClass();
if (DLabel.class == c || LayerSet.class == c) {
tmp = d; // since ital.next() has moved forward already
break;
}
if (Patch.class == c) {
al_paint.add(d);
if (preload_patches) al_patches.add((Patch)d);
} else {
if (!top && d == active) top = true; // no Patch on al_top ever
if (top) al_top.add(d); // so active is added to al_top, if it's not a Patch
else al_paint.add(d);
}
first_non_patch += 1;
}
// preload concurrently as many as possible
if (preload_patches) Loader.preload(al_patches, magnification, false); // must be false; a 'true' would incur in an infinite loop.
// paint the ZDisplayables here, before the labels and LayerSets, if any
while (itzd.hasNext()) {
final Displayable zd = itzd.next();
if (zd == active) top = true;
if (top) al_top.add(zd);
else al_paint.add(zd);
}
// paint LayerSet and DLabel objects!
if (null != tmp) {
if (tmp == active) top = true;
if (top) al_top.add(tmp);
else al_paint.add(tmp);
}
while (ital.hasNext()) {
final Displayable d = ital.next();
if (d == active) top = true;
if (top) al_top.add(d);
else al_paint.add(d);
}
return first_non_patch;
}
@Deprecated
public BufferedImage paintOffscreen(final Layer layer, final int g_width, final int g_height,
final Rectangle srcRect, final double magnification, final Displayable active,
final int c_alphas, final Rectangle clipRect, final Loader loader, final HashMap<Color,Layer> hm,
final ArrayList<LayerPanel> blending_list, final int mode, final GraphicsSource graphics_source,
final boolean prepaint, final ArrayList<Displayable> al_top) {
return paintOffscreen(layer, g_width, g_height, srcRect, magnification, active,
c_alphas, clipRect, loader, hm, blending_list, mode, graphics_source,
prepaint, al_top, false);
}
/** This method uses data only from the arguments, and changes none.
* Will fill @param al_top with proper Displayable objects, or none when none are selected. */
public BufferedImage paintOffscreen(final Layer layer, final int g_width, final int g_height,
final Rectangle srcRect, final double magnification, final Displayable active,
final int c_alphas, final Rectangle clipRect, final Loader loader, final HashMap<Color,Layer> hm,
final ArrayList<LayerPanel> blending_list, final int mode, final GraphicsSource graphics_source,
final boolean prepaint, final ArrayList<Displayable> al_top, final boolean preload) {
final ArrayList<Displayable> al_paint = new ArrayList<Displayable>();
int first_non_patch = gatherDisplayables(layer, srcRect, active, al_paint, al_top, preload);
return paintOffscreen(layer, al_paint, active, g_width, g_height, c_alphas, loader, hm, blending_list, mode, graphics_source, prepaint, first_non_patch);
}
public BufferedImage paintOffscreen(final Layer layer, final ArrayList<Displayable> al_paint, final Displayable active, final int g_width, final int g_height, final int c_alphas, final Loader loader, final HashMap<Color,Layer> hm, final ArrayList<LayerPanel> blending_list, final int mode, final GraphicsSource graphics_source, final boolean prepaint, int first_non_patch) {
try {
// ALMOST, but not always perfect //if (null != clipRect) g.setClip(clipRect);
// prepare the canvas for the srcRect and magnification
final AffineTransform atc = new AffineTransform();
atc.scale(magnification, magnification);
atc.translate(-srcRect.x, -srcRect.y);
// the non-srcRect areas, in offscreen coords
final Rectangle r1 = new Rectangle(srcRect.x + srcRect.width, srcRect.y, (int)(g_width / magnification) - srcRect.width, (int)(g_height / magnification));
final Rectangle r2 = new Rectangle(srcRect.x, srcRect.y + srcRect.height, srcRect.width, (int)(g_height / magnification) - srcRect.height);
// create new graphics
try {
display.getProject().getLoader().releaseToFit(g_width * g_height * 10);
} catch (Exception e) {} // when closing, asynch state may throw for a null loader.
final BufferedImage target = getGraphicsConfiguration().createCompatibleImage(g_width, g_height, Transparency.TRANSLUCENT); // creates a BufferedImage.TYPE_INT_ARGB image in my T60p ATI FireGL laptop
//Utils.log2("offscreen acceleration priority: " + target.getAccelerationPriority());
final Graphics2D g = target.createGraphics();
g.setTransform(atc); //at_original);
//setRenderingHints(g);
// always a stroke of 1.0, regardless of magnification; the stroke below corrects for that
g.setStroke(stroke);
// Testing: removed Area.subtract, now need to fill in background
g.setColor(Color.black);
g.fillRect(0, 0, g_width - r1.x, g_height - r2.y);
// paint:
// 1 - background
// 2 - images and anything else not on al_top
// 3 - non-srcRect areas
//Utils.log2("offscreen painting: " + al_paint.size());
// filter paintables
final Collection<? extends Paintable> paintables = graphics_source.asPaintable(al_paint);
// adjust:
first_non_patch = paintables.size() - (al_paint.size() - first_non_patch);
// Determine painting mode
if (Display.REPAINT_SINGLE_LAYER == mode) {
if (display.isLiveFilteringEnabled()) {
paintWithFiltering(g, al_paint, paintables, first_non_patch, g_width, g_height, active, c_alphas, layer, true);
} else {
// Direct painting mode, with prePaint abilities
int i = 0;
for (final Paintable d : paintables) {
- i++;
if (i == first_non_patch) {
//Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
//Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}
if (prepaint) d.prePaint(g, srcRect, magnification, d == active, c_alphas, layer);
else d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
+ i++;
}
}
} else if (Display.REPAINT_MULTI_LAYER == mode) {
// paint first the current layer Patches only (to set the background)
// With prePaint capabilities:
if (display.isLiveFilteringEnabled()) {
paintWithFiltering(g, al_paint, paintables, first_non_patch, g_width, g_height, active, c_alphas, layer, false);
} else {
int i = 0;
if (prepaint) {
for (final Paintable d : paintables) {
if (first_non_patch == i) break;
d.prePaint(g, srcRect, magnification, d == active, c_alphas, layer);
i++;
}
} else {
for (final Paintable d : paintables) {
if (first_non_patch == i) break;
d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
i++;
}
}
}
// then blend on top the ImageData of the others, in reverse Z order and using the alpha of the LayerPanel
final Composite original = g.getComposite();
// reset
g.setTransform(new AffineTransform());
for (final ListIterator<LayerPanel> it = blending_list.listIterator(blending_list.size()); it.hasPrevious(); ) {
final LayerPanel lp = it.previous();
if (lp.layer == layer) continue;
layer.getProject().getLoader().releaseToFit(g_width * g_height * 4 + 1024);
final BufferedImage bi = getGraphicsConfiguration().createCompatibleImage(g_width, g_height, Transparency.TRANSLUCENT);
final Graphics2D gb = bi.createGraphics();
gb.setTransform(atc);
for (final Displayable d : lp.layer.find(srcRect, true)) {
if ( ! ImageData.class.isInstance(d)) continue; // skip non-images
d.paint(gb, srcRect, magnification, false, c_alphas, lp.layer); // not prePaint! We want direct painting, even if potentially slow
}
// Repeating loop ... the human compiler at work, just because one cannot lazily concatenate both sequences:
for (final Displayable d : lp.layer.getParent().roughlyFindZDisplayables(lp.layer, srcRect, true)) {
if ( ! ImageData.class.isInstance(d)) continue; // skip non-images
d.paint(gb, srcRect, magnification, false, c_alphas, lp.layer); // not prePaint! We want direct painting, even if potentially slow
}
try {
g.setComposite(Displayable.getComposite(display.getLayerCompositeMode(lp.layer), lp.getAlpha()));
g.drawImage(display.applyFilters(bi), 0, 0, null);
} catch (Throwable t) {
Utils.log("Could not use composite mode for layer overlays! Your graphics card may not support it.");
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, lp.getAlpha()));
g.drawImage(bi, 0, 0, null);
IJError.print(t);
}
bi.flush();
}
// restore
g.setComposite(original);
g.setTransform(atc);
// then paint the non-Patch objects of the current layer
//Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
//Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
// TODO this loop should be reading from the paintable_patches and paintables, since they length/order *could* have changed
// And yes this means iterating and checking the Class of each.
for (int i = first_non_patch; i < al_paint.size(); i++) {
final Displayable d = al_paint.get(i);
d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
}
} else if(Display.REPAINT_RGB_LAYER == mode) {
// TODO rewrite to avoid calling the list twice
final Collection<? extends Paintable> paintable_patches = graphics_source.asPaintable(al_paint);
//
final HashMap<Color,byte[]> channels = new HashMap<Color,byte[]>();
hm.put(Color.green, layer);
for (final Map.Entry<Color,Layer> e : hm.entrySet()) {
final BufferedImage bi = new BufferedImage(g_width, g_height, BufferedImage.TYPE_BYTE_GRAY); //INDEXED, Loader.GRAY_LUT);
final Graphics2D gb = bi.createGraphics();
gb.setTransform(atc);
final Layer la = e.getValue();
ArrayList<Paintable> list = new ArrayList<Paintable>();
if (la == layer) {
if (Color.green != e.getKey()) continue; // don't paint current layer in two channels
list.addAll(paintable_patches);
} else {
list.addAll(la.find(Patch.class, srcRect, true));
}
list.addAll(la.getParent().getZDisplayables(ImageData.class, true)); // Stack.class and perhaps others
for (final Paintable d : list) {
d.paint(gb, srcRect, magnification, false, c_alphas, la);
}
channels.put(e.getKey(), (byte[])new ByteProcessor(bi).getPixels());
}
final byte[] red, green, blue;
green = channels.get(Color.green);
if (null == channels.get(Color.red)) red = new byte[green.length];
else red = channels.get(Color.red);
if (null == channels.get(Color.blue)) blue = new byte[green.length];
else blue = channels.get(Color.blue);
final int[] pix = new int[green.length];
for (int i=0; i<green.length; i++) {
pix[i] = ((red[i] & 0xff) << 16) + ((green[i] & 0xff) << 8) + (blue[i] & 0xff);
}
// undo transform, is intended for Displayable objects
g.setTransform(new AffineTransform());
final ColorProcessor cp = new ColorProcessor(g_width, g_height, pix);
if (display.invert_colors) cp.invert();
display.applyFilters(cp);
final Image img = cp.createImage();
g.drawImage(img, 0, 0, null);
img.flush();
// reset
g.setTransform(atc);
// then paint the non-Image objects of the current layer
//Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
//Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
for (final Displayable d : al_paint) {
if (ImageData.class.isInstance(d)) continue;
d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
}
// TODO having each object type in a key/list<type> table would be so much easier and likely performant.
}
// finally, paint non-srcRect areas
if (r1.width > 0 || r1.height > 0 || r2.width > 0 || r2.height > 0) {
g.setColor(Color.gray);
g.setClip(r1);
g.fill(r1);
g.setClip(r2);
g.fill(r2);
}
return target;
} catch (OutOfMemoryError oome) {
// so OutOfMemoryError won't generate locks
IJError.print(oome);
} catch (Exception e) {
IJError.print(e);
}
return null;
}
private final void paintWithFiltering(final Graphics2D g, final ArrayList<Displayable> al_paint,
final Collection<? extends Paintable> paintables,
final int first_non_patch,
final int g_width, final int g_height,
final Displayable active, final int c_alphas,
final Layer layer, final boolean paint_non_images) {
// Determine the type of the image: if any Patch is of type COLOR_RGB or COLOR_256, use RGB
int type = BufferedImage.TYPE_BYTE_GRAY;
search: for (final Displayable d : al_paint) {
if (d.getClass() == Patch.class) {
switch (((Patch)d).getType()) {
case ImagePlus.COLOR_256:
case ImagePlus.COLOR_RGB:
type = BufferedImage.TYPE_INT_ARGB;
break search;
}
}
}
// Paint all patches to an image
final BufferedImage bi = new BufferedImage(g_width, g_height, type);
final Graphics2D gpre = bi.createGraphics();
gpre.setTransform(atc);
int i = 0;
for (final Paintable p : paintables) {
if (i == first_non_patch) break;
p.paint(gpre, srcRect, magnification, p == active, c_alphas, layer);
i++;
}
gpre.dispose();
final ImagePlus imp = new ImagePlus("filtered", type == BufferedImage.TYPE_BYTE_GRAY ? new ByteProcessor(bi) : new ColorProcessor(bi));
bi.flush();
display.applyFilters(imp);
// Paint the filtered image
final AffineTransform aff = g.getTransform();
g.setTransform(new AffineTransform()); // reset
g.drawImage(imp.getProcessor().createImage(), 0, 0, null);
// Paint the remaining elements if any
if (paint_non_images && first_non_patch != paintables.size()) {
g.setTransform(aff); // restore srcRect and magnification
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
i = 0;
for (final Paintable p : paintables) {
if (i < first_non_patch) {
i++;
continue;
}
p.paint(g, srcRect, magnification, p == active, c_alphas, layer);
i++;
}
}
}
// added here to prevent flickering, but doesn't help. All it does is avoid a call to imp.redraw()
protected void scroll(int sx, int sy) {
int ox = xSrcStart + (int)(sx/magnification); //convert to offscreen coordinates
int oy = ySrcStart + (int)(sy/magnification);
int newx = xSrcStart + (xMouseStart-ox);
int newy = ySrcStart + (yMouseStart-oy);
if (newx<0) newx = 0;
if (newy<0) newy = 0;
if ((newx+srcRect.width)>imageWidth) newx = imageWidth-srcRect.width;
if ((newy+srcRect.height)>imageHeight) newy = imageHeight-srcRect.height;
srcRect.x = newx;
srcRect.y = newy;
display.getMode().srcRectUpdated(srcRect, magnification);
}
private void handleHide(final KeyEvent ke) {
if (ke.isAltDown() && !ke.isShiftDown()) {
// show hidden
Display.updateCheckboxes(display.getLayer().getParent().setAllVisible(false), DisplayablePanel.VISIBILITY_STATE);
//Display.repaint(display.getLayer());
Display.update(display.getLayer());
ke.consume();
return;
}
if (ke.isShiftDown()) {
// hide deselected
display.hideDeselected(ke.isAltDown());
ke.consume();
return;
}
// else, hide selected
display.getSelection().setVisible(false);
Display.update(display.getLayer());
ke.consume();
}
DisplayCanvas.Screenshot createScreenshot(Layer layer) {
return new Screenshot(layer);
}
protected class ScreenshotProperties {
final Layer layer;
final Rectangle srcRect;
final double magnification;
final int g_width, g_height, c_alphas;
final GraphicsSource graphics_source;
final ArrayList<LayerPanel> blending_list;
final HashMap<Color,Layer> hm;
final int mode;
ScreenshotProperties(Layer layer, Rectangle srcRect, double magnification, int g_width, int g_height, int c_alphas, GraphicsSource graphics_source) {
this.srcRect = new Rectangle(srcRect);
this.magnification = magnification;
this.layer = layer;
this.blending_list = new ArrayList<LayerPanel>();
this.hm = new HashMap<Color,Layer>();
this.mode = display.getPaintMode(hm, blending_list);
this.g_width = g_width;
this.g_height = g_height;
this.graphics_source = graphics_source;
this.c_alphas = c_alphas;
Layer current_layer = display.getLayer();
if (Display.REPAINT_RGB_LAYER == mode) {
Layer red = hm.get(Color.red);
Layer blue = hm.get(Color.blue);
if (null != red || null != blue) {
LayerSet ls = layer.getParent();
int i_layer = ls.indexOf(layer);
int i_current = ls.indexOf(current_layer);
if (null != red) {
int i_red = ls.indexOf(red);
Layer l = red.getParent().getLayer(i_red + i_current - i_layer);
if (null != l) {
hm.put(Color.red, l);
} else {
hm.remove(Color.red);
}
}
if (null != blue) {
int i_blue = ls.indexOf(blue);
Layer l = blue.getParent().getLayer(i_blue + i_current - i_layer);
if (null != l) {
hm.put(Color.blue, l);
} else {
hm.remove(Color.blue);
}
}
}
}
}
public final boolean equals(final Object o) {
final ScreenshotProperties s = (ScreenshotProperties)o;
return s.layer == this.layer
&& s.magnification == this.magnification
&& s.srcRect.x == this.srcRect.x && s.srcRect.y == this.srcRect.y
&& s.srcRect.width == this.srcRect.width && s.srcRect.height == this.srcRect.height
&& s.mode == this.mode
&& s.c_alphas == this.c_alphas
&& Utils.equalContent(s.blending_list, this.blending_list)
&& Utils.equalContent(s.hm, this.hm);
}
public int hashCode() { return 0; } //$%^&$#@!
}
public class Screenshot {
final Layer layer;
long sid = Long.MIN_VALUE;
long born = 0;
final ArrayList<Displayable> al_top = new ArrayList<Displayable>();
final ScreenshotProperties props;
Screenshot(Layer layer) {
this(layer, DisplayCanvas.this.srcRect, DisplayCanvas.this.magnification, DisplayCanvas.this.getWidth(), DisplayCanvas.this.getHeight(), DisplayCanvas.this.display.getDisplayChannelAlphas(), DisplayCanvas.this.display.getMode().getGraphicsSource());
}
Screenshot(Layer layer, Rectangle srcRect, double magnification, int g_width, int g_height, int c_alphas, GraphicsSource graphics_source) {
this.layer = layer;
this.props = new ScreenshotProperties(layer, srcRect, magnification, g_width, g_height, c_alphas, graphics_source);
}
public long init() {
this.born = System.currentTimeMillis();
this.sid = layer.getProject().getLoader().getNextTempId();
return this.sid;
}
/** Associate @param img to this, with a new sid. */
public long assoc(BufferedImage img) {
init();
if (null != img) layer.getProject().getLoader().cacheAWT(this.sid, img);
return this.sid;
}
public void createImage() {
BufferedImage img = paintOffscreen(layer, props.g_width, props.g_height, props.srcRect, props.magnification,
display.getActive(), props.c_alphas, null, layer.getProject().getLoader(),
props.hm, props.blending_list, props.mode, props.graphics_source, false, al_top, false);
layer.getProject().getLoader().cacheAWT(sid, img);
}
public void flush() {
layer.getProject().getLoader().decacheAWT(sid);
}
}
private boolean browseToNodeLayer(final boolean is_shift_down) {
// find visible instances of Tree that are currently painting in the canvas
try {
final Layer active_layer = display.getLayer();
final Point po = getCursorLoc(); // in offscreen coords
for (final ZDisplayable zd : display.getLayerSet().getDisplayableList()) {
if (!(zd instanceof Tree)) continue;
final Tree t = (Tree)zd;
final Node<?> nd = t.findClosestNodeW(t.getNodesToPaint(active_layer), po.x, po.y, magnification);
if (null == nd) continue;
// Else:
display.toLayer(nd.la);
t.setLastVisited(nd);
if (!is_shift_down) display.getSelection().clear();
display.getSelection().add(t);
switch (ProjectToolbar.getToolId()) {
case ProjectToolbar.PEN:
case ProjectToolbar.BRUSH:
break;
default:
ProjectToolbar.setTool(ProjectToolbar.PEN);
break;
}
return true;
}
} catch (Exception e) {
Utils.log2("Oops: " + e);
}
return false;
}
/** Smoothly move the canvas from x0,y0,layer0 to x1,y1,layer1 */
protected void animateBrowsing(final int dx, final int dy) {
// check preconditions
final float mag = (float)this.magnification;
final Rectangle startSrcRect = (Rectangle)this.srcRect.clone();
// The motion will be displaced by some screen pixels at every time step.
final Vector2f v = new Vector2f(dx, dy);
final float sqdist_to_travel = v.lengthSquared();
v.normalize();
v.scale(20/mag);
final Point2f cp = new Point2f(0, 0); // the current deltas
//
final ScheduledFuture<?>[] sf = new ScheduledFuture[1];
sf[0] = animate(new Runnable() {
public void run() {
cp.add(v);
//Utils.log2("advanced by x,y = " + cp.x + ", " + cp.y);
int x, y;
if (v.lengthSquared() >= sqdist_to_travel) {
// set target position
x = startSrcRect.x + dx;
y = startSrcRect.y + dy;
// quit animation
cancelAnimation(sf[0]);
} else {
// set position
x = startSrcRect.x + (int)(cp.x);
y = startSrcRect.y + (int)(cp.y);
}
setSrcRect(x, y, startSrcRect.width, startSrcRect.height);
display.repaintAll2();
}
}, 0, 50, TimeUnit.MILLISECONDS);
}
/** Smoothly move the canvas from its current position until the given rectangle is included within the srcRect.
* If the given rectangle is larger than the srcRect, it will refuse to work (for now). */
public boolean animateBrowsing(final Rectangle target_, final Layer target_layer) {
// Crop target to world's 2D dimensions
Area a = new Area(target_);
a.intersect(new Area(display.getLayerSet().get2DBounds()));
final Rectangle target = a.getBounds();
if (0 == target.width || 0 == target.height) {
return false;
}
// animate at all?
if (this.srcRect.contains(target) && target_layer == display.getLayer()) {
// So: don't animate, but at least highlight the target
playHighlight(target);
return false;
}
// The motion will be displaced by some screen pixels at every time step.
final int ox = srcRect.x + srcRect.width/2;
final int oy = srcRect.y + srcRect.height/2;
final int tx = target.x + target.width/2;
final int ty = target.y + target.height/2;
final Vector2f v = new Vector2f(tx - ox, ty - oy);
v.normalize();
v.scale(20/(float)magnification);
// The layer range
final Layer start_layer = display.getLayer();
/*
int ithis = display.getLayerSet().indexOf(start_layer);
int itarget = display.getLayerSet().indexOf(target_layer);
final java.util.List<Layer> layers = display.getLayerSet().getLayers(ithis, itarget);
*/
Calibration cal = display.getLayerSet().getCalibrationCopy();
final double pixelWidth = cal.pixelWidth;
final double pixelHeight = cal.pixelHeight;
//final double dist_to_travel = Math.sqrt(Math.pow((tx - ox)*pixelWidth, 2) + Math.pow((ty - oy)*pixelHeight, 2)
// + Math.pow((start_layer.getZ() - target_layer.getZ()) * pixelWidth, 2));
// vector in calibrated coords between origin and target
final Vector3d g = new Vector3d((tx - ox)*pixelWidth, (ty - oy)*pixelHeight, (target_layer.getZ() - start_layer.getZ())*pixelWidth);
final ScheduledFuture<?>[] sf = new ScheduledFuture[1];
sf[0] = animate(new Runnable() {
public void run() {
if (DisplayCanvas.this.srcRect.contains(target)) {
// reached destination
if (display.getLayer() != target_layer) display.toLayer(target_layer);
playHighlight(target);
cancelAnimation(sf[0]);
} else {
setSrcRect(srcRect.x + (int)v.x, srcRect.y + (int)v.y, srcRect.width, srcRect.height);
// which layer?
if (start_layer != target_layer) {
int cx = srcRect.x + srcRect.width/2;
int cy = srcRect.y + srcRect.height/2;
double dist = Math.sqrt(Math.pow((cx - ox)*pixelWidth, 2) + Math.pow((cy - oy)*pixelHeight, 2)
+ Math.pow((display.getLayer().getZ() - start_layer.getZ()) * pixelWidth, 2));
Vector3d gg = new Vector3d(g);
gg.normalize();
gg.scale((float)dist);
Layer la = display.getLayerSet().getNearestLayer(start_layer.getZ() + gg.z/pixelWidth);
if (la != display.getLayer()) {
display.toLayer(la);
}
}
display.repaintAll2();
}
}
}, 0, 50, TimeUnit.MILLISECONDS);
return true;
}
private ScheduledExecutorService animator = null;
private boolean zoom_and_pan = true;
private final Vector<ScheduledFuture<?>> sfs = new Vector<ScheduledFuture<?>>();
private void cancelAnimations() {
if (sfs.isEmpty()) return;
Vector<ScheduledFuture<?>> sfs = (Vector<ScheduledFuture<?>>)this.sfs.clone();
for (ScheduledFuture<?> sf : sfs) {
sf.cancel(true);
}
this.sfs.clear();
try {
// wait
Thread.sleep(150);
} catch (InterruptedException ie) {}
// Re-enable input, in case the watcher task is canceled as well:
// (It's necessary since there isn't any easy way to tell the scheduler to execute a code block when it cancels its tasks).
restoreUserInput();
}
private void cancelAnimation(final ScheduledFuture<?> sf) {
sfs.remove(sf);
sf.cancel(true);
restoreUserInput();
}
private void restoreUserInput() {
zoom_and_pan = true;
display.getProject().setReceivesInput(true);
}
private ScheduledFuture<?> animate(Runnable run, long initialDelay, long delay, TimeUnit units) {
initAnimator();
// Cancel any animations currently running
cancelAnimations();
// Disable user input
display.getProject().setReceivesInput(false);
zoom_and_pan = false;
// Create tasks to run periodically: a task and a watcher task
final ScheduledFuture<?>[] sf = new ScheduledFuture[2];
sf[0] = animator.scheduleWithFixedDelay(run, initialDelay, delay, units);
sf[1] = animator.scheduleWithFixedDelay(new Runnable() {
public void run() {
if (sf[0].isCancelled()) {
// Enable user input
zoom_and_pan = true;
display.getProject().setReceivesInput(true);
// cancel yourself
sf[1].cancel(true);
}
}
}, 100, 700, TimeUnit.MILLISECONDS);
// Store task for future cancelation
sfs.add(sf[0]);
// but not the watcher task, which must finish on its own after the main task finishes.
return sf[0];
}
/** Draw a dotted circle centered on the given Rectangle. */
private final class Highlighter {
Ellipse2D.Float elf;
final Stroke stroke = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 3, new float[]{4,4,4,4}, 0);
final float dec;
final Rectangle target;
Highlighter(final Rectangle target) {
this.target = target;
elf = new Ellipse2D.Float(target.x, target.y, target.width, target.height);
display.getLayerSet().getOverlay().add(elf, Color.yellow, stroke, true);
dec = (float)((Math.max(target.width, target.height)*magnification / 10)/magnification);
}
boolean next() {
invalidateVolatile();
repaint(target, 5, false);
// setup next iteration
display.getLayerSet().getOverlay().remove(elf);
Ellipse2D.Float elf2 = (Ellipse2D.Float) elf.clone();
elf2.x += dec;
elf2.y += dec;
elf2.width -= (dec+dec);
elf2.height -= (dec+dec);
if (elf2.width > 1 || elf2.height > 1) {
elf = elf2;
display.getLayerSet().getOverlay().add(elf, Color.yellow, stroke, true);
return true;
} else {
display.getLayerSet().getOverlay().remove(elf);
return false;
}
}
void cleanup() {
display.getLayerSet().getOverlay().remove(elf);
}
}
private abstract class Animation implements Runnable {
final Highlighter h;
Animation(final Highlighter h) {
this.h = h;
}
}
private ScheduledFuture<?> playHighlight(final Rectangle target) {
initAnimator();
final Highlighter highlight = new Highlighter(target);
final ScheduledFuture<?>[] sf = (ScheduledFuture<?>[])new ScheduledFuture[2];
sf[0] = animator.scheduleWithFixedDelay(new Animation(highlight) {
public void run() {
if (!highlight.next()) {
cancelAnimation(sf[0]);
highlight.cleanup();
}
}
}, 10, 100, TimeUnit.MILLISECONDS);
sf[1] = animator.scheduleWithFixedDelay(new Animation(highlight) {
public void run() {
if (sf[0].isCancelled()) {
highlight.cleanup();
sf[1].cancel(true); // itself
}
}
}, 50, 100, TimeUnit.MILLISECONDS);
sfs.add(sf[0]);
return sf[0];
}
synchronized private void initAnimator() {
if (null == animator) animator = Executors.newScheduledThreadPool(2);
}
}
| false | true | public BufferedImage paintOffscreen(final Layer layer, final ArrayList<Displayable> al_paint, final Displayable active, final int g_width, final int g_height, final int c_alphas, final Loader loader, final HashMap<Color,Layer> hm, final ArrayList<LayerPanel> blending_list, final int mode, final GraphicsSource graphics_source, final boolean prepaint, int first_non_patch) {
try {
// ALMOST, but not always perfect //if (null != clipRect) g.setClip(clipRect);
// prepare the canvas for the srcRect and magnification
final AffineTransform atc = new AffineTransform();
atc.scale(magnification, magnification);
atc.translate(-srcRect.x, -srcRect.y);
// the non-srcRect areas, in offscreen coords
final Rectangle r1 = new Rectangle(srcRect.x + srcRect.width, srcRect.y, (int)(g_width / magnification) - srcRect.width, (int)(g_height / magnification));
final Rectangle r2 = new Rectangle(srcRect.x, srcRect.y + srcRect.height, srcRect.width, (int)(g_height / magnification) - srcRect.height);
// create new graphics
try {
display.getProject().getLoader().releaseToFit(g_width * g_height * 10);
} catch (Exception e) {} // when closing, asynch state may throw for a null loader.
final BufferedImage target = getGraphicsConfiguration().createCompatibleImage(g_width, g_height, Transparency.TRANSLUCENT); // creates a BufferedImage.TYPE_INT_ARGB image in my T60p ATI FireGL laptop
//Utils.log2("offscreen acceleration priority: " + target.getAccelerationPriority());
final Graphics2D g = target.createGraphics();
g.setTransform(atc); //at_original);
//setRenderingHints(g);
// always a stroke of 1.0, regardless of magnification; the stroke below corrects for that
g.setStroke(stroke);
// Testing: removed Area.subtract, now need to fill in background
g.setColor(Color.black);
g.fillRect(0, 0, g_width - r1.x, g_height - r2.y);
// paint:
// 1 - background
// 2 - images and anything else not on al_top
// 3 - non-srcRect areas
//Utils.log2("offscreen painting: " + al_paint.size());
// filter paintables
final Collection<? extends Paintable> paintables = graphics_source.asPaintable(al_paint);
// adjust:
first_non_patch = paintables.size() - (al_paint.size() - first_non_patch);
// Determine painting mode
if (Display.REPAINT_SINGLE_LAYER == mode) {
if (display.isLiveFilteringEnabled()) {
paintWithFiltering(g, al_paint, paintables, first_non_patch, g_width, g_height, active, c_alphas, layer, true);
} else {
// Direct painting mode, with prePaint abilities
int i = 0;
for (final Paintable d : paintables) {
i++;
if (i == first_non_patch) {
//Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
//Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}
if (prepaint) d.prePaint(g, srcRect, magnification, d == active, c_alphas, layer);
else d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
}
}
} else if (Display.REPAINT_MULTI_LAYER == mode) {
// paint first the current layer Patches only (to set the background)
// With prePaint capabilities:
if (display.isLiveFilteringEnabled()) {
paintWithFiltering(g, al_paint, paintables, first_non_patch, g_width, g_height, active, c_alphas, layer, false);
} else {
int i = 0;
if (prepaint) {
for (final Paintable d : paintables) {
if (first_non_patch == i) break;
d.prePaint(g, srcRect, magnification, d == active, c_alphas, layer);
i++;
}
} else {
for (final Paintable d : paintables) {
if (first_non_patch == i) break;
d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
i++;
}
}
}
// then blend on top the ImageData of the others, in reverse Z order and using the alpha of the LayerPanel
final Composite original = g.getComposite();
// reset
g.setTransform(new AffineTransform());
for (final ListIterator<LayerPanel> it = blending_list.listIterator(blending_list.size()); it.hasPrevious(); ) {
final LayerPanel lp = it.previous();
if (lp.layer == layer) continue;
layer.getProject().getLoader().releaseToFit(g_width * g_height * 4 + 1024);
final BufferedImage bi = getGraphicsConfiguration().createCompatibleImage(g_width, g_height, Transparency.TRANSLUCENT);
final Graphics2D gb = bi.createGraphics();
gb.setTransform(atc);
for (final Displayable d : lp.layer.find(srcRect, true)) {
if ( ! ImageData.class.isInstance(d)) continue; // skip non-images
d.paint(gb, srcRect, magnification, false, c_alphas, lp.layer); // not prePaint! We want direct painting, even if potentially slow
}
// Repeating loop ... the human compiler at work, just because one cannot lazily concatenate both sequences:
for (final Displayable d : lp.layer.getParent().roughlyFindZDisplayables(lp.layer, srcRect, true)) {
if ( ! ImageData.class.isInstance(d)) continue; // skip non-images
d.paint(gb, srcRect, magnification, false, c_alphas, lp.layer); // not prePaint! We want direct painting, even if potentially slow
}
try {
g.setComposite(Displayable.getComposite(display.getLayerCompositeMode(lp.layer), lp.getAlpha()));
g.drawImage(display.applyFilters(bi), 0, 0, null);
} catch (Throwable t) {
Utils.log("Could not use composite mode for layer overlays! Your graphics card may not support it.");
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, lp.getAlpha()));
g.drawImage(bi, 0, 0, null);
IJError.print(t);
}
bi.flush();
}
// restore
g.setComposite(original);
g.setTransform(atc);
// then paint the non-Patch objects of the current layer
//Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
//Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
// TODO this loop should be reading from the paintable_patches and paintables, since they length/order *could* have changed
// And yes this means iterating and checking the Class of each.
for (int i = first_non_patch; i < al_paint.size(); i++) {
final Displayable d = al_paint.get(i);
d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
}
} else if(Display.REPAINT_RGB_LAYER == mode) {
// TODO rewrite to avoid calling the list twice
final Collection<? extends Paintable> paintable_patches = graphics_source.asPaintable(al_paint);
//
final HashMap<Color,byte[]> channels = new HashMap<Color,byte[]>();
hm.put(Color.green, layer);
for (final Map.Entry<Color,Layer> e : hm.entrySet()) {
final BufferedImage bi = new BufferedImage(g_width, g_height, BufferedImage.TYPE_BYTE_GRAY); //INDEXED, Loader.GRAY_LUT);
final Graphics2D gb = bi.createGraphics();
gb.setTransform(atc);
final Layer la = e.getValue();
ArrayList<Paintable> list = new ArrayList<Paintable>();
if (la == layer) {
if (Color.green != e.getKey()) continue; // don't paint current layer in two channels
list.addAll(paintable_patches);
} else {
list.addAll(la.find(Patch.class, srcRect, true));
}
list.addAll(la.getParent().getZDisplayables(ImageData.class, true)); // Stack.class and perhaps others
for (final Paintable d : list) {
d.paint(gb, srcRect, magnification, false, c_alphas, la);
}
channels.put(e.getKey(), (byte[])new ByteProcessor(bi).getPixels());
}
final byte[] red, green, blue;
green = channels.get(Color.green);
if (null == channels.get(Color.red)) red = new byte[green.length];
else red = channels.get(Color.red);
if (null == channels.get(Color.blue)) blue = new byte[green.length];
else blue = channels.get(Color.blue);
final int[] pix = new int[green.length];
for (int i=0; i<green.length; i++) {
pix[i] = ((red[i] & 0xff) << 16) + ((green[i] & 0xff) << 8) + (blue[i] & 0xff);
}
// undo transform, is intended for Displayable objects
g.setTransform(new AffineTransform());
final ColorProcessor cp = new ColorProcessor(g_width, g_height, pix);
if (display.invert_colors) cp.invert();
display.applyFilters(cp);
final Image img = cp.createImage();
g.drawImage(img, 0, 0, null);
img.flush();
// reset
g.setTransform(atc);
// then paint the non-Image objects of the current layer
//Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
//Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
for (final Displayable d : al_paint) {
if (ImageData.class.isInstance(d)) continue;
d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
}
// TODO having each object type in a key/list<type> table would be so much easier and likely performant.
}
// finally, paint non-srcRect areas
if (r1.width > 0 || r1.height > 0 || r2.width > 0 || r2.height > 0) {
g.setColor(Color.gray);
g.setClip(r1);
g.fill(r1);
g.setClip(r2);
g.fill(r2);
}
return target;
} catch (OutOfMemoryError oome) {
// so OutOfMemoryError won't generate locks
IJError.print(oome);
} catch (Exception e) {
IJError.print(e);
}
return null;
}
| public BufferedImage paintOffscreen(final Layer layer, final ArrayList<Displayable> al_paint, final Displayable active, final int g_width, final int g_height, final int c_alphas, final Loader loader, final HashMap<Color,Layer> hm, final ArrayList<LayerPanel> blending_list, final int mode, final GraphicsSource graphics_source, final boolean prepaint, int first_non_patch) {
try {
// ALMOST, but not always perfect //if (null != clipRect) g.setClip(clipRect);
// prepare the canvas for the srcRect and magnification
final AffineTransform atc = new AffineTransform();
atc.scale(magnification, magnification);
atc.translate(-srcRect.x, -srcRect.y);
// the non-srcRect areas, in offscreen coords
final Rectangle r1 = new Rectangle(srcRect.x + srcRect.width, srcRect.y, (int)(g_width / magnification) - srcRect.width, (int)(g_height / magnification));
final Rectangle r2 = new Rectangle(srcRect.x, srcRect.y + srcRect.height, srcRect.width, (int)(g_height / magnification) - srcRect.height);
// create new graphics
try {
display.getProject().getLoader().releaseToFit(g_width * g_height * 10);
} catch (Exception e) {} // when closing, asynch state may throw for a null loader.
final BufferedImage target = getGraphicsConfiguration().createCompatibleImage(g_width, g_height, Transparency.TRANSLUCENT); // creates a BufferedImage.TYPE_INT_ARGB image in my T60p ATI FireGL laptop
//Utils.log2("offscreen acceleration priority: " + target.getAccelerationPriority());
final Graphics2D g = target.createGraphics();
g.setTransform(atc); //at_original);
//setRenderingHints(g);
// always a stroke of 1.0, regardless of magnification; the stroke below corrects for that
g.setStroke(stroke);
// Testing: removed Area.subtract, now need to fill in background
g.setColor(Color.black);
g.fillRect(0, 0, g_width - r1.x, g_height - r2.y);
// paint:
// 1 - background
// 2 - images and anything else not on al_top
// 3 - non-srcRect areas
//Utils.log2("offscreen painting: " + al_paint.size());
// filter paintables
final Collection<? extends Paintable> paintables = graphics_source.asPaintable(al_paint);
// adjust:
first_non_patch = paintables.size() - (al_paint.size() - first_non_patch);
// Determine painting mode
if (Display.REPAINT_SINGLE_LAYER == mode) {
if (display.isLiveFilteringEnabled()) {
paintWithFiltering(g, al_paint, paintables, first_non_patch, g_width, g_height, active, c_alphas, layer, true);
} else {
// Direct painting mode, with prePaint abilities
int i = 0;
for (final Paintable d : paintables) {
if (i == first_non_patch) {
//Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
//Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}
if (prepaint) d.prePaint(g, srcRect, magnification, d == active, c_alphas, layer);
else d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
i++;
}
}
} else if (Display.REPAINT_MULTI_LAYER == mode) {
// paint first the current layer Patches only (to set the background)
// With prePaint capabilities:
if (display.isLiveFilteringEnabled()) {
paintWithFiltering(g, al_paint, paintables, first_non_patch, g_width, g_height, active, c_alphas, layer, false);
} else {
int i = 0;
if (prepaint) {
for (final Paintable d : paintables) {
if (first_non_patch == i) break;
d.prePaint(g, srcRect, magnification, d == active, c_alphas, layer);
i++;
}
} else {
for (final Paintable d : paintables) {
if (first_non_patch == i) break;
d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
i++;
}
}
}
// then blend on top the ImageData of the others, in reverse Z order and using the alpha of the LayerPanel
final Composite original = g.getComposite();
// reset
g.setTransform(new AffineTransform());
for (final ListIterator<LayerPanel> it = blending_list.listIterator(blending_list.size()); it.hasPrevious(); ) {
final LayerPanel lp = it.previous();
if (lp.layer == layer) continue;
layer.getProject().getLoader().releaseToFit(g_width * g_height * 4 + 1024);
final BufferedImage bi = getGraphicsConfiguration().createCompatibleImage(g_width, g_height, Transparency.TRANSLUCENT);
final Graphics2D gb = bi.createGraphics();
gb.setTransform(atc);
for (final Displayable d : lp.layer.find(srcRect, true)) {
if ( ! ImageData.class.isInstance(d)) continue; // skip non-images
d.paint(gb, srcRect, magnification, false, c_alphas, lp.layer); // not prePaint! We want direct painting, even if potentially slow
}
// Repeating loop ... the human compiler at work, just because one cannot lazily concatenate both sequences:
for (final Displayable d : lp.layer.getParent().roughlyFindZDisplayables(lp.layer, srcRect, true)) {
if ( ! ImageData.class.isInstance(d)) continue; // skip non-images
d.paint(gb, srcRect, magnification, false, c_alphas, lp.layer); // not prePaint! We want direct painting, even if potentially slow
}
try {
g.setComposite(Displayable.getComposite(display.getLayerCompositeMode(lp.layer), lp.getAlpha()));
g.drawImage(display.applyFilters(bi), 0, 0, null);
} catch (Throwable t) {
Utils.log("Could not use composite mode for layer overlays! Your graphics card may not support it.");
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, lp.getAlpha()));
g.drawImage(bi, 0, 0, null);
IJError.print(t);
}
bi.flush();
}
// restore
g.setComposite(original);
g.setTransform(atc);
// then paint the non-Patch objects of the current layer
//Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
//Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
// TODO this loop should be reading from the paintable_patches and paintables, since they length/order *could* have changed
// And yes this means iterating and checking the Class of each.
for (int i = first_non_patch; i < al_paint.size(); i++) {
final Displayable d = al_paint.get(i);
d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
}
} else if(Display.REPAINT_RGB_LAYER == mode) {
// TODO rewrite to avoid calling the list twice
final Collection<? extends Paintable> paintable_patches = graphics_source.asPaintable(al_paint);
//
final HashMap<Color,byte[]> channels = new HashMap<Color,byte[]>();
hm.put(Color.green, layer);
for (final Map.Entry<Color,Layer> e : hm.entrySet()) {
final BufferedImage bi = new BufferedImage(g_width, g_height, BufferedImage.TYPE_BYTE_GRAY); //INDEXED, Loader.GRAY_LUT);
final Graphics2D gb = bi.createGraphics();
gb.setTransform(atc);
final Layer la = e.getValue();
ArrayList<Paintable> list = new ArrayList<Paintable>();
if (la == layer) {
if (Color.green != e.getKey()) continue; // don't paint current layer in two channels
list.addAll(paintable_patches);
} else {
list.addAll(la.find(Patch.class, srcRect, true));
}
list.addAll(la.getParent().getZDisplayables(ImageData.class, true)); // Stack.class and perhaps others
for (final Paintable d : list) {
d.paint(gb, srcRect, magnification, false, c_alphas, la);
}
channels.put(e.getKey(), (byte[])new ByteProcessor(bi).getPixels());
}
final byte[] red, green, blue;
green = channels.get(Color.green);
if (null == channels.get(Color.red)) red = new byte[green.length];
else red = channels.get(Color.red);
if (null == channels.get(Color.blue)) blue = new byte[green.length];
else blue = channels.get(Color.blue);
final int[] pix = new int[green.length];
for (int i=0; i<green.length; i++) {
pix[i] = ((red[i] & 0xff) << 16) + ((green[i] & 0xff) << 8) + (blue[i] & 0xff);
}
// undo transform, is intended for Displayable objects
g.setTransform(new AffineTransform());
final ColorProcessor cp = new ColorProcessor(g_width, g_height, pix);
if (display.invert_colors) cp.invert();
display.applyFilters(cp);
final Image img = cp.createImage();
g.drawImage(img, 0, 0, null);
img.flush();
// reset
g.setTransform(atc);
// then paint the non-Image objects of the current layer
//Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images
//Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
for (final Displayable d : al_paint) {
if (ImageData.class.isInstance(d)) continue;
d.paint(g, srcRect, magnification, d == active, c_alphas, layer);
}
// TODO having each object type in a key/list<type> table would be so much easier and likely performant.
}
// finally, paint non-srcRect areas
if (r1.width > 0 || r1.height > 0 || r2.width > 0 || r2.height > 0) {
g.setColor(Color.gray);
g.setClip(r1);
g.fill(r1);
g.setClip(r2);
g.fill(r2);
}
return target;
} catch (OutOfMemoryError oome) {
// so OutOfMemoryError won't generate locks
IJError.print(oome);
} catch (Exception e) {
IJError.print(e);
}
return null;
}
|
diff --git a/src/org/letstalktech/aahw/POSTRequest.java b/src/org/letstalktech/aahw/POSTRequest.java
index 276ae59..723bfa8 100644
--- a/src/org/letstalktech/aahw/POSTRequest.java
+++ b/src/org/letstalktech/aahw/POSTRequest.java
@@ -1,137 +1,137 @@
package org.letstalktech.aahw;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.BitmapFactory;
public class POSTRequest extends HTTPRequest {
HttpPost post;
public POSTRequest(CookieStore cookieStore, Callback cb){
super(cookieStore,cb);
}
public POSTRequest(CookieStore cookieStore, Callback cb, Callback errorCallback){
super(cookieStore,cb,errorCallback);
}
public POSTRequest(){
super();
}
public POSTRequest(CookieStore cookieStore){
super(cookieStore);
}
@Override
protected Result doInBackground(Parameters... parameters) {
Result result = new Result();
android.util.Log.v("POSTRequest","Entered the POSTRequest");
try {
String postURL = serverAddress+parameters[0].getPath();
post = new HttpPost(postURL);
android.util.Log.e("POSTRequest",postURL);
if(parameters[0].getUserAgent().length() > 0)
post.getParams().setParameter(CoreProtocolPNames.USER_AGENT, parameters[0].getUserAgent());
//List<NameValuePair> params = new ArrayList<NameValuePair>();
MultipartEntity ent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
Charset chars = Charset.forName("UTF-8");
- for (Map.Entry<String, Object> e : parameters[0].getParams().entrySet())
+ for (Map.Entry<String, Object> e : parameters[0].getHeaders().entrySet())
{
post.addHeader(e.getKey(), e.getValue().toString());
}
for (Map.Entry<String, Object> e : parameters[0].getParams().entrySet())
{
// params.add(new BasicNameValuePair(e.getKey(), e.getValue().toString()));
if(e.getValue().getClass().getSimpleName().contentEquals("File"))
ent.addPart(e.getKey(),new FileBody((File)e.getValue()));
else{
StringBody test = new StringBody(e.getValue().toString(),"text/plain",chars);
ent.addPart(e.getKey(),test);
}
}
//UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
//post.addHeader("Content-Type", "multipart/form-data");
post.setEntity(ent);
response = httpclient.execute(post,localContext);
result.setStatus(response.getStatusLine().getStatusCode());
android.util.Log.v("POSTRequest",String.valueOf(result.getStatus()));
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
try{
android.util.Log.v("POSTRequest", response.getHeaders("Content-Type")[0].getValue());
if(response.getHeaders("Content-Type")[0].getValue().contains("image")){
android.util.Log.e("POSTRequest","I'm an image!");
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(resEntity);
InputStream is = bufHttpEntity.getContent();
result.setResponse(BitmapFactory.decodeStream(is));
}
else
if(response.getHeaders("Content-Type")[0].getValue().contains("json")){
JSONObject json = null;
try {
String teste = EntityUtils.toString(resEntity);
android.util.Log.e("POSTRequest",teste);
json=new JSONObject(teste);
// android.util.Log.e("POSTRequest",json.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.setResponse(json);
}
else
if(response.getHeaders("Content-Type")[0].getValue().contains("text/html")){
result.setResponse(EntityUtils.toString(resEntity));
android.util.Log.e("POSTRequest",(String) result.getResponse());
}
}catch(NullPointerException e){
result.setResponse(new String("null"));
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
// protected void onPostExecute(Result result){
// android.util.Log.v("POSTRequest",String.valueOf(result.getStatus()));
// if(callback != null)
// callback.run(result);
// }
}
| true | true | protected Result doInBackground(Parameters... parameters) {
Result result = new Result();
android.util.Log.v("POSTRequest","Entered the POSTRequest");
try {
String postURL = serverAddress+parameters[0].getPath();
post = new HttpPost(postURL);
android.util.Log.e("POSTRequest",postURL);
if(parameters[0].getUserAgent().length() > 0)
post.getParams().setParameter(CoreProtocolPNames.USER_AGENT, parameters[0].getUserAgent());
//List<NameValuePair> params = new ArrayList<NameValuePair>();
MultipartEntity ent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
Charset chars = Charset.forName("UTF-8");
for (Map.Entry<String, Object> e : parameters[0].getParams().entrySet())
{
post.addHeader(e.getKey(), e.getValue().toString());
}
for (Map.Entry<String, Object> e : parameters[0].getParams().entrySet())
{
// params.add(new BasicNameValuePair(e.getKey(), e.getValue().toString()));
if(e.getValue().getClass().getSimpleName().contentEquals("File"))
ent.addPart(e.getKey(),new FileBody((File)e.getValue()));
else{
StringBody test = new StringBody(e.getValue().toString(),"text/plain",chars);
ent.addPart(e.getKey(),test);
}
}
//UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
//post.addHeader("Content-Type", "multipart/form-data");
post.setEntity(ent);
response = httpclient.execute(post,localContext);
result.setStatus(response.getStatusLine().getStatusCode());
android.util.Log.v("POSTRequest",String.valueOf(result.getStatus()));
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
try{
android.util.Log.v("POSTRequest", response.getHeaders("Content-Type")[0].getValue());
if(response.getHeaders("Content-Type")[0].getValue().contains("image")){
android.util.Log.e("POSTRequest","I'm an image!");
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(resEntity);
InputStream is = bufHttpEntity.getContent();
result.setResponse(BitmapFactory.decodeStream(is));
}
else
if(response.getHeaders("Content-Type")[0].getValue().contains("json")){
JSONObject json = null;
try {
String teste = EntityUtils.toString(resEntity);
android.util.Log.e("POSTRequest",teste);
json=new JSONObject(teste);
// android.util.Log.e("POSTRequest",json.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.setResponse(json);
}
else
if(response.getHeaders("Content-Type")[0].getValue().contains("text/html")){
result.setResponse(EntityUtils.toString(resEntity));
android.util.Log.e("POSTRequest",(String) result.getResponse());
}
}catch(NullPointerException e){
result.setResponse(new String("null"));
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
| protected Result doInBackground(Parameters... parameters) {
Result result = new Result();
android.util.Log.v("POSTRequest","Entered the POSTRequest");
try {
String postURL = serverAddress+parameters[0].getPath();
post = new HttpPost(postURL);
android.util.Log.e("POSTRequest",postURL);
if(parameters[0].getUserAgent().length() > 0)
post.getParams().setParameter(CoreProtocolPNames.USER_AGENT, parameters[0].getUserAgent());
//List<NameValuePair> params = new ArrayList<NameValuePair>();
MultipartEntity ent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
Charset chars = Charset.forName("UTF-8");
for (Map.Entry<String, Object> e : parameters[0].getHeaders().entrySet())
{
post.addHeader(e.getKey(), e.getValue().toString());
}
for (Map.Entry<String, Object> e : parameters[0].getParams().entrySet())
{
// params.add(new BasicNameValuePair(e.getKey(), e.getValue().toString()));
if(e.getValue().getClass().getSimpleName().contentEquals("File"))
ent.addPart(e.getKey(),new FileBody((File)e.getValue()));
else{
StringBody test = new StringBody(e.getValue().toString(),"text/plain",chars);
ent.addPart(e.getKey(),test);
}
}
//UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
//post.addHeader("Content-Type", "multipart/form-data");
post.setEntity(ent);
response = httpclient.execute(post,localContext);
result.setStatus(response.getStatusLine().getStatusCode());
android.util.Log.v("POSTRequest",String.valueOf(result.getStatus()));
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
try{
android.util.Log.v("POSTRequest", response.getHeaders("Content-Type")[0].getValue());
if(response.getHeaders("Content-Type")[0].getValue().contains("image")){
android.util.Log.e("POSTRequest","I'm an image!");
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(resEntity);
InputStream is = bufHttpEntity.getContent();
result.setResponse(BitmapFactory.decodeStream(is));
}
else
if(response.getHeaders("Content-Type")[0].getValue().contains("json")){
JSONObject json = null;
try {
String teste = EntityUtils.toString(resEntity);
android.util.Log.e("POSTRequest",teste);
json=new JSONObject(teste);
// android.util.Log.e("POSTRequest",json.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.setResponse(json);
}
else
if(response.getHeaders("Content-Type")[0].getValue().contains("text/html")){
result.setResponse(EntityUtils.toString(resEntity));
android.util.Log.e("POSTRequest",(String) result.getResponse());
}
}catch(NullPointerException e){
result.setResponse(new String("null"));
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
|
diff --git a/org.eclipse.virgo.kernel.osgi/src/test/java/org/eclipse/virgo/kernel/osgi/region/RegionManagerTests.java b/org.eclipse.virgo.kernel.osgi/src/test/java/org/eclipse/virgo/kernel/osgi/region/RegionManagerTests.java
index 7da5074e..d515db84 100644
--- a/org.eclipse.virgo.kernel.osgi/src/test/java/org/eclipse/virgo/kernel/osgi/region/RegionManagerTests.java
+++ b/org.eclipse.virgo.kernel.osgi/src/test/java/org/eclipse/virgo/kernel/osgi/region/RegionManagerTests.java
@@ -1,91 +1,91 @@
/*******************************************************************************
* Copyright (c) 2008, 2010 VMware Inc.
* 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:
* VMware Inc. - initial contribution
*******************************************************************************/
package org.eclipse.virgo.kernel.osgi.region;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.launch.Framework;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.framework.CompositeBundle;
import org.osgi.service.framework.CompositeBundleFactory;
import org.osgi.service.framework.SurrogateBundle;
import org.eclipse.virgo.kernel.osgi.region.RegionManager;
import org.eclipse.virgo.medic.eventlog.EventLogger;
import org.eclipse.virgo.kernel.core.Shutdown;
import org.eclipse.virgo.teststubs.osgi.framework.StubBundleContext;
import org.eclipse.virgo.teststubs.osgi.framework.StubServiceRegistration;
/**
*/
@SuppressWarnings("deprecation")
public class RegionManagerTests {
@Test
public void testStartAndStop() throws Exception {
StubBundleContext bundleContext = new StubBundleContext();
StubBundleContext surrogateBundleContext = new StubBundleContext();
Framework user = createMock(Framework.class);
SurrogateBundle surrogate = createMock(SurrogateBundle.class);
- ServiceFactory serviceFactory = createMock(ServiceFactory.class);
+ ServiceFactory<EventLogger> serviceFactory = createMock(ServiceFactory.class);
CompositeBundleFactory factory = createMock(CompositeBundleFactory.class);
CompositeBundle bundle = createMock(CompositeBundle.class);
expect(factory.installCompositeBundle(isA(Map.class), isA(String.class), isA(Map.class))).andReturn(bundle);
expect(bundle.getCompositeFramework()).andReturn(user);
bundle.start();
expect(bundle.getSurrogateBundle()).andReturn(surrogate);
expect(surrogate.getBundleContext()).andReturn(surrogateBundleContext);
EventAdmin eventAdmin = createMock(EventAdmin.class);
eventAdmin.sendEvent(isA(Event.class));
Dictionary<String, String> properties = new Hashtable<String, String>();
Configuration config = createMock(Configuration.class);
expect(config.getProperties()).andReturn(properties);
ConfigurationAdmin configAdmin = createMock(ConfigurationAdmin.class);
expect(configAdmin.getConfiguration(isA(String.class))).andReturn(config);
EventLogger eventLogger = createMock(EventLogger.class);
Shutdown shutdown = createMock(Shutdown.class);
replay(factory, bundle, surrogate, eventAdmin, configAdmin, config);
RegionManager manager = new RegionManager(bundleContext, factory, eventAdmin, serviceFactory, configAdmin, eventLogger, shutdown);
manager.start();
- List<StubServiceRegistration> serviceRegistrations = bundleContext.getServiceRegistrations();
+ List<StubServiceRegistration<Object>> serviceRegistrations = bundleContext.getServiceRegistrations();
assertEquals("Regions not registered", 2, serviceRegistrations.size());
manager.stop();
verify(factory, bundle, surrogate, eventAdmin, configAdmin, config);
}
}
| false | true | public void testStartAndStop() throws Exception {
StubBundleContext bundleContext = new StubBundleContext();
StubBundleContext surrogateBundleContext = new StubBundleContext();
Framework user = createMock(Framework.class);
SurrogateBundle surrogate = createMock(SurrogateBundle.class);
ServiceFactory serviceFactory = createMock(ServiceFactory.class);
CompositeBundleFactory factory = createMock(CompositeBundleFactory.class);
CompositeBundle bundle = createMock(CompositeBundle.class);
expect(factory.installCompositeBundle(isA(Map.class), isA(String.class), isA(Map.class))).andReturn(bundle);
expect(bundle.getCompositeFramework()).andReturn(user);
bundle.start();
expect(bundle.getSurrogateBundle()).andReturn(surrogate);
expect(surrogate.getBundleContext()).andReturn(surrogateBundleContext);
EventAdmin eventAdmin = createMock(EventAdmin.class);
eventAdmin.sendEvent(isA(Event.class));
Dictionary<String, String> properties = new Hashtable<String, String>();
Configuration config = createMock(Configuration.class);
expect(config.getProperties()).andReturn(properties);
ConfigurationAdmin configAdmin = createMock(ConfigurationAdmin.class);
expect(configAdmin.getConfiguration(isA(String.class))).andReturn(config);
EventLogger eventLogger = createMock(EventLogger.class);
Shutdown shutdown = createMock(Shutdown.class);
replay(factory, bundle, surrogate, eventAdmin, configAdmin, config);
RegionManager manager = new RegionManager(bundleContext, factory, eventAdmin, serviceFactory, configAdmin, eventLogger, shutdown);
manager.start();
List<StubServiceRegistration> serviceRegistrations = bundleContext.getServiceRegistrations();
assertEquals("Regions not registered", 2, serviceRegistrations.size());
manager.stop();
verify(factory, bundle, surrogate, eventAdmin, configAdmin, config);
}
| public void testStartAndStop() throws Exception {
StubBundleContext bundleContext = new StubBundleContext();
StubBundleContext surrogateBundleContext = new StubBundleContext();
Framework user = createMock(Framework.class);
SurrogateBundle surrogate = createMock(SurrogateBundle.class);
ServiceFactory<EventLogger> serviceFactory = createMock(ServiceFactory.class);
CompositeBundleFactory factory = createMock(CompositeBundleFactory.class);
CompositeBundle bundle = createMock(CompositeBundle.class);
expect(factory.installCompositeBundle(isA(Map.class), isA(String.class), isA(Map.class))).andReturn(bundle);
expect(bundle.getCompositeFramework()).andReturn(user);
bundle.start();
expect(bundle.getSurrogateBundle()).andReturn(surrogate);
expect(surrogate.getBundleContext()).andReturn(surrogateBundleContext);
EventAdmin eventAdmin = createMock(EventAdmin.class);
eventAdmin.sendEvent(isA(Event.class));
Dictionary<String, String> properties = new Hashtable<String, String>();
Configuration config = createMock(Configuration.class);
expect(config.getProperties()).andReturn(properties);
ConfigurationAdmin configAdmin = createMock(ConfigurationAdmin.class);
expect(configAdmin.getConfiguration(isA(String.class))).andReturn(config);
EventLogger eventLogger = createMock(EventLogger.class);
Shutdown shutdown = createMock(Shutdown.class);
replay(factory, bundle, surrogate, eventAdmin, configAdmin, config);
RegionManager manager = new RegionManager(bundleContext, factory, eventAdmin, serviceFactory, configAdmin, eventLogger, shutdown);
manager.start();
List<StubServiceRegistration<Object>> serviceRegistrations = bundleContext.getServiceRegistrations();
assertEquals("Regions not registered", 2, serviceRegistrations.size());
manager.stop();
verify(factory, bundle, surrogate, eventAdmin, configAdmin, config);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.