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/rivr-voicexml/src/main/java/com/nuecho/rivr/voicexml/servlet/DefaultVoiceXmlRootDocumentFactory.java b/rivr-voicexml/src/main/java/com/nuecho/rivr/voicexml/servlet/DefaultVoiceXmlRootDocumentFactory.java
index 0c7969b..7b9c0d4 100644
--- a/rivr-voicexml/src/main/java/com/nuecho/rivr/voicexml/servlet/DefaultVoiceXmlRootDocumentFactory.java
+++ b/rivr-voicexml/src/main/java/com/nuecho/rivr/voicexml/servlet/DefaultVoiceXmlRootDocumentFactory.java
@@ -1,53 +1,53 @@
/*
* Copyright (c) 2013 Nu Echo Inc. All rights reserved.
*/
package com.nuecho.rivr.voicexml.servlet;
import static com.nuecho.rivr.voicexml.rendering.voicexml.VoiceXmlDomUtil.*;
import javax.servlet.http.*;
import org.w3c.dom.*;
import com.nuecho.rivr.core.servlet.session.*;
import com.nuecho.rivr.core.util.*;
import com.nuecho.rivr.voicexml.rendering.voicexml.*;
import com.nuecho.rivr.voicexml.turn.first.*;
import com.nuecho.rivr.voicexml.turn.input.*;
import com.nuecho.rivr.voicexml.turn.last.*;
import com.nuecho.rivr.voicexml.turn.output.*;
/**
* @author Nu Echo Inc.
*/
public class DefaultVoiceXmlRootDocumentFactory implements VoiceXmlRootDocumentFactory {
@Override
public Document getDocument(HttpServletRequest request,
Session<VoiceXmlInputTurn, VoiceXmlOutputTurn, VoiceXmlFirstTurn, VoiceXmlLastTurn, VoiceXmlDialogueContext> session) {
VoiceXmlDialogueContext dialogueContext = session.getDialogueContext();
String contextPath = dialogueContext.getContextPath();
String servletPath = dialogueContext.getServletPath();
String sessionId = session.getId();
return createElement(contextPath, servletPath, sessionId, dialogueContext);
}
protected Document createElement(String contextPath,
String servletPath,
String sessionId,
VoiceXmlDialogueContext dialogueContext) {
Element vxmlElement = createVoiceXmlDocumentRoot(dialogueContext);
- createVarElement(vxmlElement, RIVR_VARIABLE, "{\"" + RIVR_DIALOGUE_ID_PROPERTY + "\": \"" + sessionId + "\"}");
+ createVarElement(vxmlElement, RIVR_VARIABLE, "({\"" + RIVR_DIALOGUE_ID_PROPERTY + "\": \"" + sessionId + "\"})");
addScript(vxmlElement, VoiceXmlDialogueServlet.RIVR_SCRIPT, contextPath + servletPath);
return vxmlElement.getOwnerDocument();
}
private static void addScript(Element parent, String scriptPath, String contextPath) {
Element scriptElement = DomUtils.appendNewElement(parent, SCRIPT_ELEMENT);
scriptElement.setAttribute(SRC_ATTRIBUTE, contextPath + scriptPath);
}
}
| true | true | protected Document createElement(String contextPath,
String servletPath,
String sessionId,
VoiceXmlDialogueContext dialogueContext) {
Element vxmlElement = createVoiceXmlDocumentRoot(dialogueContext);
createVarElement(vxmlElement, RIVR_VARIABLE, "{\"" + RIVR_DIALOGUE_ID_PROPERTY + "\": \"" + sessionId + "\"}");
addScript(vxmlElement, VoiceXmlDialogueServlet.RIVR_SCRIPT, contextPath + servletPath);
return vxmlElement.getOwnerDocument();
}
| protected Document createElement(String contextPath,
String servletPath,
String sessionId,
VoiceXmlDialogueContext dialogueContext) {
Element vxmlElement = createVoiceXmlDocumentRoot(dialogueContext);
createVarElement(vxmlElement, RIVR_VARIABLE, "({\"" + RIVR_DIALOGUE_ID_PROPERTY + "\": \"" + sessionId + "\"})");
addScript(vxmlElement, VoiceXmlDialogueServlet.RIVR_SCRIPT, contextPath + servletPath);
return vxmlElement.getOwnerDocument();
}
|
diff --git a/astrid/src/com/todoroo/astrid/widget/TasksWidget.java b/astrid/src/com/todoroo/astrid/widget/TasksWidget.java
index a6b869eb2..a38b28821 100644
--- a/astrid/src/com/todoroo/astrid/widget/TasksWidget.java
+++ b/astrid/src/com/todoroo/astrid/widget/TasksWidget.java
@@ -1,259 +1,260 @@
package com.todoroo.astrid.widget;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.RemoteViews;
import com.timsu.astrid.R;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.utility.AndroidUtilities;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.activity.TaskEditActivity;
import com.todoroo.astrid.activity.TaskListActivity;
import com.todoroo.astrid.api.Filter;
import com.todoroo.astrid.core.CoreFilterExposer;
import com.todoroo.astrid.core.SortHelper;
import com.todoroo.astrid.dao.Database;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.service.AstridDependencyInjector;
import com.todoroo.astrid.service.TaskService;
import com.todoroo.astrid.utility.AstridPreferences;
public class TasksWidget extends AppWidgetProvider {
static {
AstridDependencyInjector.initialize();
}
public final static int[] TEXT_IDS = { R.id.task_1, R.id.task_2,
R.id.task_3, R.id.task_4, R.id.task_5 };
public final static int[] SEPARATOR_IDS = { R.id.separator_1,
R.id.separator_2, R.id.separator_3, R.id.separator_4 };
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
try {
ContextManager.setContext(context);
super.onUpdate(context, appWidgetManager, appWidgetIds);
// Start in service to prevent Application Not Responding timeout
updateWidgets(context);
} catch (Exception e) {
Log.e("astrid-update-widget", "widget update error", e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Update all widgets
* @param id
*/
public static void updateWidgets(Context context) {
context.startService(new Intent(context,
TasksWidget.UpdateService.class));
}
/**
* Update widget with the given id
* @param id
*/
public static void updateWidget(Context context, int id) {
Intent intent = new Intent(ContextManager.getContext(),
TasksWidget.UpdateService.class);
intent.putExtra(UpdateService.EXTRA_WIDGET_ID, id);
context.startService(intent);
}
public static class ConfigActivity extends WidgetConfigActivity {
@Override
public void updateWidget() {
TasksWidget.updateWidget(this, mAppWidgetId);
}
}
public static class UpdateService extends Service {
public static String EXTRA_WIDGET_ID = "widget_id"; //$NON-NLS-1$
@Autowired
Database database;
@Autowired
TaskService taskService;
@Override
public void onStart(final Intent intent, int startId) {
ContextManager.setContext(this);
new Thread(new Runnable() {
@Override
public void run() {
startServiceInBackgroundThread(intent);
}
}).start();
}
public void startServiceInBackgroundThread(Intent intent) {
ComponentName thisWidget = new ComponentName(this,
TasksWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
int extrasId = AppWidgetManager.INVALID_APPWIDGET_ID;
if(intent != null)
extrasId = intent.getIntExtra(EXTRA_WIDGET_ID, extrasId);
if(extrasId == AppWidgetManager.INVALID_APPWIDGET_ID) {
for(int id : manager.getAppWidgetIds(thisWidget)) {
RemoteViews updateViews = buildUpdate(this, id);
manager.updateAppWidget(id, updateViews);
}
} else {
int id = extrasId;
RemoteViews updateViews = buildUpdate(this, id);
manager.updateAppWidget(id, updateViews);
}
stopSelf();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressWarnings("nls")
public RemoteViews buildUpdate(Context context, int widgetId) {
DependencyInjectionService.getInstance().inject(this);
RemoteViews views = null;
views = new RemoteViews(context.getPackageName(),
R.layout.widget_initialized);
int[] textIDs = TEXT_IDS;
int[] separatorIDs = SEPARATOR_IDS;
int numberOfTasks = 5;
for(int i = 0; i < textIDs.length; i++)
views.setTextViewText(textIDs[i], "");
TodorooCursor<Task> cursor = null;
Filter filter = null;
try {
filter = getFilter(widgetId);
views.setTextViewText(R.id.widget_title, filter.title);
SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(this);
int flags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0);
int sort = publicPrefs.getInt(SortHelper.PREF_SORT_SORT, 0);
+ // FIXME: Hotfix for task limit in recently modified tasks-filter
String query = SortHelper.adjustQueryForFlagsAndSort(
- filter.sqlQuery, flags, sort) + " LIMIT " + numberOfTasks;
+ filter.sqlQuery, flags, sort).replaceAll("LIMIT 15", "") + " LIMIT " + numberOfTasks;
database.openForReading();
cursor = taskService.fetchFiltered(query, null, Task.ID, Task.TITLE, Task.DUE_DATE, Task.COMPLETION_DATE);
Task task = new Task();
for (int i = 0; i < cursor.getCount() && i < numberOfTasks; i++) {
cursor.moveToPosition(i);
task.readFromCursor(cursor);
String textContent = "";
int textColor = Color.WHITE;
textContent = task.getValue(Task.TITLE);
if(task.isCompleted())
textColor = context.getResources().getColor(R.color.task_list_done);
else if(task.hasDueDate() && task.getValue(Task.DUE_DATE) < DateUtilities.now())
textColor = context.getResources().getColor(R.color.task_list_overdue);
if(i > 0)
views.setViewVisibility(separatorIDs[i-1], View.VISIBLE);
views.setTextViewText(textIDs[i], textContent);
views.setTextColor(textIDs[i], textColor);
}
for(int i = cursor.getCount() - 1; i < separatorIDs.length; i++) {
if(i >= 0)
views.setViewVisibility(separatorIDs[i], View.INVISIBLE);
}
} catch (Exception e) {
// can happen if database is not ready
Log.e("WIDGET-UPDATE", "Error updating widget", e);
} finally {
if(cursor != null)
cursor.close();
}
updateForScreenSize(views);
Intent listIntent = new Intent(context, TaskListActivity.class);
listIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
if(filter != null) {
listIntent.putExtra(TaskListActivity.TOKEN_FILTER, filter);
listIntent.setType(filter.sqlQuery);
}
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
listIntent, 0);
views.setOnClickPendingIntent(R.id.taskbody, pendingIntent);
Intent editIntent = new Intent(context, TaskEditActivity.class);
editIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
if(filter != null && filter.valuesForNewTasks != null) {
String values = AndroidUtilities.contentValuesToSerializedString(filter.valuesForNewTasks);
editIntent.putExtra(TaskEditActivity.TOKEN_VALUES, values);
editIntent.setType(values);
}
pendingIntent = PendingIntent.getActivity(context, 0,
editIntent, 0);
views.setOnClickPendingIntent(R.id.widget_button, pendingIntent);
return views;
}
private void updateForScreenSize(RemoteViews views) {
Display display = ((WindowManager) this.getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
if(metrics.density <= 0.75) {
views.setViewVisibility(SEPARATOR_IDS[3], View.INVISIBLE);
views.setViewVisibility(TEXT_IDS[4], View.INVISIBLE);
}
}
private Filter getFilter(int widgetId) {
// base our filter off the inbox filter, replace stuff if we have it
Filter filter = CoreFilterExposer.buildInboxFilter(getResources());
String sql = Preferences.getStringValue(WidgetConfigActivity.PREF_SQL + widgetId);
if(sql != null)
filter.sqlQuery = sql;
String title = Preferences.getStringValue(WidgetConfigActivity.PREF_TITLE + widgetId);
if(title != null)
filter.title = title;
String contentValues = Preferences.getStringValue(WidgetConfigActivity.PREF_VALUES + widgetId);
if(contentValues != null)
filter.valuesForNewTasks = AndroidUtilities.contentValuesFromSerializedString(contentValues);
return filter;
}
}
}
| false | true | public RemoteViews buildUpdate(Context context, int widgetId) {
DependencyInjectionService.getInstance().inject(this);
RemoteViews views = null;
views = new RemoteViews(context.getPackageName(),
R.layout.widget_initialized);
int[] textIDs = TEXT_IDS;
int[] separatorIDs = SEPARATOR_IDS;
int numberOfTasks = 5;
for(int i = 0; i < textIDs.length; i++)
views.setTextViewText(textIDs[i], "");
TodorooCursor<Task> cursor = null;
Filter filter = null;
try {
filter = getFilter(widgetId);
views.setTextViewText(R.id.widget_title, filter.title);
SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(this);
int flags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0);
int sort = publicPrefs.getInt(SortHelper.PREF_SORT_SORT, 0);
String query = SortHelper.adjustQueryForFlagsAndSort(
filter.sqlQuery, flags, sort) + " LIMIT " + numberOfTasks;
database.openForReading();
cursor = taskService.fetchFiltered(query, null, Task.ID, Task.TITLE, Task.DUE_DATE, Task.COMPLETION_DATE);
Task task = new Task();
for (int i = 0; i < cursor.getCount() && i < numberOfTasks; i++) {
cursor.moveToPosition(i);
task.readFromCursor(cursor);
String textContent = "";
int textColor = Color.WHITE;
textContent = task.getValue(Task.TITLE);
if(task.isCompleted())
textColor = context.getResources().getColor(R.color.task_list_done);
else if(task.hasDueDate() && task.getValue(Task.DUE_DATE) < DateUtilities.now())
textColor = context.getResources().getColor(R.color.task_list_overdue);
if(i > 0)
views.setViewVisibility(separatorIDs[i-1], View.VISIBLE);
views.setTextViewText(textIDs[i], textContent);
views.setTextColor(textIDs[i], textColor);
}
for(int i = cursor.getCount() - 1; i < separatorIDs.length; i++) {
if(i >= 0)
views.setViewVisibility(separatorIDs[i], View.INVISIBLE);
}
} catch (Exception e) {
// can happen if database is not ready
Log.e("WIDGET-UPDATE", "Error updating widget", e);
} finally {
if(cursor != null)
cursor.close();
}
updateForScreenSize(views);
Intent listIntent = new Intent(context, TaskListActivity.class);
listIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
if(filter != null) {
listIntent.putExtra(TaskListActivity.TOKEN_FILTER, filter);
listIntent.setType(filter.sqlQuery);
}
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
listIntent, 0);
views.setOnClickPendingIntent(R.id.taskbody, pendingIntent);
Intent editIntent = new Intent(context, TaskEditActivity.class);
editIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
if(filter != null && filter.valuesForNewTasks != null) {
String values = AndroidUtilities.contentValuesToSerializedString(filter.valuesForNewTasks);
editIntent.putExtra(TaskEditActivity.TOKEN_VALUES, values);
editIntent.setType(values);
}
pendingIntent = PendingIntent.getActivity(context, 0,
editIntent, 0);
views.setOnClickPendingIntent(R.id.widget_button, pendingIntent);
return views;
}
| public RemoteViews buildUpdate(Context context, int widgetId) {
DependencyInjectionService.getInstance().inject(this);
RemoteViews views = null;
views = new RemoteViews(context.getPackageName(),
R.layout.widget_initialized);
int[] textIDs = TEXT_IDS;
int[] separatorIDs = SEPARATOR_IDS;
int numberOfTasks = 5;
for(int i = 0; i < textIDs.length; i++)
views.setTextViewText(textIDs[i], "");
TodorooCursor<Task> cursor = null;
Filter filter = null;
try {
filter = getFilter(widgetId);
views.setTextViewText(R.id.widget_title, filter.title);
SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(this);
int flags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0);
int sort = publicPrefs.getInt(SortHelper.PREF_SORT_SORT, 0);
// FIXME: Hotfix for task limit in recently modified tasks-filter
String query = SortHelper.adjustQueryForFlagsAndSort(
filter.sqlQuery, flags, sort).replaceAll("LIMIT 15", "") + " LIMIT " + numberOfTasks;
database.openForReading();
cursor = taskService.fetchFiltered(query, null, Task.ID, Task.TITLE, Task.DUE_DATE, Task.COMPLETION_DATE);
Task task = new Task();
for (int i = 0; i < cursor.getCount() && i < numberOfTasks; i++) {
cursor.moveToPosition(i);
task.readFromCursor(cursor);
String textContent = "";
int textColor = Color.WHITE;
textContent = task.getValue(Task.TITLE);
if(task.isCompleted())
textColor = context.getResources().getColor(R.color.task_list_done);
else if(task.hasDueDate() && task.getValue(Task.DUE_DATE) < DateUtilities.now())
textColor = context.getResources().getColor(R.color.task_list_overdue);
if(i > 0)
views.setViewVisibility(separatorIDs[i-1], View.VISIBLE);
views.setTextViewText(textIDs[i], textContent);
views.setTextColor(textIDs[i], textColor);
}
for(int i = cursor.getCount() - 1; i < separatorIDs.length; i++) {
if(i >= 0)
views.setViewVisibility(separatorIDs[i], View.INVISIBLE);
}
} catch (Exception e) {
// can happen if database is not ready
Log.e("WIDGET-UPDATE", "Error updating widget", e);
} finally {
if(cursor != null)
cursor.close();
}
updateForScreenSize(views);
Intent listIntent = new Intent(context, TaskListActivity.class);
listIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
if(filter != null) {
listIntent.putExtra(TaskListActivity.TOKEN_FILTER, filter);
listIntent.setType(filter.sqlQuery);
}
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
listIntent, 0);
views.setOnClickPendingIntent(R.id.taskbody, pendingIntent);
Intent editIntent = new Intent(context, TaskEditActivity.class);
editIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
if(filter != null && filter.valuesForNewTasks != null) {
String values = AndroidUtilities.contentValuesToSerializedString(filter.valuesForNewTasks);
editIntent.putExtra(TaskEditActivity.TOKEN_VALUES, values);
editIntent.setType(values);
}
pendingIntent = PendingIntent.getActivity(context, 0,
editIntent, 0);
views.setOnClickPendingIntent(R.id.widget_button, pendingIntent);
return views;
}
|
diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/cache/database/ChecksumExtractor.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/cache/database/ChecksumExtractor.java
index 7851716d..92bda68b 100644
--- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/cache/database/ChecksumExtractor.java
+++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/cache/database/ChecksumExtractor.java
@@ -1,302 +1,305 @@
/*
* #%L
* Bitrepository Reference Pillar
* %%
* Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
package org.bitrepository.pillar.cache.database;
import static org.bitrepository.pillar.cache.database.DatabaseConstants.CHECKSUM_TABLE;
import static org.bitrepository.pillar.cache.database.DatabaseConstants.CS_CHECKSUM;
import static org.bitrepository.pillar.cache.database.DatabaseConstants.CS_DATE;
import static org.bitrepository.pillar.cache.database.DatabaseConstants.CS_FILE_ID;
import static org.bitrepository.pillar.cache.database.DatabaseConstants.CS_COLLECTION_ID;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.bitrepository.common.ArgumentValidator;
import org.bitrepository.common.utils.CalendarUtils;
import org.bitrepository.pillar.cache.ChecksumEntry;
import org.bitrepository.service.database.DBConnector;
import org.bitrepository.service.database.DatabaseUtils;
/**
* Extracts data from the checksum database.
*/
public class ChecksumExtractor {
/** The connector for the database.*/
private final DBConnector connector;
/**
* Constructor.
* @param connector The connector for the database.
*/
public ChecksumExtractor(DBConnector connector) {
ArgumentValidator.checkNotNull(connector, "DBConnector connector");
this.connector = connector;
}
/**
* Extracts the date for a given file.
* @param fileId The id of the file to extract the date for.
* @param collectionId The collection id for the file.
* @return The date for the given file.
*/
public Date extractDateForFile(String fileId, String collectionId) {
ArgumentValidator.checkNotNullOrEmpty(fileId, "String fileId");
String sql = "SELECT " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND "
+ CS_COLLECTION_ID + " = ?";
return DatabaseUtils.selectDateValue(connector, sql, fileId, collectionId);
}
/**
* Extracts the checksum for a given file.
* @param fileId The id of the file to extract the checksum for.
* @param collectionId The collection id for the file.
* @return The checksum for the given file.
*/
public String extractChecksumForFile(String fileId, String collectionId) {
ArgumentValidator.checkNotNullOrEmpty(fileId, "String fileId");
String sql = "SELECT " + CS_CHECKSUM + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND "
+ CS_COLLECTION_ID + " = ?";
return DatabaseUtils.selectStringValue(connector, sql, fileId, collectionId);
}
/**
* Extracts whether a given file exists.
* @param fileId The id of the file to extract whose existence is in question.
* @param collectionId The collection id for the file.
* @return Whether the given file exists.
*/
public boolean hasFile(String fileId, String collectionId) {
ArgumentValidator.checkNotNullOrEmpty(fileId, "String fileId");
String sql = "SELECT COUNT(*) FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND "
+ CS_COLLECTION_ID + " = ?";
return DatabaseUtils.selectIntValue(connector, sql, fileId, collectionId) != 0;
}
/**
* Extracts the checksum entry for a single file.
* @param fileId The id of the file whose checksum entry should be extracted.
* @param collectionId The collection id for the extraction.
* @return The checksum entry for the file.
*/
public ChecksumEntry extractSingleEntry(String fileId, String collectionId) {
ArgumentValidator.checkNotNullOrEmpty(fileId, "String fileId");
String sql = "SELECT " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE
+ " WHERE " + CS_FILE_ID + " = ? AND " + CS_COLLECTION_ID + " = ?";
try {
PreparedStatement ps = null;
ResultSet res = null;
Connection conn = null;
try {
conn = connector.getConnection();
ps = DatabaseUtils.createPreparedStatement(conn, sql, fileId, collectionId);
res = ps.executeQuery();
if(!res.next()) {
throw new IllegalStateException("No entry for the file '" + fileId + "'.");
}
return extractChecksumEntry(res);
} finally {
if(res != null) {
res.close();
}
if(ps != null) {
ps.close();
}
if(conn != null) {
conn.close();
}
}
} catch (SQLException e) {
throw new IllegalStateException("Cannot extract the ChecksumEntry for '" + fileId + "'", e);
}
}
/**
* Extracts the file ids within the given optional limitations.
*
* @param minTimeStamp The minimum date for the timestamp of the extracted file ids.
* @param maxTimeStamp The maximum date for the timestamp of the extracted file ids.
* @param maxNumberOfResults The maximum number of results.
* @param collectionId The collection id for the extraction.
* @return The requested collection of file ids.
*/
public ExtractedFileIDsResultSet getFileIDs(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp,
Long maxNumberOfResults, String collectionId) {
List<Object> args = new ArrayList<Object>();
StringBuilder sql = new StringBuilder();
sql.append("SELECT " + CS_FILE_ID + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_COLLECTION_ID
+ " = ?");
args.add(collectionId);
if(minTimeStamp != null) {
sql.append(" AND " + CS_DATE + " > ? ");
args.add(CalendarUtils.convertFromXMLGregorianCalendar(minTimeStamp));
}
if(maxTimeStamp != null) {
sql.append(" AND " + CS_DATE + " <= ? ");
args.add(CalendarUtils.convertFromXMLGregorianCalendar(maxTimeStamp));
}
sql.append(" ORDER BY " + CS_DATE + " ASC ");
ExtractedFileIDsResultSet results = new ExtractedFileIDsResultSet();
try {
PreparedStatement ps = null;
ResultSet res = null;
Connection conn = null;
try {
conn = connector.getConnection();
ps = DatabaseUtils.createPreparedStatement(conn, sql.toString(), args.toArray());
+ conn.setAutoCommit(false);
+ ps.setFetchSize(100);
res = ps.executeQuery();
int i = 0;
while(res.next() && (maxNumberOfResults == null || i < maxNumberOfResults)) {
results.insertFileID(res.getString(1), res.getTimestamp(2));
i++;
}
if(maxNumberOfResults != null && i >= maxNumberOfResults) {
results.reportMoreEntriesFound();
}
} finally {
if(res != null) {
res.close();
}
if(ps != null) {
ps.close();
}
if(conn != null) {
+ conn.setAutoCommit(true);
conn.close();
}
}
} catch (SQLException e) {
throw new IllegalStateException("Cannot extract the file ids with the arguments, minTimestamp = '"
+ minTimeStamp + "', maxTimestamp = '"+ maxTimeStamp + "', maxNumberOfResults = '"
+ maxNumberOfResults + "'", e);
}
return results;
}
/**
* Retrieves all the file ids for a given collection id within the database.
* @param collectionId The collection id for the extraction.
* @return The list of file ids extracted from the database.
*/
public List<String> extractAllFileIDs(String collectionId) {
String sql = "SELECT " + CS_FILE_ID + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_COLLECTION_ID + " = ?";
return DatabaseUtils.selectStringList(connector, sql, collectionId);
}
/**
* Extracts the checksum entries within the given optional limitations.
*
* @param minTimeStamp The minimum date for the timestamp of the extracted checksum entries.
* @param maxTimeStamp The maximum date for the timestamp of the extracted checksum entries.
* @param maxNumberOfResults The maximum number of results.
* @param collectionId The collection id for the extraction.
* @return The requested collection of file ids.
*/
public ExtractedChecksumResultSet extractEntries(XMLGregorianCalendar minTimeStamp,
XMLGregorianCalendar maxTimeStamp, Long maxNumberOfResults, String collectionId) {
List<Object> args = new ArrayList<Object>();
StringBuilder sql = new StringBuilder();
sql.append("SELECT " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE
+ " WHERE " + CS_COLLECTION_ID + " = ?");
args.add(collectionId);
if(minTimeStamp != null) {
sql.append(" AND " + CS_DATE + " >= ? ");
args.add(CalendarUtils.convertFromXMLGregorianCalendar(minTimeStamp));
}
if(maxTimeStamp != null) {
sql.append(" AND " + CS_DATE + " <= ? ");
args.add(CalendarUtils.convertFromXMLGregorianCalendar(maxTimeStamp));
}
sql.append(" ORDER BY " + CS_DATE + " ASC ");
ExtractedChecksumResultSet results = new ExtractedChecksumResultSet();
try {
PreparedStatement ps = null;
ResultSet res = null;
Connection conn = null;
try {
conn = connector.getConnection();
ps = DatabaseUtils.createPreparedStatement(conn, sql.toString(), args.toArray());
res = ps.executeQuery();
int i = 0;
while(res.next() && (maxNumberOfResults == null || i < maxNumberOfResults)) {
results.insertChecksumEntry(extractChecksumEntry(res));
i++;
}
if(maxNumberOfResults != null && i >= maxNumberOfResults) {
results.reportMoreEntriesFound();
}
} finally {
if(res != null) {
res.close();
}
if(ps != null) {
ps.close();
}
if(conn != null) {
conn.close();
}
}
} catch (SQLException e) {
throw new IllegalStateException("Cannot extract the checksum entries with the arguments, minTimestamp = '"
+ minTimeStamp + "', maxTimestamp = '"+ maxTimeStamp + "', maxNumberOfResults = '"
+ maxNumberOfResults + "'", e);
}
return results;
}
/**
* Extracts a checksum entry from a result set.
* The result set needs to have requested the elements in the right order:
* - File id.
* - Checksum.
* - Date.
*
* @param resSet The resultset from the database.
* @return The checksum entry extracted from the result set.
*/
private ChecksumEntry extractChecksumEntry(ResultSet resSet) throws SQLException {
String fileId = resSet.getString(1);
String checksum = resSet.getString(2);
Date date = resSet.getTimestamp(3);
return new ChecksumEntry(fileId, checksum, date);
}
}
| false | true | public ExtractedFileIDsResultSet getFileIDs(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp,
Long maxNumberOfResults, String collectionId) {
List<Object> args = new ArrayList<Object>();
StringBuilder sql = new StringBuilder();
sql.append("SELECT " + CS_FILE_ID + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_COLLECTION_ID
+ " = ?");
args.add(collectionId);
if(minTimeStamp != null) {
sql.append(" AND " + CS_DATE + " > ? ");
args.add(CalendarUtils.convertFromXMLGregorianCalendar(minTimeStamp));
}
if(maxTimeStamp != null) {
sql.append(" AND " + CS_DATE + " <= ? ");
args.add(CalendarUtils.convertFromXMLGregorianCalendar(maxTimeStamp));
}
sql.append(" ORDER BY " + CS_DATE + " ASC ");
ExtractedFileIDsResultSet results = new ExtractedFileIDsResultSet();
try {
PreparedStatement ps = null;
ResultSet res = null;
Connection conn = null;
try {
conn = connector.getConnection();
ps = DatabaseUtils.createPreparedStatement(conn, sql.toString(), args.toArray());
res = ps.executeQuery();
int i = 0;
while(res.next() && (maxNumberOfResults == null || i < maxNumberOfResults)) {
results.insertFileID(res.getString(1), res.getTimestamp(2));
i++;
}
if(maxNumberOfResults != null && i >= maxNumberOfResults) {
results.reportMoreEntriesFound();
}
} finally {
if(res != null) {
res.close();
}
if(ps != null) {
ps.close();
}
if(conn != null) {
conn.close();
}
}
} catch (SQLException e) {
throw new IllegalStateException("Cannot extract the file ids with the arguments, minTimestamp = '"
+ minTimeStamp + "', maxTimestamp = '"+ maxTimeStamp + "', maxNumberOfResults = '"
+ maxNumberOfResults + "'", e);
}
return results;
}
| public ExtractedFileIDsResultSet getFileIDs(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp,
Long maxNumberOfResults, String collectionId) {
List<Object> args = new ArrayList<Object>();
StringBuilder sql = new StringBuilder();
sql.append("SELECT " + CS_FILE_ID + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_COLLECTION_ID
+ " = ?");
args.add(collectionId);
if(minTimeStamp != null) {
sql.append(" AND " + CS_DATE + " > ? ");
args.add(CalendarUtils.convertFromXMLGregorianCalendar(minTimeStamp));
}
if(maxTimeStamp != null) {
sql.append(" AND " + CS_DATE + " <= ? ");
args.add(CalendarUtils.convertFromXMLGregorianCalendar(maxTimeStamp));
}
sql.append(" ORDER BY " + CS_DATE + " ASC ");
ExtractedFileIDsResultSet results = new ExtractedFileIDsResultSet();
try {
PreparedStatement ps = null;
ResultSet res = null;
Connection conn = null;
try {
conn = connector.getConnection();
ps = DatabaseUtils.createPreparedStatement(conn, sql.toString(), args.toArray());
conn.setAutoCommit(false);
ps.setFetchSize(100);
res = ps.executeQuery();
int i = 0;
while(res.next() && (maxNumberOfResults == null || i < maxNumberOfResults)) {
results.insertFileID(res.getString(1), res.getTimestamp(2));
i++;
}
if(maxNumberOfResults != null && i >= maxNumberOfResults) {
results.reportMoreEntriesFound();
}
} finally {
if(res != null) {
res.close();
}
if(ps != null) {
ps.close();
}
if(conn != null) {
conn.setAutoCommit(true);
conn.close();
}
}
} catch (SQLException e) {
throw new IllegalStateException("Cannot extract the file ids with the arguments, minTimestamp = '"
+ minTimeStamp + "', maxTimestamp = '"+ maxTimeStamp + "', maxNumberOfResults = '"
+ maxNumberOfResults + "'", e);
}
return results;
}
|
diff --git a/src/main/java/org/oztrack/view/OaiPmhRecordWriter.java b/src/main/java/org/oztrack/view/OaiPmhRecordWriter.java
index f7341d5a..606ba553 100644
--- a/src/main/java/org/oztrack/view/OaiPmhRecordWriter.java
+++ b/src/main/java/org/oztrack/view/OaiPmhRecordWriter.java
@@ -1,439 +1,439 @@
package org.oztrack.view;
import static org.oztrack.util.OaiPmhConstants.DC;
import static org.oztrack.util.OaiPmhConstants.OAI_DC;
import static org.oztrack.util.OaiPmhConstants.RIF_CS;
import static org.oztrack.util.OaiPmhConstants.XSI;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.lang3.StringUtils;
import org.oztrack.data.access.OaiPmhEntityProducer;
import org.oztrack.data.model.types.OaiPmhRecord;
import org.oztrack.data.model.types.OaiPmhRecord.Name.NamePart;
import org.oztrack.util.OaiPmhMetadataFormat;
public class OaiPmhRecordWriter {
private SimpleDateFormat utcDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
private final XMLStreamWriter out;
private final OaiPmhMetadataFormat metadataFormat;
private final boolean headerOnly;
public OaiPmhRecordWriter(XMLStreamWriter out, OaiPmhMetadataFormat metadataFormat, boolean headerOnly) {
this.out = out;
this.metadataFormat = metadataFormat;
this.headerOnly = headerOnly;
}
public void write(OaiPmhEntityProducer<OaiPmhRecord> producer) throws XMLStreamException {
for (OaiPmhRecord record : producer) {
write(record);
}
}
private void write(OaiPmhRecord record) throws XMLStreamException {
if (StringUtils.isBlank(record.getOaiPmhRecordIdentifier())) {
throw new IllegalArgumentException("Record must have OAI-PMH identifier");
}
if (!headerOnly) {
out.writeStartElement("record");
}
out.writeStartElement("header");
// A unique identifier unambiguously identifies an item within a repository.
// The format of the unique identifier must correspond to that of the URI syntax.
// http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm#UniqueIdentifier
out.writeStartElement("identifier");
out.writeCharacters(record.getOaiPmhRecordIdentifier());
out.writeEndElement(); // identifier
// Date of creation, modification or deletion of the record for the purpose of selective harvesting.
// http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm#Record
Date datestampDate =
(record.getRecordUpdateDate() != null) ? record.getRecordUpdateDate() :
(record.getRecordCreateDate() != null) ? record.getRecordCreateDate() :
null;
if (datestampDate != null) {
out.writeStartElement("datestamp");
out.writeCharacters(utcDateTimeFormat.format(datestampDate));
out.writeEndElement(); // datestamp
}
out.writeEndElement(); // header
if (!headerOnly) {
out.writeStartElement("metadata");
if (metadataFormat.equals(OAI_DC)) {
writeOaiDcRepositoryMetadataElement(record);
}
else if (metadataFormat.equals(RIF_CS)) {
writeRifCsRepositoryMetadataElement(record);
}
out.writeEndElement(); // metadata
}
if (!headerOnly) {
out.writeEndElement(); // record
}
}
private void writeOaiDcRepositoryMetadataElement(OaiPmhRecord record) throws XMLStreamException {
out.writeStartElement(OAI_DC.nsPrefix, "dc", OAI_DC.nsUri);
// Every metadata part must include xmlns attributes for its metadata formats.
// http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm#Record
out.setPrefix(OAI_DC.nsPrefix, OAI_DC.nsUri);
out.writeNamespace(OAI_DC.nsPrefix, OAI_DC.nsUri);
out.setPrefix(DC.nsPrefix, DC.nsUri);
out.writeNamespace(DC.nsPrefix, DC.nsUri);
// Every metadata part must include the attributes xmlns:xsi (namespace URI for XML schema) and
// xsi:schemaLocation (namespace URI and XML schema URL for validating metadata that follows).
// http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm#Record
out.setPrefix(XSI.nsPrefix, XSI.nsUri);
out.writeNamespace(XSI.nsPrefix, XSI.nsUri);
out.writeAttribute(XSI.nsUri, "schemaLocation", OAI_DC.nsUri + " " + OAI_DC.xsdUri);
if (StringUtils.isNotBlank(record.getObjectIdentifier())) {
out.writeStartElement(DC.nsUri, "identifier");
out.writeCharacters(record.getObjectIdentifier());
out.writeEndElement(); // identifier
}
Transformer namePartToTextTransformer = new Transformer() {
@Override
public Object transform(Object input) {
return ((OaiPmhRecord.Name.NamePart) input).getNamePartText();
}
};
String title = StringUtils.join(CollectionUtils.collect(record.getName().getNameParts(), namePartToTextTransformer), " ");
if (StringUtils.isNotBlank(title)) {
out.writeStartElement(DC.nsUri, "title");
out.writeCharacters(title);
out.writeEndElement(); // title
}
if (StringUtils.isNotBlank(record.getDescription())) {
out.writeStartElement(DC.nsUri, "description");
out.writeCharacters(record.getDescription());
out.writeEndElement(); // description
}
if (StringUtils.isNotBlank(record.getCreator())) {
out.writeStartElement(DC.nsUri, "creator");
out.writeCharacters(record.getCreator());
out.writeEndElement(); // creator
}
if (record.getRecordCreateDate() != null) {
out.writeStartElement(DC.nsUri, "created");
out.writeCharacters(utcDateTimeFormat.format(record.getRecordCreateDate()));
out.writeEndElement(); // created
}
if (record.getRecordUpdateDate() != null) {
out.writeStartElement(DC.nsUri, "date");
out.writeCharacters(utcDateTimeFormat.format(record.getRecordUpdateDate()));
out.writeEndElement(); // date
}
if (record.getSpatialCoverage() != null) {
out.writeStartElement(DC.nsUri, "coverage");
out.writeCharacters("North " + record.getSpatialCoverage().getMaxY() + ", ");
out.writeCharacters("East " + record.getSpatialCoverage().getMaxX() + ", ");
out.writeCharacters("South " + record.getSpatialCoverage().getMinY() + ", ");
out.writeCharacters("West " + record.getSpatialCoverage().getMinX() + ".");
out.writeEndElement(); // coverage
}
if (StringUtils.isNotBlank(record.getAccessRights())) {
out.writeStartElement(DC.nsUri, "accessRights");
out.writeCharacters(record.getAccessRights());
out.writeEndElement(); // accessRights
}
if ((record.getLicence() != null) && StringUtils.isNotBlank(record.getLicence().getLicenceText())) {
out.writeStartElement(DC.nsUri, "license");
out.writeCharacters(record.getLicence().getLicenceText());
out.writeEndElement(); // license
}
if (StringUtils.isNotBlank(record.getRightsStatement())) {
out.writeStartElement(DC.nsUri, "rights");
out.writeCharacters(record.getRightsStatement());
out.writeEndElement(); // rights
}
if (record.getRelations() != null) {
for (OaiPmhRecord.Relation relation : record.getRelations()) {
out.writeStartElement(DC.nsUri, "relation");
out.writeAttribute("type", relation.getRelationType());
out.writeCharacters(relation.getRelatedObjectIdentifier());
out.writeEndElement(); // relation
}
}
if (record.getSubjects() != null) {
for (OaiPmhRecord.Subject subject : record.getSubjects()) {
if (subject.getSubjectType().equals("local")) {
out.writeStartElement(DC.nsUri, "subject");
out.writeCharacters(subject.getSubjectText());
out.writeEndElement(); // subject
}
}
}
if (StringUtils.isNotBlank(record.getDcType())) {
out.writeStartElement(DC.nsUri, "type");
out.writeCharacters(record.getDcType());
out.writeEndElement(); // type
}
out.writeEndElement(); // dc
}
private void writeRifCsRepositoryMetadataElement(OaiPmhRecord record) throws XMLStreamException {
if (StringUtils.isBlank(record.getRifCsObjectElemName())) {
throw new IllegalArgumentException("Record must have RIF-CS object element name");
}
out.writeStartElement(RIF_CS.nsPrefix, "registryObjects", RIF_CS.nsUri);
// Every metadata part must include xmlns attributes for its metadata formats.
// http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm#Record
out.setPrefix(RIF_CS.nsPrefix, RIF_CS.nsUri);
out.writeNamespace(RIF_CS.nsPrefix, RIF_CS.nsUri);
// Every metadata part must include the attributes xmlns:xsi (namespace URI for XML schema) and
// xsi:schemaLocation (namespace URI and XML schema URL for validating metadata that follows).
// http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm#Record
out.setPrefix(XSI.nsPrefix, XSI.nsUri);
out.writeNamespace(XSI.nsPrefix, XSI.nsUri);
out.writeAttribute(XSI.nsUri, "schemaLocation", RIF_CS.nsUri + " " + RIF_CS.xsdUri);
out.writeStartElement(RIF_CS.nsUri, "registryObject");
if (StringUtils.isNotBlank(record.getRifCsGroup())) {
out.writeAttribute("group", record.getRifCsGroup());
}
// Do not use the identifier for an object as the key for a metadata record describing
// that object - the metadata record needs its own unique separate identifier.
// http://ands.org.au/guides/cpguide/cpgidentifiers.html
if (StringUtils.isNotBlank(record.getRifCsRecordIdentifier())) {
out.writeStartElement(RIF_CS.nsUri, "key");
out.writeCharacters(record.getRifCsRecordIdentifier());
out.writeEndElement(); // key
}
if (StringUtils.isNotBlank(record.getOriginatingSource())) {
out.writeStartElement(RIF_CS.nsUri, "originatingSource");
out.writeAttribute("type", "authoritative");
out.writeCharacters(record.getOriginatingSource());
out.writeEndElement(); // originatingSource
}
out.writeStartElement(RIF_CS.nsUri, record.getRifCsObjectElemName());
if (StringUtils.isNotBlank(record.getRifCsObjectTypeAttr())) {
out.writeAttribute("type", record.getRifCsObjectTypeAttr());
}
if (record.getRecordUpdateDate() != null) {
out.writeAttribute("dateModified", utcDateTimeFormat.format(record.getRecordUpdateDate()));
}
if (StringUtils.isNotBlank(record.getObjectIdentifier())) {
out.writeStartElement(RIF_CS.nsUri, "identifier");
out.writeAttribute("type", "uri");
out.writeCharacters(record.getObjectIdentifier());
out.writeEndElement(); // identifier
}
if (record.getUriIdentifiers() != null) {
for (String uriIdentifier : record.getUriIdentifiers()) {
if (StringUtils.isNotBlank(uriIdentifier)) {
out.writeStartElement(RIF_CS.nsUri, "identifier");
out.writeAttribute("type", "uri");
out.writeCharacters(uriIdentifier);
out.writeEndElement(); // identifier
}
}
}
if ((record.getName() != null) && (record.getName().getNameParts() != null) && !record.getName().getNameParts().isEmpty()) {
out.writeStartElement(RIF_CS.nsUri, "name");
out.writeAttribute("type", "primary");
for (NamePart namePart : record.getName().getNameParts()) {
out.writeStartElement(RIF_CS.nsUri, "namePart");
if (StringUtils.isNotBlank(namePart.getNamePartType())) {
out.writeAttribute("type", namePart.getNamePartType());
}
out.writeCharacters(namePart.getNamePartText());
out.writeEndElement(); // namePart
}
out.writeEndElement(); // name
}
if (StringUtils.isNotBlank(record.getDescription())) {
out.writeStartElement(RIF_CS.nsUri, "description");
out.writeAttribute("type", "full");
out.writeCharacters(record.getDescription());
out.writeEndElement(); // description
}
if (StringUtils.isNotBlank(record.getUrl()) || StringUtils.isNotBlank(record.getEmail())) {
out.writeStartElement(RIF_CS.nsUri, "location");
out.writeStartElement(RIF_CS.nsUri, "address");
if (StringUtils.isNotBlank(record.getUrl())) {
out.writeStartElement(RIF_CS.nsUri, "electronic");
out.writeAttribute("type", "url");
out.writeStartElement(RIF_CS.nsUri, "value");
out.writeCharacters(record.getUrl());
out.writeEndElement(); // value
out.writeEndElement(); // electronic
}
if (StringUtils.isNotBlank(record.getEmail())) {
out.writeStartElement(RIF_CS.nsUri, "electronic");
out.writeAttribute("type", "email");
out.writeStartElement(RIF_CS.nsUri, "value");
out.writeCharacters(record.getEmail());
out.writeEndElement(); // value
out.writeEndElement(); // electronic
}
out.writeEndElement(); // address
out.writeEndElement(); // location
}
if (Arrays.asList("activity", "party", "service").contains(record.getRifCsObjectElemName())) {
if ((record.getExistenceStartDate() != null) || (record.getExistenceEndDate() != null)) {
out.writeStartElement(RIF_CS.nsUri, "existenceDates");
if (record.getExistenceStartDate() != null) {
out.writeStartElement(RIF_CS.nsUri, "startDate");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getExistenceStartDate()));
out.writeEndElement(); // startDate
}
if (record.getExistenceEndDate() != null) {
out.writeStartElement(RIF_CS.nsUri, "endDate");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getExistenceEndDate()));
out.writeEndElement(); // endDate
}
out.writeEndElement(); // existenceDates
}
}
if (record.getRifCsObjectElemName().equals("collection")) {
if (record.getRecordCreateDate() != null) {
out.writeStartElement(RIF_CS.nsUri, "dates");
out.writeAttribute("type", "created");
out.writeStartElement(RIF_CS.nsUri, "date");
out.writeAttribute("type", "dateFrom");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getRecordCreateDate()));
out.writeEndElement(); // date
out.writeEndElement(); // dates
}
}
if (record.getTemporalCoverage() != null) {
out.writeStartElement(RIF_CS.nsUri, "coverage");
out.writeStartElement(RIF_CS.nsUri, "temporal");
out.writeStartElement(RIF_CS.nsUri, "date");
out.writeAttribute("type", "dateFrom");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getTemporalCoverage().getMinimum()));
out.writeEndElement(); // date
out.writeStartElement(RIF_CS.nsUri, "date");
out.writeAttribute("type", "dateTo");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getTemporalCoverage().getMaximum()));
out.writeEndElement(); // date
out.writeEndElement(); // temporal
out.writeEndElement(); // coverage
}
if (record.getSpatialCoverage() != null) {
out.writeStartElement(RIF_CS.nsUri, "coverage");
out.writeStartElement(RIF_CS.nsUri, "spatial");
out.writeAttribute("type", "iso19139dcmiBox");
out.writeCharacters("northlimit=" + record.getSpatialCoverage().getMaxY() + "; ");
out.writeCharacters("eastLimit=" +
((record.getSpatialCoverage().getMaxX() > 180d)
? (record.getSpatialCoverage().getMaxX() - 360d)
: record.getSpatialCoverage().getMaxX()) + "; ");
out.writeCharacters("southlimit=" + record.getSpatialCoverage().getMinY() + "; ");
out.writeCharacters("westlimit=" +
((record.getSpatialCoverage().getMinX() > 180d)
? (record.getSpatialCoverage().getMinX() - 360d)
: record.getSpatialCoverage().getMinX()) + "; ");
out.writeCharacters("projection=WGS84");
out.writeEndElement(); // spatial
out.writeEndElement(); // coverage
}
if (
StringUtils.isNotBlank(record.getAccessRights()) ||
(
(record.getLicence() != null) && (
StringUtils.isNotBlank(record.getLicence().getLicenceType()) ||
StringUtils.isNotBlank(record.getLicence().getRightsUri()) ||
StringUtils.isNotBlank(record.getLicence().getLicenceText())
)
) ||
StringUtils.isNotBlank(record.getRightsStatement())
) {
out.writeStartElement(RIF_CS.nsUri, "rights");
if (StringUtils.isNotBlank(record.getAccessRights())) {
out.writeStartElement(RIF_CS.nsUri, "accessRights");
out.writeCharacters(record.getAccessRights());
out.writeEndElement(); // accessRights
}
if (record.getLicence() != null) {
- out.writeStartElement(RIF_CS.nsUri, "license");
+ out.writeStartElement(RIF_CS.nsUri, "licence");
if (StringUtils.isNotBlank(record.getLicence().getLicenceType())) {
out.writeAttribute("type", record.getLicence().getLicenceType());
}
if (StringUtils.isNotBlank(record.getLicence().getRightsUri())) {
out.writeAttribute("rightsUri", record.getLicence().getRightsUri());
}
if (StringUtils.isNotBlank(record.getLicence().getLicenceText())) {
out.writeCharacters(record.getLicence().getLicenceText());
}
out.writeEndElement(); // license
}
if (StringUtils.isNotBlank(record.getRightsStatement())) {
out.writeStartElement(RIF_CS.nsUri, "rightsStatement");
out.writeCharacters(record.getRightsStatement());
out.writeEndElement(); // rightsStatement
}
out.writeEndElement(); // rights
}
if (record.getRelations() != null) {
for (OaiPmhRecord.Relation relation : record.getRelations()) {
out.writeStartElement(RIF_CS.nsUri, "relatedObject");
out.writeStartElement(RIF_CS.nsUri, "key");
out.writeCharacters(relation.getRelatedRifCsRecordIdentifier());
out.writeEndElement(); // key
out.writeStartElement(RIF_CS.nsUri, "relation");
out.writeAttribute("type", relation.getRelationType());
out.writeEndElement(); // relation
out.writeEndElement(); // relatedObject
}
}
if (record.getSubjects() != null) {
for (OaiPmhRecord.Subject subject : record.getSubjects()) {
out.writeStartElement(RIF_CS.nsUri, "subject");
out.writeAttribute("type", subject.getSubjectType());
out.writeCharacters(subject.getSubjectText());
out.writeEndElement(); // subject
}
}
out.writeEndElement(); // service
out.writeEndElement(); // registryObject
out.writeEndElement(); // registryObjects
}
}
| true | true | private void writeRifCsRepositoryMetadataElement(OaiPmhRecord record) throws XMLStreamException {
if (StringUtils.isBlank(record.getRifCsObjectElemName())) {
throw new IllegalArgumentException("Record must have RIF-CS object element name");
}
out.writeStartElement(RIF_CS.nsPrefix, "registryObjects", RIF_CS.nsUri);
// Every metadata part must include xmlns attributes for its metadata formats.
// http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm#Record
out.setPrefix(RIF_CS.nsPrefix, RIF_CS.nsUri);
out.writeNamespace(RIF_CS.nsPrefix, RIF_CS.nsUri);
// Every metadata part must include the attributes xmlns:xsi (namespace URI for XML schema) and
// xsi:schemaLocation (namespace URI and XML schema URL for validating metadata that follows).
// http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm#Record
out.setPrefix(XSI.nsPrefix, XSI.nsUri);
out.writeNamespace(XSI.nsPrefix, XSI.nsUri);
out.writeAttribute(XSI.nsUri, "schemaLocation", RIF_CS.nsUri + " " + RIF_CS.xsdUri);
out.writeStartElement(RIF_CS.nsUri, "registryObject");
if (StringUtils.isNotBlank(record.getRifCsGroup())) {
out.writeAttribute("group", record.getRifCsGroup());
}
// Do not use the identifier for an object as the key for a metadata record describing
// that object - the metadata record needs its own unique separate identifier.
// http://ands.org.au/guides/cpguide/cpgidentifiers.html
if (StringUtils.isNotBlank(record.getRifCsRecordIdentifier())) {
out.writeStartElement(RIF_CS.nsUri, "key");
out.writeCharacters(record.getRifCsRecordIdentifier());
out.writeEndElement(); // key
}
if (StringUtils.isNotBlank(record.getOriginatingSource())) {
out.writeStartElement(RIF_CS.nsUri, "originatingSource");
out.writeAttribute("type", "authoritative");
out.writeCharacters(record.getOriginatingSource());
out.writeEndElement(); // originatingSource
}
out.writeStartElement(RIF_CS.nsUri, record.getRifCsObjectElemName());
if (StringUtils.isNotBlank(record.getRifCsObjectTypeAttr())) {
out.writeAttribute("type", record.getRifCsObjectTypeAttr());
}
if (record.getRecordUpdateDate() != null) {
out.writeAttribute("dateModified", utcDateTimeFormat.format(record.getRecordUpdateDate()));
}
if (StringUtils.isNotBlank(record.getObjectIdentifier())) {
out.writeStartElement(RIF_CS.nsUri, "identifier");
out.writeAttribute("type", "uri");
out.writeCharacters(record.getObjectIdentifier());
out.writeEndElement(); // identifier
}
if (record.getUriIdentifiers() != null) {
for (String uriIdentifier : record.getUriIdentifiers()) {
if (StringUtils.isNotBlank(uriIdentifier)) {
out.writeStartElement(RIF_CS.nsUri, "identifier");
out.writeAttribute("type", "uri");
out.writeCharacters(uriIdentifier);
out.writeEndElement(); // identifier
}
}
}
if ((record.getName() != null) && (record.getName().getNameParts() != null) && !record.getName().getNameParts().isEmpty()) {
out.writeStartElement(RIF_CS.nsUri, "name");
out.writeAttribute("type", "primary");
for (NamePart namePart : record.getName().getNameParts()) {
out.writeStartElement(RIF_CS.nsUri, "namePart");
if (StringUtils.isNotBlank(namePart.getNamePartType())) {
out.writeAttribute("type", namePart.getNamePartType());
}
out.writeCharacters(namePart.getNamePartText());
out.writeEndElement(); // namePart
}
out.writeEndElement(); // name
}
if (StringUtils.isNotBlank(record.getDescription())) {
out.writeStartElement(RIF_CS.nsUri, "description");
out.writeAttribute("type", "full");
out.writeCharacters(record.getDescription());
out.writeEndElement(); // description
}
if (StringUtils.isNotBlank(record.getUrl()) || StringUtils.isNotBlank(record.getEmail())) {
out.writeStartElement(RIF_CS.nsUri, "location");
out.writeStartElement(RIF_CS.nsUri, "address");
if (StringUtils.isNotBlank(record.getUrl())) {
out.writeStartElement(RIF_CS.nsUri, "electronic");
out.writeAttribute("type", "url");
out.writeStartElement(RIF_CS.nsUri, "value");
out.writeCharacters(record.getUrl());
out.writeEndElement(); // value
out.writeEndElement(); // electronic
}
if (StringUtils.isNotBlank(record.getEmail())) {
out.writeStartElement(RIF_CS.nsUri, "electronic");
out.writeAttribute("type", "email");
out.writeStartElement(RIF_CS.nsUri, "value");
out.writeCharacters(record.getEmail());
out.writeEndElement(); // value
out.writeEndElement(); // electronic
}
out.writeEndElement(); // address
out.writeEndElement(); // location
}
if (Arrays.asList("activity", "party", "service").contains(record.getRifCsObjectElemName())) {
if ((record.getExistenceStartDate() != null) || (record.getExistenceEndDate() != null)) {
out.writeStartElement(RIF_CS.nsUri, "existenceDates");
if (record.getExistenceStartDate() != null) {
out.writeStartElement(RIF_CS.nsUri, "startDate");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getExistenceStartDate()));
out.writeEndElement(); // startDate
}
if (record.getExistenceEndDate() != null) {
out.writeStartElement(RIF_CS.nsUri, "endDate");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getExistenceEndDate()));
out.writeEndElement(); // endDate
}
out.writeEndElement(); // existenceDates
}
}
if (record.getRifCsObjectElemName().equals("collection")) {
if (record.getRecordCreateDate() != null) {
out.writeStartElement(RIF_CS.nsUri, "dates");
out.writeAttribute("type", "created");
out.writeStartElement(RIF_CS.nsUri, "date");
out.writeAttribute("type", "dateFrom");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getRecordCreateDate()));
out.writeEndElement(); // date
out.writeEndElement(); // dates
}
}
if (record.getTemporalCoverage() != null) {
out.writeStartElement(RIF_CS.nsUri, "coverage");
out.writeStartElement(RIF_CS.nsUri, "temporal");
out.writeStartElement(RIF_CS.nsUri, "date");
out.writeAttribute("type", "dateFrom");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getTemporalCoverage().getMinimum()));
out.writeEndElement(); // date
out.writeStartElement(RIF_CS.nsUri, "date");
out.writeAttribute("type", "dateTo");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getTemporalCoverage().getMaximum()));
out.writeEndElement(); // date
out.writeEndElement(); // temporal
out.writeEndElement(); // coverage
}
if (record.getSpatialCoverage() != null) {
out.writeStartElement(RIF_CS.nsUri, "coverage");
out.writeStartElement(RIF_CS.nsUri, "spatial");
out.writeAttribute("type", "iso19139dcmiBox");
out.writeCharacters("northlimit=" + record.getSpatialCoverage().getMaxY() + "; ");
out.writeCharacters("eastLimit=" +
((record.getSpatialCoverage().getMaxX() > 180d)
? (record.getSpatialCoverage().getMaxX() - 360d)
: record.getSpatialCoverage().getMaxX()) + "; ");
out.writeCharacters("southlimit=" + record.getSpatialCoverage().getMinY() + "; ");
out.writeCharacters("westlimit=" +
((record.getSpatialCoverage().getMinX() > 180d)
? (record.getSpatialCoverage().getMinX() - 360d)
: record.getSpatialCoverage().getMinX()) + "; ");
out.writeCharacters("projection=WGS84");
out.writeEndElement(); // spatial
out.writeEndElement(); // coverage
}
if (
StringUtils.isNotBlank(record.getAccessRights()) ||
(
(record.getLicence() != null) && (
StringUtils.isNotBlank(record.getLicence().getLicenceType()) ||
StringUtils.isNotBlank(record.getLicence().getRightsUri()) ||
StringUtils.isNotBlank(record.getLicence().getLicenceText())
)
) ||
StringUtils.isNotBlank(record.getRightsStatement())
) {
out.writeStartElement(RIF_CS.nsUri, "rights");
if (StringUtils.isNotBlank(record.getAccessRights())) {
out.writeStartElement(RIF_CS.nsUri, "accessRights");
out.writeCharacters(record.getAccessRights());
out.writeEndElement(); // accessRights
}
if (record.getLicence() != null) {
out.writeStartElement(RIF_CS.nsUri, "license");
if (StringUtils.isNotBlank(record.getLicence().getLicenceType())) {
out.writeAttribute("type", record.getLicence().getLicenceType());
}
if (StringUtils.isNotBlank(record.getLicence().getRightsUri())) {
out.writeAttribute("rightsUri", record.getLicence().getRightsUri());
}
if (StringUtils.isNotBlank(record.getLicence().getLicenceText())) {
out.writeCharacters(record.getLicence().getLicenceText());
}
out.writeEndElement(); // license
}
if (StringUtils.isNotBlank(record.getRightsStatement())) {
out.writeStartElement(RIF_CS.nsUri, "rightsStatement");
out.writeCharacters(record.getRightsStatement());
out.writeEndElement(); // rightsStatement
}
out.writeEndElement(); // rights
}
if (record.getRelations() != null) {
for (OaiPmhRecord.Relation relation : record.getRelations()) {
out.writeStartElement(RIF_CS.nsUri, "relatedObject");
out.writeStartElement(RIF_CS.nsUri, "key");
out.writeCharacters(relation.getRelatedRifCsRecordIdentifier());
out.writeEndElement(); // key
out.writeStartElement(RIF_CS.nsUri, "relation");
out.writeAttribute("type", relation.getRelationType());
out.writeEndElement(); // relation
out.writeEndElement(); // relatedObject
}
}
if (record.getSubjects() != null) {
for (OaiPmhRecord.Subject subject : record.getSubjects()) {
out.writeStartElement(RIF_CS.nsUri, "subject");
out.writeAttribute("type", subject.getSubjectType());
out.writeCharacters(subject.getSubjectText());
out.writeEndElement(); // subject
}
}
out.writeEndElement(); // service
out.writeEndElement(); // registryObject
out.writeEndElement(); // registryObjects
}
| private void writeRifCsRepositoryMetadataElement(OaiPmhRecord record) throws XMLStreamException {
if (StringUtils.isBlank(record.getRifCsObjectElemName())) {
throw new IllegalArgumentException("Record must have RIF-CS object element name");
}
out.writeStartElement(RIF_CS.nsPrefix, "registryObjects", RIF_CS.nsUri);
// Every metadata part must include xmlns attributes for its metadata formats.
// http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm#Record
out.setPrefix(RIF_CS.nsPrefix, RIF_CS.nsUri);
out.writeNamespace(RIF_CS.nsPrefix, RIF_CS.nsUri);
// Every metadata part must include the attributes xmlns:xsi (namespace URI for XML schema) and
// xsi:schemaLocation (namespace URI and XML schema URL for validating metadata that follows).
// http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm#Record
out.setPrefix(XSI.nsPrefix, XSI.nsUri);
out.writeNamespace(XSI.nsPrefix, XSI.nsUri);
out.writeAttribute(XSI.nsUri, "schemaLocation", RIF_CS.nsUri + " " + RIF_CS.xsdUri);
out.writeStartElement(RIF_CS.nsUri, "registryObject");
if (StringUtils.isNotBlank(record.getRifCsGroup())) {
out.writeAttribute("group", record.getRifCsGroup());
}
// Do not use the identifier for an object as the key for a metadata record describing
// that object - the metadata record needs its own unique separate identifier.
// http://ands.org.au/guides/cpguide/cpgidentifiers.html
if (StringUtils.isNotBlank(record.getRifCsRecordIdentifier())) {
out.writeStartElement(RIF_CS.nsUri, "key");
out.writeCharacters(record.getRifCsRecordIdentifier());
out.writeEndElement(); // key
}
if (StringUtils.isNotBlank(record.getOriginatingSource())) {
out.writeStartElement(RIF_CS.nsUri, "originatingSource");
out.writeAttribute("type", "authoritative");
out.writeCharacters(record.getOriginatingSource());
out.writeEndElement(); // originatingSource
}
out.writeStartElement(RIF_CS.nsUri, record.getRifCsObjectElemName());
if (StringUtils.isNotBlank(record.getRifCsObjectTypeAttr())) {
out.writeAttribute("type", record.getRifCsObjectTypeAttr());
}
if (record.getRecordUpdateDate() != null) {
out.writeAttribute("dateModified", utcDateTimeFormat.format(record.getRecordUpdateDate()));
}
if (StringUtils.isNotBlank(record.getObjectIdentifier())) {
out.writeStartElement(RIF_CS.nsUri, "identifier");
out.writeAttribute("type", "uri");
out.writeCharacters(record.getObjectIdentifier());
out.writeEndElement(); // identifier
}
if (record.getUriIdentifiers() != null) {
for (String uriIdentifier : record.getUriIdentifiers()) {
if (StringUtils.isNotBlank(uriIdentifier)) {
out.writeStartElement(RIF_CS.nsUri, "identifier");
out.writeAttribute("type", "uri");
out.writeCharacters(uriIdentifier);
out.writeEndElement(); // identifier
}
}
}
if ((record.getName() != null) && (record.getName().getNameParts() != null) && !record.getName().getNameParts().isEmpty()) {
out.writeStartElement(RIF_CS.nsUri, "name");
out.writeAttribute("type", "primary");
for (NamePart namePart : record.getName().getNameParts()) {
out.writeStartElement(RIF_CS.nsUri, "namePart");
if (StringUtils.isNotBlank(namePart.getNamePartType())) {
out.writeAttribute("type", namePart.getNamePartType());
}
out.writeCharacters(namePart.getNamePartText());
out.writeEndElement(); // namePart
}
out.writeEndElement(); // name
}
if (StringUtils.isNotBlank(record.getDescription())) {
out.writeStartElement(RIF_CS.nsUri, "description");
out.writeAttribute("type", "full");
out.writeCharacters(record.getDescription());
out.writeEndElement(); // description
}
if (StringUtils.isNotBlank(record.getUrl()) || StringUtils.isNotBlank(record.getEmail())) {
out.writeStartElement(RIF_CS.nsUri, "location");
out.writeStartElement(RIF_CS.nsUri, "address");
if (StringUtils.isNotBlank(record.getUrl())) {
out.writeStartElement(RIF_CS.nsUri, "electronic");
out.writeAttribute("type", "url");
out.writeStartElement(RIF_CS.nsUri, "value");
out.writeCharacters(record.getUrl());
out.writeEndElement(); // value
out.writeEndElement(); // electronic
}
if (StringUtils.isNotBlank(record.getEmail())) {
out.writeStartElement(RIF_CS.nsUri, "electronic");
out.writeAttribute("type", "email");
out.writeStartElement(RIF_CS.nsUri, "value");
out.writeCharacters(record.getEmail());
out.writeEndElement(); // value
out.writeEndElement(); // electronic
}
out.writeEndElement(); // address
out.writeEndElement(); // location
}
if (Arrays.asList("activity", "party", "service").contains(record.getRifCsObjectElemName())) {
if ((record.getExistenceStartDate() != null) || (record.getExistenceEndDate() != null)) {
out.writeStartElement(RIF_CS.nsUri, "existenceDates");
if (record.getExistenceStartDate() != null) {
out.writeStartElement(RIF_CS.nsUri, "startDate");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getExistenceStartDate()));
out.writeEndElement(); // startDate
}
if (record.getExistenceEndDate() != null) {
out.writeStartElement(RIF_CS.nsUri, "endDate");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getExistenceEndDate()));
out.writeEndElement(); // endDate
}
out.writeEndElement(); // existenceDates
}
}
if (record.getRifCsObjectElemName().equals("collection")) {
if (record.getRecordCreateDate() != null) {
out.writeStartElement(RIF_CS.nsUri, "dates");
out.writeAttribute("type", "created");
out.writeStartElement(RIF_CS.nsUri, "date");
out.writeAttribute("type", "dateFrom");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getRecordCreateDate()));
out.writeEndElement(); // date
out.writeEndElement(); // dates
}
}
if (record.getTemporalCoverage() != null) {
out.writeStartElement(RIF_CS.nsUri, "coverage");
out.writeStartElement(RIF_CS.nsUri, "temporal");
out.writeStartElement(RIF_CS.nsUri, "date");
out.writeAttribute("type", "dateFrom");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getTemporalCoverage().getMinimum()));
out.writeEndElement(); // date
out.writeStartElement(RIF_CS.nsUri, "date");
out.writeAttribute("type", "dateTo");
out.writeAttribute("dateFormat", "W3CDTF");
out.writeCharacters(utcDateTimeFormat.format(record.getTemporalCoverage().getMaximum()));
out.writeEndElement(); // date
out.writeEndElement(); // temporal
out.writeEndElement(); // coverage
}
if (record.getSpatialCoverage() != null) {
out.writeStartElement(RIF_CS.nsUri, "coverage");
out.writeStartElement(RIF_CS.nsUri, "spatial");
out.writeAttribute("type", "iso19139dcmiBox");
out.writeCharacters("northlimit=" + record.getSpatialCoverage().getMaxY() + "; ");
out.writeCharacters("eastLimit=" +
((record.getSpatialCoverage().getMaxX() > 180d)
? (record.getSpatialCoverage().getMaxX() - 360d)
: record.getSpatialCoverage().getMaxX()) + "; ");
out.writeCharacters("southlimit=" + record.getSpatialCoverage().getMinY() + "; ");
out.writeCharacters("westlimit=" +
((record.getSpatialCoverage().getMinX() > 180d)
? (record.getSpatialCoverage().getMinX() - 360d)
: record.getSpatialCoverage().getMinX()) + "; ");
out.writeCharacters("projection=WGS84");
out.writeEndElement(); // spatial
out.writeEndElement(); // coverage
}
if (
StringUtils.isNotBlank(record.getAccessRights()) ||
(
(record.getLicence() != null) && (
StringUtils.isNotBlank(record.getLicence().getLicenceType()) ||
StringUtils.isNotBlank(record.getLicence().getRightsUri()) ||
StringUtils.isNotBlank(record.getLicence().getLicenceText())
)
) ||
StringUtils.isNotBlank(record.getRightsStatement())
) {
out.writeStartElement(RIF_CS.nsUri, "rights");
if (StringUtils.isNotBlank(record.getAccessRights())) {
out.writeStartElement(RIF_CS.nsUri, "accessRights");
out.writeCharacters(record.getAccessRights());
out.writeEndElement(); // accessRights
}
if (record.getLicence() != null) {
out.writeStartElement(RIF_CS.nsUri, "licence");
if (StringUtils.isNotBlank(record.getLicence().getLicenceType())) {
out.writeAttribute("type", record.getLicence().getLicenceType());
}
if (StringUtils.isNotBlank(record.getLicence().getRightsUri())) {
out.writeAttribute("rightsUri", record.getLicence().getRightsUri());
}
if (StringUtils.isNotBlank(record.getLicence().getLicenceText())) {
out.writeCharacters(record.getLicence().getLicenceText());
}
out.writeEndElement(); // license
}
if (StringUtils.isNotBlank(record.getRightsStatement())) {
out.writeStartElement(RIF_CS.nsUri, "rightsStatement");
out.writeCharacters(record.getRightsStatement());
out.writeEndElement(); // rightsStatement
}
out.writeEndElement(); // rights
}
if (record.getRelations() != null) {
for (OaiPmhRecord.Relation relation : record.getRelations()) {
out.writeStartElement(RIF_CS.nsUri, "relatedObject");
out.writeStartElement(RIF_CS.nsUri, "key");
out.writeCharacters(relation.getRelatedRifCsRecordIdentifier());
out.writeEndElement(); // key
out.writeStartElement(RIF_CS.nsUri, "relation");
out.writeAttribute("type", relation.getRelationType());
out.writeEndElement(); // relation
out.writeEndElement(); // relatedObject
}
}
if (record.getSubjects() != null) {
for (OaiPmhRecord.Subject subject : record.getSubjects()) {
out.writeStartElement(RIF_CS.nsUri, "subject");
out.writeAttribute("type", subject.getSubjectType());
out.writeCharacters(subject.getSubjectText());
out.writeEndElement(); // subject
}
}
out.writeEndElement(); // service
out.writeEndElement(); // registryObject
out.writeEndElement(); // registryObjects
}
|
diff --git a/spring-ws/src/main/java/com/dare2date/businessservice/FacebookService.java b/spring-ws/src/main/java/com/dare2date/businessservice/FacebookService.java
index e14ba99..af5bbb9 100644
--- a/spring-ws/src/main/java/com/dare2date/businessservice/FacebookService.java
+++ b/spring-ws/src/main/java/com/dare2date/businessservice/FacebookService.java
@@ -1,75 +1,77 @@
/**
* Copyright (c) 2013 HAN University of Applied Sciences
* Arjan Oortgiese
* Joëll Portier
*
* 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.dare2date.businessservice;
import com.dare2date.applicationservice.IAuthorisationService;
import com.dare2date.domein.facebook.FacebookData;
import com.dare2date.externeservice.facebook.IFacebookAPI;
/**
* Facebook service.
*/
public class FacebookService {
private IAuthorisationService authorisationService;
private IFacebookAPI facebook;
/**
* Set the authorisation service.
*
* @param authorisationService Authorisation service.
*/
public void setAuthorisationService(IAuthorisationService authorisationService) {
this.authorisationService = authorisationService;
}
/**
* Set the Facebook API implementation to use.
*
* @param facebook Facebook API implementation.
*/
public void setFacebook(IFacebookAPI facebook) {
this.facebook = facebook;
}
/**
* Get Facebook events, work history and education history form the user.
*
* @param username Dare2Data username.
* @return FacebookData object with History, Education and events.
*/
public FacebookData getFacebookMatch(String username) {
String accessToken = authorisationService.getAccessToken(username, "facebook");
FacebookData data = new FacebookData();
- data.setEvents(facebook.getUsersEvents(accessToken));
- data.setWorkHistory(facebook.getUsersWorkHistory(accessToken));
- data.setEducationHistory(facebook.getUsersEducationHistory(accessToken));
+ if (accessToken != null) {
+ data.setEvents(facebook.getUsersEvents(accessToken));
+ data.setWorkHistory(facebook.getUsersWorkHistory(accessToken));
+ data.setEducationHistory(facebook.getUsersEducationHistory(accessToken));
+ }
return data;
}
}
| true | true | public FacebookData getFacebookMatch(String username) {
String accessToken = authorisationService.getAccessToken(username, "facebook");
FacebookData data = new FacebookData();
data.setEvents(facebook.getUsersEvents(accessToken));
data.setWorkHistory(facebook.getUsersWorkHistory(accessToken));
data.setEducationHistory(facebook.getUsersEducationHistory(accessToken));
return data;
}
| public FacebookData getFacebookMatch(String username) {
String accessToken = authorisationService.getAccessToken(username, "facebook");
FacebookData data = new FacebookData();
if (accessToken != null) {
data.setEvents(facebook.getUsersEvents(accessToken));
data.setWorkHistory(facebook.getUsersWorkHistory(accessToken));
data.setEducationHistory(facebook.getUsersEducationHistory(accessToken));
}
return data;
}
|
diff --git a/src/util/FileUtil.java b/src/util/FileUtil.java
index 6cb3f65..6a7d910 100755
--- a/src/util/FileUtil.java
+++ b/src/util/FileUtil.java
@@ -1,542 +1,543 @@
package util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.commons.codec.digest.DigestUtils;
import org.jfree.io.IOUtils;
public class FileUtil
{
public static interface ColumnExclude
{
public boolean exclude(int columnIndex, String columnName);
}
public static interface RowRemove
{
public boolean remove(int rowIndex, String row[]);
}
public static class CSVFile
{
public List<String> comments = new ArrayList<String>();
public List<String[]> content = new ArrayList<String[]>();
public CSVFile merge(CSVFile csvFile)
{
if (comments.size() > 0 || csvFile.comments.size() > 0)
throw new Error("merging comments not yet implemented");
if (content.size() != csvFile.content.size())
throw new IllegalArgumentException();
CSVFile newCsv = new CSVFile();
for (int i = 0; i < content.size(); i++)
newCsv.content.add(ArrayUtil.concat(String.class, content.get(i), csvFile.content.get(i)));
return newCsv;
}
public String[] getHeader()
{
return content.get(0);
}
public CSVFile removeRow(RowRemove remove)
{
Set<Integer> rowIndex = new HashSet<Integer>();
for (int i = 1; i < content.size(); i++)
if (remove.remove(i, content.get(i)))
rowIndex.add(i);
return removeRow(ArrayUtil.toPrimitiveIntArray(rowIndex));
}
public CSVFile removeRow(int... rows)
{
CSVFile csv = new CSVFile();
csv.comments = ListUtil.clone(comments);
csv.content = ListUtil.clone(content);
Arrays.sort(rows);
for (int i = rows.length - 1; i >= 0; i--)
csv.content.remove(rows[i]);
return csv;
}
public CSVFile exclude(ColumnExclude exclude)
{
Set<Integer> colIndex = new HashSet<Integer>();
for (int i = 0; i < getHeader().length; i++)
if (exclude.exclude(i, getHeader()[i]))
colIndex.add(i);
return exclude(ArrayUtil.toPrimitiveIntArray(colIndex));
}
public CSVFile exclude(String... columns)
{
List<Integer> colIndex = new ArrayList<Integer>();
for (String s : columns)
{
int i = ArrayUtil.indexOf(getHeader(), s);
if (i == -1)
throw new IllegalArgumentException("not found: " + columns);
colIndex.add(i);
}
return exclude(ArrayUtil.toPrimitiveIntArray(colIndex));
}
public CSVFile exclude(int... columns)
{
CSVFile csv = new CSVFile();
csv.comments = ListUtil.clone(comments);
csv.content = ListUtil.clone(content);
Arrays.sort(columns);
for (int i = columns.length - 1; i >= 0; i--)
{
// System.err.println(ArrayUtil.toString(csv.getHeader()));
// System.err.println("remove " + columns[i] + ", length: " + csv.getHeader().length);
List<String[]> contentNew = new ArrayList<String[]>();
for (String s[] : csv.content)
contentNew.add(ArrayUtil.removeAt(String.class, s, columns[i]));
csv.content = contentNew;
}
return csv;
}
public String toString()
{
StringLineAdder s = new StringLineAdder();
for (String st : comments)
s.add(st);
for (String[] st : content)
s.add(ArrayUtil.toCSVString(st));
return s.toString();
}
}
public static void writeCSV(String file, CSVFile csv, boolean append)
{
if (csv.comments.size() > 0)
throw new Error("merging comments not yet implemented");
try
{
BufferedWriter w = new BufferedWriter(new FileWriter(file, append));
for (String s[] : csv.content)
{
boolean first = true;
for (String string : s)
{
if (first)
first = false;
else
w.write(",");
if (string != null)
{
w.write("\"");
w.write(string);
w.write("\"");
}
}
w.write("\n");
}
w.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static CSVFile readCSV(String filename)
{
return readCSV(filename, -1);
}
public static CSVFile readCSV(String filename, int expectedSize)
{
return readCSV(filename, -1, null);
}
public static CSVFile readCSV(String filename, int expectedSize, String sep)
{
if (sep != null && sep.length() != 1)
throw new IllegalArgumentException("seperator must have length 1");
try
{
List<String[]> l = new ArrayList<String[]>();
List<String> c = new ArrayList<String>();
BufferedReader b = new BufferedReader(new FileReader(new File(filename)));
String s = "";
char seperator = ',';
while ((s = b.readLine()) != null)
{
if (s.trim().length() == 0)
continue;
if (s.startsWith("#"))
c.add(s);
else
{
if (l.size() == 0)
{
if (sep != null)
seperator = sep.charAt(0);
else
{
- if (StringUtil.numOccurences(s, ";") > StringUtil.numOccurences(s, ","))
+ if (s.split(";(?=([^\"]*\"[^\"]*\")*[^\"]*$)").length > s
+ .split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)").length)
seperator = ';';
else
seperator = ',';
}
}
Vector<String> line = VectorUtil.fromCSVString(s, false, expectedSize, seperator);
if (l.size() > 0 && l.get(0).length != line.size())
throw new IllegalArgumentException("error reading csv " + l.get(0).length + " != "
+ line.size());
l.add(ArrayUtil.toArray(String.class, line));
}
}
b.close();
CSVFile csv = new CSVFile();
csv.comments = c;
csv.content = l;
return csv;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* renameto is not reliable to windows
*
* @param source
* @param dest
* @return
*/
public static boolean robustRenameTo(File source, File dest)
{
if (OSUtil.isWindows())
{
try
{
String line;
String cmd = "cmd /c MOVE /Y " + source.getAbsolutePath() + " " + dest.getAbsolutePath();
System.out.println(cmd);
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null)
System.out.println(line);
input.close();
BufferedReader input2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = input2.readLine()) != null)
System.out.println(line);
input2.close();
p.waitFor();
// System.err.println(p.exitValue());
return p.exitValue() == 0;
}
catch (Exception err)
{
err.printStackTrace();
return false;
}
}
else
return source.renameTo(dest);
}
/**
* replace a backslash in windows with a double-backslash
*
* @param f
* @return
*/
public static String getAbsolutePathEscaped(File f)
{
if (OSUtil.isWindows())
return f.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\");
else
return f.getAbsolutePath();
}
public static boolean concat(File dest, List<File> source)
{
return concat(dest, source, false);
}
public static boolean concat(File dest, List<File> source, boolean append)
{
if (dest.exists() && !append)
if (!dest.delete())
return false;
for (File s : source)
if (!copy(s, dest, true))
return false;
return true;
}
public static boolean copy(File source, File dest)
{
return copy(source, dest, false);
}
public static boolean copy(File source, File dest, boolean append)
{
FileInputStream from = null;
FileOutputStream to = null;
try
{
from = new FileInputStream(source);
to = new FileOutputStream(dest, append);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1)
to.write(buffer, 0, bytesRead); // write
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
finally
{
if (from != null)
try
{
from.close();
}
catch (IOException e)
{
}
if (to != null)
try
{
to.close();
}
catch (IOException e)
{
}
}
}
public static boolean isContentEqual(String file1, String file2)
{
File f1 = new File(file1);
File f2 = new File(file2);
if (!f1.exists() || !f2.exists())
throw new IllegalArgumentException();
if (f1.length() != f2.length())
return false;
return getMD5String(file1).equals(getMD5String(file2));
}
public static String getMD5String(String filename)
{
try
{
FileInputStream fis = new FileInputStream(new File(filename));
return DigestUtils.md5Hex(fis);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
return null;
}
public static String getFilename(String file)
{
return getFilename(file, true);
}
public static String getFilename(String file, boolean withExtension)
{
String n = new File(file).getName();
if (withExtension)
return n;
else
{
int index = n.lastIndexOf('.');
if (index == -1)
return n;
else
return n.substring(0, index);
}
}
/**
* without .
*/
public static String getFilenamExtension(String file)
{
String n = new File(file).getName();
int index = n.lastIndexOf('.');
if (index == -1)
return "";
else
return n.substring(index + 1);
}
public static String getParent(String file)
{
return new File(file).getParent();
}
public static void writeStringToFile(String file, String content)
{
writeStringToFile(file, content, false);
}
public static void writeStringToFile(String file, String content, boolean append)
{
try
{
BufferedWriter w = new BufferedWriter(new FileWriter(file, append));
w.write(content);
w.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void join(String input1, String input2, String output)
{
try
{
InputStream i1 = new FileInputStream(new File(input1));
InputStream i2 = new FileInputStream(new File(input2));
InputStream i = new SequenceInputStream(i1, i2);
IOUtils.getInstance().copyStreams(i, new FileOutputStream(output));
}
catch (Exception e)
{
e.printStackTrace();
}
// FileUtil.writeStringToFile(output, FileUtil.readStringFromFile(input1));
// FileUtil.writeStringToFile(output, FileUtil.readStringFromFile(input2), true);
}
public static String readStringFromFile(String file)
{
try
{
StringBuffer res = new StringBuffer();
String line;
BufferedReader r = new BufferedReader(new FileReader(file));
while ((line = r.readLine()) != null)
{
res.append(line);
res.append("\n");
}
r.close();
return res.toString();
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
public static Vector<File> getFilesRecursiv(String commaSeperatedFilesOrDirectories)
{
StringTokenizer tok = new StringTokenizer(commaSeperatedFilesOrDirectories, ",");
Vector<File> res = new Vector<File>();
while (tok.hasMoreTokens())
res.addAll(FileUtil.getFilesRecursiv(new File(tok.nextToken())));
return res;
}
public static Vector<File> getFilesRecursiv(File fileOrDirectory)
{
Vector<File> res = new Vector<File>();
if (!fileOrDirectory.exists())
throw new IllegalStateException("file does not exist: " + fileOrDirectory);
if (fileOrDirectory.isDirectory())
{
File dir[] = fileOrDirectory.listFiles();
for (File file : dir)
res.addAll(FileUtil.getFilesRecursiv(file));
}
else if (fileOrDirectory.isHidden())
System.err.println("omitting hidden file: " + fileOrDirectory);
else
res.add(fileOrDirectory);
return res;
}
public static void createParentFolders(String file)
{
createParentFolders(new File(file));
}
public static void createParentFolders(File file)
{
File p = new File(file.getParent());
if (!p.exists())
{
boolean b = p.mkdirs();
if (!b)
throw new Error("could not create folder: " + p);
}
}
public static String toCygwinPosixPath(String path)
{
String s = path.replaceAll("\\\\", "/");
if (Character.isLetter(s.charAt(0)) && s.charAt(1) == ':' && s.charAt(2) == '/')
s = "/cygdrive/" + s.charAt(0) + s.substring(2);
return s;
}
public static String getCygwinPosixPath(File f)
{
if (SystemUtil.isWindows())
return toCygwinPosixPath(f.getAbsolutePath());
else
return f.getAbsolutePath();
}
public static void main(String args[])
{
//System.out.println(getAbsolutePathEscaped(new File(".")));
System.out.println(getMD5String("/home/martin/data/test8.csv"));
// String s = "C:\\bla\\blub";
// System.out.println(s);
// System.out.println(toCygwinPosixPath(s));
// System.out.println(FileUtil.isContentEqual(
// "/home/martin/workspace/ClusterViewer/cluster_data/nctrer_small_3d/002.nctrer.distances.table",
// "/home/martin/workspace/ClusterViewer/cluster_data/nctrer_small_3d/003.nctrer.distances.table"));
}
}
| true | true | public static CSVFile readCSV(String filename, int expectedSize, String sep)
{
if (sep != null && sep.length() != 1)
throw new IllegalArgumentException("seperator must have length 1");
try
{
List<String[]> l = new ArrayList<String[]>();
List<String> c = new ArrayList<String>();
BufferedReader b = new BufferedReader(new FileReader(new File(filename)));
String s = "";
char seperator = ',';
while ((s = b.readLine()) != null)
{
if (s.trim().length() == 0)
continue;
if (s.startsWith("#"))
c.add(s);
else
{
if (l.size() == 0)
{
if (sep != null)
seperator = sep.charAt(0);
else
{
if (StringUtil.numOccurences(s, ";") > StringUtil.numOccurences(s, ","))
seperator = ';';
else
seperator = ',';
}
}
Vector<String> line = VectorUtil.fromCSVString(s, false, expectedSize, seperator);
if (l.size() > 0 && l.get(0).length != line.size())
throw new IllegalArgumentException("error reading csv " + l.get(0).length + " != "
+ line.size());
l.add(ArrayUtil.toArray(String.class, line));
}
}
b.close();
CSVFile csv = new CSVFile();
csv.comments = c;
csv.content = l;
return csv;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
| public static CSVFile readCSV(String filename, int expectedSize, String sep)
{
if (sep != null && sep.length() != 1)
throw new IllegalArgumentException("seperator must have length 1");
try
{
List<String[]> l = new ArrayList<String[]>();
List<String> c = new ArrayList<String>();
BufferedReader b = new BufferedReader(new FileReader(new File(filename)));
String s = "";
char seperator = ',';
while ((s = b.readLine()) != null)
{
if (s.trim().length() == 0)
continue;
if (s.startsWith("#"))
c.add(s);
else
{
if (l.size() == 0)
{
if (sep != null)
seperator = sep.charAt(0);
else
{
if (s.split(";(?=([^\"]*\"[^\"]*\")*[^\"]*$)").length > s
.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)").length)
seperator = ';';
else
seperator = ',';
}
}
Vector<String> line = VectorUtil.fromCSVString(s, false, expectedSize, seperator);
if (l.size() > 0 && l.get(0).length != line.size())
throw new IllegalArgumentException("error reading csv " + l.get(0).length + " != "
+ line.size());
l.add(ArrayUtil.toArray(String.class, line));
}
}
b.close();
CSVFile csv = new CSVFile();
csv.comments = c;
csv.content = l;
return csv;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
|
diff --git a/router/java/src/net/i2p/router/InNetMessagePool.java b/router/java/src/net/i2p/router/InNetMessagePool.java
index bf08cc8d4..0db43c561 100644
--- a/router/java/src/net/i2p/router/InNetMessagePool.java
+++ b/router/java/src/net/i2p/router/InNetMessagePool.java
@@ -1,188 +1,190 @@
package net.i2p.router;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* with no warranty of any kind, either expressed or implied.
* It probably won't make your computer catch on fire, or eat
* your children, but it might. Use at your own risk.
*
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.i2p.data.i2np.DeliveryStatusMessage;
import net.i2p.data.i2np.I2NPMessage;
import net.i2p.util.Log;
/**
* Manage a pool of inbound InNetMessages. This pool is filled by the
* Network communication system when it receives messages, and various jobs
* periodically retrieve them for processing.
*
*/
public class InNetMessagePool {
private Log _log;
private RouterContext _context;
private List _messages;
private Map _handlerJobBuilders;
public InNetMessagePool(RouterContext context) {
_context = context;
_messages = new ArrayList();
_handlerJobBuilders = new HashMap();
_log = _context.logManager().getLog(InNetMessagePool.class);
_context.statManager().createRateStat("inNetPool.dropped", "How often do we drop a message", "InNetPool", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l });
_context.statManager().createRateStat("inNetPool.droppedDeliveryStatusDelay", "How long after a delivery status message is created do we receive it back again (for messages that are too slow to be handled)", "InNetPool", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l });
_context.statManager().createRateStat("inNetPool.duplicate", "How often do we receive a duplicate message", "InNetPool", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l });
}
public HandlerJobBuilder registerHandlerJobBuilder(int i2npMessageType, HandlerJobBuilder builder) {
return (HandlerJobBuilder)_handlerJobBuilders.put(new Integer(i2npMessageType), builder);
}
public HandlerJobBuilder unregisterHandlerJobBuilder(int i2npMessageType) {
return (HandlerJobBuilder)_handlerJobBuilders.remove(new Integer(i2npMessageType));
}
/**
* Add a new message to the pool, returning the number of messages in the
* pool so that the comm system can throttle inbound messages. If there is
* a HandlerJobBuilder for the inbound message type, the message is loaded
* into a job created by that builder and queued up for processing instead
* (though if the builder doesn't create a job, it is added to the pool)
*
*/
public int add(InNetMessage msg) {
I2NPMessage messageBody = msg.getMessage();
msg.processingComplete();
Date exp = messageBody.getMessageExpiration();
boolean valid = _context.messageValidator().validateMessage(messageBody.getUniqueId(), exp.getTime());
if (!valid) {
if (_log.shouldLog(Log.WARN))
_log.warn("Duplicate message received [" + messageBody.getUniqueId()
+ " expiring on " + exp + "]: " + messageBody.getClass().getName());
_context.statManager().addRateData("inNetPool.dropped", 1, 0);
_context.statManager().addRateData("inNetPool.duplicate", 1, 0);
_context.messageHistory().droppedOtherMessage(messageBody);
_context.messageHistory().messageProcessingError(messageBody.getUniqueId(),
messageBody.getClass().getName(),
"Duplicate/expired");
return -1;
} else {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Message received [" + messageBody.getUniqueId()
+ " expiring on " + exp + "] is NOT a duplicate or exipired");
}
int size = -1;
int type = messageBody.getType();
HandlerJobBuilder builder = (HandlerJobBuilder)_handlerJobBuilders.get(new Integer(type));
if (_log.shouldLog(Log.DEBUG))
_log.debug("Add message to the inNetMessage pool - builder: " + builder
+ " message class: " + messageBody.getClass().getName());
if (builder != null) {
Job job = builder.createJob(messageBody, msg.getFromRouter(),
msg.getFromRouterHash(), msg.getReplyBlock());
if (job != null) {
_context.jobQueue().addJob(job);
synchronized (_messages) {
size = _messages.size();
}
}
}
List origMessages = _context.messageRegistry().getOriginalMessages(messageBody);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Original messages for inbound message: " + origMessages.size());
if (origMessages.size() > 1) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Orig: " + origMessages + " \nthe above are replies for: " + msg,
new Exception("Multiple matches"));
}
for (int i = 0; i < origMessages.size(); i++) {
OutNetMessage omsg = (OutNetMessage)origMessages.get(i);
ReplyJob job = omsg.getOnReplyJob();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Original message [" + i + "] " + omsg.getReplySelector()
+ " : " + omsg + ": reply job: " + job);
if (job != null) {
job.setMessage(messageBody);
_context.jobQueue().addJob(job);
}
}
if (origMessages.size() <= 0) {
// not handled as a reply
if (size == -1) {
// was not handled via HandlerJobBuilder
_context.messageHistory().droppedOtherMessage(messageBody);
if (type == DeliveryStatusMessage.MESSAGE_TYPE) {
long timeSinceSent = _context.clock().now() -
((DeliveryStatusMessage)messageBody).getArrival().getTime();
if (_log.shouldLog(Log.INFO))
_log.info("Dropping unhandled delivery status message created " + timeSinceSent + "ms ago: " + msg);
_context.statManager().addRateData("inNetPool.droppedDeliveryStatusDelay", timeSinceSent, timeSinceSent);
} else {
if (_log.shouldLog(Log.ERROR))
- _log.error("Message " + messageBody + " was not handled by a HandlerJobBuilder - DROPPING: "
+ _log.error("Message " + messageBody + " expiring on "
+ + (messageBody != null ? (messageBody.getMessageExpiration()+"") : " [unknown]")
+ + " was not handled by a HandlerJobBuilder - DROPPING: "
+ msg, new Exception("DROPPED MESSAGE"));
_context.statManager().addRateData("inNetPool.dropped", 1, 0);
}
} else {
String mtype = messageBody.getClass().getName();
_context.messageHistory().receiveMessage(mtype, messageBody.getUniqueId(),
messageBody.getMessageExpiration(),
msg.getFromRouterHash(), true);
return size;
}
}
String mtype = messageBody.getClass().getName();
_context.messageHistory().receiveMessage(mtype, messageBody.getUniqueId(),
messageBody.getMessageExpiration(),
msg.getFromRouterHash(), true);
return size;
}
/**
* Remove up to maxNumMessages InNetMessages from the pool and return them.
*
*/
public List getNext(int maxNumMessages) {
ArrayList msgs = new ArrayList(maxNumMessages);
synchronized (_messages) {
for (int i = 0; (i < maxNumMessages) && (_messages.size() > 0); i++)
msgs.add(_messages.remove(0));
}
return msgs;
}
/**
* Retrieve the next message
*
*/
public InNetMessage getNext() {
synchronized (_messages) {
if (_messages.size() <= 0) return null;
return (InNetMessage)_messages.remove(0);
}
}
/**
* Retrieve the size of the pool
*
*/
public int getCount() {
synchronized (_messages) {
return _messages.size();
}
}
}
| true | true | public int add(InNetMessage msg) {
I2NPMessage messageBody = msg.getMessage();
msg.processingComplete();
Date exp = messageBody.getMessageExpiration();
boolean valid = _context.messageValidator().validateMessage(messageBody.getUniqueId(), exp.getTime());
if (!valid) {
if (_log.shouldLog(Log.WARN))
_log.warn("Duplicate message received [" + messageBody.getUniqueId()
+ " expiring on " + exp + "]: " + messageBody.getClass().getName());
_context.statManager().addRateData("inNetPool.dropped", 1, 0);
_context.statManager().addRateData("inNetPool.duplicate", 1, 0);
_context.messageHistory().droppedOtherMessage(messageBody);
_context.messageHistory().messageProcessingError(messageBody.getUniqueId(),
messageBody.getClass().getName(),
"Duplicate/expired");
return -1;
} else {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Message received [" + messageBody.getUniqueId()
+ " expiring on " + exp + "] is NOT a duplicate or exipired");
}
int size = -1;
int type = messageBody.getType();
HandlerJobBuilder builder = (HandlerJobBuilder)_handlerJobBuilders.get(new Integer(type));
if (_log.shouldLog(Log.DEBUG))
_log.debug("Add message to the inNetMessage pool - builder: " + builder
+ " message class: " + messageBody.getClass().getName());
if (builder != null) {
Job job = builder.createJob(messageBody, msg.getFromRouter(),
msg.getFromRouterHash(), msg.getReplyBlock());
if (job != null) {
_context.jobQueue().addJob(job);
synchronized (_messages) {
size = _messages.size();
}
}
}
List origMessages = _context.messageRegistry().getOriginalMessages(messageBody);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Original messages for inbound message: " + origMessages.size());
if (origMessages.size() > 1) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Orig: " + origMessages + " \nthe above are replies for: " + msg,
new Exception("Multiple matches"));
}
for (int i = 0; i < origMessages.size(); i++) {
OutNetMessage omsg = (OutNetMessage)origMessages.get(i);
ReplyJob job = omsg.getOnReplyJob();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Original message [" + i + "] " + omsg.getReplySelector()
+ " : " + omsg + ": reply job: " + job);
if (job != null) {
job.setMessage(messageBody);
_context.jobQueue().addJob(job);
}
}
if (origMessages.size() <= 0) {
// not handled as a reply
if (size == -1) {
// was not handled via HandlerJobBuilder
_context.messageHistory().droppedOtherMessage(messageBody);
if (type == DeliveryStatusMessage.MESSAGE_TYPE) {
long timeSinceSent = _context.clock().now() -
((DeliveryStatusMessage)messageBody).getArrival().getTime();
if (_log.shouldLog(Log.INFO))
_log.info("Dropping unhandled delivery status message created " + timeSinceSent + "ms ago: " + msg);
_context.statManager().addRateData("inNetPool.droppedDeliveryStatusDelay", timeSinceSent, timeSinceSent);
} else {
if (_log.shouldLog(Log.ERROR))
_log.error("Message " + messageBody + " was not handled by a HandlerJobBuilder - DROPPING: "
+ msg, new Exception("DROPPED MESSAGE"));
_context.statManager().addRateData("inNetPool.dropped", 1, 0);
}
} else {
String mtype = messageBody.getClass().getName();
_context.messageHistory().receiveMessage(mtype, messageBody.getUniqueId(),
messageBody.getMessageExpiration(),
msg.getFromRouterHash(), true);
return size;
}
}
String mtype = messageBody.getClass().getName();
_context.messageHistory().receiveMessage(mtype, messageBody.getUniqueId(),
messageBody.getMessageExpiration(),
msg.getFromRouterHash(), true);
return size;
}
| public int add(InNetMessage msg) {
I2NPMessage messageBody = msg.getMessage();
msg.processingComplete();
Date exp = messageBody.getMessageExpiration();
boolean valid = _context.messageValidator().validateMessage(messageBody.getUniqueId(), exp.getTime());
if (!valid) {
if (_log.shouldLog(Log.WARN))
_log.warn("Duplicate message received [" + messageBody.getUniqueId()
+ " expiring on " + exp + "]: " + messageBody.getClass().getName());
_context.statManager().addRateData("inNetPool.dropped", 1, 0);
_context.statManager().addRateData("inNetPool.duplicate", 1, 0);
_context.messageHistory().droppedOtherMessage(messageBody);
_context.messageHistory().messageProcessingError(messageBody.getUniqueId(),
messageBody.getClass().getName(),
"Duplicate/expired");
return -1;
} else {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Message received [" + messageBody.getUniqueId()
+ " expiring on " + exp + "] is NOT a duplicate or exipired");
}
int size = -1;
int type = messageBody.getType();
HandlerJobBuilder builder = (HandlerJobBuilder)_handlerJobBuilders.get(new Integer(type));
if (_log.shouldLog(Log.DEBUG))
_log.debug("Add message to the inNetMessage pool - builder: " + builder
+ " message class: " + messageBody.getClass().getName());
if (builder != null) {
Job job = builder.createJob(messageBody, msg.getFromRouter(),
msg.getFromRouterHash(), msg.getReplyBlock());
if (job != null) {
_context.jobQueue().addJob(job);
synchronized (_messages) {
size = _messages.size();
}
}
}
List origMessages = _context.messageRegistry().getOriginalMessages(messageBody);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Original messages for inbound message: " + origMessages.size());
if (origMessages.size() > 1) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Orig: " + origMessages + " \nthe above are replies for: " + msg,
new Exception("Multiple matches"));
}
for (int i = 0; i < origMessages.size(); i++) {
OutNetMessage omsg = (OutNetMessage)origMessages.get(i);
ReplyJob job = omsg.getOnReplyJob();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Original message [" + i + "] " + omsg.getReplySelector()
+ " : " + omsg + ": reply job: " + job);
if (job != null) {
job.setMessage(messageBody);
_context.jobQueue().addJob(job);
}
}
if (origMessages.size() <= 0) {
// not handled as a reply
if (size == -1) {
// was not handled via HandlerJobBuilder
_context.messageHistory().droppedOtherMessage(messageBody);
if (type == DeliveryStatusMessage.MESSAGE_TYPE) {
long timeSinceSent = _context.clock().now() -
((DeliveryStatusMessage)messageBody).getArrival().getTime();
if (_log.shouldLog(Log.INFO))
_log.info("Dropping unhandled delivery status message created " + timeSinceSent + "ms ago: " + msg);
_context.statManager().addRateData("inNetPool.droppedDeliveryStatusDelay", timeSinceSent, timeSinceSent);
} else {
if (_log.shouldLog(Log.ERROR))
_log.error("Message " + messageBody + " expiring on "
+ (messageBody != null ? (messageBody.getMessageExpiration()+"") : " [unknown]")
+ " was not handled by a HandlerJobBuilder - DROPPING: "
+ msg, new Exception("DROPPED MESSAGE"));
_context.statManager().addRateData("inNetPool.dropped", 1, 0);
}
} else {
String mtype = messageBody.getClass().getName();
_context.messageHistory().receiveMessage(mtype, messageBody.getUniqueId(),
messageBody.getMessageExpiration(),
msg.getFromRouterHash(), true);
return size;
}
}
String mtype = messageBody.getClass().getName();
_context.messageHistory().receiveMessage(mtype, messageBody.getUniqueId(),
messageBody.getMessageExpiration(),
msg.getFromRouterHash(), true);
return size;
}
|
diff --git a/src/com/android/settings/cyanogenmod/ScreenSecurity.java b/src/com/android/settings/cyanogenmod/ScreenSecurity.java
index 6ab6236b..c196d940 100644
--- a/src/com/android/settings/cyanogenmod/ScreenSecurity.java
+++ b/src/com/android/settings/cyanogenmod/ScreenSecurity.java
@@ -1,460 +1,460 @@
/*
* Copyright (C) 2012 CyanogenMod
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.cyanogenmod;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import java.util.ArrayList;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.util.Log;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.ChooseLockSettingsHelper;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
public class ScreenSecurity extends SettingsPreferenceFragment implements
Preference.OnPreferenceChangeListener, DialogInterface.OnClickListener {
private static final String TAG = "ScreenSecurity";
private static final String KEY_UNLOCK_SET_OR_CHANGE = "unlock_set_or_change";
private static final String KEY_BIOMETRIC_WEAK_IMPROVE_MATCHING = "biometric_weak_improve_matching";
private static final String KEY_LOCK_ENABLED = "lockenabled";
private static final String KEY_VISIBLE_PATTERN = "visiblepattern";
private static final String KEY_TACTILE_FEEDBACK_ENABLED = "unlock_tactile_feedback";
private static final String KEY_SECURITY_CATEGORY = "security_category";
private static final String KEY_LOCK_AFTER_TIMEOUT = "lock_after_timeout";
private static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST = 123;
private static final int CONFIRM_EXISTING_FOR_BIOMETRIC_IMPROVE_REQUEST = 124;
private static final String SLIDE_LOCK_DELAY_TOGGLE = "slide_lock_delay_toggle";
private static final String SLIDE_LOCK_TIMEOUT_DELAY = "slide_lock_timeout_delay";
private static final String SLIDE_LOCK_SCREENOFF_DELAY = "slide_lock_screenoff_delay";
private static final String MENU_UNLOCK_PREF = "menu_unlock";
private static final String LOCKSCREEN_QUICK_UNLOCK_CONTROL = "quick_unlock_control";
private LockPatternUtils mLockPatternUtils;
private CheckBoxPreference mSlideLockDelayToggle;
private ListPreference mSlideLockTimeoutDelay;
private ListPreference mSlideLockScreenOffDelay;
DevicePolicyManager mDPM;
private ChooseLockSettingsHelper mChooseLockSettingsHelper;
private ListPreference mLockAfter;
private CheckBoxPreference mVisiblePattern;
private CheckBoxPreference mTactileFeedback;
private CheckBoxPreference mMenuUnlock;
private CheckBoxPreference mQuickUnlockScreen;
boolean mHasNavigationBar = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLockPatternUtils = new LockPatternUtils(getActivity());
mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
mChooseLockSettingsHelper = new ChooseLockSettingsHelper(getActivity());
}
private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.screen_security);
root = getPreferenceScreen();
// Add options for lock/unlock screen
int resid = 0;
if (!mLockPatternUtils.isSecure()) {
if (mLockPatternUtils.isLockScreenDisabled()) {
resid = R.xml.security_settings_lockscreen;
} else {
resid = R.xml.security_settings_chooser;
}
} else if (mLockPatternUtils.usingBiometricWeak() &&
mLockPatternUtils.isBiometricWeakInstalled()) {
resid = R.xml.security_settings_biometric_weak;
} else {
switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {
case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
resid = R.xml.security_settings_pattern;
break;
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
resid = R.xml.security_settings_pin;
break;
case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
resid = R.xml.security_settings_password;
break;
}
}
addPreferencesFromResource(resid);
// lock after preference
// For secure lock screen the default AOSP time delay implementation is used
// For slide lock screen use the CyanogenMod slide lock delay and timeout settings
mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);
if (mLockAfter != null) {
setupLockAfterPreference();
updateLockAfterPreferenceSummary();
} else if (!mLockPatternUtils.isLockScreenDisabled()) {
addPreferencesFromResource(R.xml.security_settings_slide_delay_cyanogenmod);
mSlideLockDelayToggle = (CheckBoxPreference) root
.findPreference(SLIDE_LOCK_DELAY_TOGGLE);
mSlideLockDelayToggle.setChecked(Settings.System.getInt(getActivity()
.getApplicationContext().getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_DELAY_TOGGLE, 0) == 1);
mSlideLockTimeoutDelay = (ListPreference) root
.findPreference(SLIDE_LOCK_TIMEOUT_DELAY);
int slideTimeoutDelay = Settings.System.getInt(getActivity().getApplicationContext()
.getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_TIMEOUT_DELAY, 5000);
mSlideLockTimeoutDelay.setValue(String.valueOf(slideTimeoutDelay));
updateSlideAfterTimeoutSummary();
mSlideLockTimeoutDelay.setOnPreferenceChangeListener(this);
mSlideLockScreenOffDelay = (ListPreference) root
.findPreference(SLIDE_LOCK_SCREENOFF_DELAY);
int slideScreenOffDelay = Settings.System.getInt(getActivity().getApplicationContext()
.getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_SCREENOFF_DELAY, 0);
mSlideLockScreenOffDelay.setValue(String.valueOf(slideScreenOffDelay));
updateSlideAfterScreenOffSummary();
mSlideLockScreenOffDelay.setOnPreferenceChangeListener(this);
}
// visible pattern
mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
// don't display visible pattern if biometric and backup is not pattern
if (resid == R.xml.security_settings_biometric_weak &&
mLockPatternUtils.getKeyguardStoredPasswordQuality() !=
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mVisiblePattern != null) {
securityCategory.removePreference(root.findPreference(KEY_VISIBLE_PATTERN));
}
}
// tactile feedback. Should be common to all unlock preference screens.
mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);
if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mTactileFeedback != null) {
securityCategory.removePreference(mTactileFeedback);
}
}
// Add the additional CyanogenMod settings
addPreferencesFromResource(R.xml.security_settings_cyanogenmod);
// Quick Unlock Screen Control
mQuickUnlockScreen = (CheckBoxPreference) root
.findPreference(LOCKSCREEN_QUICK_UNLOCK_CONTROL);
mQuickUnlockScreen.setChecked(Settings.System.getInt(getActivity()
.getApplicationContext().getContentResolver(),
Settings.System.LOCKSCREEN_QUICK_UNLOCK_CONTROL, 0) == 1);
// Menu Unlock
mMenuUnlock = (CheckBoxPreference) root.findPreference(MENU_UNLOCK_PREF);
mMenuUnlock.setChecked(Settings.System.getInt(getActivity().getApplicationContext()
.getContentResolver(),
Settings.System.MENU_UNLOCK_SCREEN, 0) == 1);
// disable lock options if lock screen set to NONE
if (!mLockPatternUtils.isSecure() && mLockPatternUtils.isLockScreenDisabled()) {
mQuickUnlockScreen.setEnabled(false);
mMenuUnlock.setEnabled(false);
}
//Disable the MenuUnlock setting if no menu button is available
- if (!getActivity().getApplicationContext().getResources()
+ if (getActivity().getApplicationContext().getResources()
.getBoolean(com.android.internal.R.bool.config_showNavigationBar)) {
mMenuUnlock.setEnabled(false);
}
return root;
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void updateSlideAfterTimeoutSummary() {
// Update summary message with current value
long currentTimeout = Settings.System.getInt(getActivity().getApplicationContext()
.getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_TIMEOUT_DELAY, 5000);
final CharSequence[] entries = mSlideLockTimeoutDelay.getEntries();
final CharSequence[] values = mSlideLockTimeoutDelay.getEntryValues();
int best = 0;
for (int i = 0; i < values.length; i++) {
long timeout = Long.valueOf(values[i].toString());
if (currentTimeout >= timeout) {
best = i;
}
}
mSlideLockTimeoutDelay.setSummary(entries[best]);
}
private void updateSlideAfterScreenOffSummary() {
// Update summary message with current value
long currentTimeout = Settings.System.getInt(getActivity().getApplicationContext()
.getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_SCREENOFF_DELAY, 0);
final CharSequence[] entries = mSlideLockScreenOffDelay.getEntries();
final CharSequence[] values = mSlideLockScreenOffDelay.getEntryValues();
int best = 0;
for (int i = 0; i < values.length; i++) {
long timeout = Long.valueOf(values[i].toString());
if (currentTimeout >= timeout) {
best = i;
}
}
mSlideLockScreenOffDelay.setSummary(entries[best]);
}
private void setupLockAfterPreference() {
// Compatible with pre-Froyo
long currentTimeout = Settings.Secure.getLong(getContentResolver(),
Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
mLockAfter.setValue(String.valueOf(currentTimeout));
mLockAfter.setOnPreferenceChangeListener(this);
final long adminTimeout = (mDPM != null ? mDPM.getMaximumTimeToLock(null) : 0);
final long displayTimeout = Math.max(0,
Settings.System.getInt(getContentResolver(), SCREEN_OFF_TIMEOUT, 0));
if (adminTimeout > 0) {
// This setting is a slave to display timeout when a device policy
// is enforced.
// As such, maxLockTimeout = adminTimeout - displayTimeout.
// If there isn't enough time, shows "immediately" setting.
disableUnusableTimeouts(Math.max(0, adminTimeout - displayTimeout));
}
}
private void updateLockAfterPreferenceSummary() {
// Update summary message with current value
long currentTimeout = Settings.Secure.getLong(getContentResolver(),
Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
final CharSequence[] entries = mLockAfter.getEntries();
final CharSequence[] values = mLockAfter.getEntryValues();
int best = 0;
for (int i = 0; i < values.length; i++) {
long timeout = Long.valueOf(values[i].toString());
if (currentTimeout >= timeout) {
best = i;
}
}
mLockAfter.setSummary(getString(R.string.lock_after_timeout_summary, entries[best]));
}
private void disableUnusableTimeouts(long maxTimeout) {
final CharSequence[] entries = mLockAfter.getEntries();
final CharSequence[] values = mLockAfter.getEntryValues();
ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>();
ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>();
for (int i = 0; i < values.length; i++) {
long timeout = Long.valueOf(values[i].toString());
if (timeout <= maxTimeout) {
revisedEntries.add(entries[i]);
revisedValues.add(values[i]);
}
}
if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) {
mLockAfter.setEntries(
revisedEntries.toArray(new CharSequence[revisedEntries.size()]));
mLockAfter.setEntryValues(
revisedValues.toArray(new CharSequence[revisedValues.size()]));
final int userPreference = Integer.valueOf(mLockAfter.getValue());
if (userPreference <= maxTimeout) {
mLockAfter.setValue(String.valueOf(userPreference));
} else {
// There will be no highlighted selection since nothing in the
// list matches
// maxTimeout. The user can still select anything less than
// maxTimeout.
// TODO: maybe append maxTimeout to the list and mark selected.
}
}
mLockAfter.setEnabled(revisedEntries.size() > 0);
}
@Override
public void onResume() {
super.onResume();
// Make sure we reload the preference hierarchy since some of these
// settings
// depend on others...
createPreferenceHierarchy();
final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
if (mVisiblePattern != null) {
mVisiblePattern.setChecked(lockPatternUtils.isVisiblePatternEnabled());
}
if (mTactileFeedback != null) {
mTactileFeedback.setChecked(lockPatternUtils.isTactileFeedbackEnabled());
}
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
boolean value;
final String key = preference.getKey();
final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
if (KEY_UNLOCK_SET_OR_CHANGE.equals(key)) {
startFragment(this, "com.android.settings.ChooseLockGeneric$ChooseLockGenericFragment",
SET_OR_CHANGE_LOCK_METHOD_REQUEST, null);
} else if (KEY_BIOMETRIC_WEAK_IMPROVE_MATCHING.equals(key)) {
ChooseLockSettingsHelper helper =
new ChooseLockSettingsHelper(this.getActivity(), this);
if (!helper.launchConfirmationActivity(
CONFIRM_EXISTING_FOR_BIOMETRIC_IMPROVE_REQUEST, null, null)) {
startBiometricWeakImprove(); // no password set, so no need to
// confirm
}
} else if (KEY_LOCK_ENABLED.equals(key)) {
lockPatternUtils.setLockPatternEnabled(isToggled(preference));
} else if (KEY_VISIBLE_PATTERN.equals(key)) {
lockPatternUtils.setVisiblePatternEnabled(isToggled(preference));
} else if (KEY_TACTILE_FEEDBACK_ENABLED.equals(key)) {
lockPatternUtils.setTactileFeedbackEnabled(isToggled(preference));
} else if (preference == mSlideLockDelayToggle) {
value = mSlideLockDelayToggle.isChecked();
Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_DELAY_TOGGLE, value ? 1 : 0);
} if (preference == mQuickUnlockScreen) {
value = mQuickUnlockScreen.isChecked();
Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(),
Settings.System.LOCKSCREEN_QUICK_UNLOCK_CONTROL, value ? 1 : 0);
} else if (preference == mMenuUnlock) {
value = mMenuUnlock.isChecked();
Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(),
Settings.System.MENU_UNLOCK_SCREEN, value ? 1 : 0);
} else {
// If we didn't handle it, let preferences handle it.
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
return true;
}
private boolean isToggled(Preference pref) {
return ((CheckBoxPreference) pref).isChecked();
}
/**
* see confirmPatternThenDisableAndClear
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CONFIRM_EXISTING_FOR_BIOMETRIC_IMPROVE_REQUEST &&
resultCode == Activity.RESULT_OK) {
startBiometricWeakImprove();
return;
}
createPreferenceHierarchy();
}
public boolean onPreferenceChange(Preference preference, Object value) {
if (preference == mLockAfter) {
int timeout = Integer.parseInt((String) value);
try {
Settings.Secure.putInt(getContentResolver(),
Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, timeout);
} catch (NumberFormatException e) {
Log.e("SecuritySettings", "could not persist lockAfter timeout setting", e);
}
updateLockAfterPreferenceSummary();
} else if (preference == mSlideLockTimeoutDelay) {
int slideTimeoutDelay = Integer.valueOf((String) value);
Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_TIMEOUT_DELAY,
slideTimeoutDelay);
updateSlideAfterTimeoutSummary();
} else if (preference == mSlideLockScreenOffDelay) {
int slideScreenOffDelay = Integer.valueOf((String) value);
Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_SCREENOFF_DELAY, slideScreenOffDelay);
updateSlideAfterScreenOffSummary();
}
return true;
}
public void startBiometricWeakImprove() {
Intent intent = new Intent();
intent.setClassName("com.android.facelock", "com.android.facelock.AddToSetup");
startActivity(intent);
}
@Override
public void onClick(DialogInterface dialog, int which) {
}
}
| true | true | private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.screen_security);
root = getPreferenceScreen();
// Add options for lock/unlock screen
int resid = 0;
if (!mLockPatternUtils.isSecure()) {
if (mLockPatternUtils.isLockScreenDisabled()) {
resid = R.xml.security_settings_lockscreen;
} else {
resid = R.xml.security_settings_chooser;
}
} else if (mLockPatternUtils.usingBiometricWeak() &&
mLockPatternUtils.isBiometricWeakInstalled()) {
resid = R.xml.security_settings_biometric_weak;
} else {
switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {
case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
resid = R.xml.security_settings_pattern;
break;
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
resid = R.xml.security_settings_pin;
break;
case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
resid = R.xml.security_settings_password;
break;
}
}
addPreferencesFromResource(resid);
// lock after preference
// For secure lock screen the default AOSP time delay implementation is used
// For slide lock screen use the CyanogenMod slide lock delay and timeout settings
mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);
if (mLockAfter != null) {
setupLockAfterPreference();
updateLockAfterPreferenceSummary();
} else if (!mLockPatternUtils.isLockScreenDisabled()) {
addPreferencesFromResource(R.xml.security_settings_slide_delay_cyanogenmod);
mSlideLockDelayToggle = (CheckBoxPreference) root
.findPreference(SLIDE_LOCK_DELAY_TOGGLE);
mSlideLockDelayToggle.setChecked(Settings.System.getInt(getActivity()
.getApplicationContext().getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_DELAY_TOGGLE, 0) == 1);
mSlideLockTimeoutDelay = (ListPreference) root
.findPreference(SLIDE_LOCK_TIMEOUT_DELAY);
int slideTimeoutDelay = Settings.System.getInt(getActivity().getApplicationContext()
.getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_TIMEOUT_DELAY, 5000);
mSlideLockTimeoutDelay.setValue(String.valueOf(slideTimeoutDelay));
updateSlideAfterTimeoutSummary();
mSlideLockTimeoutDelay.setOnPreferenceChangeListener(this);
mSlideLockScreenOffDelay = (ListPreference) root
.findPreference(SLIDE_LOCK_SCREENOFF_DELAY);
int slideScreenOffDelay = Settings.System.getInt(getActivity().getApplicationContext()
.getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_SCREENOFF_DELAY, 0);
mSlideLockScreenOffDelay.setValue(String.valueOf(slideScreenOffDelay));
updateSlideAfterScreenOffSummary();
mSlideLockScreenOffDelay.setOnPreferenceChangeListener(this);
}
// visible pattern
mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
// don't display visible pattern if biometric and backup is not pattern
if (resid == R.xml.security_settings_biometric_weak &&
mLockPatternUtils.getKeyguardStoredPasswordQuality() !=
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mVisiblePattern != null) {
securityCategory.removePreference(root.findPreference(KEY_VISIBLE_PATTERN));
}
}
// tactile feedback. Should be common to all unlock preference screens.
mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);
if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mTactileFeedback != null) {
securityCategory.removePreference(mTactileFeedback);
}
}
// Add the additional CyanogenMod settings
addPreferencesFromResource(R.xml.security_settings_cyanogenmod);
// Quick Unlock Screen Control
mQuickUnlockScreen = (CheckBoxPreference) root
.findPreference(LOCKSCREEN_QUICK_UNLOCK_CONTROL);
mQuickUnlockScreen.setChecked(Settings.System.getInt(getActivity()
.getApplicationContext().getContentResolver(),
Settings.System.LOCKSCREEN_QUICK_UNLOCK_CONTROL, 0) == 1);
// Menu Unlock
mMenuUnlock = (CheckBoxPreference) root.findPreference(MENU_UNLOCK_PREF);
mMenuUnlock.setChecked(Settings.System.getInt(getActivity().getApplicationContext()
.getContentResolver(),
Settings.System.MENU_UNLOCK_SCREEN, 0) == 1);
// disable lock options if lock screen set to NONE
if (!mLockPatternUtils.isSecure() && mLockPatternUtils.isLockScreenDisabled()) {
mQuickUnlockScreen.setEnabled(false);
mMenuUnlock.setEnabled(false);
}
//Disable the MenuUnlock setting if no menu button is available
if (!getActivity().getApplicationContext().getResources()
.getBoolean(com.android.internal.R.bool.config_showNavigationBar)) {
mMenuUnlock.setEnabled(false);
}
return root;
}
| private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.screen_security);
root = getPreferenceScreen();
// Add options for lock/unlock screen
int resid = 0;
if (!mLockPatternUtils.isSecure()) {
if (mLockPatternUtils.isLockScreenDisabled()) {
resid = R.xml.security_settings_lockscreen;
} else {
resid = R.xml.security_settings_chooser;
}
} else if (mLockPatternUtils.usingBiometricWeak() &&
mLockPatternUtils.isBiometricWeakInstalled()) {
resid = R.xml.security_settings_biometric_weak;
} else {
switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {
case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
resid = R.xml.security_settings_pattern;
break;
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
resid = R.xml.security_settings_pin;
break;
case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
resid = R.xml.security_settings_password;
break;
}
}
addPreferencesFromResource(resid);
// lock after preference
// For secure lock screen the default AOSP time delay implementation is used
// For slide lock screen use the CyanogenMod slide lock delay and timeout settings
mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);
if (mLockAfter != null) {
setupLockAfterPreference();
updateLockAfterPreferenceSummary();
} else if (!mLockPatternUtils.isLockScreenDisabled()) {
addPreferencesFromResource(R.xml.security_settings_slide_delay_cyanogenmod);
mSlideLockDelayToggle = (CheckBoxPreference) root
.findPreference(SLIDE_LOCK_DELAY_TOGGLE);
mSlideLockDelayToggle.setChecked(Settings.System.getInt(getActivity()
.getApplicationContext().getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_DELAY_TOGGLE, 0) == 1);
mSlideLockTimeoutDelay = (ListPreference) root
.findPreference(SLIDE_LOCK_TIMEOUT_DELAY);
int slideTimeoutDelay = Settings.System.getInt(getActivity().getApplicationContext()
.getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_TIMEOUT_DELAY, 5000);
mSlideLockTimeoutDelay.setValue(String.valueOf(slideTimeoutDelay));
updateSlideAfterTimeoutSummary();
mSlideLockTimeoutDelay.setOnPreferenceChangeListener(this);
mSlideLockScreenOffDelay = (ListPreference) root
.findPreference(SLIDE_LOCK_SCREENOFF_DELAY);
int slideScreenOffDelay = Settings.System.getInt(getActivity().getApplicationContext()
.getContentResolver(),
Settings.System.SCREEN_LOCK_SLIDE_SCREENOFF_DELAY, 0);
mSlideLockScreenOffDelay.setValue(String.valueOf(slideScreenOffDelay));
updateSlideAfterScreenOffSummary();
mSlideLockScreenOffDelay.setOnPreferenceChangeListener(this);
}
// visible pattern
mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
// don't display visible pattern if biometric and backup is not pattern
if (resid == R.xml.security_settings_biometric_weak &&
mLockPatternUtils.getKeyguardStoredPasswordQuality() !=
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mVisiblePattern != null) {
securityCategory.removePreference(root.findPreference(KEY_VISIBLE_PATTERN));
}
}
// tactile feedback. Should be common to all unlock preference screens.
mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);
if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mTactileFeedback != null) {
securityCategory.removePreference(mTactileFeedback);
}
}
// Add the additional CyanogenMod settings
addPreferencesFromResource(R.xml.security_settings_cyanogenmod);
// Quick Unlock Screen Control
mQuickUnlockScreen = (CheckBoxPreference) root
.findPreference(LOCKSCREEN_QUICK_UNLOCK_CONTROL);
mQuickUnlockScreen.setChecked(Settings.System.getInt(getActivity()
.getApplicationContext().getContentResolver(),
Settings.System.LOCKSCREEN_QUICK_UNLOCK_CONTROL, 0) == 1);
// Menu Unlock
mMenuUnlock = (CheckBoxPreference) root.findPreference(MENU_UNLOCK_PREF);
mMenuUnlock.setChecked(Settings.System.getInt(getActivity().getApplicationContext()
.getContentResolver(),
Settings.System.MENU_UNLOCK_SCREEN, 0) == 1);
// disable lock options if lock screen set to NONE
if (!mLockPatternUtils.isSecure() && mLockPatternUtils.isLockScreenDisabled()) {
mQuickUnlockScreen.setEnabled(false);
mMenuUnlock.setEnabled(false);
}
//Disable the MenuUnlock setting if no menu button is available
if (getActivity().getApplicationContext().getResources()
.getBoolean(com.android.internal.R.bool.config_showNavigationBar)) {
mMenuUnlock.setEnabled(false);
}
return root;
}
|
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/services/BbsDashClockExtension.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/services/BbsDashClockExtension.java
index cd0c7f9e..3891bb90 100644
--- a/BetterBatteryStats/src/com/asksven/betterbatterystats/services/BbsDashClockExtension.java
+++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/services/BbsDashClockExtension.java
@@ -1,140 +1,147 @@
/*
* Copyright (C) 2011-2013 asksven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asksven.betterbatterystats.services;
import java.util.ArrayList;
import com.asksven.android.common.privateapiproxies.BatteryStatsProxy;
import com.asksven.android.common.privateapiproxies.Misc;
import com.asksven.android.common.privateapiproxies.StatElement;
import com.asksven.android.common.utils.DateUtils;
import com.asksven.betterbatterystats.LogSettings;
import com.asksven.betterbatterystats.PreferencesActivity;
import com.asksven.betterbatterystats.R;
import com.asksven.betterbatterystats.StatsActivity;
import com.asksven.betterbatterystats.data.Reference;
import com.asksven.betterbatterystats.data.ReferenceStore;
import com.asksven.betterbatterystats.data.StatsProvider;
import com.asksven.betterbatterystats.widgetproviders.SmallWidgetProvider;
import com.asksven.betterbatterystats.widgets.WidgetBattery;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
public class BbsDashClockExtension extends DashClockExtension
{
private static final String TAG = "BbsDashClockExtension";
public static final String PREF_NAME = "pref_name";
@Override
protected void onUpdateData(int reason)
{
// Get preference value.
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// we want to refresh out stats each time the screen goes on
setUpdateWhenScreenOn(true);
// collect some data
String refFrom = sharedPrefs.getString("dashclock_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
long timeAwake = 0;
long timeSince = 0;
long drain = 0;
String strAwake = "";
String strDrain = "";
StatsProvider stats = StatsProvider.getInstance(this);
// make sure to flush cache
BatteryStatsProxy.getInstance(this).invalidate();
try
{
Reference toRef = StatsProvider.getInstance(this).getUncachedPartialReference(0);
Reference fromRef = ReferenceStore.getReferenceByName(refFrom, this);
ArrayList<StatElement> otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
timeSince = stats.getSince(fromRef, toRef);
drain = stats.getBatteryLevelStat(fromRef, toRef);
if ( (otherStats == null) || ( otherStats.size() == 1) )
{
// the desired stat type is unavailable, pick the alternate one and go on with that one
refFrom = sharedPrefs.getString("dashclock_fallback_stat_type", Reference.UNPLUGGED_REF_FILENAME);
fromRef = ReferenceStore.getReferenceByName(refFrom, this);
otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
}
if ( (otherStats != null) && ( otherStats.size() > 1) )
{
Misc timeAwakeStat = (Misc) stats.getElementByKey(otherStats, "Awake");
if (timeAwakeStat != null)
{
timeAwake = timeAwakeStat.getTimeOn();
}
else
{
timeAwake = 0;
}
}
}
catch (Exception e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
finally
{
if (LogSettings.DEBUG)
{
Log.d(TAG, "Awake: " + DateUtils.formatDuration(timeAwake));
Log.d(TAG, "Since: " + DateUtils.formatDuration(timeSince));
Log.d(TAG, "Drain: " + drain);
- Log.d(TAG, "Drain %/h: " + drain/timeSince);
+ if (timeSince != 0)
+ {
+ Log.d(TAG, "Drain %/h: " + drain/timeSince);
+ }
+ else
+ {
+ Log.d(TAG, "Drain %/h: 0");
+ }
}
strAwake = DateUtils.formatDurationCompressed(timeAwake);
if (timeSince != 0)
{
float pct = drain / ((float)timeSince / 1000F / 60F / 60F);
strDrain = String.format("%.1f", pct) + "%/h";
}
else
{
strDrain = "0 %/h";
}
}
String refs = getString(R.string.label_since) + " " + Reference.getLabel(refFrom);
// Publish the extension data update.
publishUpdate(new ExtensionData().visible(true).icon(R.drawable.icon_notext).status(strDrain)
.expandedTitle(strAwake + " " + getString(R.string.label_awake_abbrev) + ", " + strDrain).expandedBody(refs)
.clickIntent(new Intent(this, StatsActivity.class)));
}
}
| true | true | protected void onUpdateData(int reason)
{
// Get preference value.
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// we want to refresh out stats each time the screen goes on
setUpdateWhenScreenOn(true);
// collect some data
String refFrom = sharedPrefs.getString("dashclock_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
long timeAwake = 0;
long timeSince = 0;
long drain = 0;
String strAwake = "";
String strDrain = "";
StatsProvider stats = StatsProvider.getInstance(this);
// make sure to flush cache
BatteryStatsProxy.getInstance(this).invalidate();
try
{
Reference toRef = StatsProvider.getInstance(this).getUncachedPartialReference(0);
Reference fromRef = ReferenceStore.getReferenceByName(refFrom, this);
ArrayList<StatElement> otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
timeSince = stats.getSince(fromRef, toRef);
drain = stats.getBatteryLevelStat(fromRef, toRef);
if ( (otherStats == null) || ( otherStats.size() == 1) )
{
// the desired stat type is unavailable, pick the alternate one and go on with that one
refFrom = sharedPrefs.getString("dashclock_fallback_stat_type", Reference.UNPLUGGED_REF_FILENAME);
fromRef = ReferenceStore.getReferenceByName(refFrom, this);
otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
}
if ( (otherStats != null) && ( otherStats.size() > 1) )
{
Misc timeAwakeStat = (Misc) stats.getElementByKey(otherStats, "Awake");
if (timeAwakeStat != null)
{
timeAwake = timeAwakeStat.getTimeOn();
}
else
{
timeAwake = 0;
}
}
}
catch (Exception e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
finally
{
if (LogSettings.DEBUG)
{
Log.d(TAG, "Awake: " + DateUtils.formatDuration(timeAwake));
Log.d(TAG, "Since: " + DateUtils.formatDuration(timeSince));
Log.d(TAG, "Drain: " + drain);
Log.d(TAG, "Drain %/h: " + drain/timeSince);
}
strAwake = DateUtils.formatDurationCompressed(timeAwake);
if (timeSince != 0)
{
float pct = drain / ((float)timeSince / 1000F / 60F / 60F);
strDrain = String.format("%.1f", pct) + "%/h";
}
else
{
strDrain = "0 %/h";
}
}
String refs = getString(R.string.label_since) + " " + Reference.getLabel(refFrom);
// Publish the extension data update.
publishUpdate(new ExtensionData().visible(true).icon(R.drawable.icon_notext).status(strDrain)
.expandedTitle(strAwake + " " + getString(R.string.label_awake_abbrev) + ", " + strDrain).expandedBody(refs)
.clickIntent(new Intent(this, StatsActivity.class)));
}
| protected void onUpdateData(int reason)
{
// Get preference value.
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// we want to refresh out stats each time the screen goes on
setUpdateWhenScreenOn(true);
// collect some data
String refFrom = sharedPrefs.getString("dashclock_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
long timeAwake = 0;
long timeSince = 0;
long drain = 0;
String strAwake = "";
String strDrain = "";
StatsProvider stats = StatsProvider.getInstance(this);
// make sure to flush cache
BatteryStatsProxy.getInstance(this).invalidate();
try
{
Reference toRef = StatsProvider.getInstance(this).getUncachedPartialReference(0);
Reference fromRef = ReferenceStore.getReferenceByName(refFrom, this);
ArrayList<StatElement> otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
timeSince = stats.getSince(fromRef, toRef);
drain = stats.getBatteryLevelStat(fromRef, toRef);
if ( (otherStats == null) || ( otherStats.size() == 1) )
{
// the desired stat type is unavailable, pick the alternate one and go on with that one
refFrom = sharedPrefs.getString("dashclock_fallback_stat_type", Reference.UNPLUGGED_REF_FILENAME);
fromRef = ReferenceStore.getReferenceByName(refFrom, this);
otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
}
if ( (otherStats != null) && ( otherStats.size() > 1) )
{
Misc timeAwakeStat = (Misc) stats.getElementByKey(otherStats, "Awake");
if (timeAwakeStat != null)
{
timeAwake = timeAwakeStat.getTimeOn();
}
else
{
timeAwake = 0;
}
}
}
catch (Exception e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
finally
{
if (LogSettings.DEBUG)
{
Log.d(TAG, "Awake: " + DateUtils.formatDuration(timeAwake));
Log.d(TAG, "Since: " + DateUtils.formatDuration(timeSince));
Log.d(TAG, "Drain: " + drain);
if (timeSince != 0)
{
Log.d(TAG, "Drain %/h: " + drain/timeSince);
}
else
{
Log.d(TAG, "Drain %/h: 0");
}
}
strAwake = DateUtils.formatDurationCompressed(timeAwake);
if (timeSince != 0)
{
float pct = drain / ((float)timeSince / 1000F / 60F / 60F);
strDrain = String.format("%.1f", pct) + "%/h";
}
else
{
strDrain = "0 %/h";
}
}
String refs = getString(R.string.label_since) + " " + Reference.getLabel(refFrom);
// Publish the extension data update.
publishUpdate(new ExtensionData().visible(true).icon(R.drawable.icon_notext).status(strDrain)
.expandedTitle(strAwake + " " + getString(R.string.label_awake_abbrev) + ", " + strDrain).expandedBody(refs)
.clickIntent(new Intent(this, StatsActivity.class)));
}
|
diff --git a/src/main/java/com/redhat/automationportal/scripts/RegenSplash.java b/src/main/java/com/redhat/automationportal/scripts/RegenSplash.java
index 1c0f517..dd43b4f 100644
--- a/src/main/java/com/redhat/automationportal/scripts/RegenSplash.java
+++ b/src/main/java/com/redhat/automationportal/scripts/RegenSplash.java
@@ -1,230 +1,230 @@
package com.redhat.automationportal.scripts;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import com.redhat.automationportal.base.AutomationBase;
import com.redhat.automationportal.rest.StringPair;
import com.redhat.ecs.commonutils.InetUtilities;
import com.redhat.ecs.commonutils.XMLUtilities;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* Requires:
*
* /opt/automation-interface/cvs/dummyeditor.sh to avoid editor prompts and errors.
* The script just needs to change the time stamp and add something to the file.
*
* #!/bin/sh
* echo "Automation Interface TOC Update" > $1
* sleep 1
* touch $1
* exit 0
*
* EDITOR environment variable needs to point to /opt/automation-interface/cvs/dummyeditor.sh
*
* Set "StrictHostKeyChecking no" in /etc/ssh/ssh_config to avoid key issues with cvs in a script
*
* empty http://empty.sourceforge.net/">http://empty.sourceforge.net/
* brewkoji http://download.devel.redhat.com/rel-eng/brew/rhel/6/
* publican >= 2.6 http://porkchop.redhat.com/rel-eng/repos/eng-rhel-6/x86_64/
* regensplash.rb https://engineering.redhat.com/trac/ContentServices/wiki/RegenSplash
* publican_build https://svn.devel.redhat.com/repos/ecs/toolkit/publican_build/publican_build
*/
public class RegenSplash extends AutomationBase
{
private static String BUILD = "20120105-0812";
//private static final String PRODUCT_RE = "<span id=\".*?\" class=\"product\">(?<product>.*?)</span>";
private static final String PASSWORD_ENV_VARIABLE_NAME = "PASSWORD";
private static final String SCRIPT_NAME = "regensplash.rb";
private static final String SCRIPT_PATH = "/opt/automation-interface/regensplash/" + SCRIPT_NAME;
private static final String DOCS_STAGE_DUMP_XML = "http://documentation-stage.bne.redhat.com/DUMP.xml";
private static final String DOCS_REDHAT_DUMP_XML = "http://docs.redhat.com/DUMP.xml";
private static final String DOCS_STAGE_TOC_URL = "http://documentation-stage.bne.redhat.com/docs/toc.html";
private static final String DOCS_REDHAT_TOC_URL = "http://docs.redhat.com/docs/toc.html";
private String product;
private String selectedSite;
private final List<StringPair> sites;
public RegenSplash()
{
this.sites = new ArrayList<StringPair>();
this.sites.add(new StringPair(DOCS_REDHAT_DUMP_XML, "Redhat Docs (Can take a few seconds to get the products)"));
this.sites.add(new StringPair(DOCS_STAGE_DUMP_XML, "Docs Stage"));
}
public List<StringPair> getSites()
{
return sites;
}
public String getBuild()
{
return BUILD;
}
public void setProduct(final String product)
{
this.product = product;
}
public String getProduct()
{
return product;
}
public void setSelectedSite(String selectedSite)
{
this.selectedSite = selectedSite;
}
public String getSelectedSite()
{
return selectedSite;
}
public List<String> getProducts(final String tocURL)
{
final List<String> products = new ArrayList<String>();
// add an empty string to represent a null selection
products.add("");
final String toc = new String(InetUtilities.getURLData(tocURL));
final Document doc = XMLUtilities.convertStringToDocument(toc);
if (doc != null)
{
final List<Node> productNodes = XMLUtilities.getNodes(doc.getDocumentElement(), "product");
for (final Node node : productNodes)
{
final String productName = node.getTextContent().replaceAll("_", " ").replaceAll("​", "").trim();
if (!products.contains(productName))
{
products.add(productName);
}
}
}
Collections.sort(products);
return products;
}
public boolean run()
{
final Integer randomInt = this.generateRandomInt();
if (!validateInput())
return false;
String tocURL = "";
if (this.selectedSite.equals(DOCS_STAGE_DUMP_XML))
tocURL = DOCS_STAGE_TOC_URL;
else if (this.selectedSite.equals(DOCS_REDHAT_DUMP_XML))
tocURL = DOCS_REDHAT_TOC_URL;
final String script =
/*
* Publican requires a Kerberos ticket to interact with the CVS repo.
* The Map we supply to the runScript function below contains the
* challenge / response data needed to supply the password.
*/
"kinit \\\"" + this.getUsername() + "\\\" " +
/* copy the script to the temporary directory */
"&& cp \\\"" + SCRIPT_PATH + "\\\" \\\"" + getTmpDirectory(randomInt) + "\\\" " +
/* create a temporary directory to hold the downloaded files */
"&& cd \\\"" + getTmpDirectory(randomInt) + "\\\" " +
/* run the regenplash.rb script */
- "&& ruby " + SCRIPT_NAME + " \\\"" + tocURL + "\\\"" + (this.product != null && this.product.length() == 0 ? " \\\"" + this.product + "\\\" " : " ") +
+ "&& ruby " + SCRIPT_NAME + " \\\"" + tocURL + "\\\"" + (this.product != null && !this.product.isEmpty() ? " \\\"" + this.product + "\\\" " : " ") +
/* dump the contents of the version_packages.txt and product_packages.txt files */
"&& echo -------------------" +
"&& echo version_packages.txt " +
"&& echo -------------------" +
"&& cat \\\"" + getTmpDirectory(randomInt) + "/version_packages.txt\\\" " +
"&& echo -------------------" +
"&& echo product_packages.txt " +
"&& echo -------------------" +
"&& cat \\\"" + getTmpDirectory(randomInt) + "/product_packages.txt\\\"";
/*
* Define some environment variables. The password is placed in a
* variable to prevent it from showing up in a ps listing. The CVSEDITOR
* variable is used to set the "editor" used by cvs to generate log
* messages. In this case the editor is just a script that changes the
* contents of the supplied file, and updates the time stamp:
*/
// #!/bin/sh
// # add a generic message echo
// "Automation Interface TOC Update" > $1
// # update the time stamp (has to be different by at least a second)
// sleep 1
// touch $1
// exit 0
final String[] environment = new String[] { PASSWORD_ENV_VARIABLE_NAME + "=" + this.getPassword(), "CVSEDITOR=/opt/automation-interface/cvs/dummyeditor.sh" };
/*
* The kinit command will expect to be fed a password for the current
* user. Here we define a challenge of REDHAT.COM to be responded with
* the users password.
*
* Use an environment variable to hold sensitive strings, like the
* password. This prevents the strings from showing up in a ps listing.
*/
final LinkedHashMap<String, String> responses = new LinkedHashMap<String, String>();
//responses.put("REDHAT.COM", "${" + PASSWORD_ENV_VARIABLE_NAME + "}");
responses.put("REDHAT.COM", this.getPassword());
runScript(script, randomInt, true, true, true, responses, environment);
cleanup(randomInt);
return true;
}
protected boolean validateInput()
{
if (super.validateInput())
{
if (selectedSite == null || selectedSite.length() == 0)
{
this.message = "You need to specify a site.";
return false;
}
boolean foundSite = false;
for (final StringPair item : this.sites)
{
if (item.getFirstString().equals(this.selectedSite))
{
foundSite = true;
break;
}
}
if (!foundSite)
{
this.message = "The site is not valid.";
return false;
}
return true;
}
return false;
}
}
| true | true | public boolean run()
{
final Integer randomInt = this.generateRandomInt();
if (!validateInput())
return false;
String tocURL = "";
if (this.selectedSite.equals(DOCS_STAGE_DUMP_XML))
tocURL = DOCS_STAGE_TOC_URL;
else if (this.selectedSite.equals(DOCS_REDHAT_DUMP_XML))
tocURL = DOCS_REDHAT_TOC_URL;
final String script =
/*
* Publican requires a Kerberos ticket to interact with the CVS repo.
* The Map we supply to the runScript function below contains the
* challenge / response data needed to supply the password.
*/
"kinit \\\"" + this.getUsername() + "\\\" " +
/* copy the script to the temporary directory */
"&& cp \\\"" + SCRIPT_PATH + "\\\" \\\"" + getTmpDirectory(randomInt) + "\\\" " +
/* create a temporary directory to hold the downloaded files */
"&& cd \\\"" + getTmpDirectory(randomInt) + "\\\" " +
/* run the regenplash.rb script */
"&& ruby " + SCRIPT_NAME + " \\\"" + tocURL + "\\\"" + (this.product != null && this.product.length() == 0 ? " \\\"" + this.product + "\\\" " : " ") +
/* dump the contents of the version_packages.txt and product_packages.txt files */
"&& echo -------------------" +
"&& echo version_packages.txt " +
"&& echo -------------------" +
"&& cat \\\"" + getTmpDirectory(randomInt) + "/version_packages.txt\\\" " +
"&& echo -------------------" +
"&& echo product_packages.txt " +
"&& echo -------------------" +
"&& cat \\\"" + getTmpDirectory(randomInt) + "/product_packages.txt\\\"";
/*
* Define some environment variables. The password is placed in a
* variable to prevent it from showing up in a ps listing. The CVSEDITOR
* variable is used to set the "editor" used by cvs to generate log
* messages. In this case the editor is just a script that changes the
* contents of the supplied file, and updates the time stamp:
*/
// #!/bin/sh
// # add a generic message echo
// "Automation Interface TOC Update" > $1
// # update the time stamp (has to be different by at least a second)
// sleep 1
// touch $1
// exit 0
final String[] environment = new String[] { PASSWORD_ENV_VARIABLE_NAME + "=" + this.getPassword(), "CVSEDITOR=/opt/automation-interface/cvs/dummyeditor.sh" };
/*
* The kinit command will expect to be fed a password for the current
* user. Here we define a challenge of REDHAT.COM to be responded with
* the users password.
*
* Use an environment variable to hold sensitive strings, like the
* password. This prevents the strings from showing up in a ps listing.
*/
final LinkedHashMap<String, String> responses = new LinkedHashMap<String, String>();
//responses.put("REDHAT.COM", "${" + PASSWORD_ENV_VARIABLE_NAME + "}");
responses.put("REDHAT.COM", this.getPassword());
runScript(script, randomInt, true, true, true, responses, environment);
cleanup(randomInt);
return true;
}
| public boolean run()
{
final Integer randomInt = this.generateRandomInt();
if (!validateInput())
return false;
String tocURL = "";
if (this.selectedSite.equals(DOCS_STAGE_DUMP_XML))
tocURL = DOCS_STAGE_TOC_URL;
else if (this.selectedSite.equals(DOCS_REDHAT_DUMP_XML))
tocURL = DOCS_REDHAT_TOC_URL;
final String script =
/*
* Publican requires a Kerberos ticket to interact with the CVS repo.
* The Map we supply to the runScript function below contains the
* challenge / response data needed to supply the password.
*/
"kinit \\\"" + this.getUsername() + "\\\" " +
/* copy the script to the temporary directory */
"&& cp \\\"" + SCRIPT_PATH + "\\\" \\\"" + getTmpDirectory(randomInt) + "\\\" " +
/* create a temporary directory to hold the downloaded files */
"&& cd \\\"" + getTmpDirectory(randomInt) + "\\\" " +
/* run the regenplash.rb script */
"&& ruby " + SCRIPT_NAME + " \\\"" + tocURL + "\\\"" + (this.product != null && !this.product.isEmpty() ? " \\\"" + this.product + "\\\" " : " ") +
/* dump the contents of the version_packages.txt and product_packages.txt files */
"&& echo -------------------" +
"&& echo version_packages.txt " +
"&& echo -------------------" +
"&& cat \\\"" + getTmpDirectory(randomInt) + "/version_packages.txt\\\" " +
"&& echo -------------------" +
"&& echo product_packages.txt " +
"&& echo -------------------" +
"&& cat \\\"" + getTmpDirectory(randomInt) + "/product_packages.txt\\\"";
/*
* Define some environment variables. The password is placed in a
* variable to prevent it from showing up in a ps listing. The CVSEDITOR
* variable is used to set the "editor" used by cvs to generate log
* messages. In this case the editor is just a script that changes the
* contents of the supplied file, and updates the time stamp:
*/
// #!/bin/sh
// # add a generic message echo
// "Automation Interface TOC Update" > $1
// # update the time stamp (has to be different by at least a second)
// sleep 1
// touch $1
// exit 0
final String[] environment = new String[] { PASSWORD_ENV_VARIABLE_NAME + "=" + this.getPassword(), "CVSEDITOR=/opt/automation-interface/cvs/dummyeditor.sh" };
/*
* The kinit command will expect to be fed a password for the current
* user. Here we define a challenge of REDHAT.COM to be responded with
* the users password.
*
* Use an environment variable to hold sensitive strings, like the
* password. This prevents the strings from showing up in a ps listing.
*/
final LinkedHashMap<String, String> responses = new LinkedHashMap<String, String>();
//responses.put("REDHAT.COM", "${" + PASSWORD_ENV_VARIABLE_NAME + "}");
responses.put("REDHAT.COM", this.getPassword());
runScript(script, randomInt, true, true, true, responses, environment);
cleanup(randomInt);
return true;
}
|
diff --git a/src/com/erman/football/server/service/LoginServiceImpl.java b/src/com/erman/football/server/service/LoginServiceImpl.java
index 8da142f..0918aee 100644
--- a/src/com/erman/football/server/service/LoginServiceImpl.java
+++ b/src/com/erman/football/server/service/LoginServiceImpl.java
@@ -1,107 +1,110 @@
package com.erman.football.server.service;
import javax.servlet.http.HttpServletRequest;
import com.erman.football.client.service.LoginService;
import com.erman.football.client.service.PlayerException;
import com.erman.football.server.data.Player;
import com.erman.football.server.data.Player_JDO_DB;
import com.erman.football.shared.ClientPlayer;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements LoginService{
public ClientPlayer login(ClientPlayer player) throws PlayerException {
ClientPlayer result = null;
HttpServletRequest request = this.getThreadLocalRequest();
if(player==null){
//Check if already logged in
String playerId = (String)request.getSession().getAttribute("player");
if(playerId == null){
return result;
}else{
if(playerId.equals("-1")){
result = new ClientPlayer();
result.setAdmin(true);
result.setEmail("admin@main");
result.setKey(0);
result.setName("admin");
return result;
}
Player playerDO = Player_JDO_DB.getUserbyId(Long.parseLong(playerId));
if(playerDO==null){
return result;
}else{
return playerDO.convert();
}
}
}
if(player.getFacebookId()!=0){
//facebook user. Add and return if not in db, return user if in db
+ //facebook user email should be null. this is not a good place to set it null
+ //but works for now
+ player.setEmail(null);
Player playerDO = Player_JDO_DB.getFacebookPlayer(player.getFacebookId());
if(playerDO==null){
try {
result = Player_JDO_DB.addUser(player);
request.getSession().setAttribute("player",String.valueOf(result.getKey()));
} catch (PlayerException e) {
//Should not be here for facebook user
}
return result;
}else{
//known facebook user
request.getSession().setAttribute("player",String.valueOf(playerDO.getKey()));
return playerDO.convert();
}
}
// a non facebook player supplied
if(player.getEmail().equals("admin")){
result = new ClientPlayer();
result.setAdmin(true);
result.setEmail("admin@main");
result.setKey(-1);
result.setName("admin");
request.getSession().setAttribute("player",String.valueOf(result.getKey()));
return result;
}
//Not admin not facebook user. Check if user is known
Player playerDO = Player_JDO_DB.getUser(player.getEmail());
if(playerDO==null){
//maybe it is a join. check name is present
if(player.getName()!=null && !player.getName().equals("") && !player.getName().equals("name")){
//it is a join. add user
return Player_JDO_DB.addUser(player);
}
// unknown user with no name provided. return null (not logged in)
return result;
}else{
//known user if username supplied it is a join
if(player.getName()!=null && !player.getName().equals("") && !player.getName().equals("name")){
//it is a join. throw exception
throw new PlayerException("Email kullaniliyor");
}
request.getSession().setAttribute("player",String.valueOf(playerDO.getKey()));
return playerDO.convert();
}
}
public ClientPlayer logout() {
HttpServletRequest request = this.getThreadLocalRequest();
String playerId = (String)request.getSession().getAttribute("player");
if(playerId == null){
return null;
}
request.getSession().setAttribute("player",null);
Player tmpPlayer = Player_JDO_DB.getUserbyId(Long.parseLong(playerId));
if(tmpPlayer!=null){
return tmpPlayer.convert();
}
return null;
}
}
| true | true | public ClientPlayer login(ClientPlayer player) throws PlayerException {
ClientPlayer result = null;
HttpServletRequest request = this.getThreadLocalRequest();
if(player==null){
//Check if already logged in
String playerId = (String)request.getSession().getAttribute("player");
if(playerId == null){
return result;
}else{
if(playerId.equals("-1")){
result = new ClientPlayer();
result.setAdmin(true);
result.setEmail("admin@main");
result.setKey(0);
result.setName("admin");
return result;
}
Player playerDO = Player_JDO_DB.getUserbyId(Long.parseLong(playerId));
if(playerDO==null){
return result;
}else{
return playerDO.convert();
}
}
}
if(player.getFacebookId()!=0){
//facebook user. Add and return if not in db, return user if in db
Player playerDO = Player_JDO_DB.getFacebookPlayer(player.getFacebookId());
if(playerDO==null){
try {
result = Player_JDO_DB.addUser(player);
request.getSession().setAttribute("player",String.valueOf(result.getKey()));
} catch (PlayerException e) {
//Should not be here for facebook user
}
return result;
}else{
//known facebook user
request.getSession().setAttribute("player",String.valueOf(playerDO.getKey()));
return playerDO.convert();
}
}
// a non facebook player supplied
if(player.getEmail().equals("admin")){
result = new ClientPlayer();
result.setAdmin(true);
result.setEmail("admin@main");
result.setKey(-1);
result.setName("admin");
request.getSession().setAttribute("player",String.valueOf(result.getKey()));
return result;
}
//Not admin not facebook user. Check if user is known
Player playerDO = Player_JDO_DB.getUser(player.getEmail());
if(playerDO==null){
//maybe it is a join. check name is present
if(player.getName()!=null && !player.getName().equals("") && !player.getName().equals("name")){
//it is a join. add user
return Player_JDO_DB.addUser(player);
}
// unknown user with no name provided. return null (not logged in)
return result;
}else{
//known user if username supplied it is a join
if(player.getName()!=null && !player.getName().equals("") && !player.getName().equals("name")){
//it is a join. throw exception
throw new PlayerException("Email kullaniliyor");
}
request.getSession().setAttribute("player",String.valueOf(playerDO.getKey()));
return playerDO.convert();
}
}
| public ClientPlayer login(ClientPlayer player) throws PlayerException {
ClientPlayer result = null;
HttpServletRequest request = this.getThreadLocalRequest();
if(player==null){
//Check if already logged in
String playerId = (String)request.getSession().getAttribute("player");
if(playerId == null){
return result;
}else{
if(playerId.equals("-1")){
result = new ClientPlayer();
result.setAdmin(true);
result.setEmail("admin@main");
result.setKey(0);
result.setName("admin");
return result;
}
Player playerDO = Player_JDO_DB.getUserbyId(Long.parseLong(playerId));
if(playerDO==null){
return result;
}else{
return playerDO.convert();
}
}
}
if(player.getFacebookId()!=0){
//facebook user. Add and return if not in db, return user if in db
//facebook user email should be null. this is not a good place to set it null
//but works for now
player.setEmail(null);
Player playerDO = Player_JDO_DB.getFacebookPlayer(player.getFacebookId());
if(playerDO==null){
try {
result = Player_JDO_DB.addUser(player);
request.getSession().setAttribute("player",String.valueOf(result.getKey()));
} catch (PlayerException e) {
//Should not be here for facebook user
}
return result;
}else{
//known facebook user
request.getSession().setAttribute("player",String.valueOf(playerDO.getKey()));
return playerDO.convert();
}
}
// a non facebook player supplied
if(player.getEmail().equals("admin")){
result = new ClientPlayer();
result.setAdmin(true);
result.setEmail("admin@main");
result.setKey(-1);
result.setName("admin");
request.getSession().setAttribute("player",String.valueOf(result.getKey()));
return result;
}
//Not admin not facebook user. Check if user is known
Player playerDO = Player_JDO_DB.getUser(player.getEmail());
if(playerDO==null){
//maybe it is a join. check name is present
if(player.getName()!=null && !player.getName().equals("") && !player.getName().equals("name")){
//it is a join. add user
return Player_JDO_DB.addUser(player);
}
// unknown user with no name provided. return null (not logged in)
return result;
}else{
//known user if username supplied it is a join
if(player.getName()!=null && !player.getName().equals("") && !player.getName().equals("name")){
//it is a join. throw exception
throw new PlayerException("Email kullaniliyor");
}
request.getSession().setAttribute("player",String.valueOf(playerDO.getKey()));
return playerDO.convert();
}
}
|
diff --git a/src/main/java/eu/europeana/portal2/web/controllers/utils/RSSFeedParser.java b/src/main/java/eu/europeana/portal2/web/controllers/utils/RSSFeedParser.java
index 78381763..97f1b804 100644
--- a/src/main/java/eu/europeana/portal2/web/controllers/utils/RSSFeedParser.java
+++ b/src/main/java/eu/europeana/portal2/web/controllers/utils/RSSFeedParser.java
@@ -1,235 +1,236 @@
/*
* Copyright 2007-2012 The Europeana Foundation
*
* Licenced under the EUPL, Version 1.1 (the "Licence") and subsequent versions as approved
* by the European Commission;
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* http://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the Licence is distributed on an "AS IS" basis, without warranties or conditions of
* any kind, either express or implied.
* See the Licence for the specific language governing permissions and limitations under
* the Licence.
*/
package eu.europeana.portal2.web.controllers.utils;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import eu.europeana.corelib.utils.ImageUtils;
import eu.europeana.portal2.web.presentation.model.data.submodel.FeedEntry;
public class RSSFeedParser {
static final String TITLE = "title";
static final String DESCRIPTION = "description";
static final String CHANNEL = "channel";
static final String LANGUAGE = "language";
static final String COPYRIGHT = "copyright";
static final String LINK = "link";
static final String AUTHOR = "author";
static final String ITEM = "item";
static final String PUB_DATE = "pubDate";
static final String GUID = "guid";
int[] responsiveWidths;
String[] fNames;
boolean useNormalImageFormat = true;
private final URL url;
String staticPagePath = "";
private final Logger log = Logger.getLogger(getClass().getName());
public void setStaticPagePath(String staticPagePath) {
this.staticPagePath = staticPagePath;
}
private int itemLimit;
public RSSFeedParser(String feedUrl, int itemLimit, String[] fNames, int[] responsiveWidths) {
try {
this.url = new URL(feedUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
this.itemLimit = itemLimit;
this.fNames = fNames;
this.responsiveWidths = responsiveWidths;
}
public RSSFeedParser(String feedUrl, int itemLimit, boolean useNormalImageFormat, String[] fNames, int[] responsiveWidths) {
this(feedUrl, itemLimit, fNames, responsiveWidths);
this.useNormalImageFormat = useNormalImageFormat;
}
private Map<String, String> createResponsiveImage(String location) {
Map<String, String> responsiveImages = new HashMap<String, String>();
String directory = staticPagePath + "/sp/rss-blog-cache/";
File dir = new File(directory);
if (!dir.exists()) {
dir.mkdir();
}
String extension = location.substring(location.lastIndexOf(".") + 1);
String nameWithoutExt = location.substring(0, location.lastIndexOf(".") - 1);
String toFS = nameWithoutExt.replace("/", "-").replace(":", "-").replace(".", "-");
BufferedImage orig = null;
try {
orig = ImageIO.read(new URL(location));
} catch (MalformedURLException e) {
log.severe("MalformedURLException during reading in location: " + e.getLocalizedMessage());
e.printStackTrace();
} catch (IOException e) {
log.severe("IOException during reading in location: " + e.getLocalizedMessage());
e.printStackTrace();
}
if (orig == null) {
return responsiveImages;
}
for (int i = 0, l = responsiveWidths.length; i<l; i++){
String fileName = toFS + fNames[i] + "." + extension;
// work out new image name
String fileUrl = "/sp/rss-blog-cache/" + fileName;
String filePath = directory + fileName;
log.info(String.format("new file is %s, url is %s, old file is %s, ", filePath, fileUrl, location));
BufferedImage responsive = null;
try {
- responsive = ImageUtils.scale(orig, responsiveWidths[i], 0); // zero-height to auto-calculate
+ int height = (int)Math.ceil((responsiveWidths[i] * orig.getHeight()) / orig.getWidth());
+ responsive = ImageUtils.scale(orig, responsiveWidths[i], height);
} catch (IOException e) {
log.severe("IOException during scaling image: " + e.getLocalizedMessage());
e.printStackTrace();
}
if (responsive == null) {
continue;
}
responsiveImages.put(fNames[i], fileUrl);
File outputfile = new File(filePath);
if (!outputfile.exists()) {
boolean created = false;
try {
created = outputfile.createNewFile();
} catch (IOException e) {
log.severe("IOException during create new file: " + e.getLocalizedMessage());
e.printStackTrace();
}
if (created) {
try {
ImageIO.write(responsive, extension, outputfile);
} catch (IOException e) {
log.severe("IOException during writing new file: " + e.getLocalizedMessage());
e.printStackTrace();
}
log.info("created");
}
}
}
return responsiveImages;
}
public List<FeedEntry> readFeed() {
try {
List<FeedEntry> feeds = new ArrayList<FeedEntry>();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(url.openStream());
NodeList nodes = doc.getElementsByTagName("item");
for (int i = 0; i < Math.min(nodes.getLength(), itemLimit); i++) {
Element element = (Element) nodes.item(i);
FeedEntry message = new FeedEntry();
if (element.getElementsByTagName(AUTHOR).getLength() > 0) {
message.setAuthor(getElementValue(element, "dc:creator"));
}
String description = getElementValue(element, DESCRIPTION);
message.setDescription(description);
message.setImages(RSSImageExtractor.extractImages(description, useNormalImageFormat));
// if no images, tries "content:encoded" element
if (message.getImages().size() == 0) {
message.setImages(
RSSImageExtractor.extractImages(
getElementValue(element, "content:encoded"),
useNormalImageFormat
)
);
}
// now we have the image URLs
for (RSSImage image : message.getImages()){
Map<String, String> responsiveFileNames = createResponsiveImage(image.getSrc());
image.setResponsiveFileNames(responsiveFileNames);
}
message.setGuid(getElementValue(element, GUID));
message.setLink(getElementValue(element, LINK));
message.setTitle(getElementValue(element, TITLE));
message.setPubDate(getElementValue(element, PUB_DATE));
feeds.add(message);
}
return feeds;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String getCharacterDataFromElement(Element e) {
try {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
} catch (Exception ex) {
}
return "";
} // private String getCharacterDataFromElement
protected float getFloat(String value) {
if (value != null && !value.equals(""))
return Float.parseFloat(value);
else
return 0;
}
protected String getElementValue(Element parent, String label) {
return getCharacterDataFromElement((Element) parent.getElementsByTagName(label).item(0));
}
}
| true | true | private Map<String, String> createResponsiveImage(String location) {
Map<String, String> responsiveImages = new HashMap<String, String>();
String directory = staticPagePath + "/sp/rss-blog-cache/";
File dir = new File(directory);
if (!dir.exists()) {
dir.mkdir();
}
String extension = location.substring(location.lastIndexOf(".") + 1);
String nameWithoutExt = location.substring(0, location.lastIndexOf(".") - 1);
String toFS = nameWithoutExt.replace("/", "-").replace(":", "-").replace(".", "-");
BufferedImage orig = null;
try {
orig = ImageIO.read(new URL(location));
} catch (MalformedURLException e) {
log.severe("MalformedURLException during reading in location: " + e.getLocalizedMessage());
e.printStackTrace();
} catch (IOException e) {
log.severe("IOException during reading in location: " + e.getLocalizedMessage());
e.printStackTrace();
}
if (orig == null) {
return responsiveImages;
}
for (int i = 0, l = responsiveWidths.length; i<l; i++){
String fileName = toFS + fNames[i] + "." + extension;
// work out new image name
String fileUrl = "/sp/rss-blog-cache/" + fileName;
String filePath = directory + fileName;
log.info(String.format("new file is %s, url is %s, old file is %s, ", filePath, fileUrl, location));
BufferedImage responsive = null;
try {
responsive = ImageUtils.scale(orig, responsiveWidths[i], 0); // zero-height to auto-calculate
} catch (IOException e) {
log.severe("IOException during scaling image: " + e.getLocalizedMessage());
e.printStackTrace();
}
if (responsive == null) {
continue;
}
responsiveImages.put(fNames[i], fileUrl);
File outputfile = new File(filePath);
if (!outputfile.exists()) {
boolean created = false;
try {
created = outputfile.createNewFile();
} catch (IOException e) {
log.severe("IOException during create new file: " + e.getLocalizedMessage());
e.printStackTrace();
}
if (created) {
try {
ImageIO.write(responsive, extension, outputfile);
} catch (IOException e) {
log.severe("IOException during writing new file: " + e.getLocalizedMessage());
e.printStackTrace();
}
log.info("created");
}
}
}
return responsiveImages;
}
| private Map<String, String> createResponsiveImage(String location) {
Map<String, String> responsiveImages = new HashMap<String, String>();
String directory = staticPagePath + "/sp/rss-blog-cache/";
File dir = new File(directory);
if (!dir.exists()) {
dir.mkdir();
}
String extension = location.substring(location.lastIndexOf(".") + 1);
String nameWithoutExt = location.substring(0, location.lastIndexOf(".") - 1);
String toFS = nameWithoutExt.replace("/", "-").replace(":", "-").replace(".", "-");
BufferedImage orig = null;
try {
orig = ImageIO.read(new URL(location));
} catch (MalformedURLException e) {
log.severe("MalformedURLException during reading in location: " + e.getLocalizedMessage());
e.printStackTrace();
} catch (IOException e) {
log.severe("IOException during reading in location: " + e.getLocalizedMessage());
e.printStackTrace();
}
if (orig == null) {
return responsiveImages;
}
for (int i = 0, l = responsiveWidths.length; i<l; i++){
String fileName = toFS + fNames[i] + "." + extension;
// work out new image name
String fileUrl = "/sp/rss-blog-cache/" + fileName;
String filePath = directory + fileName;
log.info(String.format("new file is %s, url is %s, old file is %s, ", filePath, fileUrl, location));
BufferedImage responsive = null;
try {
int height = (int)Math.ceil((responsiveWidths[i] * orig.getHeight()) / orig.getWidth());
responsive = ImageUtils.scale(orig, responsiveWidths[i], height);
} catch (IOException e) {
log.severe("IOException during scaling image: " + e.getLocalizedMessage());
e.printStackTrace();
}
if (responsive == null) {
continue;
}
responsiveImages.put(fNames[i], fileUrl);
File outputfile = new File(filePath);
if (!outputfile.exists()) {
boolean created = false;
try {
created = outputfile.createNewFile();
} catch (IOException e) {
log.severe("IOException during create new file: " + e.getLocalizedMessage());
e.printStackTrace();
}
if (created) {
try {
ImageIO.write(responsive, extension, outputfile);
} catch (IOException e) {
log.severe("IOException during writing new file: " + e.getLocalizedMessage());
e.printStackTrace();
}
log.info("created");
}
}
}
return responsiveImages;
}
|
diff --git a/beam-core/src/main/java/org/esa/beam/glayer/PlacemarkLayer.java b/beam-core/src/main/java/org/esa/beam/glayer/PlacemarkLayer.java
index 66607e365..92796a6e9 100644
--- a/beam-core/src/main/java/org/esa/beam/glayer/PlacemarkLayer.java
+++ b/beam-core/src/main/java/org/esa/beam/glayer/PlacemarkLayer.java
@@ -1,184 +1,188 @@
package org.esa.beam.glayer;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.Style;
import com.bc.ceres.grender.Rendering;
import com.bc.ceres.grender.Viewport;
import org.esa.beam.framework.datamodel.*;
import java.awt.*;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
public class PlacemarkLayer extends Layer {
public static final String PROPERTY_NAME_TEXT_FONT = "text.font";
public static final String PROPERTY_NAME_TEXT_ENABLED = "text.enabled";
public static final String PROPERTY_NAME_TEXT_FG_COLOR = "text.fg.color";
public static final String PROPERTY_NAME_TEXT_BG_COLOR = "text.bg.color";
private static final boolean DEFAULT_TEXT_ENABLED = false;
private static final Font DEFAULT_TEXT_FONT = new Font("Helvetica", Font.BOLD, 14);
private static final Color DEFAULT_TEXT_FG_COLOR = Color.WHITE;
private static final Color DEFAULT_TEXT_BG_COLOR = Color.BLACK;
private Product product;
private PlacemarkDescriptor placemarkDescriptor;
private final AffineTransform imageToModelTransform;
public PlacemarkLayer(Product product, PlacemarkDescriptor placemarkDescriptor, AffineTransform imageToModelTransform) {
this.product = product;
this.placemarkDescriptor = placemarkDescriptor;
this.imageToModelTransform = new AffineTransform(imageToModelTransform);
}
@Override
public void disposeLayer() {
product = null;
placemarkDescriptor = null;
}
protected ProductNodeGroup<Pin> getPlacemarkGroup() {
return placemarkDescriptor.getPlacemarkGroup(getProduct());
}
public Product getProduct() {
return product;
}
public AffineTransform getImageToModelTransform() {
return new AffineTransform(imageToModelTransform);
}
@Override
protected void renderLayer(Rendering rendering) {
Graphics2D g2d = rendering.getGraphics();
Viewport viewport = rendering.getViewport();
AffineTransform oldTransform = g2d.getTransform();
Object oldAntialiasing = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
Object oldTextAntialiasing = g2d.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
try {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
final AffineTransform transform = new AffineTransform();
transform.concatenate(oldTransform);
transform.concatenate(viewport.getModelToViewTransform());
transform.concatenate(imageToModelTransform);
g2d.setTransform(transform);
ProductNodeGroup<Pin> pinGroup = getPlacemarkGroup();
Pin[] pins = pinGroup.toArray(new Pin[pinGroup.getNodeCount()]);
for (final Pin pin : pins) {
final PixelPos pixelPos = pin.getPixelPos();
if (pixelPos != null) {
g2d.translate(pixelPos.getX(), pixelPos.getY());
+ final double scaleX = g2d.getTransform().getScaleX();
+ final double scaleY = g2d.getTransform().getScaleY();
+ g2d.scale(1 / scaleX, 1 / scaleY);
g2d.rotate(viewport.getOrientation());
if (pin.isSelected()) {
pin.getSymbol().drawSelected(g2d);
} else {
pin.getSymbol().draw(g2d);
}
if (isTextEnabled()) {
drawTextLabel(g2d, pin);
}
g2d.rotate(-viewport.getOrientation());
+ g2d.scale(scaleX, scaleY);
g2d.translate(-pixelPos.getX(), -pixelPos.getY());
}
}
} finally {
g2d.setTransform(oldTransform);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAntialiasing);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldTextAntialiasing);
}
}
private void drawTextLabel(Graphics2D g2d, Pin pin) {
final String label = pin.getLabel();
g2d.setFont(getTextFont());
GlyphVector glyphVector = getTextFont().createGlyphVector(g2d.getFontRenderContext(), label);
Rectangle2D logicalBounds = glyphVector.getLogicalBounds();
float tx = (float) (logicalBounds.getX() - 0.5 * logicalBounds.getWidth());
float ty = (float) (1.0 + logicalBounds.getHeight());
Shape outline = glyphVector.getOutline(tx, ty);
int[] alphas = new int[]{64, 128, 192, 255};
for (int i = 0; i < alphas.length; i++) {
BasicStroke selectionStroke = new BasicStroke((alphas.length - i));
Color selectionColor = new Color(getTextBgColor().getRed(),
getTextBgColor().getGreen(),
getTextBgColor().getGreen(),
alphas[i]);
g2d.setStroke(selectionStroke);
g2d.setPaint(selectionColor);
g2d.draw(outline);
}
g2d.setPaint(getTextFgColor());
g2d.fill(outline);
}
private boolean isTextEnabled() {
final Style style = getStyle();
if (style.hasProperty(PROPERTY_NAME_TEXT_ENABLED)) {
return (Boolean) style.getProperty(PROPERTY_NAME_TEXT_ENABLED);
}
return DEFAULT_TEXT_ENABLED;
}
public void setTextEnabled(boolean textEnabled) {
getStyle().setProperty(PROPERTY_NAME_TEXT_ENABLED, textEnabled);
}
public Font getTextFont() {
final Style style = getStyle();
if (style.hasProperty(PROPERTY_NAME_TEXT_FONT)) {
return (Font) style.getProperty(PROPERTY_NAME_TEXT_FONT);
}
return DEFAULT_TEXT_FONT;
}
public void setTextFont(Font font) {
getStyle().setProperty(PROPERTY_NAME_TEXT_FONT, font);
}
public Color getTextFgColor() {
final Style style = getStyle();
if (style.hasProperty(PROPERTY_NAME_TEXT_FG_COLOR)) {
return (Color) style.getProperty(PROPERTY_NAME_TEXT_FG_COLOR);
}
return DEFAULT_TEXT_FG_COLOR;
}
public void setTextFgColor(Color color) {
getStyle().setProperty(PROPERTY_NAME_TEXT_FG_COLOR, color);
}
public Color getTextBgColor() {
final Style style = getStyle();
if (style.hasProperty(PROPERTY_NAME_TEXT_BG_COLOR)) {
return (Color) style.getProperty(PROPERTY_NAME_TEXT_BG_COLOR);
}
return DEFAULT_TEXT_BG_COLOR;
}
public void setTextBgColor(Color color) {
getStyle().setProperty(PROPERTY_NAME_TEXT_BG_COLOR, color);
}
}
| false | true | protected void renderLayer(Rendering rendering) {
Graphics2D g2d = rendering.getGraphics();
Viewport viewport = rendering.getViewport();
AffineTransform oldTransform = g2d.getTransform();
Object oldAntialiasing = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
Object oldTextAntialiasing = g2d.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
try {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
final AffineTransform transform = new AffineTransform();
transform.concatenate(oldTransform);
transform.concatenate(viewport.getModelToViewTransform());
transform.concatenate(imageToModelTransform);
g2d.setTransform(transform);
ProductNodeGroup<Pin> pinGroup = getPlacemarkGroup();
Pin[] pins = pinGroup.toArray(new Pin[pinGroup.getNodeCount()]);
for (final Pin pin : pins) {
final PixelPos pixelPos = pin.getPixelPos();
if (pixelPos != null) {
g2d.translate(pixelPos.getX(), pixelPos.getY());
g2d.rotate(viewport.getOrientation());
if (pin.isSelected()) {
pin.getSymbol().drawSelected(g2d);
} else {
pin.getSymbol().draw(g2d);
}
if (isTextEnabled()) {
drawTextLabel(g2d, pin);
}
g2d.rotate(-viewport.getOrientation());
g2d.translate(-pixelPos.getX(), -pixelPos.getY());
}
}
} finally {
g2d.setTransform(oldTransform);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAntialiasing);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldTextAntialiasing);
}
}
| protected void renderLayer(Rendering rendering) {
Graphics2D g2d = rendering.getGraphics();
Viewport viewport = rendering.getViewport();
AffineTransform oldTransform = g2d.getTransform();
Object oldAntialiasing = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
Object oldTextAntialiasing = g2d.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
try {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
final AffineTransform transform = new AffineTransform();
transform.concatenate(oldTransform);
transform.concatenate(viewport.getModelToViewTransform());
transform.concatenate(imageToModelTransform);
g2d.setTransform(transform);
ProductNodeGroup<Pin> pinGroup = getPlacemarkGroup();
Pin[] pins = pinGroup.toArray(new Pin[pinGroup.getNodeCount()]);
for (final Pin pin : pins) {
final PixelPos pixelPos = pin.getPixelPos();
if (pixelPos != null) {
g2d.translate(pixelPos.getX(), pixelPos.getY());
final double scaleX = g2d.getTransform().getScaleX();
final double scaleY = g2d.getTransform().getScaleY();
g2d.scale(1 / scaleX, 1 / scaleY);
g2d.rotate(viewport.getOrientation());
if (pin.isSelected()) {
pin.getSymbol().drawSelected(g2d);
} else {
pin.getSymbol().draw(g2d);
}
if (isTextEnabled()) {
drawTextLabel(g2d, pin);
}
g2d.rotate(-viewport.getOrientation());
g2d.scale(scaleX, scaleY);
g2d.translate(-pixelPos.getX(), -pixelPos.getY());
}
}
} finally {
g2d.setTransform(oldTransform);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAntialiasing);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldTextAntialiasing);
}
}
|
diff --git a/src/edu/umw/cpsc/collegesim/Group.java b/src/edu/umw/cpsc/collegesim/Group.java
index acafe4b..008f67e 100644
--- a/src/edu/umw/cpsc/collegesim/Group.java
+++ b/src/edu/umw/cpsc/collegesim/Group.java
@@ -1,269 +1,271 @@
package edu.umw.cpsc.collegesim;
import java.util.ArrayList;
import ec.util.*;
import sim.engine.*;
/*TODO: clean up size stuff, maybe get rid of the variable all together and just keep the setter and use students.size() in the class.
* Should I change students to people? That way it would be consistant throughout the program
* maybe change factors to 0-1 rather than 0-10?
* What are we doing with tightness? Does it help determine recruitement? Or should it deal with leaving a group?
* maybe have a max/min num students per group factor?
*/
public class Group implements Steppable{
//all hard coded rands are subject to change
private final int MINIMUM_START_GROUP_SIZE = 3;
private final int MAXIMUM_START_GROUP_SIZE = 8;
private final int RECRUITMENT_REQUIRED = 8; //lower this to accept more students in group per step
private final double LIKELYHOOD_OF_RANDOMLY_LEAVING_GROUP = .1; //increase this to remove more students in group per step
private final double LIKELYHOOD_OF_RANDOMLY_CHANGING_ATTRIBUTE = .1;
private int id;
private int size = 0;//based on how many people join-- affects it for now by decreasing the recruitment factor when increased-- gotta think of a way to scale it though to effect the closeness appropriately
private int tightness=0;//based on individual students' willingness to make friends in the group
private int frequency;//random 1-10
private int recruitmentFactor;//random 1-10
static MersenneTwisterFast rand;
private ArrayList<Person> students;
public Group(int x){
id = x;
rand = Sim.instance( ).random;
frequency=rand.nextInt(10)+1;
recruitmentFactor=rand.nextInt(10)+1;
students = new ArrayList<Person>();
}
void selectStartingStudents(ArrayList<Person> people){
int initialGroupSize = rand.nextInt(MAXIMUM_START_GROUP_SIZE-MINIMUM_START_GROUP_SIZE)+MINIMUM_START_GROUP_SIZE+1;
Person randStudent;
if(initialGroupSize>Sim.getNumPeople()){
initialGroupSize=Sim.getNumPeople(); //to insure the initial group size is never greater than the number of total people
}
for(int x = 0; x < initialGroupSize; x++){
randStudent = people.get(rand.nextInt(people.size()));
while(doesGroupContainStudent(randStudent)){
randStudent = people.get(rand.nextInt(people.size()));
}
students.add(randStudent);
randStudent.joinGroup(this);
}
size = students.size();
}
void recruitStudent(Person s){
if(!doesGroupContainStudent(s)){
/*System.out.println("A: " + affinityTo(s));
System.out.println("RF: " +recruitmentFactor);
System.out.println("Willing: " + s.getWillingnessToMakeFriends());
System.out.println("Rand: " + rand.nextInt(10));
*/
double r = (affinityTo(s) + recruitmentFactor + s.getWillingnessToMakeFriends()*2 + (rand.nextInt(10)+1)*2)/6.0; //want to mess with balence here
System.out.println("\nFinal Recruitment: " + r);
System.out.println("Person " + s.getID() + " looks at group " + id);
if(r>RECRUITMENT_REQUIRED){
students.add(s);
s.joinGroup(this);
System.out.println("Person " + s.getID() + " joined group " + id);
}
size = students.size();
int t=0;
for(int x = 0; x<size; x++){
t += students.get(x).getWillingnessToMakeFriends();
}
if(size>0){
tightness = t/size;
}
}
}
private boolean doesGroupContainStudent(Person p){
for (int x = 0; x<students.size(); x++){
if (p.getID()==students.get(x).getID()){
return true;
}
}
return false;
}
boolean equals(Group a){
return (id==a.getID());
}
/*
* Return a number from 0 to 1 indicating the degree of affinity the
* Person passed has to the existing members of this group.
*/
double affinityTo(Person p) {
if(size>0){
double temp=0;
for(int x = 0; x<students.size(); x++){
temp = p.similarityTo(students.get(x));
}
return (temp/students.size()*10);
}else{
return 5;
}
// write this maddie
// ideas:
// for each of the person's attributes, find the avg number of
// group members (with that attribute, and then take the avg of
// those averages.
// Ex: The group has persons F, T, Q. The Person in question is
// person A. Person A has three attributes: 1, 4, and 5. Attribute
// 1 is owned by F and T. Attribute 4 is owned by F, T, and Q.
// Attribute 5 is owned by no one in the group. So, the affinity
// for Person A to this group is (2/3 + 3/3 + 0/3)/3 = 5/3/3
//
// question: what to return from this method if the group is empty?
// .5?
}
void influenceMembers(){
+ if(students.size()>0){
System.out.println("**Influence members**");
ArrayList<Double> independentAverage = new ArrayList<Double>();
ArrayList<Double> dependentAverage = new ArrayList<Double>();
double tempTotal;
for (int x = 0; x<students.get(0).getIndependentAttributes().size(); x++){
tempTotal=0;
for (int y = 0; y<students.size(); y++){
tempTotal+=students.get(y).getIndependentAttributes().get(x);
}
independentAverage.add(tempTotal/students.size());
}
for (int x = 0; x<students.get(0).getDependentAttributes().size(); x++){
tempTotal=0;
for (int y = 0; y<students.size(); y++){
tempTotal+=students.get(y).getDependentAttributes().get(x);
}
dependentAverage.add(tempTotal/students.size());
}
//At this point, both independentAverage and dependentAverage are filled
//the following should use two rands-- one to see if the attribute should in fact change, and another to be used to multiply by the distance to calculate how much it would increment by
//note that a group's influence will never directly decrement any attributes-- dependent attributes may only decrement by indirect normalization
//We have to keep our numbers pretty low here-- this will be called at every step
double distanceI; //distance between current person's current independent attribute and the group's average attribute
double distanceD; //distance between current person's current dependent attribute and group's average attribute
double increment; //how much each attribute will increment by
for(int x = 0; x<students.size(); x++){
for (int y = 0; y<independentAverage.size(); y++){
distanceI = independentAverage.get(y) - students.get(x).getIndependentAttributes().get(y);
distanceD = dependentAverage.get(y) - students.get(x).getDependentAttributes().get(y);
if(rand.nextDouble(true,true)<LIKELYHOOD_OF_RANDOMLY_CHANGING_ATTRIBUTE && distanceI>0){ //rand subject to change
increment = (rand.nextDouble(true,true)/52)*distanceI; //random number inclusively from 0-1, then divide by 5, then multiply by the distance that attribute is from the group's average
students.get(x).setIndAttrValue(y, (students.get(x).getIndependentAttributes().get(y))+increment);
System.out.println("Person " + students.get(x).getID() + "has changed an independent attribute");
}
if(rand.nextDouble(true,true)<LIKELYHOOD_OF_RANDOMLY_CHANGING_ATTRIBUTE && distanceD>0){
increment = (rand.nextDouble(true, true)/5)*distanceD;
students.get(x).setDepAttrValue(y, (students.get(x).getDependentAttributes().get(y))+increment); //Morgan's method
System.out.println("Person " + students.get(x).getID() + " has changed a dependent attribute");
}
}
}
+ }
}
public void possiblyLeaveGroup(Person p){
if(rand.nextDouble(true,true)<LIKELYHOOD_OF_RANDOMLY_LEAVING_GROUP){
p.leaveGroup(this);
removeStudent(p);
System.out.println("Removing Student "+p.getID()+" from group " + id);
}
}
public void step(SimState state){
ArrayList<Person> allPeople = Sim.getPeople();
influenceMembers();
for(int x = 0; x<allPeople.size(); x++){ //do we want to narrow down the list of people who could possibly join?
recruitStudent(allPeople.get(x));
}
for(int x = 0; x<students.size(); x++){
possiblyLeaveGroup(students.get(x));
}
if (Sim.instance().nextMonthInAcademicYear()) {
// It's not the end of the academic year yet. Run again
// next month.
Sim.instance( ).schedule.scheduleOnceIn(1, this);
} else {
// It's summer break! Sleep for the summer.
Sim.instance( ).schedule.scheduleOnceIn(
Sim.NUM_MONTHS_IN_SUMMER, this);
}
}
public void setSize(int s){
size=s;
}
public void setTightness(int t){
tightness=t;
}
public void setFrequency(int f){
frequency=f;
}
public void setRecruitmentFactor(int r){
recruitmentFactor=r;
}
public int getSize(){
return students.size();
}
public int getTightness(){
return tightness;
}
public int getFrequency(){
return frequency;
}
public double getRecruitmentFactor(){
return recruitmentFactor;
}
public int getCloseness(){
return (tightness+frequency+recruitmentFactor)/3; //maybe this could be used for leaving the group
}
public String toString(){
return "Closeness: "+ getCloseness() + " (Size: " + size + " Tightness: " + tightness + " Frequency: " + frequency + " Recruitment Factor: "+ recruitmentFactor + ")";
}
public void listMembers(){
System.out.println("The following students are in group " + id + ":");
for(int x = 0; x < students.size(); x++){
System.out.println("\t" + students.get(x));
}
}
public int getID(){
return id;
}
public void setID(int i){
id=i;
}
public Person getPersonAtIndex(int x){
return students.get(x);
}
public void removeStudent(Person p){
for(int x = 0; x<students.size(); x++){
if(students.get(x).equals(p)){
students.remove(x);
}
}
}
}
| false | true | void influenceMembers(){
System.out.println("**Influence members**");
ArrayList<Double> independentAverage = new ArrayList<Double>();
ArrayList<Double> dependentAverage = new ArrayList<Double>();
double tempTotal;
for (int x = 0; x<students.get(0).getIndependentAttributes().size(); x++){
tempTotal=0;
for (int y = 0; y<students.size(); y++){
tempTotal+=students.get(y).getIndependentAttributes().get(x);
}
independentAverage.add(tempTotal/students.size());
}
for (int x = 0; x<students.get(0).getDependentAttributes().size(); x++){
tempTotal=0;
for (int y = 0; y<students.size(); y++){
tempTotal+=students.get(y).getDependentAttributes().get(x);
}
dependentAverage.add(tempTotal/students.size());
}
//At this point, both independentAverage and dependentAverage are filled
//the following should use two rands-- one to see if the attribute should in fact change, and another to be used to multiply by the distance to calculate how much it would increment by
//note that a group's influence will never directly decrement any attributes-- dependent attributes may only decrement by indirect normalization
//We have to keep our numbers pretty low here-- this will be called at every step
double distanceI; //distance between current person's current independent attribute and the group's average attribute
double distanceD; //distance between current person's current dependent attribute and group's average attribute
double increment; //how much each attribute will increment by
for(int x = 0; x<students.size(); x++){
for (int y = 0; y<independentAverage.size(); y++){
distanceI = independentAverage.get(y) - students.get(x).getIndependentAttributes().get(y);
distanceD = dependentAverage.get(y) - students.get(x).getDependentAttributes().get(y);
if(rand.nextDouble(true,true)<LIKELYHOOD_OF_RANDOMLY_CHANGING_ATTRIBUTE && distanceI>0){ //rand subject to change
increment = (rand.nextDouble(true,true)/52)*distanceI; //random number inclusively from 0-1, then divide by 5, then multiply by the distance that attribute is from the group's average
students.get(x).setIndAttrValue(y, (students.get(x).getIndependentAttributes().get(y))+increment);
System.out.println("Person " + students.get(x).getID() + "has changed an independent attribute");
}
if(rand.nextDouble(true,true)<LIKELYHOOD_OF_RANDOMLY_CHANGING_ATTRIBUTE && distanceD>0){
increment = (rand.nextDouble(true, true)/5)*distanceD;
students.get(x).setDepAttrValue(y, (students.get(x).getDependentAttributes().get(y))+increment); //Morgan's method
System.out.println("Person " + students.get(x).getID() + " has changed a dependent attribute");
}
}
}
}
| void influenceMembers(){
if(students.size()>0){
System.out.println("**Influence members**");
ArrayList<Double> independentAverage = new ArrayList<Double>();
ArrayList<Double> dependentAverage = new ArrayList<Double>();
double tempTotal;
for (int x = 0; x<students.get(0).getIndependentAttributes().size(); x++){
tempTotal=0;
for (int y = 0; y<students.size(); y++){
tempTotal+=students.get(y).getIndependentAttributes().get(x);
}
independentAverage.add(tempTotal/students.size());
}
for (int x = 0; x<students.get(0).getDependentAttributes().size(); x++){
tempTotal=0;
for (int y = 0; y<students.size(); y++){
tempTotal+=students.get(y).getDependentAttributes().get(x);
}
dependentAverage.add(tempTotal/students.size());
}
//At this point, both independentAverage and dependentAverage are filled
//the following should use two rands-- one to see if the attribute should in fact change, and another to be used to multiply by the distance to calculate how much it would increment by
//note that a group's influence will never directly decrement any attributes-- dependent attributes may only decrement by indirect normalization
//We have to keep our numbers pretty low here-- this will be called at every step
double distanceI; //distance between current person's current independent attribute and the group's average attribute
double distanceD; //distance between current person's current dependent attribute and group's average attribute
double increment; //how much each attribute will increment by
for(int x = 0; x<students.size(); x++){
for (int y = 0; y<independentAverage.size(); y++){
distanceI = independentAverage.get(y) - students.get(x).getIndependentAttributes().get(y);
distanceD = dependentAverage.get(y) - students.get(x).getDependentAttributes().get(y);
if(rand.nextDouble(true,true)<LIKELYHOOD_OF_RANDOMLY_CHANGING_ATTRIBUTE && distanceI>0){ //rand subject to change
increment = (rand.nextDouble(true,true)/52)*distanceI; //random number inclusively from 0-1, then divide by 5, then multiply by the distance that attribute is from the group's average
students.get(x).setIndAttrValue(y, (students.get(x).getIndependentAttributes().get(y))+increment);
System.out.println("Person " + students.get(x).getID() + "has changed an independent attribute");
}
if(rand.nextDouble(true,true)<LIKELYHOOD_OF_RANDOMLY_CHANGING_ATTRIBUTE && distanceD>0){
increment = (rand.nextDouble(true, true)/5)*distanceD;
students.get(x).setDepAttrValue(y, (students.get(x).getDependentAttributes().get(y))+increment); //Morgan's method
System.out.println("Person " + students.get(x).getID() + " has changed a dependent attribute");
}
}
}
}
}
|
diff --git a/zssapp/test/SS_150_Test.java b/zssapp/test/SS_150_Test.java
index e47d406..19af37b 100644
--- a/zssapp/test/SS_150_Test.java
+++ b/zssapp/test/SS_150_Test.java
@@ -1,36 +1,36 @@
import org.zkoss.ztl.JQuery;
/* order_test_1Test.java
Purpose:
Description:
History:
Sep, 7, 2010 17:30:59 PM
Copyright (C) 2010 Potix Corporation. All Rights Reserved.
This program is distributed under Apache License Version 2.0 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
*/
//right click "Border" to have popup menu: B11:F13
public class SS_150_Test extends SSAbstractTestCase {
@Override
protected void executeTest() {
rightClickCells(1,10,5,12);
// Click Border icon
JQuery borderIcon = jq("$borderBtn:eq(2)");
mouseOver(borderIcon);
waitResponse();
clickAt(borderIcon, "30,0");
waitResponse();
//verify
String bottomBorder = jq(".z-menu-popup:last a:eq(1)").text();
- verifyEquals(bottomBorder, "Bottom border");
+ verifyEquals(bottomBorder, " Bottom border");
}
}
| true | true | protected void executeTest() {
rightClickCells(1,10,5,12);
// Click Border icon
JQuery borderIcon = jq("$borderBtn:eq(2)");
mouseOver(borderIcon);
waitResponse();
clickAt(borderIcon, "30,0");
waitResponse();
//verify
String bottomBorder = jq(".z-menu-popup:last a:eq(1)").text();
verifyEquals(bottomBorder, "Bottom border");
}
| protected void executeTest() {
rightClickCells(1,10,5,12);
// Click Border icon
JQuery borderIcon = jq("$borderBtn:eq(2)");
mouseOver(borderIcon);
waitResponse();
clickAt(borderIcon, "30,0");
waitResponse();
//verify
String bottomBorder = jq(".z-menu-popup:last a:eq(1)").text();
verifyEquals(bottomBorder, " Bottom border");
}
|
diff --git a/src/com/shadoom/shadplug/ShadCommand.java b/src/com/shadoom/shadplug/ShadCommand.java
index 69965f8..791651f 100644
--- a/src/com/shadoom/shadplug/ShadCommand.java
+++ b/src/com/shadoom/shadplug/ShadCommand.java
@@ -1,800 +1,800 @@
package com.shadoom.shadplug;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class ShadCommand extends ShadPlug implements CommandExecutor {
private ShadPlug plugin;
public ShadCommand(ShadPlug plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd,
String cmdLabel, String[] args) {
boolean erfolg = false;
String commandName = cmd.getName().toLowerCase();
final Player player;
// Making sure its a player -- Beginning
if (sender instanceof Player) {
player = (Player) sender;
} else {
return true;
}
// Making sure its a player -- End
if (commandName.equals("sc")) {
if (args.length > 0) {
if (ShadConfig.TeamBlue.containsKey(player.getName())) {
// String playername = player.getName();
List<String> peopletosendto = null;
peopletosendto = plugin.getConfig().getStringList(
"ShadPlug.Teams.Blue.Members");
if (peopletosendto == null)
return false;
int playeron = 0;
int sizeoflist = 0;
sizeoflist = ShadConfig.bluechatonline.size();
while (playeron < sizeoflist) {
String playerstring = "";
playerstring = ShadConfig.bluechatonline.get(playeron);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend + args[lengthon]
+ " ";
lengthon++;
}
String newmessagetosend = messagetosend;
- playersend.sendMessage("�6[�1Team�6] �2"
+ playersend.sendMessage("�6[�1Blue�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
- System.out.println("�6[�1Team�6] �2"
+ System.out.println("�6[�1Blue�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
playeron++;
}
int playeron1 = 0;
int sizeoflist1 = 0;
sizeoflist1 = ShadConfig.opChatOnline.size();
while (playeron1 < sizeoflist1) {
String playerstring = "";
playerstring = ShadConfig.opChatOnline.get(playeron1);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend + args[lengthon]
+ " ";
lengthon++;
}
String newmessagetosend = messagetosend;
if (ShadConfig.bluechatonline.contains(playersend
.getName()) == false) {
playersend
.sendMessage("�6[�1Blue �aOp View�6] �2"
+ player.getDisplayName()
+ "�f: �e" + newmessagetosend);
System.out.println("�6[�1Blue �aOp View�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
}
playeron1++;
}
} else {
if (ShadConfig.TeamRed.containsKey(player.getName())) {
// String playername = player.getName();
List<String> peopletosendto = null;
peopletosendto = plugin.getConfig().getStringList(
"ShadPlug.Teams.Red.Members");
if (peopletosendto == null)
return false;
int playeron = 0;
int sizeoflist = 0;
sizeoflist = ShadConfig.redchatonline.size();
while (playeron < sizeoflist) {
String playerstring = "";
playerstring = ShadConfig.redchatonline
.get(playeron);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend
+ args[lengthon] + " ";
lengthon++;
}
String newmessagetosend = messagetosend;
- playersend.sendMessage("�6[�4Team�6] �2"
+ playersend.sendMessage("�6[�4Red�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
- System.out.println("�6[�4Team�6] �2"
+ System.out.println("�6[�4Red�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
playeron++;
}
int playeron1 = 0;
int sizeoflist1 = 0;
sizeoflist1 = ShadConfig.opChatOnline.size();
while (playeron1 < sizeoflist1) {
String playerstring = "";
playerstring = ShadConfig.opChatOnline.get(playeron1);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend + args[lengthon]
+ " ";
lengthon++;
}
String newmessagetosend = messagetosend;
if (ShadConfig.redchatonline.contains(playersend
.getName()) == false) {
playersend
.sendMessage("�6[�4Red �aOp View�6] �2"
+ player.getDisplayName()
+ "�f: �e" + newmessagetosend);
System.out.println("�6[�4Red �aOp View�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
}
playeron1++;
}
} else {
player.sendMessage(ChatColor.RED
+ "You are not in a team!");
}
}
}
if (args.length == 0) {
if (ShadConfig.instantchat.containsKey(player.getName()) == false) {
;
if (ShadConfig.TeamBlue.containsKey(player.getName())) {
ShadConfig.instantchat.put(player.getName(), "blue");
player.sendMessage(ChatColor.GOLD
+ "Auto chat is now on");
} else {
if (ShadConfig.TeamRed.containsKey(player.getName())) {
ShadConfig.instantchat.put(player.getName(), "red");
player.sendMessage(ChatColor.GOLD
+ "Auto chat is now on");
} else {
player.sendMessage(ChatColor.RED
+ "You are not in a team!");
}
}
} else {
ShadConfig.instantchat.remove(player.getName());
player.sendMessage(ChatColor.AQUA + "Auto chat is now off!");
}
}
}
// Shad Command -- Beginning
if (commandName.equals("shad")) {
if (args.length == 0) {
erfolg = true;
player.sendMessage("ShadPlug is developed by ShaDooM.com");
player.sendMessage("Type " + ChatColor.AQUA + "/shad help"
+ ChatColor.WHITE + " to get more information.");
// This Command exists so let it be true
erfolg = true;
}
// for Argument number 1
if (args.length == 1) {
String first;
first = args[0];
if (first.equalsIgnoreCase("addworld")) {
erfolg = true;
player.sendMessage(ChatColor.RED + "Correct usage is: "
+ ChatColor.AQUA + "/shad addworld [WORLD]");
}
if (first.equalsIgnoreCase("remworld")) {
erfolg = true;
player.sendMessage(ChatColor.RED + "Correct usage is: "
+ ChatColor.AQUA + "/shad remworld [WORLD]");
}
// Display Help
if (first.equalsIgnoreCase("help")) {
player.sendMessage("=======" + ChatColor.RED
+ ChatColor.BOLD + " Welcome to ShadPVP "
+ ChatColor.WHITE + "=======");
player.sendMessage(ChatColor.AQUA + ""
+ ChatColor.UNDERLINE
+ "Commands Description");
player.sendMessage("");
player.sendMessage(ChatColor.AQUA + "/shad help"
+ ChatColor.RED + " Shows this help.");
player.sendMessage(ChatColor.AQUA + "/shad join"
+ ChatColor.RED
+ " Puts you in a Team(Auto)");
player.sendMessage(ChatColor.AQUA + "/shad score"
+ ChatColor.RED
+ " Shows the score of both Teams(Kills)");
player.sendMessage(ChatColor.AQUA + "/shad list red"
+ ChatColor.RED
+ " Lists all members of Team Red");
player.sendMessage(ChatColor.AQUA + "/shad list blue"
+ ChatColor.RED
+ " Lists all members of Team Blue");
player.sendMessage(ChatColor.AQUA + "/shad spawn"
+ ChatColor.RED + " Spawn at your Team's HQ");
player.sendMessage(ChatColor.AQUA + "/sc [TEXT]"
+ ChatColor.RED + " QuickChat with your team");
player.sendMessage(ChatColor.AQUA + "/sc" + ChatColor.RED
+ " Toggle Teamchat");
player.sendMessage(ChatColor.AQUA
+ "/shad setspawn red/blue" + ChatColor.RED
+ " Setspawn of the Team.");
player.sendMessage(ChatColor.AQUA + "/shad reload"
+ ChatColor.RED + " Reloads the config.yml");
player.sendMessage(ChatColor.AQUA + "/shad clear"
+ ChatColor.RED
+ " Nullifies everything in config.yml");
player.sendMessage(ChatColor.AQUA
+ "/shad addworld [WORLD]" + ChatColor.RED
+ " Adds [WORLD] to config.yml");
player.sendMessage("===================================");
erfolg = true;
}
if (first.equalsIgnoreCase("spawn")) {
erfolg = true;
if (ShadConfig.TeamBlue.containsKey(player.getName())) {
World world;
world = Bukkit.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Blue.World"));
final Location location = new Location(world,
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.X"), plugin
.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Y"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Pitch"));
player.sendMessage("You will be ported to the Blue base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 11));
}
}, 100L); // 100 ticks (20 ticks = 1
// second)
}
if (ShadConfig.TeamRed.containsKey(player.getName())) {
World world;
world = Bukkit.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Red.World"));
final Location location = new Location(world, plugin
.getConfig().getDouble("ShadPlug.Spawn.Red.X"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Y"), plugin
.getConfig().getDouble(
"ShadPlug.Spawn.Red.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Pitch"));
player.sendMessage("You will be ported to the Red base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 14));
}
}, 100L);
}
}
// Join a team, Red or Blue
if (first.equalsIgnoreCase("join")) {
erfolg = true;
if (plugin.getConfig().isSet("ShadPlug.Spawn.Blue.World")
&& plugin.getConfig().isSet(
"ShadPlug.Spawn.Red.World")) {
List<String> teamredList = plugin.getConfig()
.getStringList("ShadPlug.Teams.Red.Members");
List<String> teamblueList = plugin.getConfig()
.getStringList("ShadPlug.Teams.Blue.Members");
// Make sure player is not in a team already
if (teamredList.contains(player.getName().toString())
|| teamblueList.contains(player.getName()
.toString())) {
player.sendMessage("Sorry bro you're already in a team");
} else {
// If TeamRed has fewer players than TeamBlue,
// player
// will join TeamRed and vice versa.
if (teamredList.size() <= teamblueList.size()) {
teamredList.add(player.getName());
ShadConfig.TeamRed.put(player.getName(), "red");
plugin.getServer().broadcastMessage(
player.getName()
+ " has joined the Red Team.");
plugin.getConfig().set(
"ShadPlug.Teams.Red.Members",
teamredList);
ShadConfig.redchatonline.add(player.getName());
plugin.saveConfig();
World world;
world = plugin.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Red.World"));
final Location location = new Location(world,
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.X"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Y"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Pitch"));
player.sendMessage("You will be ported to the Red base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 14));
}
}, 100L);
} else {
teamblueList.add(player.getName());
ShadConfig.TeamBlue.put(player.getName(),
"blue");
plugin.getServer().broadcastMessage(
player.getName()
+ " has joined the Blue Team.");
ShadConfig.bluechatonline.add(player.getName());
plugin.getConfig().set(
"ShadPlug.Teams.Blue.Members",
teamblueList);
plugin.saveConfig();
World world;
world = Bukkit.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Blue.World"));
final Location location = new Location(world,
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.X"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Y"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Pitch"));
player.sendMessage("You will be ported to the Blue base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 11));
}
}, 100L);
}
}
} else {
player.sendMessage("The Spawnpoints for the Teams are not set.");
}
}
/*
* Display Team scores
*/
if (first.equalsIgnoreCase("score")) {
erfolg = true;
player.sendMessage(ChatColor.RED + "====================");
player.sendMessage(ChatColor.WHITE
+ "Red Blue");
player.sendMessage(ChatColor.AQUA + ""
+ ShadConfig.redScore + " "
+ ShadConfig.blueScore);
player.sendMessage(ChatColor.RED + "====================");
}
/*
* Spit out help how to use List command
*/
if (first.equalsIgnoreCase("list")) {
erfolg = true;
player.sendMessage(ChatColor.GOLD + "Type: "
+ ChatColor.AQUA + ChatColor.BOLD + "/shad list "
+ ChatColor.RED + ChatColor.BOLD + "Red"
+ ChatColor.GOLD + " or " + ChatColor.AQUA
+ ChatColor.BOLD + "/shad list " + ChatColor.BLUE
+ ChatColor.BOLD + "Blue.");
player.sendMessage(ChatColor.GOLD
+ "To see the members of each team.");
}
/*
* Spit out help how to use SetSpawn command
*/
if (first.equalsIgnoreCase("setspawn")) {
erfolg = true;
player.sendMessage("Correct Usage is" + ChatColor.AQUA
+ " /shad setspawn RED/BLUE");
}
/*
* Reload Config.yml
*/
if (first.equalsIgnoreCase("reload")) {
erfolg = true;
plugin.reloadConfig();
player.sendMessage(ChatColor.AQUA
+ "ShadPlugs config.yml has been reloaded.");
}
if (first.equalsIgnoreCase("clear")) {
erfolg = true;
ShadConfig.TeamBlue.clear();
ShadConfig.TeamRed.clear();
ShadConfig.redScoreHashMap.clear();
ShadConfig.blueScoreHashMap.clear();
ShadConfig.bluechatonline.clear();
ShadConfig.redchatonline.clear();
ShadConfig.instantchat.clear();
plugin.getConfig().set("ShadPlug.Spawn.Red", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.World", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.X", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Y", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Z", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Pitch", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Yaw", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.World", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.X", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Y", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Z", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Pitch", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Yaw", null);
plugin.getConfig().set("ShadPlug.Teams.Blue", null);
plugin.getConfig().set("ShadPlug.Teams.Blue.Members", null);
plugin.getConfig().set("ShadPlug.Teams.Blue.Members.Score",
null);
plugin.getConfig().set("ShadPlug.Teams.Red", null);
plugin.getConfig().set("ShadPlug.Teams.Red.Members", null);
plugin.getConfig().set("ShadPlug.Teams.Red.Members.Score",
null);
plugin.getConfig().set("ShadPlug.Worlds", null);
plugin.saveConfig();
}
}
if (args.length == 2) {
String first;
String second;
first = args[0];
second = args[1];
/*
* Add a world to the enabled Worlds.
*/
if (first.equals("addworld")) {
erfolg = true;
List<String> worldList = plugin.getConfig().getStringList(
"ShadPlug.Worlds");
worldList.add(second);
plugin.getConfig().set("ShadPlug.Worlds", worldList);
player.sendMessage(ChatColor.RED.toString()
+ ChatColor.BOLD.toString() + second
+ ChatColor.AQUA
+ " has been added to the enabled Worlds.");
plugin.saveConfig();
}
/*
* Remove a world from the enabled Worlds.
*/
if (first.equals("remworld")) {
erfolg = true;
List<String> worldList = plugin.getConfig().getStringList(
"ShadPlug.Worlds");
worldList.remove(second);
plugin.getConfig().set("ShadPlug.Worlds", worldList);
player.sendMessage(ChatColor.RED.toString()
+ ChatColor.BOLD.toString() + second
+ ChatColor.AQUA + " has been " + ChatColor.RED
+ "removed" + ChatColor.AQUA
+ " from the enabled Worlds.");
plugin.saveConfig();
}
/*
* Set Red spawn
*/
if (first.equalsIgnoreCase("setspawn")
&& second.equalsIgnoreCase("red")) {
erfolg = true;
if (player.hasPermission("ShadPlug.Admin.SetSpawn")) {
String World = player.getWorld().getName();
Location location = player.getLocation();
double spawnX = player.getLocation().getX();
double spawnY = player.getLocation().getY();
double spawnZ = player.getLocation().getZ();
float pitch = location.getPitch();
float yaw = location.getYaw();
if (!plugin.getConfig()
.getStringList("ShadPlug.Worlds")
.contains(World)) {
player.sendMessage(ChatColor.RED
+ "WARNING:"
+ ChatColor.AQUA
+ " The world where you just set Spawn is not enabled in the config.yml");
}
ShadConfig.savePosToConfigRed(1, World, spawnX, spawnY,
spawnZ, pitch, yaw);
player.sendMessage("Spawnpoint for Red-Team set");
plugin.saveConfig();
} else {
player.sendMessage("ShadPlug.Admin.SetSpawn Perms missing.");
}
}
/*
* Set Blue spawn
*/
if (first.equalsIgnoreCase("setspawn")
&& second.equalsIgnoreCase("blue")) {
erfolg = true;
if (player.hasPermission("ShadPlug.Admin.SetSpawn")) {
String World = player.getWorld().getName();
Location location = player.getLocation();
double spawnX = player.getLocation().getX();
double spawnY = player.getLocation().getY();
double spawnZ = player.getLocation().getZ();
float pitch = location.getPitch();
float yaw = location.getYaw();
if (!plugin.getConfig()
.getStringList("ShadPlug.Worlds")
.contains(World)) {
player.sendMessage(ChatColor.RED
+ "WARNING:"
+ ChatColor.AQUA
+ " The world where you just set Spawn is not enabled in the config.yml");
}
ShadConfig.savePosToConfigBlue(1, World, spawnX,
spawnY, spawnZ, pitch, yaw);
player.sendMessage("Spawnpoint for Blue-Team set");
plugin.saveConfig();
} else {
player.sendMessage("ShadPlug.Admin.SetSpawn Perms missing.");
}
}
/*
* List Red and Blue players.
*/
if (first.equalsIgnoreCase("list")
&& second.equalsIgnoreCase("red")) {
erfolg = true;
player.sendMessage("Team "
+ ChatColor.RED
+ "Red "
+ ChatColor.WHITE
+ plugin.getConfig()
.get("ShadPlug.Teams.Red.Members")
.toString());
}
if (first.equalsIgnoreCase("list")
&& second.equalsIgnoreCase("blue")) {
erfolg = true;
player.sendMessage("Team "
+ ChatColor.BLUE
+ "Blue "
+ ChatColor.WHITE
+ plugin.getConfig()
.get("ShadPlug.Teams.Blue.Members")
.toString());
}
}
// Checking for existing arguments
if (erfolg == false) { // Notice the ==, double = means its
// checking, if its just a single = then its
// setting
player.sendMessage(ChatColor.RED
+ "Unknown Command - Please type " + ChatColor.AQUA
+ ChatColor.BOLD + "/shad help" + ChatColor.RED
+ " to get help.");
}
}
return erfolg;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd,
String cmdLabel, String[] args) {
boolean erfolg = false;
String commandName = cmd.getName().toLowerCase();
final Player player;
// Making sure its a player -- Beginning
if (sender instanceof Player) {
player = (Player) sender;
} else {
return true;
}
// Making sure its a player -- End
if (commandName.equals("sc")) {
if (args.length > 0) {
if (ShadConfig.TeamBlue.containsKey(player.getName())) {
// String playername = player.getName();
List<String> peopletosendto = null;
peopletosendto = plugin.getConfig().getStringList(
"ShadPlug.Teams.Blue.Members");
if (peopletosendto == null)
return false;
int playeron = 0;
int sizeoflist = 0;
sizeoflist = ShadConfig.bluechatonline.size();
while (playeron < sizeoflist) {
String playerstring = "";
playerstring = ShadConfig.bluechatonline.get(playeron);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend + args[lengthon]
+ " ";
lengthon++;
}
String newmessagetosend = messagetosend;
playersend.sendMessage("�6[�1Team�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
System.out.println("�6[�1Team�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
playeron++;
}
int playeron1 = 0;
int sizeoflist1 = 0;
sizeoflist1 = ShadConfig.opChatOnline.size();
while (playeron1 < sizeoflist1) {
String playerstring = "";
playerstring = ShadConfig.opChatOnline.get(playeron1);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend + args[lengthon]
+ " ";
lengthon++;
}
String newmessagetosend = messagetosend;
if (ShadConfig.bluechatonline.contains(playersend
.getName()) == false) {
playersend
.sendMessage("�6[�1Blue �aOp View�6] �2"
+ player.getDisplayName()
+ "�f: �e" + newmessagetosend);
System.out.println("�6[�1Blue �aOp View�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
}
playeron1++;
}
} else {
if (ShadConfig.TeamRed.containsKey(player.getName())) {
// String playername = player.getName();
List<String> peopletosendto = null;
peopletosendto = plugin.getConfig().getStringList(
"ShadPlug.Teams.Red.Members");
if (peopletosendto == null)
return false;
int playeron = 0;
int sizeoflist = 0;
sizeoflist = ShadConfig.redchatonline.size();
while (playeron < sizeoflist) {
String playerstring = "";
playerstring = ShadConfig.redchatonline
.get(playeron);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend
+ args[lengthon] + " ";
lengthon++;
}
String newmessagetosend = messagetosend;
playersend.sendMessage("�6[�4Team�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
System.out.println("�6[�4Team�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
playeron++;
}
int playeron1 = 0;
int sizeoflist1 = 0;
sizeoflist1 = ShadConfig.opChatOnline.size();
while (playeron1 < sizeoflist1) {
String playerstring = "";
playerstring = ShadConfig.opChatOnline.get(playeron1);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend + args[lengthon]
+ " ";
lengthon++;
}
String newmessagetosend = messagetosend;
if (ShadConfig.redchatonline.contains(playersend
.getName()) == false) {
playersend
.sendMessage("�6[�4Red �aOp View�6] �2"
+ player.getDisplayName()
+ "�f: �e" + newmessagetosend);
System.out.println("�6[�4Red �aOp View�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
}
playeron1++;
}
} else {
player.sendMessage(ChatColor.RED
+ "You are not in a team!");
}
}
}
if (args.length == 0) {
if (ShadConfig.instantchat.containsKey(player.getName()) == false) {
;
if (ShadConfig.TeamBlue.containsKey(player.getName())) {
ShadConfig.instantchat.put(player.getName(), "blue");
player.sendMessage(ChatColor.GOLD
+ "Auto chat is now on");
} else {
if (ShadConfig.TeamRed.containsKey(player.getName())) {
ShadConfig.instantchat.put(player.getName(), "red");
player.sendMessage(ChatColor.GOLD
+ "Auto chat is now on");
} else {
player.sendMessage(ChatColor.RED
+ "You are not in a team!");
}
}
} else {
ShadConfig.instantchat.remove(player.getName());
player.sendMessage(ChatColor.AQUA + "Auto chat is now off!");
}
}
}
// Shad Command -- Beginning
if (commandName.equals("shad")) {
if (args.length == 0) {
erfolg = true;
player.sendMessage("ShadPlug is developed by ShaDooM.com");
player.sendMessage("Type " + ChatColor.AQUA + "/shad help"
+ ChatColor.WHITE + " to get more information.");
// This Command exists so let it be true
erfolg = true;
}
// for Argument number 1
if (args.length == 1) {
String first;
first = args[0];
if (first.equalsIgnoreCase("addworld")) {
erfolg = true;
player.sendMessage(ChatColor.RED + "Correct usage is: "
+ ChatColor.AQUA + "/shad addworld [WORLD]");
}
if (first.equalsIgnoreCase("remworld")) {
erfolg = true;
player.sendMessage(ChatColor.RED + "Correct usage is: "
+ ChatColor.AQUA + "/shad remworld [WORLD]");
}
// Display Help
if (first.equalsIgnoreCase("help")) {
player.sendMessage("=======" + ChatColor.RED
+ ChatColor.BOLD + " Welcome to ShadPVP "
+ ChatColor.WHITE + "=======");
player.sendMessage(ChatColor.AQUA + ""
+ ChatColor.UNDERLINE
+ "Commands Description");
player.sendMessage("");
player.sendMessage(ChatColor.AQUA + "/shad help"
+ ChatColor.RED + " Shows this help.");
player.sendMessage(ChatColor.AQUA + "/shad join"
+ ChatColor.RED
+ " Puts you in a Team(Auto)");
player.sendMessage(ChatColor.AQUA + "/shad score"
+ ChatColor.RED
+ " Shows the score of both Teams(Kills)");
player.sendMessage(ChatColor.AQUA + "/shad list red"
+ ChatColor.RED
+ " Lists all members of Team Red");
player.sendMessage(ChatColor.AQUA + "/shad list blue"
+ ChatColor.RED
+ " Lists all members of Team Blue");
player.sendMessage(ChatColor.AQUA + "/shad spawn"
+ ChatColor.RED + " Spawn at your Team's HQ");
player.sendMessage(ChatColor.AQUA + "/sc [TEXT]"
+ ChatColor.RED + " QuickChat with your team");
player.sendMessage(ChatColor.AQUA + "/sc" + ChatColor.RED
+ " Toggle Teamchat");
player.sendMessage(ChatColor.AQUA
+ "/shad setspawn red/blue" + ChatColor.RED
+ " Setspawn of the Team.");
player.sendMessage(ChatColor.AQUA + "/shad reload"
+ ChatColor.RED + " Reloads the config.yml");
player.sendMessage(ChatColor.AQUA + "/shad clear"
+ ChatColor.RED
+ " Nullifies everything in config.yml");
player.sendMessage(ChatColor.AQUA
+ "/shad addworld [WORLD]" + ChatColor.RED
+ " Adds [WORLD] to config.yml");
player.sendMessage("===================================");
erfolg = true;
}
if (first.equalsIgnoreCase("spawn")) {
erfolg = true;
if (ShadConfig.TeamBlue.containsKey(player.getName())) {
World world;
world = Bukkit.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Blue.World"));
final Location location = new Location(world,
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.X"), plugin
.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Y"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Pitch"));
player.sendMessage("You will be ported to the Blue base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 11));
}
}, 100L); // 100 ticks (20 ticks = 1
// second)
}
if (ShadConfig.TeamRed.containsKey(player.getName())) {
World world;
world = Bukkit.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Red.World"));
final Location location = new Location(world, plugin
.getConfig().getDouble("ShadPlug.Spawn.Red.X"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Y"), plugin
.getConfig().getDouble(
"ShadPlug.Spawn.Red.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Pitch"));
player.sendMessage("You will be ported to the Red base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 14));
}
}, 100L);
}
}
// Join a team, Red or Blue
if (first.equalsIgnoreCase("join")) {
erfolg = true;
if (plugin.getConfig().isSet("ShadPlug.Spawn.Blue.World")
&& plugin.getConfig().isSet(
"ShadPlug.Spawn.Red.World")) {
List<String> teamredList = plugin.getConfig()
.getStringList("ShadPlug.Teams.Red.Members");
List<String> teamblueList = plugin.getConfig()
.getStringList("ShadPlug.Teams.Blue.Members");
// Make sure player is not in a team already
if (teamredList.contains(player.getName().toString())
|| teamblueList.contains(player.getName()
.toString())) {
player.sendMessage("Sorry bro you're already in a team");
} else {
// If TeamRed has fewer players than TeamBlue,
// player
// will join TeamRed and vice versa.
if (teamredList.size() <= teamblueList.size()) {
teamredList.add(player.getName());
ShadConfig.TeamRed.put(player.getName(), "red");
plugin.getServer().broadcastMessage(
player.getName()
+ " has joined the Red Team.");
plugin.getConfig().set(
"ShadPlug.Teams.Red.Members",
teamredList);
ShadConfig.redchatonline.add(player.getName());
plugin.saveConfig();
World world;
world = plugin.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Red.World"));
final Location location = new Location(world,
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.X"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Y"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Pitch"));
player.sendMessage("You will be ported to the Red base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 14));
}
}, 100L);
} else {
teamblueList.add(player.getName());
ShadConfig.TeamBlue.put(player.getName(),
"blue");
plugin.getServer().broadcastMessage(
player.getName()
+ " has joined the Blue Team.");
ShadConfig.bluechatonline.add(player.getName());
plugin.getConfig().set(
"ShadPlug.Teams.Blue.Members",
teamblueList);
plugin.saveConfig();
World world;
world = Bukkit.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Blue.World"));
final Location location = new Location(world,
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.X"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Y"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Pitch"));
player.sendMessage("You will be ported to the Blue base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 11));
}
}, 100L);
}
}
} else {
player.sendMessage("The Spawnpoints for the Teams are not set.");
}
}
/*
* Display Team scores
*/
if (first.equalsIgnoreCase("score")) {
erfolg = true;
player.sendMessage(ChatColor.RED + "====================");
player.sendMessage(ChatColor.WHITE
+ "Red Blue");
player.sendMessage(ChatColor.AQUA + ""
+ ShadConfig.redScore + " "
+ ShadConfig.blueScore);
player.sendMessage(ChatColor.RED + "====================");
}
/*
* Spit out help how to use List command
*/
if (first.equalsIgnoreCase("list")) {
erfolg = true;
player.sendMessage(ChatColor.GOLD + "Type: "
+ ChatColor.AQUA + ChatColor.BOLD + "/shad list "
+ ChatColor.RED + ChatColor.BOLD + "Red"
+ ChatColor.GOLD + " or " + ChatColor.AQUA
+ ChatColor.BOLD + "/shad list " + ChatColor.BLUE
+ ChatColor.BOLD + "Blue.");
player.sendMessage(ChatColor.GOLD
+ "To see the members of each team.");
}
/*
* Spit out help how to use SetSpawn command
*/
if (first.equalsIgnoreCase("setspawn")) {
erfolg = true;
player.sendMessage("Correct Usage is" + ChatColor.AQUA
+ " /shad setspawn RED/BLUE");
}
/*
* Reload Config.yml
*/
if (first.equalsIgnoreCase("reload")) {
erfolg = true;
plugin.reloadConfig();
player.sendMessage(ChatColor.AQUA
+ "ShadPlugs config.yml has been reloaded.");
}
if (first.equalsIgnoreCase("clear")) {
erfolg = true;
ShadConfig.TeamBlue.clear();
ShadConfig.TeamRed.clear();
ShadConfig.redScoreHashMap.clear();
ShadConfig.blueScoreHashMap.clear();
ShadConfig.bluechatonline.clear();
ShadConfig.redchatonline.clear();
ShadConfig.instantchat.clear();
plugin.getConfig().set("ShadPlug.Spawn.Red", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.World", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.X", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Y", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Z", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Pitch", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Yaw", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.World", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.X", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Y", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Z", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Pitch", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Yaw", null);
plugin.getConfig().set("ShadPlug.Teams.Blue", null);
plugin.getConfig().set("ShadPlug.Teams.Blue.Members", null);
plugin.getConfig().set("ShadPlug.Teams.Blue.Members.Score",
null);
plugin.getConfig().set("ShadPlug.Teams.Red", null);
plugin.getConfig().set("ShadPlug.Teams.Red.Members", null);
plugin.getConfig().set("ShadPlug.Teams.Red.Members.Score",
null);
plugin.getConfig().set("ShadPlug.Worlds", null);
plugin.saveConfig();
}
}
if (args.length == 2) {
String first;
String second;
first = args[0];
second = args[1];
/*
* Add a world to the enabled Worlds.
*/
if (first.equals("addworld")) {
erfolg = true;
List<String> worldList = plugin.getConfig().getStringList(
"ShadPlug.Worlds");
worldList.add(second);
plugin.getConfig().set("ShadPlug.Worlds", worldList);
player.sendMessage(ChatColor.RED.toString()
+ ChatColor.BOLD.toString() + second
+ ChatColor.AQUA
+ " has been added to the enabled Worlds.");
plugin.saveConfig();
}
/*
* Remove a world from the enabled Worlds.
*/
if (first.equals("remworld")) {
erfolg = true;
List<String> worldList = plugin.getConfig().getStringList(
"ShadPlug.Worlds");
worldList.remove(second);
plugin.getConfig().set("ShadPlug.Worlds", worldList);
player.sendMessage(ChatColor.RED.toString()
+ ChatColor.BOLD.toString() + second
+ ChatColor.AQUA + " has been " + ChatColor.RED
+ "removed" + ChatColor.AQUA
+ " from the enabled Worlds.");
plugin.saveConfig();
}
/*
* Set Red spawn
*/
if (first.equalsIgnoreCase("setspawn")
&& second.equalsIgnoreCase("red")) {
erfolg = true;
if (player.hasPermission("ShadPlug.Admin.SetSpawn")) {
String World = player.getWorld().getName();
Location location = player.getLocation();
double spawnX = player.getLocation().getX();
double spawnY = player.getLocation().getY();
double spawnZ = player.getLocation().getZ();
float pitch = location.getPitch();
float yaw = location.getYaw();
if (!plugin.getConfig()
.getStringList("ShadPlug.Worlds")
.contains(World)) {
player.sendMessage(ChatColor.RED
+ "WARNING:"
+ ChatColor.AQUA
+ " The world where you just set Spawn is not enabled in the config.yml");
}
ShadConfig.savePosToConfigRed(1, World, spawnX, spawnY,
spawnZ, pitch, yaw);
player.sendMessage("Spawnpoint for Red-Team set");
plugin.saveConfig();
} else {
player.sendMessage("ShadPlug.Admin.SetSpawn Perms missing.");
}
}
/*
* Set Blue spawn
*/
if (first.equalsIgnoreCase("setspawn")
&& second.equalsIgnoreCase("blue")) {
erfolg = true;
if (player.hasPermission("ShadPlug.Admin.SetSpawn")) {
String World = player.getWorld().getName();
Location location = player.getLocation();
double spawnX = player.getLocation().getX();
double spawnY = player.getLocation().getY();
double spawnZ = player.getLocation().getZ();
float pitch = location.getPitch();
float yaw = location.getYaw();
if (!plugin.getConfig()
.getStringList("ShadPlug.Worlds")
.contains(World)) {
player.sendMessage(ChatColor.RED
+ "WARNING:"
+ ChatColor.AQUA
+ " The world where you just set Spawn is not enabled in the config.yml");
}
ShadConfig.savePosToConfigBlue(1, World, spawnX,
spawnY, spawnZ, pitch, yaw);
player.sendMessage("Spawnpoint for Blue-Team set");
plugin.saveConfig();
} else {
player.sendMessage("ShadPlug.Admin.SetSpawn Perms missing.");
}
}
/*
* List Red and Blue players.
*/
if (first.equalsIgnoreCase("list")
&& second.equalsIgnoreCase("red")) {
erfolg = true;
player.sendMessage("Team "
+ ChatColor.RED
+ "Red "
+ ChatColor.WHITE
+ plugin.getConfig()
.get("ShadPlug.Teams.Red.Members")
.toString());
}
if (first.equalsIgnoreCase("list")
&& second.equalsIgnoreCase("blue")) {
erfolg = true;
player.sendMessage("Team "
+ ChatColor.BLUE
+ "Blue "
+ ChatColor.WHITE
+ plugin.getConfig()
.get("ShadPlug.Teams.Blue.Members")
.toString());
}
}
// Checking for existing arguments
if (erfolg == false) { // Notice the ==, double = means its
// checking, if its just a single = then its
// setting
player.sendMessage(ChatColor.RED
+ "Unknown Command - Please type " + ChatColor.AQUA
+ ChatColor.BOLD + "/shad help" + ChatColor.RED
+ " to get help.");
}
}
return erfolg;
}
| public boolean onCommand(CommandSender sender, Command cmd,
String cmdLabel, String[] args) {
boolean erfolg = false;
String commandName = cmd.getName().toLowerCase();
final Player player;
// Making sure its a player -- Beginning
if (sender instanceof Player) {
player = (Player) sender;
} else {
return true;
}
// Making sure its a player -- End
if (commandName.equals("sc")) {
if (args.length > 0) {
if (ShadConfig.TeamBlue.containsKey(player.getName())) {
// String playername = player.getName();
List<String> peopletosendto = null;
peopletosendto = plugin.getConfig().getStringList(
"ShadPlug.Teams.Blue.Members");
if (peopletosendto == null)
return false;
int playeron = 0;
int sizeoflist = 0;
sizeoflist = ShadConfig.bluechatonline.size();
while (playeron < sizeoflist) {
String playerstring = "";
playerstring = ShadConfig.bluechatonline.get(playeron);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend + args[lengthon]
+ " ";
lengthon++;
}
String newmessagetosend = messagetosend;
playersend.sendMessage("�6[�1Blue�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
System.out.println("�6[�1Blue�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
playeron++;
}
int playeron1 = 0;
int sizeoflist1 = 0;
sizeoflist1 = ShadConfig.opChatOnline.size();
while (playeron1 < sizeoflist1) {
String playerstring = "";
playerstring = ShadConfig.opChatOnline.get(playeron1);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend + args[lengthon]
+ " ";
lengthon++;
}
String newmessagetosend = messagetosend;
if (ShadConfig.bluechatonline.contains(playersend
.getName()) == false) {
playersend
.sendMessage("�6[�1Blue �aOp View�6] �2"
+ player.getDisplayName()
+ "�f: �e" + newmessagetosend);
System.out.println("�6[�1Blue �aOp View�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
}
playeron1++;
}
} else {
if (ShadConfig.TeamRed.containsKey(player.getName())) {
// String playername = player.getName();
List<String> peopletosendto = null;
peopletosendto = plugin.getConfig().getStringList(
"ShadPlug.Teams.Red.Members");
if (peopletosendto == null)
return false;
int playeron = 0;
int sizeoflist = 0;
sizeoflist = ShadConfig.redchatonline.size();
while (playeron < sizeoflist) {
String playerstring = "";
playerstring = ShadConfig.redchatonline
.get(playeron);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend
+ args[lengthon] + " ";
lengthon++;
}
String newmessagetosend = messagetosend;
playersend.sendMessage("�6[�4Red�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
System.out.println("�6[�4Red�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
playeron++;
}
int playeron1 = 0;
int sizeoflist1 = 0;
sizeoflist1 = ShadConfig.opChatOnline.size();
while (playeron1 < sizeoflist1) {
String playerstring = "";
playerstring = ShadConfig.opChatOnline.get(playeron1);
Player playersend = Bukkit.getPlayer(playerstring);
if (playersend != null) {
int messagelength = args.length;
int lengthon = 0;
String messagetosend = "";
while (lengthon < messagelength) {
messagetosend = messagetosend + args[lengthon]
+ " ";
lengthon++;
}
String newmessagetosend = messagetosend;
if (ShadConfig.redchatonline.contains(playersend
.getName()) == false) {
playersend
.sendMessage("�6[�4Red �aOp View�6] �2"
+ player.getDisplayName()
+ "�f: �e" + newmessagetosend);
System.out.println("�6[�4Red �aOp View�6] �2"
+ player.getDisplayName() + "�f: �e"
+ newmessagetosend);
}
}
playeron1++;
}
} else {
player.sendMessage(ChatColor.RED
+ "You are not in a team!");
}
}
}
if (args.length == 0) {
if (ShadConfig.instantchat.containsKey(player.getName()) == false) {
;
if (ShadConfig.TeamBlue.containsKey(player.getName())) {
ShadConfig.instantchat.put(player.getName(), "blue");
player.sendMessage(ChatColor.GOLD
+ "Auto chat is now on");
} else {
if (ShadConfig.TeamRed.containsKey(player.getName())) {
ShadConfig.instantchat.put(player.getName(), "red");
player.sendMessage(ChatColor.GOLD
+ "Auto chat is now on");
} else {
player.sendMessage(ChatColor.RED
+ "You are not in a team!");
}
}
} else {
ShadConfig.instantchat.remove(player.getName());
player.sendMessage(ChatColor.AQUA + "Auto chat is now off!");
}
}
}
// Shad Command -- Beginning
if (commandName.equals("shad")) {
if (args.length == 0) {
erfolg = true;
player.sendMessage("ShadPlug is developed by ShaDooM.com");
player.sendMessage("Type " + ChatColor.AQUA + "/shad help"
+ ChatColor.WHITE + " to get more information.");
// This Command exists so let it be true
erfolg = true;
}
// for Argument number 1
if (args.length == 1) {
String first;
first = args[0];
if (first.equalsIgnoreCase("addworld")) {
erfolg = true;
player.sendMessage(ChatColor.RED + "Correct usage is: "
+ ChatColor.AQUA + "/shad addworld [WORLD]");
}
if (first.equalsIgnoreCase("remworld")) {
erfolg = true;
player.sendMessage(ChatColor.RED + "Correct usage is: "
+ ChatColor.AQUA + "/shad remworld [WORLD]");
}
// Display Help
if (first.equalsIgnoreCase("help")) {
player.sendMessage("=======" + ChatColor.RED
+ ChatColor.BOLD + " Welcome to ShadPVP "
+ ChatColor.WHITE + "=======");
player.sendMessage(ChatColor.AQUA + ""
+ ChatColor.UNDERLINE
+ "Commands Description");
player.sendMessage("");
player.sendMessage(ChatColor.AQUA + "/shad help"
+ ChatColor.RED + " Shows this help.");
player.sendMessage(ChatColor.AQUA + "/shad join"
+ ChatColor.RED
+ " Puts you in a Team(Auto)");
player.sendMessage(ChatColor.AQUA + "/shad score"
+ ChatColor.RED
+ " Shows the score of both Teams(Kills)");
player.sendMessage(ChatColor.AQUA + "/shad list red"
+ ChatColor.RED
+ " Lists all members of Team Red");
player.sendMessage(ChatColor.AQUA + "/shad list blue"
+ ChatColor.RED
+ " Lists all members of Team Blue");
player.sendMessage(ChatColor.AQUA + "/shad spawn"
+ ChatColor.RED + " Spawn at your Team's HQ");
player.sendMessage(ChatColor.AQUA + "/sc [TEXT]"
+ ChatColor.RED + " QuickChat with your team");
player.sendMessage(ChatColor.AQUA + "/sc" + ChatColor.RED
+ " Toggle Teamchat");
player.sendMessage(ChatColor.AQUA
+ "/shad setspawn red/blue" + ChatColor.RED
+ " Setspawn of the Team.");
player.sendMessage(ChatColor.AQUA + "/shad reload"
+ ChatColor.RED + " Reloads the config.yml");
player.sendMessage(ChatColor.AQUA + "/shad clear"
+ ChatColor.RED
+ " Nullifies everything in config.yml");
player.sendMessage(ChatColor.AQUA
+ "/shad addworld [WORLD]" + ChatColor.RED
+ " Adds [WORLD] to config.yml");
player.sendMessage("===================================");
erfolg = true;
}
if (first.equalsIgnoreCase("spawn")) {
erfolg = true;
if (ShadConfig.TeamBlue.containsKey(player.getName())) {
World world;
world = Bukkit.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Blue.World"));
final Location location = new Location(world,
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.X"), plugin
.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Y"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Pitch"));
player.sendMessage("You will be ported to the Blue base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 11));
}
}, 100L); // 100 ticks (20 ticks = 1
// second)
}
if (ShadConfig.TeamRed.containsKey(player.getName())) {
World world;
world = Bukkit.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Red.World"));
final Location location = new Location(world, plugin
.getConfig().getDouble("ShadPlug.Spawn.Red.X"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Y"), plugin
.getConfig().getDouble(
"ShadPlug.Spawn.Red.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Pitch"));
player.sendMessage("You will be ported to the Red base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 14));
}
}, 100L);
}
}
// Join a team, Red or Blue
if (first.equalsIgnoreCase("join")) {
erfolg = true;
if (plugin.getConfig().isSet("ShadPlug.Spawn.Blue.World")
&& plugin.getConfig().isSet(
"ShadPlug.Spawn.Red.World")) {
List<String> teamredList = plugin.getConfig()
.getStringList("ShadPlug.Teams.Red.Members");
List<String> teamblueList = plugin.getConfig()
.getStringList("ShadPlug.Teams.Blue.Members");
// Make sure player is not in a team already
if (teamredList.contains(player.getName().toString())
|| teamblueList.contains(player.getName()
.toString())) {
player.sendMessage("Sorry bro you're already in a team");
} else {
// If TeamRed has fewer players than TeamBlue,
// player
// will join TeamRed and vice versa.
if (teamredList.size() <= teamblueList.size()) {
teamredList.add(player.getName());
ShadConfig.TeamRed.put(player.getName(), "red");
plugin.getServer().broadcastMessage(
player.getName()
+ " has joined the Red Team.");
plugin.getConfig().set(
"ShadPlug.Teams.Red.Members",
teamredList);
ShadConfig.redchatonline.add(player.getName());
plugin.saveConfig();
World world;
world = plugin.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Red.World"));
final Location location = new Location(world,
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.X"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Y"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Red.Pitch"));
player.sendMessage("You will be ported to the Red base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 14));
}
}, 100L);
} else {
teamblueList.add(player.getName());
ShadConfig.TeamBlue.put(player.getName(),
"blue");
plugin.getServer().broadcastMessage(
player.getName()
+ " has joined the Blue Team.");
ShadConfig.bluechatonline.add(player.getName());
plugin.getConfig().set(
"ShadPlug.Teams.Blue.Members",
teamblueList);
plugin.saveConfig();
World world;
world = Bukkit.getServer().getWorld(
plugin.getConfig().getString(
"ShadPlug.Spawn.Blue.World"));
final Location location = new Location(world,
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.X"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Y"),
plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Z"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Yaw"),
(float) plugin.getConfig().getDouble(
"ShadPlug.Spawn.Blue.Pitch"));
player.sendMessage("You will be ported to the Blue base in 5 seconds.");
plugin.getServer()
.getScheduler()
.scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
player.teleport(location);
player.getInventory()
.setHelmet(
new ItemStack(
Material.WOOL,
1,
(short) 11));
}
}, 100L);
}
}
} else {
player.sendMessage("The Spawnpoints for the Teams are not set.");
}
}
/*
* Display Team scores
*/
if (first.equalsIgnoreCase("score")) {
erfolg = true;
player.sendMessage(ChatColor.RED + "====================");
player.sendMessage(ChatColor.WHITE
+ "Red Blue");
player.sendMessage(ChatColor.AQUA + ""
+ ShadConfig.redScore + " "
+ ShadConfig.blueScore);
player.sendMessage(ChatColor.RED + "====================");
}
/*
* Spit out help how to use List command
*/
if (first.equalsIgnoreCase("list")) {
erfolg = true;
player.sendMessage(ChatColor.GOLD + "Type: "
+ ChatColor.AQUA + ChatColor.BOLD + "/shad list "
+ ChatColor.RED + ChatColor.BOLD + "Red"
+ ChatColor.GOLD + " or " + ChatColor.AQUA
+ ChatColor.BOLD + "/shad list " + ChatColor.BLUE
+ ChatColor.BOLD + "Blue.");
player.sendMessage(ChatColor.GOLD
+ "To see the members of each team.");
}
/*
* Spit out help how to use SetSpawn command
*/
if (first.equalsIgnoreCase("setspawn")) {
erfolg = true;
player.sendMessage("Correct Usage is" + ChatColor.AQUA
+ " /shad setspawn RED/BLUE");
}
/*
* Reload Config.yml
*/
if (first.equalsIgnoreCase("reload")) {
erfolg = true;
plugin.reloadConfig();
player.sendMessage(ChatColor.AQUA
+ "ShadPlugs config.yml has been reloaded.");
}
if (first.equalsIgnoreCase("clear")) {
erfolg = true;
ShadConfig.TeamBlue.clear();
ShadConfig.TeamRed.clear();
ShadConfig.redScoreHashMap.clear();
ShadConfig.blueScoreHashMap.clear();
ShadConfig.bluechatonline.clear();
ShadConfig.redchatonline.clear();
ShadConfig.instantchat.clear();
plugin.getConfig().set("ShadPlug.Spawn.Red", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.World", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.X", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Y", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Z", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Pitch", null);
plugin.getConfig().set("ShadPlug.Spawn.Red.Yaw", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.World", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.X", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Y", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Z", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Pitch", null);
plugin.getConfig().set("ShadPlug.Spawn.Blue.Yaw", null);
plugin.getConfig().set("ShadPlug.Teams.Blue", null);
plugin.getConfig().set("ShadPlug.Teams.Blue.Members", null);
plugin.getConfig().set("ShadPlug.Teams.Blue.Members.Score",
null);
plugin.getConfig().set("ShadPlug.Teams.Red", null);
plugin.getConfig().set("ShadPlug.Teams.Red.Members", null);
plugin.getConfig().set("ShadPlug.Teams.Red.Members.Score",
null);
plugin.getConfig().set("ShadPlug.Worlds", null);
plugin.saveConfig();
}
}
if (args.length == 2) {
String first;
String second;
first = args[0];
second = args[1];
/*
* Add a world to the enabled Worlds.
*/
if (first.equals("addworld")) {
erfolg = true;
List<String> worldList = plugin.getConfig().getStringList(
"ShadPlug.Worlds");
worldList.add(second);
plugin.getConfig().set("ShadPlug.Worlds", worldList);
player.sendMessage(ChatColor.RED.toString()
+ ChatColor.BOLD.toString() + second
+ ChatColor.AQUA
+ " has been added to the enabled Worlds.");
plugin.saveConfig();
}
/*
* Remove a world from the enabled Worlds.
*/
if (first.equals("remworld")) {
erfolg = true;
List<String> worldList = plugin.getConfig().getStringList(
"ShadPlug.Worlds");
worldList.remove(second);
plugin.getConfig().set("ShadPlug.Worlds", worldList);
player.sendMessage(ChatColor.RED.toString()
+ ChatColor.BOLD.toString() + second
+ ChatColor.AQUA + " has been " + ChatColor.RED
+ "removed" + ChatColor.AQUA
+ " from the enabled Worlds.");
plugin.saveConfig();
}
/*
* Set Red spawn
*/
if (first.equalsIgnoreCase("setspawn")
&& second.equalsIgnoreCase("red")) {
erfolg = true;
if (player.hasPermission("ShadPlug.Admin.SetSpawn")) {
String World = player.getWorld().getName();
Location location = player.getLocation();
double spawnX = player.getLocation().getX();
double spawnY = player.getLocation().getY();
double spawnZ = player.getLocation().getZ();
float pitch = location.getPitch();
float yaw = location.getYaw();
if (!plugin.getConfig()
.getStringList("ShadPlug.Worlds")
.contains(World)) {
player.sendMessage(ChatColor.RED
+ "WARNING:"
+ ChatColor.AQUA
+ " The world where you just set Spawn is not enabled in the config.yml");
}
ShadConfig.savePosToConfigRed(1, World, spawnX, spawnY,
spawnZ, pitch, yaw);
player.sendMessage("Spawnpoint for Red-Team set");
plugin.saveConfig();
} else {
player.sendMessage("ShadPlug.Admin.SetSpawn Perms missing.");
}
}
/*
* Set Blue spawn
*/
if (first.equalsIgnoreCase("setspawn")
&& second.equalsIgnoreCase("blue")) {
erfolg = true;
if (player.hasPermission("ShadPlug.Admin.SetSpawn")) {
String World = player.getWorld().getName();
Location location = player.getLocation();
double spawnX = player.getLocation().getX();
double spawnY = player.getLocation().getY();
double spawnZ = player.getLocation().getZ();
float pitch = location.getPitch();
float yaw = location.getYaw();
if (!plugin.getConfig()
.getStringList("ShadPlug.Worlds")
.contains(World)) {
player.sendMessage(ChatColor.RED
+ "WARNING:"
+ ChatColor.AQUA
+ " The world where you just set Spawn is not enabled in the config.yml");
}
ShadConfig.savePosToConfigBlue(1, World, spawnX,
spawnY, spawnZ, pitch, yaw);
player.sendMessage("Spawnpoint for Blue-Team set");
plugin.saveConfig();
} else {
player.sendMessage("ShadPlug.Admin.SetSpawn Perms missing.");
}
}
/*
* List Red and Blue players.
*/
if (first.equalsIgnoreCase("list")
&& second.equalsIgnoreCase("red")) {
erfolg = true;
player.sendMessage("Team "
+ ChatColor.RED
+ "Red "
+ ChatColor.WHITE
+ plugin.getConfig()
.get("ShadPlug.Teams.Red.Members")
.toString());
}
if (first.equalsIgnoreCase("list")
&& second.equalsIgnoreCase("blue")) {
erfolg = true;
player.sendMessage("Team "
+ ChatColor.BLUE
+ "Blue "
+ ChatColor.WHITE
+ plugin.getConfig()
.get("ShadPlug.Teams.Blue.Members")
.toString());
}
}
// Checking for existing arguments
if (erfolg == false) { // Notice the ==, double = means its
// checking, if its just a single = then its
// setting
player.sendMessage(ChatColor.RED
+ "Unknown Command - Please type " + ChatColor.AQUA
+ ChatColor.BOLD + "/shad help" + ChatColor.RED
+ " to get help.");
}
}
return erfolg;
}
|
diff --git a/src/org/intellij/erlang/formatter/ErlangFormattingModelBuilder.java b/src/org/intellij/erlang/formatter/ErlangFormattingModelBuilder.java
index 9f25a9d6..cb15a30c 100644
--- a/src/org/intellij/erlang/formatter/ErlangFormattingModelBuilder.java
+++ b/src/org/intellij/erlang/formatter/ErlangFormattingModelBuilder.java
@@ -1,159 +1,161 @@
/*
* Copyright 2012 Sergey Ignatov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.erlang.formatter;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.tree.TokenSet;
import org.intellij.erlang.ErlangLanguage;
import org.intellij.erlang.formatter.settings.ErlangCodeStyleSettings;
import org.jetbrains.annotations.NotNull;
import static org.intellij.erlang.ErlangTypes.*;
/**
* @author ignatov
*/
public class ErlangFormattingModelBuilder implements FormattingModelBuilder {
@NotNull
@Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
CommonCodeStyleSettings commonSettings = settings.getCommonSettings(ErlangLanguage.INSTANCE);
ErlangCodeStyleSettings erlangSettings = settings.getCustomSettings(ErlangCodeStyleSettings.class);
final ErlangBlock block = new ErlangBlock(null, element.getNode(), null, null, commonSettings, erlangSettings,
createSpacingBuilder(commonSettings));
return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(), block, settings);
}
private static SpacingBuilder createSpacingBuilder(CommonCodeStyleSettings settings) {
TokenSet rules = TokenSet.create(ERL_RULE, ERL_RECORD_DEFINITION, ERL_INCLUDE, ERL_MACROS_DEFINITION, ERL_ATTRIBUTE);
TokenSet keywords = TokenSet.create(
ERL_AFTER, ERL_WHEN, ERL_BEGIN, ERL_END, ERL_OF, ERL_CASE, ERL_QUERY, ERL_CATCH, ERL_IF, ERL_RECEIVE,
ERL_TRY, ERL_DIV, ERL_REM, ERL_OR, ERL_XOR, ERL_BOR, ERL_BXOR, ERL_BSL, ERL_BSR, ERL_AND, ERL_BAND);
return new SpacingBuilder(settings.getRootSettings())
.before(ERL_COMMA).spaceIf(settings.SPACE_BEFORE_COMMA)
.after(ERL_COMMA).spaceIf(settings.SPACE_AFTER_COMMA)
// .betweenInside(ERL_OP_EQ, ERL_BINARY_EXPRESSION, ERL_RECORD_FIELD).spaces(1)
// .betweenInside(ERL_OP_EQ, ERL_BINARY_TYPE, ERL_RECORD_FIELD).spaces(1)
// .betweenInside(ERL_OP_EQ, ERL_LIST_COMPREHENSION, ERL_RECORD_FIELD).spaces(1)
// .aroundInside(ERL_OP_EQ, ERL_RECORD_FIELD).none()
// .aroundInside(ERL_OP_EQ, ERL_TYPED_EXPR).none()
.around(ERL_OP_EQ).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.around(ERL_OP_LT_MINUS).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.around(ERL_OP_EXL).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.after(ERL_ARROW).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.before(ERL_CLAUSE_BODY).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.around(ERL_OP_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS)
.around(ERL_OP_PLUS_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS)
.aroundInside(ERL_OP_MINUS, ERL_ADDITIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS)
.aroundInside(ERL_OP_AR_DIV, ERL_MULTIPLICATIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS)
.around(ERL_OP_AR_MUL).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS)
.around(ERL_OP_EQ_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_EQ_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_EQ_COL_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OP_EQ_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OP_GT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OP_GT_EQ).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OR_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.after(ERL_BRACKET_LEFT).none()
.before(ERL_BRACKET_RIGHT).none()
.after(ERL_CURLY_LEFT).none()
.before(ERL_CURLY_RIGHT).none()
.after(ERL_BIN_START).none()
.before(ERL_BIN_END).none()
.before(ERL_ARGUMENT_DEFINITION_LIST).none()
.before(ERL_ARGUMENT_LIST).none()
.withinPair(ERL_PAR_LEFT, ERL_PAR_RIGHT).spaceIf(settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES)
.withinPair(ERL_BRACKET_LEFT, ERL_BRACKET_RIGHT).spaceIf(true)
.withinPair(ERL_CURLY_LEFT, ERL_CURLY_RIGHT).spaceIf(true)
.withinPair(ERL_BIN_START, ERL_BIN_END).spaceIf(true)
.beforeInside(rules, ERL_PAR_LEFT).none()
.around(keywords).spaces(1)
.before(ERL_FUN_TYPE_SIGS_BRACES).none()
.between(ERL_SPEC_FUN, ERL_TYPE_SIG).none()
.aroundInside(ERL_OP_AR_DIV, ERL_SPEC_FUN).none()
.beforeInside(ERL_PAR_LEFT, ERL_EXPORT).none()
.beforeInside(ERL_PAR_LEFT, ERL_EXPORT_TYPE_ATTRIBUTE).none()
.beforeInside(ERL_PAR_LEFT, ERL_INCLUDE).none()
.beforeInside(ERL_PAR_LEFT, ERL_RECORD_DEFINITION).none()
.beforeInside(ERL_PAR_LEFT, ERL_MODULE).none()
.beforeInside(ERL_PAR_LEFT, ERL_MACROS_DEFINITION).none()
.beforeInside(ERL_PAR_LEFT, ERL_BEHAVIOUR).none()
.beforeInside(ERL_TYPED_ATTR_VAL, ERL_ATOM_ATTRIBUTE).spaces(1)
.afterInside(ERL_Q_ATOM, ERL_ATOM_ATTRIBUTE).none()
.beforeInside(ERL_PAR_LEFT, ERL_SPECIFICATION).none()
.beforeInside(ERL_FUN_TYPE_SIGS, ERL_SPECIFICATION).spaces(1)
.beforeInside(ERL_PAR_LEFT, ERL_CALLBACK_SPEC).none()
.beforeInside(ERL_FUN_TYPE_SIGS, ERL_CALLBACK_SPEC).spaces(1)
.aroundInside(ERL_OP_AR_DIV, ERL_FUN_TYPE_SIGS).none()
.aroundInside(ERL_OP_AR_DIV, ERL_EXPORT_FUNCTION).none()
.aroundInside(ERL_OP_AR_DIV, ERL_EXPORT_TYPE).none()
.aroundInside(ERL_COLON_COLON, ERL_FUN_TYPE_SIGS).spaces(1)
.betweenInside(ERL_COLON_COLON, ERL_TYPE_SIG, ERL_FUN_TYPE_SIGS).spaces(1)
.between(ERL_FUN_TYPE_ARGUMENTS, ERL_TOP_TYPE_CLAUSE).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.betweenInside(ERL_Q_ATOM, ERL_PAR_LEFT, ERL_TYPE).none()
.before(ERL_CLAUSE_GUARD).spaces(1)
.before(ERL_FUN_TYPE_SIGS).spaces(1)
.around(ERL_FUN_TYPE).spaces(1)
.around(ERL_TYPE_SIG).spaces(1)
.beforeInside(ERL_PAR_LEFT, ERL_FUN_TYPE).spaces(1)
.afterInside(ERL_PAR_RIGHT, ERL_FUN_TYPE).spaces(1)
.aroundInside(ERL_COLON, ERL_GLOBAL_FUNCTION_CALL_EXPRESSION).none()
.around(ERL_COLON_COLON).spaces(1)
.aroundInside(ERL_DOT, ERL_RECORD_FIELD).none()
.before(ERL_RECORD_FIELD).none()
.aroundInside(ERL_RADIX, ERL_RECORD_EXPRESSION).none()
.before(ERL_DOT).none()
.around(ERL_QMARK).none()
.before(ERL_RECORD_TUPLE).none()
+ .between(ERL_FUN, ERL_MODULE_REF).spaces(1)
+ .between(ERL_FUN, ERL_FUNCTION_WITH_ARITY).spaces(1)
.after(ERL_FUN).none()
.before(ERL_END).spaces(1)
;
}
@Override
public TextRange getRangeAffectingIndent(PsiFile psiFile, int i, ASTNode astNode) {
return null;
}
}
| true | true | private static SpacingBuilder createSpacingBuilder(CommonCodeStyleSettings settings) {
TokenSet rules = TokenSet.create(ERL_RULE, ERL_RECORD_DEFINITION, ERL_INCLUDE, ERL_MACROS_DEFINITION, ERL_ATTRIBUTE);
TokenSet keywords = TokenSet.create(
ERL_AFTER, ERL_WHEN, ERL_BEGIN, ERL_END, ERL_OF, ERL_CASE, ERL_QUERY, ERL_CATCH, ERL_IF, ERL_RECEIVE,
ERL_TRY, ERL_DIV, ERL_REM, ERL_OR, ERL_XOR, ERL_BOR, ERL_BXOR, ERL_BSL, ERL_BSR, ERL_AND, ERL_BAND);
return new SpacingBuilder(settings.getRootSettings())
.before(ERL_COMMA).spaceIf(settings.SPACE_BEFORE_COMMA)
.after(ERL_COMMA).spaceIf(settings.SPACE_AFTER_COMMA)
// .betweenInside(ERL_OP_EQ, ERL_BINARY_EXPRESSION, ERL_RECORD_FIELD).spaces(1)
// .betweenInside(ERL_OP_EQ, ERL_BINARY_TYPE, ERL_RECORD_FIELD).spaces(1)
// .betweenInside(ERL_OP_EQ, ERL_LIST_COMPREHENSION, ERL_RECORD_FIELD).spaces(1)
// .aroundInside(ERL_OP_EQ, ERL_RECORD_FIELD).none()
// .aroundInside(ERL_OP_EQ, ERL_TYPED_EXPR).none()
.around(ERL_OP_EQ).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.around(ERL_OP_LT_MINUS).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.around(ERL_OP_EXL).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.after(ERL_ARROW).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.before(ERL_CLAUSE_BODY).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.around(ERL_OP_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS)
.around(ERL_OP_PLUS_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS)
.aroundInside(ERL_OP_MINUS, ERL_ADDITIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS)
.aroundInside(ERL_OP_AR_DIV, ERL_MULTIPLICATIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS)
.around(ERL_OP_AR_MUL).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS)
.around(ERL_OP_EQ_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_EQ_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_EQ_COL_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OP_EQ_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OP_GT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OP_GT_EQ).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OR_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.after(ERL_BRACKET_LEFT).none()
.before(ERL_BRACKET_RIGHT).none()
.after(ERL_CURLY_LEFT).none()
.before(ERL_CURLY_RIGHT).none()
.after(ERL_BIN_START).none()
.before(ERL_BIN_END).none()
.before(ERL_ARGUMENT_DEFINITION_LIST).none()
.before(ERL_ARGUMENT_LIST).none()
.withinPair(ERL_PAR_LEFT, ERL_PAR_RIGHT).spaceIf(settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES)
.withinPair(ERL_BRACKET_LEFT, ERL_BRACKET_RIGHT).spaceIf(true)
.withinPair(ERL_CURLY_LEFT, ERL_CURLY_RIGHT).spaceIf(true)
.withinPair(ERL_BIN_START, ERL_BIN_END).spaceIf(true)
.beforeInside(rules, ERL_PAR_LEFT).none()
.around(keywords).spaces(1)
.before(ERL_FUN_TYPE_SIGS_BRACES).none()
.between(ERL_SPEC_FUN, ERL_TYPE_SIG).none()
.aroundInside(ERL_OP_AR_DIV, ERL_SPEC_FUN).none()
.beforeInside(ERL_PAR_LEFT, ERL_EXPORT).none()
.beforeInside(ERL_PAR_LEFT, ERL_EXPORT_TYPE_ATTRIBUTE).none()
.beforeInside(ERL_PAR_LEFT, ERL_INCLUDE).none()
.beforeInside(ERL_PAR_LEFT, ERL_RECORD_DEFINITION).none()
.beforeInside(ERL_PAR_LEFT, ERL_MODULE).none()
.beforeInside(ERL_PAR_LEFT, ERL_MACROS_DEFINITION).none()
.beforeInside(ERL_PAR_LEFT, ERL_BEHAVIOUR).none()
.beforeInside(ERL_TYPED_ATTR_VAL, ERL_ATOM_ATTRIBUTE).spaces(1)
.afterInside(ERL_Q_ATOM, ERL_ATOM_ATTRIBUTE).none()
.beforeInside(ERL_PAR_LEFT, ERL_SPECIFICATION).none()
.beforeInside(ERL_FUN_TYPE_SIGS, ERL_SPECIFICATION).spaces(1)
.beforeInside(ERL_PAR_LEFT, ERL_CALLBACK_SPEC).none()
.beforeInside(ERL_FUN_TYPE_SIGS, ERL_CALLBACK_SPEC).spaces(1)
.aroundInside(ERL_OP_AR_DIV, ERL_FUN_TYPE_SIGS).none()
.aroundInside(ERL_OP_AR_DIV, ERL_EXPORT_FUNCTION).none()
.aroundInside(ERL_OP_AR_DIV, ERL_EXPORT_TYPE).none()
.aroundInside(ERL_COLON_COLON, ERL_FUN_TYPE_SIGS).spaces(1)
.betweenInside(ERL_COLON_COLON, ERL_TYPE_SIG, ERL_FUN_TYPE_SIGS).spaces(1)
.between(ERL_FUN_TYPE_ARGUMENTS, ERL_TOP_TYPE_CLAUSE).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.betweenInside(ERL_Q_ATOM, ERL_PAR_LEFT, ERL_TYPE).none()
.before(ERL_CLAUSE_GUARD).spaces(1)
.before(ERL_FUN_TYPE_SIGS).spaces(1)
.around(ERL_FUN_TYPE).spaces(1)
.around(ERL_TYPE_SIG).spaces(1)
.beforeInside(ERL_PAR_LEFT, ERL_FUN_TYPE).spaces(1)
.afterInside(ERL_PAR_RIGHT, ERL_FUN_TYPE).spaces(1)
.aroundInside(ERL_COLON, ERL_GLOBAL_FUNCTION_CALL_EXPRESSION).none()
.around(ERL_COLON_COLON).spaces(1)
.aroundInside(ERL_DOT, ERL_RECORD_FIELD).none()
.before(ERL_RECORD_FIELD).none()
.aroundInside(ERL_RADIX, ERL_RECORD_EXPRESSION).none()
.before(ERL_DOT).none()
.around(ERL_QMARK).none()
.before(ERL_RECORD_TUPLE).none()
.after(ERL_FUN).none()
.before(ERL_END).spaces(1)
;
}
| private static SpacingBuilder createSpacingBuilder(CommonCodeStyleSettings settings) {
TokenSet rules = TokenSet.create(ERL_RULE, ERL_RECORD_DEFINITION, ERL_INCLUDE, ERL_MACROS_DEFINITION, ERL_ATTRIBUTE);
TokenSet keywords = TokenSet.create(
ERL_AFTER, ERL_WHEN, ERL_BEGIN, ERL_END, ERL_OF, ERL_CASE, ERL_QUERY, ERL_CATCH, ERL_IF, ERL_RECEIVE,
ERL_TRY, ERL_DIV, ERL_REM, ERL_OR, ERL_XOR, ERL_BOR, ERL_BXOR, ERL_BSL, ERL_BSR, ERL_AND, ERL_BAND);
return new SpacingBuilder(settings.getRootSettings())
.before(ERL_COMMA).spaceIf(settings.SPACE_BEFORE_COMMA)
.after(ERL_COMMA).spaceIf(settings.SPACE_AFTER_COMMA)
// .betweenInside(ERL_OP_EQ, ERL_BINARY_EXPRESSION, ERL_RECORD_FIELD).spaces(1)
// .betweenInside(ERL_OP_EQ, ERL_BINARY_TYPE, ERL_RECORD_FIELD).spaces(1)
// .betweenInside(ERL_OP_EQ, ERL_LIST_COMPREHENSION, ERL_RECORD_FIELD).spaces(1)
// .aroundInside(ERL_OP_EQ, ERL_RECORD_FIELD).none()
// .aroundInside(ERL_OP_EQ, ERL_TYPED_EXPR).none()
.around(ERL_OP_EQ).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.around(ERL_OP_LT_MINUS).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.around(ERL_OP_EXL).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.after(ERL_ARROW).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.before(ERL_CLAUSE_BODY).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.around(ERL_OP_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS)
.around(ERL_OP_PLUS_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS)
.aroundInside(ERL_OP_MINUS, ERL_ADDITIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS)
.aroundInside(ERL_OP_AR_DIV, ERL_MULTIPLICATIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS)
.around(ERL_OP_AR_MUL).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS)
.around(ERL_OP_EQ_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_EQ_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_EQ_COL_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS)
.around(ERL_OP_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OP_EQ_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OP_GT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OP_GT_EQ).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OR_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.around(ERL_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS)
.after(ERL_BRACKET_LEFT).none()
.before(ERL_BRACKET_RIGHT).none()
.after(ERL_CURLY_LEFT).none()
.before(ERL_CURLY_RIGHT).none()
.after(ERL_BIN_START).none()
.before(ERL_BIN_END).none()
.before(ERL_ARGUMENT_DEFINITION_LIST).none()
.before(ERL_ARGUMENT_LIST).none()
.withinPair(ERL_PAR_LEFT, ERL_PAR_RIGHT).spaceIf(settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES)
.withinPair(ERL_BRACKET_LEFT, ERL_BRACKET_RIGHT).spaceIf(true)
.withinPair(ERL_CURLY_LEFT, ERL_CURLY_RIGHT).spaceIf(true)
.withinPair(ERL_BIN_START, ERL_BIN_END).spaceIf(true)
.beforeInside(rules, ERL_PAR_LEFT).none()
.around(keywords).spaces(1)
.before(ERL_FUN_TYPE_SIGS_BRACES).none()
.between(ERL_SPEC_FUN, ERL_TYPE_SIG).none()
.aroundInside(ERL_OP_AR_DIV, ERL_SPEC_FUN).none()
.beforeInside(ERL_PAR_LEFT, ERL_EXPORT).none()
.beforeInside(ERL_PAR_LEFT, ERL_EXPORT_TYPE_ATTRIBUTE).none()
.beforeInside(ERL_PAR_LEFT, ERL_INCLUDE).none()
.beforeInside(ERL_PAR_LEFT, ERL_RECORD_DEFINITION).none()
.beforeInside(ERL_PAR_LEFT, ERL_MODULE).none()
.beforeInside(ERL_PAR_LEFT, ERL_MACROS_DEFINITION).none()
.beforeInside(ERL_PAR_LEFT, ERL_BEHAVIOUR).none()
.beforeInside(ERL_TYPED_ATTR_VAL, ERL_ATOM_ATTRIBUTE).spaces(1)
.afterInside(ERL_Q_ATOM, ERL_ATOM_ATTRIBUTE).none()
.beforeInside(ERL_PAR_LEFT, ERL_SPECIFICATION).none()
.beforeInside(ERL_FUN_TYPE_SIGS, ERL_SPECIFICATION).spaces(1)
.beforeInside(ERL_PAR_LEFT, ERL_CALLBACK_SPEC).none()
.beforeInside(ERL_FUN_TYPE_SIGS, ERL_CALLBACK_SPEC).spaces(1)
.aroundInside(ERL_OP_AR_DIV, ERL_FUN_TYPE_SIGS).none()
.aroundInside(ERL_OP_AR_DIV, ERL_EXPORT_FUNCTION).none()
.aroundInside(ERL_OP_AR_DIV, ERL_EXPORT_TYPE).none()
.aroundInside(ERL_COLON_COLON, ERL_FUN_TYPE_SIGS).spaces(1)
.betweenInside(ERL_COLON_COLON, ERL_TYPE_SIG, ERL_FUN_TYPE_SIGS).spaces(1)
.between(ERL_FUN_TYPE_ARGUMENTS, ERL_TOP_TYPE_CLAUSE).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.betweenInside(ERL_Q_ATOM, ERL_PAR_LEFT, ERL_TYPE).none()
.before(ERL_CLAUSE_GUARD).spaces(1)
.before(ERL_FUN_TYPE_SIGS).spaces(1)
.around(ERL_FUN_TYPE).spaces(1)
.around(ERL_TYPE_SIG).spaces(1)
.beforeInside(ERL_PAR_LEFT, ERL_FUN_TYPE).spaces(1)
.afterInside(ERL_PAR_RIGHT, ERL_FUN_TYPE).spaces(1)
.aroundInside(ERL_COLON, ERL_GLOBAL_FUNCTION_CALL_EXPRESSION).none()
.around(ERL_COLON_COLON).spaces(1)
.aroundInside(ERL_DOT, ERL_RECORD_FIELD).none()
.before(ERL_RECORD_FIELD).none()
.aroundInside(ERL_RADIX, ERL_RECORD_EXPRESSION).none()
.before(ERL_DOT).none()
.around(ERL_QMARK).none()
.before(ERL_RECORD_TUPLE).none()
.between(ERL_FUN, ERL_MODULE_REF).spaces(1)
.between(ERL_FUN, ERL_FUNCTION_WITH_ARITY).spaces(1)
.after(ERL_FUN).none()
.before(ERL_END).spaces(1)
;
}
|
diff --git a/src/edu/wheaton/simulator/gui/screen/SetupScreen.java b/src/edu/wheaton/simulator/gui/screen/SetupScreen.java
index ae9ad384..010d9a19 100644
--- a/src/edu/wheaton/simulator/gui/screen/SetupScreen.java
+++ b/src/edu/wheaton/simulator/gui/screen/SetupScreen.java
@@ -1,413 +1,413 @@
package edu.wheaton.simulator.gui.screen;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import com.google.common.collect.ImmutableMap;
import edu.wheaton.simulator.gui.BoxLayoutAxis;
import edu.wheaton.simulator.gui.Gui;
import edu.wheaton.simulator.gui.MaxSize;
import edu.wheaton.simulator.gui.MinSize;
import edu.wheaton.simulator.gui.PrefSize;
import edu.wheaton.simulator.gui.SimulatorFacade;
//TODO add elements for step delay
public class SetupScreen extends Screen {
private JTextField nameField;
private JTextField timeField;
private JTextField widthField;
private JTextField heightField;
private JTextField delayField;
private String[] agentNames;
private JComboBox updateBox;
private ArrayList<JComboBox> agentTypes;
private ArrayList<JTextField> values;
private ArrayList<JButton> deleteButtons;
private ArrayList<JPanel> subPanels;
private JScrollPane scrollPane;
private JPanel conListPanel;
private JButton addConditionButton;
private static final long serialVersionUID = -8347080877399964861L;
public SetupScreen(final SimulatorFacade gm) {
super(gm);
this.setLayout(new GridBagLayout());
this.setMinimumSize(new MinSize(410,400));
this.setPreferredSize(new PrefSize(410,400));
agentNames = new String[0];
agentTypes = new ArrayList<JComboBox>();
deleteButtons = new ArrayList<JButton>();
subPanels = new ArrayList<JPanel>();
agentTypes = new ArrayList<JComboBox>();
values = new ArrayList<JTextField>();
JLabel nameLabel = Gui.makeLabel("Name:",
new MinSize(50,30));
nameField = Gui.makeTextField(gm.getSimName(), 20,
null, new MinSize(75,30));
JLabel widthLabel = Gui.makeLabel("Width:",
new MinSize(50,30));
widthField = Gui.makeTextField("10", 5, MaxSize.NULL,
new MinSize(50,30));
JLabel yLabel = Gui.makeLabel("Height:",
new MinSize(60,30));
heightField = Gui.makeTextField("10", 5, MaxSize.NULL,
new MinSize(50,30));
JLabel updateLabel = Gui.makeLabel("Update type:", MaxSize.NULL, null);
updateBox = Gui.makeComboBox(new String[] { "Linear", "Atomic",
"Priority" }, MaxSize.NULL);
updateBox.setMinimumSize(new MinSize(250,30));
updateBox.setPreferredSize(new PrefSize(250,30));
//TODO working on adding step delay components
JLabel delayLabel = Gui.makeLabel("Step delay (ms):", MaxSize.NULL, null);
delayField = Gui.makeTextField("1.0", 20, MaxSize.NULL,
new MinSize(100,30));
JLabel timeLabel = Gui.makeLabel("Max steps:", MaxSize.NULL,
null);
timeField = Gui.makeTextField(null, 20, MaxSize.NULL,
new MinSize(60,30));
JLabel agentTypeLabel = Gui.makeLabel("Agent Type", MaxSize.NULL, null);
JLabel valueLabel = Gui.makeLabel("Population Limit", MaxSize.NULL, null);
conListPanel = makeConditionListPanel();
conListPanel.setMinimumSize(new MinSize(250,300));
conListPanel.setPreferredSize(new PrefSize(250,300));
scrollPane = new JScrollPane(conListPanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setMinimumSize(new MinSize(400,300));
scrollPane.setPreferredSize(new PrefSize(400,300));
JPanel scrollPaneWrapper = Gui.makePanel((BoxLayoutAxis)null,MaxSize.NULL,null,(Component[])null);
scrollPaneWrapper.add(scrollPane);
addConditionButton = Gui.makeButton("Add Field", null,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addCondition();
}
});
JPanel bottomButtons = Gui.makePanel(
Gui.makeButton("Revert", null, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
load();
}
}), makeConfirmButton(),addConditionButton);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 3);
this.add(nameLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 3;
c.insets = new Insets(0, 0, 0, 3);
this.add(nameField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 3);
this.add(widthLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
- c.insets = new Insets(0, -4, 0, 3);
+ c.insets = new Insets(0, -53, 0, 3);
this.add(widthField, c);
c = new GridBagConstraints();
c.gridx = 2;
c.gridy = 1;
- c.insets = new Insets(0, 0, 0, 3);
+ c.insets = new Insets(0, -45, 0, 3);
this.add(yLabel, c);
c = new GridBagConstraints();
c.gridx = 3;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 3);
this.add(heightField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(0, 0, 0, 3);
this.add(delayLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
c.insets = new Insets(0, 0, 0, 3);
c.gridwidth = 3;
this.add(delayField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 3;
c.insets = new Insets(0, 0, 0, 3);
this.add(updateLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 3;
c.insets = new Insets(0, 0, 0, 3);
c.gridwidth = 3;
this.add(updateBox, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 4;
c.insets = new Insets(0,0, 0, 3);
this.add(timeLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 4;
c.insets = new Insets(0, 0, 0, 3);
c.gridwidth = 3;
this.add(timeField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 5;
- c.insets = new Insets(10, 0, 0, 0);
+ c.insets = new Insets(10, 30, 0, 0);
this.add(agentTypeLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 5;
- c.insets = new Insets(10, 0, 0, 3);
+ c.insets = new Insets(10, 50, 0, 0);
this.add(valueLabel, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 6;
c.gridwidth = 4;
c.insets = new Insets(2,0, 0, 0);
c.fill = c.HORIZONTAL;
this.add(scrollPaneWrapper,c);
c = new GridBagConstraints();
c.gridy = 8;
c.insets = new Insets(0,0,0,0);
c.gridwidth = 4;
c.fill = c.HORIZONTAL;
this.add(Gui.makePanel(bottomButtons),c);
validate();
}
private JButton makeConfirmButton() {
return Gui.makeButton("Confirm", null, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
SimulatorFacade gm = getGuiManager();
int newWidth = Integer.parseInt(widthField.getText());
int newHeight = Integer.parseInt(widthField.getText());
int newTime = Integer.parseInt(timeField.getText());
int newDelay = Integer.parseInt(delayField.getText());
if (newWidth <= 0 || newHeight <= 0 || newTime <= 0 || newDelay < 0)
throw new NumberFormatException();
if (newWidth < gm.getGridWidth()
|| newHeight < gm.getGridHeight()) {
int selection = JOptionPane
.showConfirmDialog(
null,
"The new grid size you provided"
+ "\nis smaller than its current value."
+ "\nThis may result in the deletion of objects placed in the grid that"
+ "\ncannot fit within these new dimensions."
+ "\nFurthermore, agent data that depended on specific coordinates may"
+ "\nneed to be checked for bugs after resizing."
+ "\n\nIf you are sure you want to apply these changes, click 'Ok', otherwise click 'No' or 'Cancel'");
if (selection == JOptionPane.YES_OPTION)
gm.resizeGrid(newWidth, newHeight);
else
return;
}
if (nameField.getText().equals(""))
throw new Exception("All fields must have input");
gm.setName(nameField.getText());
for (int i = 0; i < values.size(); i++)
if (values.get(i).getText().equals(""))
throw new Exception("All fields must have input.");
gm.resizeGrid(newWidth, newHeight);
gm.setStepLimit(newTime);
gm.setSleepPeriod(newDelay);
String str = (String) updateBox.getSelectedItem();
if (str.equals("Linear"))
gm.setLinearUpdate();
else if (str.equals("Atomic"))
gm.setAtomicUpdate();
else
gm.setPriorityUpdate(0, 50);
for (int i = 0; i < values.size(); i++) {
gm.setPopLimit(
(String) (agentTypes.get(i).getSelectedItem()),
Integer.parseInt(values.get(i).getText()));
}
load();
} catch (NumberFormatException excep) {
JOptionPane
.showMessageDialog(null,
"Width and Height fields must be integers greater than 0. Time delay must not be less than 0.");
} catch (Exception excep) {
JOptionPane.showMessageDialog(null, excep.getMessage());
}
}
});
}
@Override
public void load() {
reset();
nameField.setText(getGuiManager().getSimName());
updateBox.setSelectedItem(getGuiManager().getCurrentUpdater());
widthField.setText(gm.getGridWidth().toString());
heightField.setText(gm.getGridHeight().toString());
delayField.setText(gm.getSleepPeriod().toString());
SimulatorFacade gm = getGuiManager();
int stepLimit = gm.getStepLimit();
agentNames = gm.getPrototypeNames().toArray(agentNames);
timeField.setText(stepLimit + "");
// to prevent accidental starting simulation with time limit of 0
if (stepLimit <= 0)
timeField.setText(10 + "");
ImmutableMap<String, Integer> popLimits = gm.getPopLimits();
if (popLimits.size() == 0) {
addConditionButton.setEnabled(true);
} else {
int i = 0;
for (String p : popLimits.keySet()) {
addCondition();
agentTypes.get(i).setSelectedItem(p);
values.get(i).setText(popLimits.get(p) + "");
i++;
}
}
validate();
}
private static JPanel makeConditionListPanel() {
JPanel conListPanel = Gui.makePanel(BoxLayoutAxis.PAGE_AXIS, null, null);
return conListPanel;
}
private void addCondition() {
JComboBox newBox = Gui.makeComboBox(agentNames, MaxSize.NULL);
newBox.setPreferredSize(new PrefSize(120,30));
agentTypes.add(newBox);
JTextField newValue = Gui.makeTextField(null, 10,
MaxSize.NULL, MinSize.NULL);
values.add(newValue);
JButton newButton = Gui.makeButton("Delete", null,
new DeleteListener());
newButton.setMinimumSize(new MinSize(80,30));
newButton.setPreferredSize(new PrefSize(80,30));
deleteButtons.add(newButton);
newButton.setActionCommand(deleteButtons.indexOf(newButton) + "");
JPanel newPanel = new JPanel();
newPanel.setPreferredSize(new PrefSize(250,30));
newPanel.add(newBox);
newPanel.add(newValue);
newPanel.add(newButton);
subPanels.add(newPanel);
conListPanel.add(newPanel);
validate();
}
private void reset() {
nameField.setText("");
conListPanel.removeAll();
agentTypes.clear();
values.clear();
deleteButtons.clear();
subPanels.clear();
}
private class DeleteListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int n = Integer.parseInt(e.getActionCommand());
String str = (String) agentTypes.get(n).getSelectedItem();
if (str != null)
getGuiManager().removePopLimit(str);
conListPanel.remove(subPanels.get(n));
agentTypes.remove(n);
values.remove(n);
deleteButtons.remove(n);
for (int i = n; i < deleteButtons.size(); i++)
deleteButtons.get(i).setActionCommand(
(Integer.parseInt(deleteButtons.get(i)
.getActionCommand()) - 1) + "");
subPanels.remove(n);
validate();
repaint();
}
}
}
| false | true | public SetupScreen(final SimulatorFacade gm) {
super(gm);
this.setLayout(new GridBagLayout());
this.setMinimumSize(new MinSize(410,400));
this.setPreferredSize(new PrefSize(410,400));
agentNames = new String[0];
agentTypes = new ArrayList<JComboBox>();
deleteButtons = new ArrayList<JButton>();
subPanels = new ArrayList<JPanel>();
agentTypes = new ArrayList<JComboBox>();
values = new ArrayList<JTextField>();
JLabel nameLabel = Gui.makeLabel("Name:",
new MinSize(50,30));
nameField = Gui.makeTextField(gm.getSimName(), 20,
null, new MinSize(75,30));
JLabel widthLabel = Gui.makeLabel("Width:",
new MinSize(50,30));
widthField = Gui.makeTextField("10", 5, MaxSize.NULL,
new MinSize(50,30));
JLabel yLabel = Gui.makeLabel("Height:",
new MinSize(60,30));
heightField = Gui.makeTextField("10", 5, MaxSize.NULL,
new MinSize(50,30));
JLabel updateLabel = Gui.makeLabel("Update type:", MaxSize.NULL, null);
updateBox = Gui.makeComboBox(new String[] { "Linear", "Atomic",
"Priority" }, MaxSize.NULL);
updateBox.setMinimumSize(new MinSize(250,30));
updateBox.setPreferredSize(new PrefSize(250,30));
//TODO working on adding step delay components
JLabel delayLabel = Gui.makeLabel("Step delay (ms):", MaxSize.NULL, null);
delayField = Gui.makeTextField("1.0", 20, MaxSize.NULL,
new MinSize(100,30));
JLabel timeLabel = Gui.makeLabel("Max steps:", MaxSize.NULL,
null);
timeField = Gui.makeTextField(null, 20, MaxSize.NULL,
new MinSize(60,30));
JLabel agentTypeLabel = Gui.makeLabel("Agent Type", MaxSize.NULL, null);
JLabel valueLabel = Gui.makeLabel("Population Limit", MaxSize.NULL, null);
conListPanel = makeConditionListPanel();
conListPanel.setMinimumSize(new MinSize(250,300));
conListPanel.setPreferredSize(new PrefSize(250,300));
scrollPane = new JScrollPane(conListPanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setMinimumSize(new MinSize(400,300));
scrollPane.setPreferredSize(new PrefSize(400,300));
JPanel scrollPaneWrapper = Gui.makePanel((BoxLayoutAxis)null,MaxSize.NULL,null,(Component[])null);
scrollPaneWrapper.add(scrollPane);
addConditionButton = Gui.makeButton("Add Field", null,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addCondition();
}
});
JPanel bottomButtons = Gui.makePanel(
Gui.makeButton("Revert", null, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
load();
}
}), makeConfirmButton(),addConditionButton);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 3);
this.add(nameLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 3;
c.insets = new Insets(0, 0, 0, 3);
this.add(nameField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 3);
this.add(widthLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0, -4, 0, 3);
this.add(widthField, c);
c = new GridBagConstraints();
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 3);
this.add(yLabel, c);
c = new GridBagConstraints();
c.gridx = 3;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 3);
this.add(heightField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(0, 0, 0, 3);
this.add(delayLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
c.insets = new Insets(0, 0, 0, 3);
c.gridwidth = 3;
this.add(delayField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 3;
c.insets = new Insets(0, 0, 0, 3);
this.add(updateLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 3;
c.insets = new Insets(0, 0, 0, 3);
c.gridwidth = 3;
this.add(updateBox, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 4;
c.insets = new Insets(0,0, 0, 3);
this.add(timeLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 4;
c.insets = new Insets(0, 0, 0, 3);
c.gridwidth = 3;
this.add(timeField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 5;
c.insets = new Insets(10, 0, 0, 0);
this.add(agentTypeLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 5;
c.insets = new Insets(10, 0, 0, 3);
this.add(valueLabel, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 6;
c.gridwidth = 4;
c.insets = new Insets(2,0, 0, 0);
c.fill = c.HORIZONTAL;
this.add(scrollPaneWrapper,c);
c = new GridBagConstraints();
c.gridy = 8;
c.insets = new Insets(0,0,0,0);
c.gridwidth = 4;
c.fill = c.HORIZONTAL;
this.add(Gui.makePanel(bottomButtons),c);
validate();
}
| public SetupScreen(final SimulatorFacade gm) {
super(gm);
this.setLayout(new GridBagLayout());
this.setMinimumSize(new MinSize(410,400));
this.setPreferredSize(new PrefSize(410,400));
agentNames = new String[0];
agentTypes = new ArrayList<JComboBox>();
deleteButtons = new ArrayList<JButton>();
subPanels = new ArrayList<JPanel>();
agentTypes = new ArrayList<JComboBox>();
values = new ArrayList<JTextField>();
JLabel nameLabel = Gui.makeLabel("Name:",
new MinSize(50,30));
nameField = Gui.makeTextField(gm.getSimName(), 20,
null, new MinSize(75,30));
JLabel widthLabel = Gui.makeLabel("Width:",
new MinSize(50,30));
widthField = Gui.makeTextField("10", 5, MaxSize.NULL,
new MinSize(50,30));
JLabel yLabel = Gui.makeLabel("Height:",
new MinSize(60,30));
heightField = Gui.makeTextField("10", 5, MaxSize.NULL,
new MinSize(50,30));
JLabel updateLabel = Gui.makeLabel("Update type:", MaxSize.NULL, null);
updateBox = Gui.makeComboBox(new String[] { "Linear", "Atomic",
"Priority" }, MaxSize.NULL);
updateBox.setMinimumSize(new MinSize(250,30));
updateBox.setPreferredSize(new PrefSize(250,30));
//TODO working on adding step delay components
JLabel delayLabel = Gui.makeLabel("Step delay (ms):", MaxSize.NULL, null);
delayField = Gui.makeTextField("1.0", 20, MaxSize.NULL,
new MinSize(100,30));
JLabel timeLabel = Gui.makeLabel("Max steps:", MaxSize.NULL,
null);
timeField = Gui.makeTextField(null, 20, MaxSize.NULL,
new MinSize(60,30));
JLabel agentTypeLabel = Gui.makeLabel("Agent Type", MaxSize.NULL, null);
JLabel valueLabel = Gui.makeLabel("Population Limit", MaxSize.NULL, null);
conListPanel = makeConditionListPanel();
conListPanel.setMinimumSize(new MinSize(250,300));
conListPanel.setPreferredSize(new PrefSize(250,300));
scrollPane = new JScrollPane(conListPanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setMinimumSize(new MinSize(400,300));
scrollPane.setPreferredSize(new PrefSize(400,300));
JPanel scrollPaneWrapper = Gui.makePanel((BoxLayoutAxis)null,MaxSize.NULL,null,(Component[])null);
scrollPaneWrapper.add(scrollPane);
addConditionButton = Gui.makeButton("Add Field", null,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addCondition();
}
});
JPanel bottomButtons = Gui.makePanel(
Gui.makeButton("Revert", null, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
load();
}
}), makeConfirmButton(),addConditionButton);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 3);
this.add(nameLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 3;
c.insets = new Insets(0, 0, 0, 3);
this.add(nameField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 3);
this.add(widthLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0, -53, 0, 3);
this.add(widthField, c);
c = new GridBagConstraints();
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0, -45, 0, 3);
this.add(yLabel, c);
c = new GridBagConstraints();
c.gridx = 3;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 3);
this.add(heightField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(0, 0, 0, 3);
this.add(delayLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
c.insets = new Insets(0, 0, 0, 3);
c.gridwidth = 3;
this.add(delayField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 3;
c.insets = new Insets(0, 0, 0, 3);
this.add(updateLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 3;
c.insets = new Insets(0, 0, 0, 3);
c.gridwidth = 3;
this.add(updateBox, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 4;
c.insets = new Insets(0,0, 0, 3);
this.add(timeLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 4;
c.insets = new Insets(0, 0, 0, 3);
c.gridwidth = 3;
this.add(timeField, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 5;
c.insets = new Insets(10, 30, 0, 0);
this.add(agentTypeLabel, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 5;
c.insets = new Insets(10, 50, 0, 0);
this.add(valueLabel, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 6;
c.gridwidth = 4;
c.insets = new Insets(2,0, 0, 0);
c.fill = c.HORIZONTAL;
this.add(scrollPaneWrapper,c);
c = new GridBagConstraints();
c.gridy = 8;
c.insets = new Insets(0,0,0,0);
c.gridwidth = 4;
c.fill = c.HORIZONTAL;
this.add(Gui.makePanel(bottomButtons),c);
validate();
}
|
diff --git a/luni/src/main/java/java/util/prefs/XMLParser.java b/luni/src/main/java/java/util/prefs/XMLParser.java
index d12169eb7..b63784c3e 100644
--- a/luni/src/main/java/java/util/prefs/XMLParser.java
+++ b/luni/src/main/java/java/util/prefs/XMLParser.java
@@ -1,506 +1,505 @@
/* 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 java.util.prefs;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import libcore.io.IoUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Utility class for the Preferences import/export from XML file.
*/
class XMLParser {
/*
* Constant - the specified DTD URL
*/
static final String PREFS_DTD_NAME = "http://java.sun.com/dtd/preferences.dtd";
/*
* Constant - the DTD string
*/
static final String PREFS_DTD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ " <!ELEMENT preferences (root)>"
+ " <!ATTLIST preferences EXTERNAL_XML_VERSION CDATA \"0.0\" >"
+ " <!ELEMENT root (map, node*) >"
+ " <!ATTLIST root type (system|user) #REQUIRED >"
+ " <!ELEMENT node (map, node*) >"
+ " <!ATTLIST node name CDATA #REQUIRED >"
+ " <!ELEMENT map (entry*) >"
+ " <!ELEMENT entry EMPTY >"
+ " <!ATTLIST entry key CDATA #REQUIRED value CDATA #REQUIRED >";
/*
* Constant - the specified header
*/
static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
/*
* Constant - the specified DOCTYPE
*/
static final String DOCTYPE = "<!DOCTYPE preferences SYSTEM";
/*
* Constant - used by FilePreferencesImpl, which is default implementation of Linux platform
*/
private static final String FILE_PREFS = "<!DOCTYPE map SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>";
/*
* Constant - specify the DTD version
*/
private static final float XML_VERSION = 1.0f;
/*
* DOM builder
*/
private static final DocumentBuilder builder;
/*
* specify the indent level
*/
private static int indent = -1;
/*
* init DOM builder
*/
static {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new Error(e);
}
builder.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
if (systemId.equals(PREFS_DTD_NAME)) {
InputSource result = new InputSource(new StringReader(
PREFS_DTD));
result.setSystemId(PREFS_DTD_NAME);
return result;
}
throw new SAXException("Invalid DOCTYPE declaration " + systemId);
}
});
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException e) throws SAXException {
throw e;
}
public void error(SAXParseException e) throws SAXException {
throw e;
}
public void fatalError(SAXParseException e) throws SAXException {
throw e;
}
});
}
private XMLParser() {// empty constructor
}
/***************************************************************************
* utilities for Preferences export
**************************************************************************/
static void exportPrefs(Preferences prefs, OutputStream stream,
boolean withSubTree) throws IOException, BackingStoreException {
indent = -1;
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"));
out.write(HEADER);
out.newLine();
out.newLine();
out.write(DOCTYPE);
out.write(" '");
out.write(PREFS_DTD_NAME);
out.write("'>");
out.newLine();
out.newLine();
flushStartTag("preferences", new String[] { "EXTERNAL_XML_VERSION" },
new String[] { String.valueOf(XML_VERSION) }, out);
flushStartTag("root", new String[] { "type" },
new String[] { prefs.isUserNode() ? "user" : "system" }, out);
flushEmptyElement("map", out);
StringTokenizer ancestors = new StringTokenizer(prefs.absolutePath(), "/");
exportNode(ancestors, prefs, withSubTree, out);
flushEndTag("root", out);
flushEndTag("preferences", out);
out.flush();
out = null;
}
private static void exportNode(StringTokenizer ancestors,
Preferences prefs, boolean withSubTree, BufferedWriter out)
throws IOException, BackingStoreException {
if (ancestors.hasMoreTokens()) {
String name = ancestors.nextToken();
flushStartTag("node", new String[] { "name" }, new String[] { name }, out);
if (ancestors.hasMoreTokens()) {
flushEmptyElement("map", out);
exportNode(ancestors, prefs, withSubTree, out);
} else {
exportEntries(prefs, out);
if (withSubTree) {
exportSubTree(prefs, out);
}
}
flushEndTag("node", out);
}
}
private static void exportSubTree(Preferences prefs, BufferedWriter out)
throws BackingStoreException, IOException {
String[] names = prefs.childrenNames();
if (names.length > 0) {
for (int i = 0; i < names.length; i++) {
Preferences child = prefs.node(names[i]);
flushStartTag("node", new String[] { "name" }, new String[] { names[i] }, out);
exportEntries(child, out);
exportSubTree(child, out);
flushEndTag("node", out);
}
}
}
private static void exportEntries(Preferences prefs, BufferedWriter out)
throws BackingStoreException, IOException {
String[] keys = prefs.keys();
String[] values = new String[keys.length];
for (int i = 0; i < keys.length; i++) {
values[i] = prefs.get(keys[i], null);
}
exportEntries(keys, values, out);
}
private static void exportEntries(String[] keys, String[] values,
BufferedWriter out) throws IOException {
if (keys.length == 0) {
flushEmptyElement("map", out);
return;
}
flushStartTag("map", out);
for (int i = 0; i < keys.length; i++) {
if (values[i] != null) {
flushEmptyElement("entry", new String[] { "key", "value" },
new String[] { keys[i], values[i] }, out);
}
}
flushEndTag("map", out);
}
private static void flushEndTag(String tagName, BufferedWriter out)
throws IOException {
flushIndent(indent--, out);
out.write("</");
out.write(tagName);
out.write(">");
out.newLine();
}
private static void flushEmptyElement(String tagName, BufferedWriter out)
throws IOException {
flushIndent(++indent, out);
out.write("<");
out.write(tagName);
out.write(" />");
out.newLine();
indent--;
}
private static void flushEmptyElement(String tagName, String[] attrKeys,
String[] attrValues, BufferedWriter out) throws IOException {
flushIndent(++indent, out);
out.write("<");
out.write(tagName);
flushPairs(attrKeys, attrValues, out);
out.write(" />");
out.newLine();
indent--;
}
private static void flushPairs(String[] attrKeys, String[] attrValues,
BufferedWriter out) throws IOException {
for (int i = 0; i < attrKeys.length; i++) {
out.write(" ");
out.write(attrKeys[i]);
out.write("=\"");
out.write(htmlEncode(attrValues[i]));
out.write("\"");
}
}
private static void flushIndent(int ind, BufferedWriter out)
throws IOException {
for (int i = 0; i < ind; i++) {
out.write(" ");
}
}
private static void flushStartTag(String tagName, String[] attrKeys,
String[] attrValues, BufferedWriter out) throws IOException {
flushIndent(++indent, out);
out.write("<");
out.write(tagName);
flushPairs(attrKeys, attrValues, out);
out.write(">");
out.newLine();
}
private static void flushStartTag(String tagName, BufferedWriter out)
throws IOException {
flushIndent(++indent, out);
out.write("<");
out.write(tagName);
out.write(">");
out.newLine();
}
private static String htmlEncode(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '&':
sb.append("&");
break;
case '"':
sb.append(""");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/***************************************************************************
* utilities for Preferences import
**************************************************************************/
static void importPrefs(InputStream in) throws IOException, InvalidPreferencesFormatException {
try {
// load XML document
Document doc = builder.parse(new InputSource(in));
// check preferences' export version
Element preferences;
preferences = doc.getDocumentElement();
String version = preferences.getAttribute("EXTERNAL_XML_VERSION");
if (version != null && Float.parseFloat(version) > XML_VERSION) {
throw new InvalidPreferencesFormatException("Preferences version " + version +
" is not supported");
}
// check preferences root's type
Element root = (Element) preferences
.getElementsByTagName("root").item(0);
Preferences prefsRoot = null;
String type = root.getAttribute("type");
if (type.equals("user")) {
prefsRoot = Preferences.userRoot();
} else {
prefsRoot = Preferences.systemRoot();
}
// load node
loadNode(prefsRoot, root);
} catch (FactoryConfigurationError e) {
throw new InvalidPreferencesFormatException(e);
} catch (SAXException e) {
throw new InvalidPreferencesFormatException(e);
}
}
private static void loadNode(Preferences prefs, Element node) {
// load preferences
NodeList children = selectNodeList(node, "node");
NodeList entries = selectNodeList(node, "map/entry");
int childNumber = children.getLength();
Preferences[] prefChildren = new Preferences[childNumber];
int entryNumber = entries.getLength();
synchronized (((AbstractPreferences) prefs).lock) {
if (((AbstractPreferences) prefs).isRemoved()) {
return;
}
for (int i = 0; i < entryNumber; i++) {
Element entry = (Element) entries.item(i);
String key = entry.getAttribute("key");
String value = entry.getAttribute("value");
prefs.put(key, value);
}
// get children preferences node
for (int i = 0; i < childNumber; i++) {
Element child = (Element) children.item(i);
String name = child.getAttribute("name");
prefChildren[i] = prefs.node(name);
}
}
// load children nodes after unlock
for (int i = 0; i < childNumber; i++) {
loadNode(prefChildren[i], (Element) children.item(i));
}
}
// TODO dirty implementation of a method from javax.xml.xpath
// should be replaced with a call to a good impl of this method
private static NodeList selectNodeList(Element documentElement, String string) {
NodeList result = null;
ArrayList<Node> input = new ArrayList<Node>();
String[] path = string.split("/");
NodeList childNodes = documentElement.getChildNodes();
if(path[0].equals("entry") || path[0].equals("node")) {
for(int i = 0; i < childNodes.getLength(); i++) {
Object next = childNodes.item(i);
if(next instanceof Element) {
- if(((Element) next).getNodeName().equals(path[0])
- && next instanceof Node) {
+ if(((Element) next).getNodeName().equals(path[0])) {
input.add((Node)next);
}
}
}
} else if(path[0].equals("map") && path[1].equals("entry")) {
for(int i = 0; i < childNodes.getLength(); i++) {
Object next = childNodes.item(i);
if(next instanceof Element) {
if(((Element) next).getNodeName().equals(path[0])
&& next instanceof Node) {
NodeList nextChildNodes = ((Node)next).getChildNodes();
for(int j = 0; j < nextChildNodes.getLength(); j++) {
Object subnext = nextChildNodes.item(j);
if(subnext instanceof Element) {
if(((Element)subnext).getNodeName().equals(path[1])) {
input.add((Node)subnext);
}
}
}
}
}
}
}
result = new NodeSet(input.iterator());
return result;
}
/**
* Returns the preferences from {@code xmlFile}. Returns empty properties if
* any errors occur.
*/
static Properties readXmlPreferences(File xmlFile) {
Properties result = new Properties();
if (!xmlFile.exists()) {
xmlFile.getParentFile().mkdirs();
} else if (xmlFile.canRead()) {
Reader reader = null;
try {
reader = new InputStreamReader(new FileInputStream(xmlFile), "UTF-8");
Document document = builder.parse(new InputSource(reader));
NodeList entries = selectNodeList(document.getDocumentElement(), "entry");
int length = entries.getLength();
for (int i = 0; i < length; i++) {
Element node = (Element) entries.item(i);
String key = node.getAttribute("key");
String value = node.getAttribute("value");
result.setProperty(key, value);
}
} catch (IOException ignored) {
} catch (SAXException ignored) {
} finally {
IoUtils.closeQuietly(reader);
}
} else {
// the prefs API requires this to be hostile towards pre-existing files
xmlFile.delete();
}
return result;
}
/**
* Writes the preferences to {@code xmlFile}.
*/
static void writeXmlPreferences(File xmlFile, Properties properties) throws IOException {
File parent = xmlFile.getParentFile();
File temporaryForWriting = new File(parent, "prefs-" + UUID.randomUUID() + ".xml.tmp");
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(temporaryForWriting), "UTF-8"));
out.write(HEADER);
out.newLine();
out.write(FILE_PREFS);
out.newLine();
String[] keys = properties.keySet().toArray(new String[properties.size()]);
int length = keys.length;
String[] values = new String[length];
for (int i = 0; i < length; i++) {
values[i] = properties.getProperty(keys[i]);
}
exportEntries(keys, values, out);
out.close();
if (!temporaryForWriting.renameTo(xmlFile)) {
throw new IOException("Failed to write preferences to " + xmlFile);
}
} finally {
IoUtils.closeQuietly(out);
temporaryForWriting.delete(); // no-op unless something failed
}
}
}
| true | true | private static NodeList selectNodeList(Element documentElement, String string) {
NodeList result = null;
ArrayList<Node> input = new ArrayList<Node>();
String[] path = string.split("/");
NodeList childNodes = documentElement.getChildNodes();
if(path[0].equals("entry") || path[0].equals("node")) {
for(int i = 0; i < childNodes.getLength(); i++) {
Object next = childNodes.item(i);
if(next instanceof Element) {
if(((Element) next).getNodeName().equals(path[0])
&& next instanceof Node) {
input.add((Node)next);
}
}
}
} else if(path[0].equals("map") && path[1].equals("entry")) {
for(int i = 0; i < childNodes.getLength(); i++) {
Object next = childNodes.item(i);
if(next instanceof Element) {
if(((Element) next).getNodeName().equals(path[0])
&& next instanceof Node) {
NodeList nextChildNodes = ((Node)next).getChildNodes();
for(int j = 0; j < nextChildNodes.getLength(); j++) {
Object subnext = nextChildNodes.item(j);
if(subnext instanceof Element) {
if(((Element)subnext).getNodeName().equals(path[1])) {
input.add((Node)subnext);
}
}
}
}
}
}
}
result = new NodeSet(input.iterator());
return result;
}
| private static NodeList selectNodeList(Element documentElement, String string) {
NodeList result = null;
ArrayList<Node> input = new ArrayList<Node>();
String[] path = string.split("/");
NodeList childNodes = documentElement.getChildNodes();
if(path[0].equals("entry") || path[0].equals("node")) {
for(int i = 0; i < childNodes.getLength(); i++) {
Object next = childNodes.item(i);
if(next instanceof Element) {
if(((Element) next).getNodeName().equals(path[0])) {
input.add((Node)next);
}
}
}
} else if(path[0].equals("map") && path[1].equals("entry")) {
for(int i = 0; i < childNodes.getLength(); i++) {
Object next = childNodes.item(i);
if(next instanceof Element) {
if(((Element) next).getNodeName().equals(path[0])
&& next instanceof Node) {
NodeList nextChildNodes = ((Node)next).getChildNodes();
for(int j = 0; j < nextChildNodes.getLength(); j++) {
Object subnext = nextChildNodes.item(j);
if(subnext instanceof Element) {
if(((Element)subnext).getNodeName().equals(path[1])) {
input.add((Node)subnext);
}
}
}
}
}
}
}
result = new NodeSet(input.iterator());
return result;
}
|
diff --git a/WithinReach/src/org/leifolson/withinreach/ServerComMgr.java b/WithinReach/src/org/leifolson/withinreach/ServerComMgr.java
index 820f215..84c2bc4 100644
--- a/WithinReach/src/org/leifolson/withinreach/ServerComMgr.java
+++ b/WithinReach/src/org/leifolson/withinreach/ServerComMgr.java
@@ -1,91 +1,91 @@
package org.leifolson.withinreach;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class ServerComMgr extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... params)
{
//params[0] should be the url of the json file. I used:
// "http://withinreach.herokuapp.com/arrival/6309" as url for this test
//to call this function in main thread:
- // new ServerCommunication().execute(url);
+ // new ServerComMgr().execute(url);
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
String result;
try //getting the http response and building a string out of it
{
response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
result = stringBuilder.toString();
try //building the JSON object and grabbing the ETA of a bus
{
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONObject("resultSet").getJSONArray("arrival");
JSONObject jsonObj = jsonArray.getJSONObject(0);
String output = jsonObj.getString("estimated");
System.out.println("ETA: " + output);
}
catch (JSONException e)
{
System.out.println(e.getMessage());
}
return null;
}
}
| true | true | protected String doInBackground(String... params)
{
//params[0] should be the url of the json file. I used:
// "http://withinreach.herokuapp.com/arrival/6309" as url for this test
//to call this function in main thread:
// new ServerCommunication().execute(url);
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
String result;
try //getting the http response and building a string out of it
{
response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
result = stringBuilder.toString();
try //building the JSON object and grabbing the ETA of a bus
{
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONObject("resultSet").getJSONArray("arrival");
JSONObject jsonObj = jsonArray.getJSONObject(0);
String output = jsonObj.getString("estimated");
System.out.println("ETA: " + output);
}
catch (JSONException e)
{
System.out.println(e.getMessage());
}
return null;
}
| protected String doInBackground(String... params)
{
//params[0] should be the url of the json file. I used:
// "http://withinreach.herokuapp.com/arrival/6309" as url for this test
//to call this function in main thread:
// new ServerComMgr().execute(url);
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
String result;
try //getting the http response and building a string out of it
{
response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
result = stringBuilder.toString();
try //building the JSON object and grabbing the ETA of a bus
{
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONObject("resultSet").getJSONArray("arrival");
JSONObject jsonObj = jsonArray.getJSONObject(0);
String output = jsonObj.getString("estimated");
System.out.println("ETA: " + output);
}
catch (JSONException e)
{
System.out.println(e.getMessage());
}
return null;
}
|
diff --git a/src/com/android/email/MessagingController.java b/src/com/android/email/MessagingController.java
index c04280f2..3ac6f7c9 100644
--- a/src/com/android/email/MessagingController.java
+++ b/src/com/android/email/MessagingController.java
@@ -1,2073 +1,2078 @@
/*
* 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.MessageRetrievalListener;
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.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.File;
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 Flag[] FLAG_LIST_SEEN = new Flag[] { Flag.SEEN };
private static 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 String[] PRUNE_ATTACHMENT_PROJECTION = new String[] {
AttachmentColumns.LOCATION
};
private static ContentValues PRUNE_ATTACHMENT_CV = new ContentValues();
static {
PRUNE_ATTACHMENT_CV.putNull(AttachmentColumns.CONTENT_URI);
}
private static MessagingController inst = null;
private BlockingQueue<Command> mCommands = new LinkedBlockingQueue<Command>();
private Thread mThread;
/**
* All access to mListeners *must* be synchronized
*/
private GroupMessagingListener mListeners = new GroupMessagingListener();
private boolean mBusy;
private Context mContext;
protected MessagingController(Context _context) {
mContext = _context;
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.
* @param application
* @return
*/
public synchronized static MessagingController getInstance(Context _context) {
if (inst == null) {
inst = new MessagingController(_context);
}
return inst;
}
/**
* Inject a mock controller. Used only for testing. Affects future calls to getInstance().
*/
public static void injectMockController(MessagingController mockController) {
inst = 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,
};
long mId;
String mDisplayName;
long mAccountKey;
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
};
int mCursorIndex;
long mId;
boolean mFlagRead;
boolean mFlagFavorite;
int mFlagLoaded;
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) {
if (content.isSaved()) {
content.update(mContext, content.toContentValues());
} else {
content.save(mContext);
}
}
/**
* 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 messageFinished(Message message, int number, int ofTotal) {
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);
// 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());
}
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
}
// 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 messageFinished(Message message, int number, int ofTotal) {
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
// 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 provider message
*
* @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)
*/
private void copyOneMessageToProvider(Message message, EmailContent.Account account,
EmailContent.Mailbox folder, int loadStatus) {
try {
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);
}
} finally {
if (c != null) {
c.close();
}
}
if (localMessage == null) {
Log.d(Email.LOG_TAG, "Could not retrieve message from db, UUID="
+ message.getUid());
return;
}
EmailContent.Body body = EmailContent.Body.restoreBodyWithMessageId(mContext,
localMessage.mId);
if (body == null) {
body = new EmailContent.Body();
}
try {
// Copy the fields that are available into the message object
LegacyConversions.updateMessageFields(localMessage, message, account.mId,
folder.mId);
// 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);
saveOrUpdate(body);
// process (and save) attachments
LegacyConversions.updateAttachments(mContext, 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);
mContext.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);
lastMessageId = oldMessage.mId;
if (oldMessage != null) {
if (mailbox == null || mailbox.mId != oldMessage.mMailboxKey) {
mailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
}
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);
}
// 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);
}
// 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;
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);
}
changeMoveToTrash = (oldMessage.mMailboxKey != newMessage.mMailboxKey)
&& (mailbox.mType == Mailbox.TYPE_TRASH);
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)) {
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) {
processPendingFlagChange(remoteStore, mailbox, changeRead, changeFlagged,
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 or flagged
*
* @param remoteStore
* @param mailbox
* @param changeRead
* @param changeFlagged
* @param newMessage
*/
private void processPendingFlagChange(Store remoteStore, Mailbox mailbox, boolean changeRead,
boolean changeFlagged, EmailContent.Message newMessage) throws MessagingException {
// 0. No remote update if the message is local-only
if (newMessage.mServerId == null || newMessage.mServerId.equals("")
|| newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) {
return;
}
// 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 flags for msg id=" + newMessage.mId
+ " read=" + newMessage.mFlagRead
+ " flagged=" + newMessage.mFlagFavorite);
}
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);
}
}
/**
* 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.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
File saveToFile = AttachmentProvider.getAttachmentFilename(mContext, accountId,
attachmentId);
Attachment attachment =
Attachment.restoreAttachmentWithId(mContext, attachmentId);
if (attachment == null) {
mListeners.loadAttachmentFailed(accountId, messageId, attachmentId,
"Attachment is null");
return;
}
if (saveToFile.exists() && attachment.mContentUri != null) {
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,
"Account, mailbox, message or attachment are null");
return;
}
// Pruning. Policy is to have one downloaded attachment at a time,
// per account, to reduce disk storage pressure.
pruneCachedAttachments(accountId);
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, null);
// 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.getMessage());
} catch (IOException ioe) {
Log.e(Email.LOG_TAG, "Error while storing attachment." + ioe.toString());
}
}});
}
/**
* Erase all stored attachments for a given account. Rules:
* 1. All files in attachment directory are up for deletion
* 2. If filename does not match an known attachment id, it's deleted
* 3. If the attachment has location data (implying that it's reloadable), it's deleted
*/
/* package */ void pruneCachedAttachments(long accountId) {
ContentResolver resolver = mContext.getContentResolver();
File cacheDir = AttachmentProvider.getAttachmentDirectory(mContext, accountId);
File[] fileList = cacheDir.listFiles();
// fileList can be null if the directory doesn't exist or if there's an IOException
if (fileList == null) return;
for (File file : fileList) {
if (file.exists()) {
long id;
try {
// the name of the file == the attachment id
id = Long.valueOf(file.getName());
Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, id);
Cursor c = resolver.query(uri, PRUNE_ATTACHMENT_PROJECTION, null, null, null);
try {
if (c.moveToNext()) {
// if there is no way to reload the attachment, don't delete it
if (c.getString(0) == null) {
continue;
}
}
} finally {
c.close();
}
// Clear the content URI field since we're losing the attachment
resolver.update(uri, PRUNE_ATTACHMENT_CV, null, null);
} catch (NumberFormatException nfe) {
// ignore filename != number error, and just delete it anyway
}
// This file can be safely deleted
if (!file.delete()) {
file.deleteOnExit();
}
}
}
}
/**
* 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);
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) {
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 one or multiple accounts. If account is null all accounts
* are checked. 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 context
* @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 messageFinished(Message message, int number, int ofTotal) {
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);
// 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());
}
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
}
// 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 messageFinished(Message message, int number, int ofTotal) {
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
// 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 messageFinished(Message message, int number, int ofTotal) {
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);
// 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());
}
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
}
// 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 messageFinished(Message message, int number, int ofTotal) {
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
// 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/src/java/fedora/server/utilities/SQLUtility.java b/src/java/fedora/server/utilities/SQLUtility.java
index cf4530285..b29ec30e5 100755
--- a/src/java/fedora/server/utilities/SQLUtility.java
+++ b/src/java/fedora/server/utilities/SQLUtility.java
@@ -1,438 +1,439 @@
package fedora.server.utilities;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import fedora.server.config.DatastoreConfiguration;
import fedora.server.config.ModuleConfiguration;
import fedora.server.config.ServerConfiguration;
import fedora.server.errors.InconsistentTableSpecException;
import fedora.server.storage.ConnectionPool;
/**
* SQL-related utility methods.
*
* @author [email protected]
* @version $Id$
*/
public abstract class SQLUtility {
/** Logger for this class. */
private static final Logger LOG = Logger.getLogger(
SQLUtility.class.getName());
public static ConnectionPool getConnectionPool(ServerConfiguration fcfg) throws SQLException {
ModuleConfiguration mcfg = fcfg.getModuleConfiguration("fedora.server.storage.ConnectionPoolManager");
String defaultPool = mcfg.getParameter("defaultPoolName").getValue();
DatastoreConfiguration dcfg = fcfg.getDatastoreConfiguration(defaultPool);
return getConnectionPool(dcfg);
}
public static ConnectionPool getConnectionPool(DatastoreConfiguration cpDC) throws SQLException {
String cpUsername = cpDC.getParameter("dbUsername").getValue();
String cpPassword = cpDC.getParameter("dbPassword").getValue();
String cpURL = cpDC.getParameter("jdbcURL").getValue();
String cpDriver = cpDC.getParameter("jdbcDriverClass").getValue();
String cpDDLConverter = cpDC.getParameter("ddlConverter").getValue();
int cpMaxActive = Integer.parseInt(cpDC.getParameter("maxActive").getValue());
int cpMaxIdle = Integer.parseInt(cpDC.getParameter("maxIdle").getValue());
long cpMaxWait = Long.parseLong(cpDC.getParameter("maxWait").getValue());
int cpMinIdle = Integer.parseInt(cpDC.getParameter("minIdle").getValue());
long cpMinEvictableIdleTimeMillis = Long.parseLong(cpDC.getParameter("minEvictableIdleTimeMillis").getValue());
int cpNumTestsPerEvictionRun = Integer.parseInt(cpDC.getParameter("numTestsPerEvictionRun").getValue());
long cpTimeBetweenEvictionRunsMillis = Long.parseLong(cpDC.getParameter("timeBetweenEvictionRunsMillis").getValue());
boolean cpTestOnBorrow = Boolean.parseBoolean(cpDC.getParameter("testOnBorrow").getValue());
boolean cpTestOnReturn = Boolean.parseBoolean(cpDC.getParameter("testOnReturn").getValue());
boolean cpTestWhileIdle = Boolean.parseBoolean(cpDC.getParameter("testWhileIdle").getValue());
byte cpWhenExhaustedAction = Byte.parseByte(cpDC.getParameter("whenExhaustedAction").getValue());
DDLConverter ddlConverter = null;
if (cpDDLConverter != null) {
try {
ddlConverter=(DDLConverter) Class.forName(cpDDLConverter).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return new ConnectionPool(cpDriver, cpURL, cpUsername,
cpPassword, ddlConverter, cpMaxActive, cpMaxIdle,
cpMaxWait, cpMinIdle, cpMinEvictableIdleTimeMillis,
cpNumTestsPerEvictionRun, cpTimeBetweenEvictionRunsMillis,
cpTestOnBorrow, cpTestOnReturn, cpTestWhileIdle,
cpWhenExhaustedAction);
}
public static void replaceInto(Connection conn, String tableName,
String[] columns, String[] values, String uniqueColumn)
throws SQLException {
replaceInto(conn, tableName, columns, values, uniqueColumn, null);
}
/**
* Adds or replaces a row in the given table.
*
* @param conn the connection to use
* @param table the name of the table
* @param columns the names of the columns whose values we're setting.
* @param values associated values
* @param uniqueColumn which column name is unique? The value of this
* column will be used in the where clause. It must be
* a column which is not numeric.
* @param numeric for each associated column, is it numeric?
* if null, all columns are assumed to be strings.
*/
public static void replaceInto(Connection conn, String table,
String[] columns, String[] values, String uniqueColumn,
boolean[] numeric)
throws SQLException {
if (!updateRow(conn, table, columns, values, uniqueColumn, numeric)) {
addRow(conn, table, columns, values, numeric);
}
}
/**
* Updates an existing row.
*
* @return false if the row did not previously exist and therefore was
* not updated.
*/
public static boolean updateRow(Connection conn, String table,
String[] columns, String[] values, String uniqueColumn,
boolean[] numeric)
throws SQLException {
// prepare update statement
StringBuffer sql = new StringBuffer();
sql.append("UPDATE " + table + " SET ");
boolean needComma = false;
for (int i = 0; i < columns.length; i++) {
if (!columns[i].equals(uniqueColumn)) {
if (needComma) {
sql.append(", ");
} else {
needComma = true;
}
sql.append(columns[i] + " = ");
if (values[i] == null) {
sql.append("NULL");
} else {
sql.append("?");
}
}
}
sql.append(" WHERE " + uniqueColumn + " = ?");
LOG.debug("About to execute: " + sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
try {
// populate values
int varIndex = 0;
for (int i = 0; i < values.length; i++) {
if (!columns[i].equals(uniqueColumn) && values[i] != null) {
varIndex++;
if (numeric != null && numeric[i]) {
setNumeric(stmt, varIndex, columns[i], values[i]);
} else {
stmt.setString(varIndex, values[i]);
}
}
}
- stmt.setString(columns.length,
+ varIndex++;
+ stmt.setString(varIndex,
getSelector(columns, values, uniqueColumn));
// execute and return true if existing row was updated
return stmt.executeUpdate() > 0;
} finally {
closeStatement(stmt);
}
}
/**
* Adds a new row.
*
* @throws SQLException if the row could not be added.
*/
public static void addRow(Connection conn, String table,
String[] columns, String[] values, boolean[] numeric)
throws SQLException {
// prepare insert statement
StringBuffer sql = new StringBuffer();
sql.append("INSERT INTO " + table + " (");
for (int i = 0; i < columns.length; i++) {
if (i > 0) {
sql.append(", ");
}
sql.append(columns[i]);
}
sql.append(") VALUES (");
for (int i = 0; i < columns.length; i++) {
if (i > 0) {
sql.append(", ");
}
if (values[i] == null) {
sql.append("NULL");
} else {
sql.append("?");
}
}
sql.append(")");
LOG.debug("About to execute: " + sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
try {
// populate values
int varIndex = 0;
for (int i = 0; i < values.length; i++) {
if (values[i] != null) {
varIndex++;
if (numeric != null && numeric[i]) {
setNumeric(stmt, varIndex, columns[i], values[i]);
} else {
stmt.setString(varIndex, values[i]);
}
}
}
// execute
stmt.executeUpdate();
} finally {
closeStatement(stmt);
}
}
/**
* Sets a numeric value in the prepared statement.
*
* Parsing the string is attempted as an int, then
* a long, and if that fails, a SQLException is thrown.
*/
private static void setNumeric(PreparedStatement stmt,
int varIndex, String columnName, String value)
throws SQLException {
try {
stmt.setInt(varIndex, Integer.parseInt(value));
} catch (NumberFormatException e) {
try {
stmt.setLong(varIndex, Long.parseLong(value));
} catch (NumberFormatException e2) {
throw new SQLException("Value specified for "
+ columnName + ", '" + value + "' was"
+ " specified as numeric, but is not");
}
}
}
/**
* Gets the value in the given array whose associated column name
* matches the given uniqueColumn name.
*
* @throws SQLException if the uniqueColumn doesn't exist in the given
* column array.
*/
private static String getSelector(String[] columns, String[] values,
String uniqueColumn)
throws SQLException {
String selector = null;
for (int i = 0; i < columns.length; i++) {
if (columns[i].equals(uniqueColumn)) {
selector = values[i];
}
}
if (selector != null) {
return selector;
} else {
throw new SQLException("Unique column does not exist in given "
+ "column array");
}
}
public static String slashEscaped(String in) {
StringBuffer out = new StringBuffer();
for (int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
if (c == '\\') {
out.append("\\\\"); // slash slash
} else {
out.append(c);
}
}
return out.toString();
}
/**
* Get a long string, which could be a TEXT or CLOB type.
* (CLOBs require special handling -- this method normalizes the reading of them)
*/
public static String getLongString(ResultSet rs, int pos) throws SQLException {
String s = rs.getString(pos);
if (s != null) {
// It's a String-based datatype, so just return it.
return s;
} else {
// It may be a CLOB. If so, return the contents as a String.
try {
Clob c = rs.getClob(pos);
return c.getSubString(1, (int) c.length());
} catch (Throwable th) {
th.printStackTrace();
return null;
}
}
}
public static void createNonExistingTables(ConnectionPool cPool,
InputStream dbSpec)
throws IOException, InconsistentTableSpecException, SQLException {
List nonExisting=null;
Connection conn=null;
try {
conn=cPool.getConnection();
nonExisting=SQLUtility.getNonExistingTables(conn,
TableSpec.getTableSpecs(dbSpec));
} finally {
if (conn!=null) {
cPool.free(conn);
}
}
if (nonExisting.size()>0) {
TableCreatingConnection tcConn=null;
try {
tcConn=cPool.getTableCreatingConnection();
if (tcConn==null) {
throw new SQLException(
"Unable to construct CREATE TABLE "
+ "statement(s) because there is no DDLConverter "
+ "registered for this connection type.");
}
SQLUtility.createTables(tcConn, nonExisting);
} finally {
if (tcConn!=null) {
cPool.free(tcConn);
}
}
}
}
public static List getNonExistingTables(Connection conn,
List tSpecs)
throws SQLException {
ArrayList nonExisting=new ArrayList();
DatabaseMetaData dbMeta=conn.getMetaData();
Iterator tSpecIter=tSpecs.iterator();
ResultSet r = null;
// Get a list of tables that don't exist, if any
try
{
r=dbMeta.getTables(null, null, "%", null);
HashSet existingTableSet=new HashSet();
while (r.next()) {
existingTableSet.add(r.getString("TABLE_NAME").toLowerCase());
}
r.close();
r=null;
while (tSpecIter.hasNext()) {
TableSpec spec=(TableSpec) tSpecIter.next();
if (!existingTableSet.contains(spec.getName().toLowerCase())) {
nonExisting.add(spec);
}
}
} catch (SQLException sqle)
{
throw new SQLException(sqle.getMessage());
} finally
{
try {
if (r != null) r.close();
} catch (SQLException sqle2) {
throw sqle2;
} finally {
r=null;
}
}
return nonExisting;
}
public static void createTables(TableCreatingConnection tcConn, List tSpecs)
throws SQLException {
Iterator nii=tSpecs.iterator();
while (nii.hasNext()) {
TableSpec spec=(TableSpec) nii.next();
if (LOG.isDebugEnabled()) {
StringBuffer sqlCmds=new StringBuffer();
Iterator iter=tcConn.getDDLConverter().getDDL(spec).iterator();
while (iter.hasNext()) {
sqlCmds.append("\n");
sqlCmds.append((String) iter.next());
sqlCmds.append(";");
}
LOG.debug("Attempting to create nonexisting "
+ "table '" + spec.getName() + "' with command(s): "
+ sqlCmds.toString());
}
tcConn.createTable(spec);
}
}
public static String backslashEscape(String in) {
if (in==null) return in;
if (in.indexOf("\\")==-1) return in;
StringBuffer out=new StringBuffer();
for (int i=0; i<in.length(); i++) {
char c=in.charAt(i);
if (c=='\\') {
out.append('\\');
}
out.append(c);
}
return out.toString();
}
public static String aposEscape(String in) {
if (in==null) return in;
if (in.indexOf("'")==-1) return in;
StringBuffer out=new StringBuffer();
for (int i=0; i<in.length(); i++) {
char c=in.charAt(i);
if (c=='\'') {
out.append('\'');
}
out.append(c);
}
return out.toString();
}
public static void closeStatement(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
LOG.warn("Unable to close statement", e);
}
}
}
}
| true | true | public static boolean updateRow(Connection conn, String table,
String[] columns, String[] values, String uniqueColumn,
boolean[] numeric)
throws SQLException {
// prepare update statement
StringBuffer sql = new StringBuffer();
sql.append("UPDATE " + table + " SET ");
boolean needComma = false;
for (int i = 0; i < columns.length; i++) {
if (!columns[i].equals(uniqueColumn)) {
if (needComma) {
sql.append(", ");
} else {
needComma = true;
}
sql.append(columns[i] + " = ");
if (values[i] == null) {
sql.append("NULL");
} else {
sql.append("?");
}
}
}
sql.append(" WHERE " + uniqueColumn + " = ?");
LOG.debug("About to execute: " + sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
try {
// populate values
int varIndex = 0;
for (int i = 0; i < values.length; i++) {
if (!columns[i].equals(uniqueColumn) && values[i] != null) {
varIndex++;
if (numeric != null && numeric[i]) {
setNumeric(stmt, varIndex, columns[i], values[i]);
} else {
stmt.setString(varIndex, values[i]);
}
}
}
stmt.setString(columns.length,
getSelector(columns, values, uniqueColumn));
// execute and return true if existing row was updated
return stmt.executeUpdate() > 0;
} finally {
closeStatement(stmt);
}
}
| public static boolean updateRow(Connection conn, String table,
String[] columns, String[] values, String uniqueColumn,
boolean[] numeric)
throws SQLException {
// prepare update statement
StringBuffer sql = new StringBuffer();
sql.append("UPDATE " + table + " SET ");
boolean needComma = false;
for (int i = 0; i < columns.length; i++) {
if (!columns[i].equals(uniqueColumn)) {
if (needComma) {
sql.append(", ");
} else {
needComma = true;
}
sql.append(columns[i] + " = ");
if (values[i] == null) {
sql.append("NULL");
} else {
sql.append("?");
}
}
}
sql.append(" WHERE " + uniqueColumn + " = ?");
LOG.debug("About to execute: " + sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
try {
// populate values
int varIndex = 0;
for (int i = 0; i < values.length; i++) {
if (!columns[i].equals(uniqueColumn) && values[i] != null) {
varIndex++;
if (numeric != null && numeric[i]) {
setNumeric(stmt, varIndex, columns[i], values[i]);
} else {
stmt.setString(varIndex, values[i]);
}
}
}
varIndex++;
stmt.setString(varIndex,
getSelector(columns, values, uniqueColumn));
// execute and return true if existing row was updated
return stmt.executeUpdate() > 0;
} finally {
closeStatement(stmt);
}
}
|
diff --git a/src/org/geometerplus/zlibrary/text/model/ZLTextPlainModel.java b/src/org/geometerplus/zlibrary/text/model/ZLTextPlainModel.java
index 0628facd..a44833d7 100644
--- a/src/org/geometerplus/zlibrary/text/model/ZLTextPlainModel.java
+++ b/src/org/geometerplus/zlibrary/text/model/ZLTextPlainModel.java
@@ -1,379 +1,385 @@
/*
* Copyright (C) 2007-2012 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.text.model;
import java.util.*;
import org.geometerplus.zlibrary.core.image.ZLImage;
import org.geometerplus.zlibrary.core.util.*;
public class ZLTextPlainModel implements ZLTextModel, ZLTextStyleEntry.Feature {
private final String myId;
private final String myLanguage;
protected int[] myStartEntryIndices;
protected int[] myStartEntryOffsets;
protected int[] myParagraphLengths;
protected int[] myTextSizes;
protected byte[] myParagraphKinds;
protected int myParagraphsNumber;
protected final CharStorage myStorage;
protected final Map<String,ZLImage> myImageMap;
private ArrayList<ZLTextMark> myMarks;
final class EntryIteratorImpl implements ZLTextParagraph.EntryIterator {
private int myCounter;
private int myLength;
private byte myType;
int myDataIndex;
int myDataOffset;
// TextEntry data
private char[] myTextData;
private int myTextOffset;
private int myTextLength;
// ControlEntry data
private byte myControlKind;
private boolean myControlIsStart;
// HyperlinkControlEntry data
private byte myHyperlinkType;
private String myHyperlinkId;
// ImageEntry
private ZLImageEntry myImageEntry;
// StyleEntry
private ZLTextStyleEntry myStyleEntry;
// FixedHSpaceEntry data
private short myFixedHSpaceLength;
EntryIteratorImpl(int index) {
myLength = myParagraphLengths[index];
myDataIndex = myStartEntryIndices[index];
myDataOffset = myStartEntryOffsets[index];
}
void reset(int index) {
myCounter = 0;
myLength = myParagraphLengths[index];
myDataIndex = myStartEntryIndices[index];
myDataOffset = myStartEntryOffsets[index];
}
public byte getType() {
return myType;
}
public char[] getTextData() {
return myTextData;
}
public int getTextOffset() {
return myTextOffset;
}
public int getTextLength() {
return myTextLength;
}
public byte getControlKind() {
return myControlKind;
}
public boolean getControlIsStart() {
return myControlIsStart;
}
public byte getHyperlinkType() {
return myHyperlinkType;
}
public String getHyperlinkId() {
return myHyperlinkId;
}
public ZLImageEntry getImageEntry() {
return myImageEntry;
}
public ZLTextStyleEntry getStyleEntry() {
return myStyleEntry;
}
public short getFixedHSpaceLength() {
return myFixedHSpaceLength;
}
public boolean hasNext() {
return myCounter < myLength;
}
public void next() {
int dataOffset = myDataOffset;
char[] data = myStorage.block(myDataIndex);
if (dataOffset == data.length) {
data = myStorage.block(++myDataIndex);
dataOffset = 0;
}
byte type = (byte)data[dataOffset];
if (type == 0) {
data = myStorage.block(++myDataIndex);
dataOffset = 0;
type = (byte)data[0];
}
myType = type;
++dataOffset;
switch (type) {
case ZLTextParagraph.Entry.TEXT:
- myTextLength =
+ {
+ int textLength =
(int)data[dataOffset++] +
(((int)data[dataOffset++]) << 16);
+ if (textLength > data.length - dataOffset) {
+ textLength = data.length - dataOffset;
+ }
+ myTextLength = textLength;
myTextData = data;
myTextOffset = dataOffset;
- dataOffset += myTextLength;
+ dataOffset += textLength;
break;
+ }
case ZLTextParagraph.Entry.CONTROL:
{
short kind = (short)data[dataOffset++];
myControlKind = (byte)kind;
myControlIsStart = (kind & 0x0100) == 0x0100;
myHyperlinkType = 0;
break;
}
case ZLTextParagraph.Entry.HYPERLINK_CONTROL:
{
short kind = (short)data[dataOffset++];
myControlKind = (byte)kind;
myControlIsStart = true;
myHyperlinkType = (byte)(kind >> 8);
short labelLength = (short)data[dataOffset++];
myHyperlinkId = new String(data, dataOffset, labelLength);
dataOffset += labelLength;
break;
}
case ZLTextParagraph.Entry.IMAGE:
{
final short vOffset = (short)data[dataOffset++];
final short len = (short)data[dataOffset++];
final String id = new String(data, dataOffset, len);
dataOffset += len;
final boolean isCover = data[dataOffset++] != 0;
myImageEntry = new ZLImageEntry(myImageMap, id, vOffset, isCover);
break;
}
case ZLTextParagraph.Entry.FIXED_HSPACE:
myFixedHSpaceLength = (short)data[dataOffset++];
break;
case ZLTextParagraph.Entry.STYLE:
{
final ZLTextStyleEntry entry = new ZLTextStyleEntry();
final short mask = (short)data[dataOffset++];
for (int i = 0; i < NUMBER_OF_LENGTHS; ++i) {
if (ZLTextStyleEntry.isFeatureSupported(mask, i)) {
final short size = (short)data[dataOffset++];
final byte unit = (byte)data[dataOffset++];
entry.setLength(i, size, unit);
}
}
if (ZLTextStyleEntry.isFeatureSupported(mask, ALIGNMENT_TYPE)) {
final short value = (short)data[dataOffset++];
entry.setAlignmentType((byte)(value & 0xFF));
}
if (ZLTextStyleEntry.isFeatureSupported(mask, FONT_FAMILY)) {
final short familyLength = (short)data[dataOffset++];
entry.setFontFamily(new String(data, dataOffset, familyLength));
dataOffset += familyLength;
}
if (ZLTextStyleEntry.isFeatureSupported(mask, FONT_STYLE_MODIFIER)) {
final short value = (short)data[dataOffset++];
entry.setFontModifiers((byte)(value & 0xFF), (byte)((value >> 8) & 0xFF));
}
myStyleEntry = entry;
}
case ZLTextParagraph.Entry.STYLE_CLOSE:
// No data
break;
case ZLTextParagraph.Entry.RESET_BIDI:
// No data
break;
}
++myCounter;
myDataOffset = dataOffset;
}
}
protected ZLTextPlainModel(
String id,
String language,
int[] entryIndices,
int[] entryOffsets,
int[] paragraphLenghts,
int[] textSizes,
byte[] paragraphKinds,
CharStorage storage,
Map<String,ZLImage> imageMap
) {
myId = id;
myLanguage = language;
myStartEntryIndices = entryIndices;
myStartEntryOffsets = entryOffsets;
myParagraphLengths = paragraphLenghts;
myTextSizes = textSizes;
myParagraphKinds = paragraphKinds;
myStorage = storage;
myImageMap = imageMap;
}
public final String getId() {
return myId;
}
public final String getLanguage() {
return myLanguage;
}
public final ZLTextMark getFirstMark() {
return ((myMarks == null) || myMarks.isEmpty()) ? null : myMarks.get(0);
}
public final ZLTextMark getLastMark() {
return ((myMarks == null) || myMarks.isEmpty()) ? null : myMarks.get(myMarks.size() - 1);
}
public final ZLTextMark getNextMark(ZLTextMark position) {
if ((position == null) || (myMarks == null)) {
return null;
}
ZLTextMark mark = null;
for (ZLTextMark current : myMarks) {
if (current.compareTo(position) >= 0) {
if ((mark == null) || (mark.compareTo(current) > 0)) {
mark = current;
}
}
}
return mark;
}
public final ZLTextMark getPreviousMark(ZLTextMark position) {
if ((position == null) || (myMarks == null)) {
return null;
}
ZLTextMark mark = null;
for (ZLTextMark current : myMarks) {
if (current.compareTo(position) < 0) {
if ((mark == null) || (mark.compareTo(current) < 0)) {
mark = current;
}
}
}
return mark;
}
public final int search(final String text, int startIndex, int endIndex, boolean ignoreCase) {
int count = 0;
ZLSearchPattern pattern = new ZLSearchPattern(text, ignoreCase);
myMarks = new ArrayList<ZLTextMark>();
if (startIndex > myParagraphsNumber) {
startIndex = myParagraphsNumber;
}
if (endIndex > myParagraphsNumber) {
endIndex = myParagraphsNumber;
}
int index = startIndex;
final EntryIteratorImpl it = new EntryIteratorImpl(index);
while (true) {
int offset = 0;
while (it.hasNext()) {
it.next();
if (it.getType() == ZLTextParagraph.Entry.TEXT) {
char[] textData = it.getTextData();
int textOffset = it.getTextOffset();
int textLength = it.getTextLength();
for (int pos = ZLSearchUtil.find(textData, textOffset, textLength, pattern); pos != -1;
pos = ZLSearchUtil.find(textData, textOffset, textLength, pattern, pos + 1)) {
myMarks.add(new ZLTextMark(index, offset + pos, pattern.getLength()));
++count;
}
offset += textLength;
}
}
if (++index >= endIndex) {
break;
}
it.reset(index);
}
return count;
}
public final List<ZLTextMark> getMarks() {
return (myMarks != null) ? myMarks : Collections.<ZLTextMark>emptyList();
}
public final void removeAllMarks() {
myMarks = null;
}
public final int getParagraphsNumber() {
return myParagraphsNumber;
}
public final ZLTextParagraph getParagraph(int index) {
final byte kind = myParagraphKinds[index];
return (kind == ZLTextParagraph.Kind.TEXT_PARAGRAPH) ?
new ZLTextParagraphImpl(this, index) :
new ZLTextSpecialParagraphImpl(kind, this, index);
}
public final int getTextLength(int index) {
return myTextSizes[Math.max(Math.min(index, myParagraphsNumber - 1), 0)];
}
private static int binarySearch(int[] array, int length, int value) {
int lowIndex = 0;
int highIndex = length - 1;
while (lowIndex <= highIndex) {
int midIndex = (lowIndex + highIndex) >>> 1;
int midValue = array[midIndex];
if (midValue > value) {
highIndex = midIndex - 1;
} else if (midValue < value) {
lowIndex = midIndex + 1;
} else {
return midIndex;
}
}
return -lowIndex - 1;
}
public final int findParagraphByTextLength(int length) {
int index = binarySearch(myTextSizes, myParagraphsNumber, length);
if (index >= 0) {
return index;
}
return Math.min(-index - 1, myParagraphsNumber - 1);
}
}
| false | true | public void next() {
int dataOffset = myDataOffset;
char[] data = myStorage.block(myDataIndex);
if (dataOffset == data.length) {
data = myStorage.block(++myDataIndex);
dataOffset = 0;
}
byte type = (byte)data[dataOffset];
if (type == 0) {
data = myStorage.block(++myDataIndex);
dataOffset = 0;
type = (byte)data[0];
}
myType = type;
++dataOffset;
switch (type) {
case ZLTextParagraph.Entry.TEXT:
myTextLength =
(int)data[dataOffset++] +
(((int)data[dataOffset++]) << 16);
myTextData = data;
myTextOffset = dataOffset;
dataOffset += myTextLength;
break;
case ZLTextParagraph.Entry.CONTROL:
{
short kind = (short)data[dataOffset++];
myControlKind = (byte)kind;
myControlIsStart = (kind & 0x0100) == 0x0100;
myHyperlinkType = 0;
break;
}
case ZLTextParagraph.Entry.HYPERLINK_CONTROL:
{
short kind = (short)data[dataOffset++];
myControlKind = (byte)kind;
myControlIsStart = true;
myHyperlinkType = (byte)(kind >> 8);
short labelLength = (short)data[dataOffset++];
myHyperlinkId = new String(data, dataOffset, labelLength);
dataOffset += labelLength;
break;
}
case ZLTextParagraph.Entry.IMAGE:
{
final short vOffset = (short)data[dataOffset++];
final short len = (short)data[dataOffset++];
final String id = new String(data, dataOffset, len);
dataOffset += len;
final boolean isCover = data[dataOffset++] != 0;
myImageEntry = new ZLImageEntry(myImageMap, id, vOffset, isCover);
break;
}
case ZLTextParagraph.Entry.FIXED_HSPACE:
myFixedHSpaceLength = (short)data[dataOffset++];
break;
case ZLTextParagraph.Entry.STYLE:
{
final ZLTextStyleEntry entry = new ZLTextStyleEntry();
final short mask = (short)data[dataOffset++];
for (int i = 0; i < NUMBER_OF_LENGTHS; ++i) {
if (ZLTextStyleEntry.isFeatureSupported(mask, i)) {
final short size = (short)data[dataOffset++];
final byte unit = (byte)data[dataOffset++];
entry.setLength(i, size, unit);
}
}
if (ZLTextStyleEntry.isFeatureSupported(mask, ALIGNMENT_TYPE)) {
final short value = (short)data[dataOffset++];
entry.setAlignmentType((byte)(value & 0xFF));
}
if (ZLTextStyleEntry.isFeatureSupported(mask, FONT_FAMILY)) {
final short familyLength = (short)data[dataOffset++];
entry.setFontFamily(new String(data, dataOffset, familyLength));
dataOffset += familyLength;
}
if (ZLTextStyleEntry.isFeatureSupported(mask, FONT_STYLE_MODIFIER)) {
final short value = (short)data[dataOffset++];
entry.setFontModifiers((byte)(value & 0xFF), (byte)((value >> 8) & 0xFF));
}
myStyleEntry = entry;
}
case ZLTextParagraph.Entry.STYLE_CLOSE:
// No data
break;
case ZLTextParagraph.Entry.RESET_BIDI:
// No data
break;
}
++myCounter;
myDataOffset = dataOffset;
}
| public void next() {
int dataOffset = myDataOffset;
char[] data = myStorage.block(myDataIndex);
if (dataOffset == data.length) {
data = myStorage.block(++myDataIndex);
dataOffset = 0;
}
byte type = (byte)data[dataOffset];
if (type == 0) {
data = myStorage.block(++myDataIndex);
dataOffset = 0;
type = (byte)data[0];
}
myType = type;
++dataOffset;
switch (type) {
case ZLTextParagraph.Entry.TEXT:
{
int textLength =
(int)data[dataOffset++] +
(((int)data[dataOffset++]) << 16);
if (textLength > data.length - dataOffset) {
textLength = data.length - dataOffset;
}
myTextLength = textLength;
myTextData = data;
myTextOffset = dataOffset;
dataOffset += textLength;
break;
}
case ZLTextParagraph.Entry.CONTROL:
{
short kind = (short)data[dataOffset++];
myControlKind = (byte)kind;
myControlIsStart = (kind & 0x0100) == 0x0100;
myHyperlinkType = 0;
break;
}
case ZLTextParagraph.Entry.HYPERLINK_CONTROL:
{
short kind = (short)data[dataOffset++];
myControlKind = (byte)kind;
myControlIsStart = true;
myHyperlinkType = (byte)(kind >> 8);
short labelLength = (short)data[dataOffset++];
myHyperlinkId = new String(data, dataOffset, labelLength);
dataOffset += labelLength;
break;
}
case ZLTextParagraph.Entry.IMAGE:
{
final short vOffset = (short)data[dataOffset++];
final short len = (short)data[dataOffset++];
final String id = new String(data, dataOffset, len);
dataOffset += len;
final boolean isCover = data[dataOffset++] != 0;
myImageEntry = new ZLImageEntry(myImageMap, id, vOffset, isCover);
break;
}
case ZLTextParagraph.Entry.FIXED_HSPACE:
myFixedHSpaceLength = (short)data[dataOffset++];
break;
case ZLTextParagraph.Entry.STYLE:
{
final ZLTextStyleEntry entry = new ZLTextStyleEntry();
final short mask = (short)data[dataOffset++];
for (int i = 0; i < NUMBER_OF_LENGTHS; ++i) {
if (ZLTextStyleEntry.isFeatureSupported(mask, i)) {
final short size = (short)data[dataOffset++];
final byte unit = (byte)data[dataOffset++];
entry.setLength(i, size, unit);
}
}
if (ZLTextStyleEntry.isFeatureSupported(mask, ALIGNMENT_TYPE)) {
final short value = (short)data[dataOffset++];
entry.setAlignmentType((byte)(value & 0xFF));
}
if (ZLTextStyleEntry.isFeatureSupported(mask, FONT_FAMILY)) {
final short familyLength = (short)data[dataOffset++];
entry.setFontFamily(new String(data, dataOffset, familyLength));
dataOffset += familyLength;
}
if (ZLTextStyleEntry.isFeatureSupported(mask, FONT_STYLE_MODIFIER)) {
final short value = (short)data[dataOffset++];
entry.setFontModifiers((byte)(value & 0xFF), (byte)((value >> 8) & 0xFF));
}
myStyleEntry = entry;
}
case ZLTextParagraph.Entry.STYLE_CLOSE:
// No data
break;
case ZLTextParagraph.Entry.RESET_BIDI:
// No data
break;
}
++myCounter;
myDataOffset = dataOffset;
}
|
diff --git a/org.ow2.mindEd.ide.ui/src/org/ow2/mindEd/ide/ui/Activator.java b/org.ow2.mindEd.ide.ui/src/org/ow2/mindEd/ide/ui/Activator.java
index e433ac4d..cb9cf595 100644
--- a/org.ow2.mindEd.ide.ui/src/org/ow2/mindEd/ide/ui/Activator.java
+++ b/org.ow2.mindEd.ide.ui/src/org/ow2/mindEd/ide/ui/Activator.java
@@ -1,139 +1,139 @@
package org.ow2.mindEd.ide.ui;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.ow2.mindEd.ide.core.MindIdeCore;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
/**
* The plug-in ID
*/
public static final String PLUGIN_ID = "org.ow2.mindEd.ide.ui";
/**
* The shared instance
*/
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given
* plug-in relative path
*
* @param path the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
/**
* Open the editors associated to the giving file
* @param jf a file
*/
static public void openFile(IFile jf) {
if (jf != null) {
try {
IEditorDescriptor editor = IDE.getDefaultEditor(jf);
if (editor == null) {
editor = PlatformUI.getWorkbench().getEditorRegistry()
.findEditor(EditorsUI.DEFAULT_TEXT_EDITOR_ID);
}
- if (editor.getId().equals("adl.diagram.part.MindDiagramEditorID")) {
+ if (editor.getId().equals("org.ow2.mindEd.adl.editor.graphic.ui.part.MindDiagramEditorID")) {
// Save model URI, needed if diagram must be created
URI modelURI = URI.createFileURI(jf.getFullPath().toPortableString());
// This is the diagram URI
jf = jf.getParent().getFile(new Path(jf.getName()+MindIdeCore.DIAGRAM_EXT));
URI diagramURI = URI.createFileURI(jf.getFullPath().toPortableString());
// If diagram file doesn't exist, create it from the model
if (!(jf.exists())) {
initGmfDiagram(modelURI, diagramURI);
}
}
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage();
IDE.openEditor(activePage, jf, true);
} catch (PartInitException e) {
MindIdeCore.log(e, "Cannot open file "+jf);
}
}
}
public static void initGmfDiagram(URI modelURI, URI diagramURI) {
initGmfDiagram(diagramURI, modelURI, new NullProgressMonitor());
}
public static void initGmfDiagram(URI diagramURI, URI modelURI,
IProgressMonitor monitor) {
try {
Bundle bundle = Platform.getBundle("org.ow2.mindEd.adl.editor.graphic.ui");
if (bundle == null) {
getDefault().getLog().log(new Status(Status.WARNING, PLUGIN_ID, "Cannot find gmf plugin digram"));
return;
}
Class cl = bundle
.loadClass("org.ow2.mindEd.adl.editor.graphic.ui.custom.part.CustomMindDiagramEditorUtil");
cl.getMethod("initDiagram",URI.class, URI.class, IProgressMonitor.class).invoke(null, diagramURI, modelURI, monitor);
} catch (Throwable e) {
getDefault().getLog().log(new Status(Status.ERROR, PLUGIN_ID, "Cannot init gmf digram", e));
}
}
}
| true | true | static public void openFile(IFile jf) {
if (jf != null) {
try {
IEditorDescriptor editor = IDE.getDefaultEditor(jf);
if (editor == null) {
editor = PlatformUI.getWorkbench().getEditorRegistry()
.findEditor(EditorsUI.DEFAULT_TEXT_EDITOR_ID);
}
if (editor.getId().equals("adl.diagram.part.MindDiagramEditorID")) {
// Save model URI, needed if diagram must be created
URI modelURI = URI.createFileURI(jf.getFullPath().toPortableString());
// This is the diagram URI
jf = jf.getParent().getFile(new Path(jf.getName()+MindIdeCore.DIAGRAM_EXT));
URI diagramURI = URI.createFileURI(jf.getFullPath().toPortableString());
// If diagram file doesn't exist, create it from the model
if (!(jf.exists())) {
initGmfDiagram(modelURI, diagramURI);
}
}
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage();
IDE.openEditor(activePage, jf, true);
} catch (PartInitException e) {
MindIdeCore.log(e, "Cannot open file "+jf);
}
}
}
| static public void openFile(IFile jf) {
if (jf != null) {
try {
IEditorDescriptor editor = IDE.getDefaultEditor(jf);
if (editor == null) {
editor = PlatformUI.getWorkbench().getEditorRegistry()
.findEditor(EditorsUI.DEFAULT_TEXT_EDITOR_ID);
}
if (editor.getId().equals("org.ow2.mindEd.adl.editor.graphic.ui.part.MindDiagramEditorID")) {
// Save model URI, needed if diagram must be created
URI modelURI = URI.createFileURI(jf.getFullPath().toPortableString());
// This is the diagram URI
jf = jf.getParent().getFile(new Path(jf.getName()+MindIdeCore.DIAGRAM_EXT));
URI diagramURI = URI.createFileURI(jf.getFullPath().toPortableString());
// If diagram file doesn't exist, create it from the model
if (!(jf.exists())) {
initGmfDiagram(modelURI, diagramURI);
}
}
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage();
IDE.openEditor(activePage, jf, true);
} catch (PartInitException e) {
MindIdeCore.log(e, "Cannot open file "+jf);
}
}
}
|
diff --git a/bundles/org.eclipselabs.emf.query/src/org/eclipselabs/emf/query/util/ExpressionBuilder.java b/bundles/org.eclipselabs.emf.query/src/org/eclipselabs/emf/query/util/ExpressionBuilder.java
index 1b41ddd..b8d4530 100644
--- a/bundles/org.eclipselabs.emf.query/src/org/eclipselabs/emf/query/util/ExpressionBuilder.java
+++ b/bundles/org.eclipselabs.emf.query/src/org/eclipselabs/emf/query/util/ExpressionBuilder.java
@@ -1,378 +1,379 @@
package org.eclipselabs.emf.query.util;
import java.util.Date;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipselabs.emf.query.BinaryOperation;
import org.eclipselabs.emf.query.Expression;
import org.eclipselabs.emf.query.FeatureAccessor;
import org.eclipselabs.emf.query.Literal;
import org.eclipselabs.emf.query.QueryFactory;
public class ExpressionBuilder
{
public static void main(String[] args)
{
Expression expression;
// System.err.println("? " + EcoreFactory.eINSTANCE.convertToString(EcorePackage.Literals.EDATE, new Date()));
expression = new ExpressionBuilder("condition == true").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("publicationDate > 1999 || publicationDate > 1999L").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("publicationDate > 2011-05-15").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("name=='Stephen%20King'").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("w + x + y + z").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("w + (x + y) + z").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("w + x + (y + z)").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("(x==y || (z == '10')) || y == z").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("x==y || ((z == '10') || y == z").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("x==y || (z == '10')").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("x==y || (z == '10') || y == z").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("x==y").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("x == y").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("x == 'foo'").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("a.b").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("(a.b)").parseExpression();
System.out.println("##" + toString(expression));
expression = new ExpressionBuilder("'foo'").parseExpression();
System.out.println("##" + toString(expression));
}
protected BasicDiagnostic diagnostic = new BasicDiagnostic();
protected String text;
protected int index;
public ExpressionBuilder(String text)
{
this.text = text;
}
protected int peek()
{
return Character.codePointAt(text, index);
}
protected void next()
{
index = Character.offsetByCodePoints(text, index, 1);
}
protected boolean hasNext()
{
return index < text.length();
}
protected void accept(int match)
{
if (!hasNext())
{
// Expecting match
}
else
{
if (peek() == match)
{
next();
}
else
{
// Expecting match
}
}
}
protected void skipWhitespace()
{
while (hasNext())
{
int codePoint = peek();
if (Character.isWhitespace(codePoint))
{
next();
}
else
{
break;
}
}
}
public Expression parseExpression()
{
Expression result = null;
skipWhitespace();
if (!hasNext())
{
// Expecting an expression.
}
else
{
result = parseTerm();
while (hasNext() && peek() != ')')
{
BinaryOperation binaryOperation = QueryFactory.eINSTANCE.createBinaryOperation();
binaryOperation.setLeftOperand(result);
int start = index;
int end = -1;
for (; hasNext(); next())
{
if (Character.isJavaIdentifierStart(peek()) || Character.isWhitespace(peek()) || peek() == '\'')
{
end = index;
break;
}
}
binaryOperation.setOperator(end == -1 ? text.substring(start) : text.substring(start, end));
binaryOperation.setRightOperand(parseTerm());
result = binaryOperation;
}
}
return result;
}
public Expression parseTerm()
{
Expression result = null;
skipWhitespace();
if (!hasNext())
{
// Expecting an expression.
}
else
{
int codePoint = Character.codePointAt(text, index);
if (codePoint == '(')
{
index = Character.offsetByCodePoints(text, index, 1);
result = parseExpression();
skipWhitespace();
accept(')');
}
else if (codePoint == '\'')
{
int start = index;
int end = -1;
for (next(); hasNext(); next())
{
if (peek() == '\'')
{
end = index;
next();
break;
}
}
if (end == -1)
{
// Expecting '
}
else
{
Literal literal = QueryFactory.eINSTANCE.createLiteral();
literal.setLiteralValue(text.substring(start + 1, end));
result = literal;
}
}
else if (Character.isJavaIdentifierStart(codePoint))
{
int start = index;
int end = -1;
for (next(); hasNext(); next())
{
if (!Character.isJavaIdentifierPart(peek()))
{
end = index;
break;
}
}
String featureName = end == -1 ? text.substring(start) : text.substring(start, end);
if ("true".equals(featureName) || "false".equals(featureName))
{
Literal literal = QueryFactory.eINSTANCE.createLiteral();
literal.setLiteralValue(featureName);
literal.setValue("true".equals(featureName) ? Boolean.TRUE : Boolean.FALSE);
result = literal;
}
else
{
FeatureAccessor featureAccessor = QueryFactory.eINSTANCE.createFeatureAccessor();
featureAccessor.setFeatureName(featureName);
for (skipWhitespace(); hasNext() && peek() == '.'; skipWhitespace())
{
next();
if (!Character.isJavaIdentifierStart(peek()))
{
// Expecting an identifier;
}
start = index;
end = -1;
for (next(); hasNext(); next())
{
if (!Character.isJavaIdentifierPart(peek()))
{
end = index;
break;
}
}
FeatureAccessor baseFeatureAccessor = featureAccessor;
featureAccessor = QueryFactory.eINSTANCE.createFeatureAccessor();
+ featureName = end == -1 ? text.substring(start) : text.substring(start, end);
featureAccessor.setFeatureName(featureName);
featureAccessor.setFeatureAccessor(baseFeatureAccessor);
}
result = featureAccessor;
}
}
else if (codePoint >= '0' || codePoint <= '9')
{
int start = index;
int end = index + 1;
boolean longLiteral = false;
boolean dateLiteral = false;
LOOP:
for (next(); hasNext(); next())
{
switch (peek())
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
end = index + 1;
break;
}
case 'L':
{
longLiteral = true;
next();
break LOOP;
}
case '-':
case '+':
case 'T':
case ':':
case '.':
case 'Z':
{
end = index + 1;
dateLiteral = true;
break;
}
default:
{
break LOOP;
}
}
}
Literal literal = QueryFactory.eINSTANCE.createLiteral();
literal.setLiteralValue(text.substring(start, end));
if (dateLiteral)
{
literal.setValue(EcoreFactory.eINSTANCE.createFromString(EcorePackage.Literals.EDATE, literal.getLiteralValue()));
}
else if (longLiteral)
{
literal.setValue(Long.valueOf(literal.getLiteralValue()));
}
else
{
literal.setValue(Integer.valueOf(literal.getLiteralValue()));
}
result = literal;
}
skipWhitespace();
if (hasNext())
{
// End expected.
}
}
return result;
}
public Diagnostic getDiagnostic()
{
return diagnostic;
}
protected BasicDiagnostic createDiagnostic
(int severity, String source, int code, String messageKey, Object[] messageSubstitutions, Object[] data)
{
String message = getString(messageKey, messageSubstitutions);
return new BasicDiagnostic(severity, source, code, message, data);
}
protected String getString(String key, Object [] substitutions)
{
ResourceLocator resourceLocator = getResourceLocator();
return substitutions == null ? resourceLocator.getString(key) : resourceLocator.getString(key, substitutions);
}
protected ResourceLocator getResourceLocator()
{
return EcorePlugin.INSTANCE;
}
private final static QuerySwitch<String> PRINTER =
new QuerySwitch<String>()
{
@Override
public String caseFeatureAccessor(FeatureAccessor object)
{
FeatureAccessor featureAccessor = object.getFeatureAccessor();
return (featureAccessor != null ? PRINTER.caseFeatureAccessor(featureAccessor) + '.' : "" ) + object.getFeatureName();
}
@Override
public String caseLiteral(Literal object)
{
Object value = object.getValue();
String literalValue = object.getLiteralValue();
return
value instanceof Integer || value instanceof Date || value instanceof Boolean ?
literalValue :
value instanceof Long ?
literalValue + "L":
"'" + literalValue + "'";
}
@Override
public String caseBinaryOperation(BinaryOperation object)
{
Expression leftOperand = object.getLeftOperand();
Expression rightOperand = object.getRightOperand();
boolean needsParentheses = rightOperand instanceof BinaryOperation;
return
(leftOperand == null ? "null" : PRINTER.doSwitch(leftOperand)) + " " +
object.getOperator() + " " +
(needsParentheses ? "(" : "") + (rightOperand == null ? "null" : PRINTER.doSwitch(rightOperand)) + (needsParentheses ? ")" : "");
}
};
public static String toString(Expression expression)
{
return PRINTER.doSwitch(expression);
}
}
| true | true | public Expression parseTerm()
{
Expression result = null;
skipWhitespace();
if (!hasNext())
{
// Expecting an expression.
}
else
{
int codePoint = Character.codePointAt(text, index);
if (codePoint == '(')
{
index = Character.offsetByCodePoints(text, index, 1);
result = parseExpression();
skipWhitespace();
accept(')');
}
else if (codePoint == '\'')
{
int start = index;
int end = -1;
for (next(); hasNext(); next())
{
if (peek() == '\'')
{
end = index;
next();
break;
}
}
if (end == -1)
{
// Expecting '
}
else
{
Literal literal = QueryFactory.eINSTANCE.createLiteral();
literal.setLiteralValue(text.substring(start + 1, end));
result = literal;
}
}
else if (Character.isJavaIdentifierStart(codePoint))
{
int start = index;
int end = -1;
for (next(); hasNext(); next())
{
if (!Character.isJavaIdentifierPart(peek()))
{
end = index;
break;
}
}
String featureName = end == -1 ? text.substring(start) : text.substring(start, end);
if ("true".equals(featureName) || "false".equals(featureName))
{
Literal literal = QueryFactory.eINSTANCE.createLiteral();
literal.setLiteralValue(featureName);
literal.setValue("true".equals(featureName) ? Boolean.TRUE : Boolean.FALSE);
result = literal;
}
else
{
FeatureAccessor featureAccessor = QueryFactory.eINSTANCE.createFeatureAccessor();
featureAccessor.setFeatureName(featureName);
for (skipWhitespace(); hasNext() && peek() == '.'; skipWhitespace())
{
next();
if (!Character.isJavaIdentifierStart(peek()))
{
// Expecting an identifier;
}
start = index;
end = -1;
for (next(); hasNext(); next())
{
if (!Character.isJavaIdentifierPart(peek()))
{
end = index;
break;
}
}
FeatureAccessor baseFeatureAccessor = featureAccessor;
featureAccessor = QueryFactory.eINSTANCE.createFeatureAccessor();
featureAccessor.setFeatureName(featureName);
featureAccessor.setFeatureAccessor(baseFeatureAccessor);
}
result = featureAccessor;
}
}
else if (codePoint >= '0' || codePoint <= '9')
{
int start = index;
int end = index + 1;
boolean longLiteral = false;
boolean dateLiteral = false;
LOOP:
for (next(); hasNext(); next())
{
switch (peek())
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
end = index + 1;
break;
}
case 'L':
{
longLiteral = true;
next();
break LOOP;
}
case '-':
case '+':
case 'T':
case ':':
case '.':
case 'Z':
{
end = index + 1;
dateLiteral = true;
break;
}
default:
{
break LOOP;
}
}
}
Literal literal = QueryFactory.eINSTANCE.createLiteral();
literal.setLiteralValue(text.substring(start, end));
if (dateLiteral)
{
literal.setValue(EcoreFactory.eINSTANCE.createFromString(EcorePackage.Literals.EDATE, literal.getLiteralValue()));
}
else if (longLiteral)
{
literal.setValue(Long.valueOf(literal.getLiteralValue()));
}
else
{
literal.setValue(Integer.valueOf(literal.getLiteralValue()));
}
result = literal;
}
skipWhitespace();
if (hasNext())
{
// End expected.
}
}
return result;
}
| public Expression parseTerm()
{
Expression result = null;
skipWhitespace();
if (!hasNext())
{
// Expecting an expression.
}
else
{
int codePoint = Character.codePointAt(text, index);
if (codePoint == '(')
{
index = Character.offsetByCodePoints(text, index, 1);
result = parseExpression();
skipWhitespace();
accept(')');
}
else if (codePoint == '\'')
{
int start = index;
int end = -1;
for (next(); hasNext(); next())
{
if (peek() == '\'')
{
end = index;
next();
break;
}
}
if (end == -1)
{
// Expecting '
}
else
{
Literal literal = QueryFactory.eINSTANCE.createLiteral();
literal.setLiteralValue(text.substring(start + 1, end));
result = literal;
}
}
else if (Character.isJavaIdentifierStart(codePoint))
{
int start = index;
int end = -1;
for (next(); hasNext(); next())
{
if (!Character.isJavaIdentifierPart(peek()))
{
end = index;
break;
}
}
String featureName = end == -1 ? text.substring(start) : text.substring(start, end);
if ("true".equals(featureName) || "false".equals(featureName))
{
Literal literal = QueryFactory.eINSTANCE.createLiteral();
literal.setLiteralValue(featureName);
literal.setValue("true".equals(featureName) ? Boolean.TRUE : Boolean.FALSE);
result = literal;
}
else
{
FeatureAccessor featureAccessor = QueryFactory.eINSTANCE.createFeatureAccessor();
featureAccessor.setFeatureName(featureName);
for (skipWhitespace(); hasNext() && peek() == '.'; skipWhitespace())
{
next();
if (!Character.isJavaIdentifierStart(peek()))
{
// Expecting an identifier;
}
start = index;
end = -1;
for (next(); hasNext(); next())
{
if (!Character.isJavaIdentifierPart(peek()))
{
end = index;
break;
}
}
FeatureAccessor baseFeatureAccessor = featureAccessor;
featureAccessor = QueryFactory.eINSTANCE.createFeatureAccessor();
featureName = end == -1 ? text.substring(start) : text.substring(start, end);
featureAccessor.setFeatureName(featureName);
featureAccessor.setFeatureAccessor(baseFeatureAccessor);
}
result = featureAccessor;
}
}
else if (codePoint >= '0' || codePoint <= '9')
{
int start = index;
int end = index + 1;
boolean longLiteral = false;
boolean dateLiteral = false;
LOOP:
for (next(); hasNext(); next())
{
switch (peek())
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
end = index + 1;
break;
}
case 'L':
{
longLiteral = true;
next();
break LOOP;
}
case '-':
case '+':
case 'T':
case ':':
case '.':
case 'Z':
{
end = index + 1;
dateLiteral = true;
break;
}
default:
{
break LOOP;
}
}
}
Literal literal = QueryFactory.eINSTANCE.createLiteral();
literal.setLiteralValue(text.substring(start, end));
if (dateLiteral)
{
literal.setValue(EcoreFactory.eINSTANCE.createFromString(EcorePackage.Literals.EDATE, literal.getLiteralValue()));
}
else if (longLiteral)
{
literal.setValue(Long.valueOf(literal.getLiteralValue()));
}
else
{
literal.setValue(Integer.valueOf(literal.getLiteralValue()));
}
result = literal;
}
skipWhitespace();
if (hasNext())
{
// End expected.
}
}
return result;
}
|
diff --git a/src/main/java/org/jboss/ejb/client/ReceiverInterceptor.java b/src/main/java/org/jboss/ejb/client/ReceiverInterceptor.java
index 9090f78..99c38a7 100644
--- a/src/main/java/org/jboss/ejb/client/ReceiverInterceptor.java
+++ b/src/main/java/org/jboss/ejb/client/ReceiverInterceptor.java
@@ -1,98 +1,98 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.ejb.client;
/**
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class ReceiverInterceptor implements EJBClientInterceptor {
public void handleInvocation(final EJBClientInvocationContext context) throws Exception {
final EJBClientContext clientContext = context.getClientContext();
final EJBLocator<?> locator = context.getLocator();
final EJBClientTransactionContext transactionContext = EJBClientTransactionContext.getCurrent();
final String transactionNode = transactionContext == null ? null : transactionContext.getTransactionNode();
final EJBReceiverContext receiverContext;
if (transactionNode != null) {
receiverContext = clientContext.requireNodeEJBReceiverContext(transactionNode);
if (!receiverContext.getReceiver().acceptsModule(locator.getAppName(), locator.getModuleName(), locator.getDistinctName())) {
- throw new IllegalStateException(String.format("Node of the current transaction (%s) does not accept (%s)", locator));
+ throw new IllegalStateException(String.format("Node of the current transaction (%s) does not accept (%s)", transactionNode, locator));
}
final Affinity affinity = locator.getAffinity();
if (affinity instanceof NodeAffinity) {
if (!transactionNode.equals(((NodeAffinity) affinity).getNodeName())) {
throw new IllegalStateException(String.format("Node of the current transaction (%s) does not accept (%s)", transactionNode, locator));
}
} else if (affinity instanceof ClusterAffinity) {
if (!clientContext.clusterContains(((ClusterAffinity) affinity).getClusterName(), transactionNode)) {
throw new IllegalStateException(String.format("Node of the current transaction (%s) does not accept (%s)", transactionNode, locator));
}
}
} else {
final Affinity affinity = locator.getAffinity();
if (affinity instanceof NodeAffinity) {
receiverContext = clientContext.requireNodeEJBReceiverContext(((NodeAffinity) affinity).getNodeName());
} else if (affinity instanceof ClusterAffinity) {
final Affinity weakAffinity = context.getInvocationHandler().getWeakAffinity();
if (weakAffinity instanceof NodeAffinity) {
final EJBReceiver nodeReceiver = clientContext.getNodeEJBReceiver(((NodeAffinity) weakAffinity).getNodeName());
if (nodeReceiver != null && clientContext.clusterContains(((ClusterAffinity) affinity).getClusterName(), nodeReceiver.getNodeName())) {
receiverContext = clientContext.requireEJBReceiverContext(nodeReceiver);
} else {
receiverContext = clientContext.requireClusterEJBReceiverContext(((ClusterAffinity) affinity).getClusterName());
}
} else {
receiverContext = clientContext.requireClusterEJBReceiverContext(((ClusterAffinity) affinity).getClusterName());
}
} else if (affinity == Affinity.NONE) {
final Affinity weakAffinity = context.getInvocationHandler().getWeakAffinity();
if (weakAffinity instanceof NodeAffinity) {
final EJBReceiver receiver = clientContext.getNodeEJBReceiver(((NodeAffinity) weakAffinity).getNodeName());
if (receiver != null) {
receiverContext = clientContext.requireEJBReceiverContext(receiver);
} else {
receiverContext = clientContext.requireEJBReceiverContext(clientContext.requireEJBReceiver(locator.getAppName(), locator.getModuleName(), locator.getDistinctName()));
}
} else if (weakAffinity instanceof ClusterAffinity) {
final EJBReceiverContext clusterReceiverContext = clientContext.getClusterEJBReceiverContext(((ClusterAffinity) weakAffinity).getClusterName());
if (clusterReceiverContext != null) {
receiverContext = clusterReceiverContext;
} else {
receiverContext = clientContext.requireEJBReceiverContext(clientContext.requireEJBReceiver(locator.getAppName(), locator.getModuleName(), locator.getDistinctName()));
}
} else {
receiverContext = clientContext.requireEJBReceiverContext(clientContext.requireEJBReceiver(locator.getAppName(), locator.getModuleName(), locator.getDistinctName()));
}
} else {
// should never happen
throw new IllegalStateException("Unknown affinity type");
}
}
context.setReceiverInvocationContext(new EJBReceiverInvocationContext(context, receiverContext));
context.sendRequest();
}
public Object handleInvocationResult(final EJBClientInvocationContext context) throws Exception {
return context.getResult();
}
}
| true | true | public void handleInvocation(final EJBClientInvocationContext context) throws Exception {
final EJBClientContext clientContext = context.getClientContext();
final EJBLocator<?> locator = context.getLocator();
final EJBClientTransactionContext transactionContext = EJBClientTransactionContext.getCurrent();
final String transactionNode = transactionContext == null ? null : transactionContext.getTransactionNode();
final EJBReceiverContext receiverContext;
if (transactionNode != null) {
receiverContext = clientContext.requireNodeEJBReceiverContext(transactionNode);
if (!receiverContext.getReceiver().acceptsModule(locator.getAppName(), locator.getModuleName(), locator.getDistinctName())) {
throw new IllegalStateException(String.format("Node of the current transaction (%s) does not accept (%s)", locator));
}
final Affinity affinity = locator.getAffinity();
if (affinity instanceof NodeAffinity) {
if (!transactionNode.equals(((NodeAffinity) affinity).getNodeName())) {
throw new IllegalStateException(String.format("Node of the current transaction (%s) does not accept (%s)", transactionNode, locator));
}
} else if (affinity instanceof ClusterAffinity) {
if (!clientContext.clusterContains(((ClusterAffinity) affinity).getClusterName(), transactionNode)) {
throw new IllegalStateException(String.format("Node of the current transaction (%s) does not accept (%s)", transactionNode, locator));
}
}
} else {
final Affinity affinity = locator.getAffinity();
if (affinity instanceof NodeAffinity) {
receiverContext = clientContext.requireNodeEJBReceiverContext(((NodeAffinity) affinity).getNodeName());
} else if (affinity instanceof ClusterAffinity) {
final Affinity weakAffinity = context.getInvocationHandler().getWeakAffinity();
if (weakAffinity instanceof NodeAffinity) {
final EJBReceiver nodeReceiver = clientContext.getNodeEJBReceiver(((NodeAffinity) weakAffinity).getNodeName());
if (nodeReceiver != null && clientContext.clusterContains(((ClusterAffinity) affinity).getClusterName(), nodeReceiver.getNodeName())) {
receiverContext = clientContext.requireEJBReceiverContext(nodeReceiver);
} else {
receiverContext = clientContext.requireClusterEJBReceiverContext(((ClusterAffinity) affinity).getClusterName());
}
} else {
receiverContext = clientContext.requireClusterEJBReceiverContext(((ClusterAffinity) affinity).getClusterName());
}
} else if (affinity == Affinity.NONE) {
final Affinity weakAffinity = context.getInvocationHandler().getWeakAffinity();
if (weakAffinity instanceof NodeAffinity) {
final EJBReceiver receiver = clientContext.getNodeEJBReceiver(((NodeAffinity) weakAffinity).getNodeName());
if (receiver != null) {
receiverContext = clientContext.requireEJBReceiverContext(receiver);
} else {
receiverContext = clientContext.requireEJBReceiverContext(clientContext.requireEJBReceiver(locator.getAppName(), locator.getModuleName(), locator.getDistinctName()));
}
} else if (weakAffinity instanceof ClusterAffinity) {
final EJBReceiverContext clusterReceiverContext = clientContext.getClusterEJBReceiverContext(((ClusterAffinity) weakAffinity).getClusterName());
if (clusterReceiverContext != null) {
receiverContext = clusterReceiverContext;
} else {
receiverContext = clientContext.requireEJBReceiverContext(clientContext.requireEJBReceiver(locator.getAppName(), locator.getModuleName(), locator.getDistinctName()));
}
} else {
receiverContext = clientContext.requireEJBReceiverContext(clientContext.requireEJBReceiver(locator.getAppName(), locator.getModuleName(), locator.getDistinctName()));
}
} else {
// should never happen
throw new IllegalStateException("Unknown affinity type");
}
}
context.setReceiverInvocationContext(new EJBReceiverInvocationContext(context, receiverContext));
context.sendRequest();
}
| public void handleInvocation(final EJBClientInvocationContext context) throws Exception {
final EJBClientContext clientContext = context.getClientContext();
final EJBLocator<?> locator = context.getLocator();
final EJBClientTransactionContext transactionContext = EJBClientTransactionContext.getCurrent();
final String transactionNode = transactionContext == null ? null : transactionContext.getTransactionNode();
final EJBReceiverContext receiverContext;
if (transactionNode != null) {
receiverContext = clientContext.requireNodeEJBReceiverContext(transactionNode);
if (!receiverContext.getReceiver().acceptsModule(locator.getAppName(), locator.getModuleName(), locator.getDistinctName())) {
throw new IllegalStateException(String.format("Node of the current transaction (%s) does not accept (%s)", transactionNode, locator));
}
final Affinity affinity = locator.getAffinity();
if (affinity instanceof NodeAffinity) {
if (!transactionNode.equals(((NodeAffinity) affinity).getNodeName())) {
throw new IllegalStateException(String.format("Node of the current transaction (%s) does not accept (%s)", transactionNode, locator));
}
} else if (affinity instanceof ClusterAffinity) {
if (!clientContext.clusterContains(((ClusterAffinity) affinity).getClusterName(), transactionNode)) {
throw new IllegalStateException(String.format("Node of the current transaction (%s) does not accept (%s)", transactionNode, locator));
}
}
} else {
final Affinity affinity = locator.getAffinity();
if (affinity instanceof NodeAffinity) {
receiverContext = clientContext.requireNodeEJBReceiverContext(((NodeAffinity) affinity).getNodeName());
} else if (affinity instanceof ClusterAffinity) {
final Affinity weakAffinity = context.getInvocationHandler().getWeakAffinity();
if (weakAffinity instanceof NodeAffinity) {
final EJBReceiver nodeReceiver = clientContext.getNodeEJBReceiver(((NodeAffinity) weakAffinity).getNodeName());
if (nodeReceiver != null && clientContext.clusterContains(((ClusterAffinity) affinity).getClusterName(), nodeReceiver.getNodeName())) {
receiverContext = clientContext.requireEJBReceiverContext(nodeReceiver);
} else {
receiverContext = clientContext.requireClusterEJBReceiverContext(((ClusterAffinity) affinity).getClusterName());
}
} else {
receiverContext = clientContext.requireClusterEJBReceiverContext(((ClusterAffinity) affinity).getClusterName());
}
} else if (affinity == Affinity.NONE) {
final Affinity weakAffinity = context.getInvocationHandler().getWeakAffinity();
if (weakAffinity instanceof NodeAffinity) {
final EJBReceiver receiver = clientContext.getNodeEJBReceiver(((NodeAffinity) weakAffinity).getNodeName());
if (receiver != null) {
receiverContext = clientContext.requireEJBReceiverContext(receiver);
} else {
receiverContext = clientContext.requireEJBReceiverContext(clientContext.requireEJBReceiver(locator.getAppName(), locator.getModuleName(), locator.getDistinctName()));
}
} else if (weakAffinity instanceof ClusterAffinity) {
final EJBReceiverContext clusterReceiverContext = clientContext.getClusterEJBReceiverContext(((ClusterAffinity) weakAffinity).getClusterName());
if (clusterReceiverContext != null) {
receiverContext = clusterReceiverContext;
} else {
receiverContext = clientContext.requireEJBReceiverContext(clientContext.requireEJBReceiver(locator.getAppName(), locator.getModuleName(), locator.getDistinctName()));
}
} else {
receiverContext = clientContext.requireEJBReceiverContext(clientContext.requireEJBReceiver(locator.getAppName(), locator.getModuleName(), locator.getDistinctName()));
}
} else {
// should never happen
throw new IllegalStateException("Unknown affinity type");
}
}
context.setReceiverInvocationContext(new EJBReceiverInvocationContext(context, receiverContext));
context.sendRequest();
}
|
diff --git a/jflex/src/JFlex/Emitter.java b/jflex/src/JFlex/Emitter.java
index 8b9a9fc..a5619a5 100644
--- a/jflex/src/JFlex/Emitter.java
+++ b/jflex/src/JFlex/Emitter.java
@@ -1,1574 +1,1576 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* JFlex 1.4 *
* Copyright (C) 1998-2004 Gerwin Klein <[email protected]> *
* All rights reserved. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License. See the file *
* COPYRIGHT for more information. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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 JFlex;
import java.io.*;
import java.util.*;
import java.text.*;
/**
* This class manages the actual code generation, putting
* the scanner together, filling in skeleton sections etc.
*
* Table compression, String packing etc. is also done here.
*
* @author Gerwin Klein
* @version JFlex 1.4, $Revision$, $Date$
*/
final public class Emitter {
// bit masks for state attributes
static final private int FINAL = 1;
static final private int PUSHBACK = 2;
static final private int LOOKEND = 4;
static final private int NOLOOK = 8;
static final private String date = (new SimpleDateFormat()).format(new Date());
private File inputFile;
private PrintWriter out;
private Skeleton skel;
private LexScan scanner;
private LexParse parser;
private DFA dfa;
// for switch statement:
// table[i][j] is the set of input characters that leads from state i to state j
private CharSet table[][];
private boolean isTransition[];
// noTarget[i] is the set of input characters that have no target state in state i
private CharSet noTarget[];
// for row killing:
private int numRows;
private int [] rowMap;
private boolean [] rowKilled;
// for col killing:
private int numCols;
private int [] colMap;
private boolean [] colKilled;
/** maps actions to their switch label */
private Hashtable actionTable = new Hashtable();
private CharClassInterval [] intervalls;
private String visibility = "public";
public Emitter(File inputFile, LexParse parser, DFA dfa) throws IOException {
String name = parser.scanner.className+".java";
File outputFile = normalize(name, inputFile);
Out.println("Writing code to \""+outputFile+"\"");
this.out = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
this.parser = parser;
this.scanner = parser.scanner;
this.visibility = scanner.visibility;
this.inputFile = inputFile;
this.dfa = dfa;
this.skel = new Skeleton(out);
}
/**
* Constructs a file in Options.getDir() or in the same directory as
* another file. Makes a backup if the file already exists.
*
* @param name the name (without path) of the file
* @param path the path where to construct the file
* @param input fallback location if path = <tt>null</tt>
* (expected to be a file in the directory to write to)
*/
public static File normalize(String name, File input) {
File outputFile;
if ( Options.getDir() == null )
if ( input == null || input.getParent() == null )
outputFile = new File(name);
else
outputFile = new File(input.getParent(), name);
else
outputFile = new File(Options.getDir(), name);
if ( outputFile.exists() && !Options.no_backup ) {
File backup = new File( outputFile.toString()+"~" );
if ( backup.exists() ) backup.delete();
if ( outputFile.renameTo( backup ) )
Out.println("Old file \""+outputFile+"\" saved as \""+backup+"\"");
else
Out.println("Couldn't save old file \""+outputFile+"\", overwriting!");
}
return outputFile;
}
private void println() {
out.println();
}
private void println(String line) {
out.println(line);
}
private void println(int i) {
out.println(i);
}
private void print(String line) {
out.print(line);
}
private void print(int i) {
out.print(i);
}
private void print(int i, int tab) {
int exp;
if (i < 0)
exp = 1;
else
exp = 10;
while (tab-- > 1) {
if (Math.abs(i) < exp) print(" ");
exp*= 10;
}
print(i);
}
private void emitScanError() {
print(" private void zzScanError(int errorCode)");
if (scanner.scanErrorException != null)
print(" throws "+scanner.scanErrorException);
println(" {");
skel.emitNext();
if (scanner.scanErrorException == null)
println(" throw new Error(message);");
else
println(" throw new "+scanner.scanErrorException+"(message);");
skel.emitNext();
print(" "+visibility+" void yypushback(int number) ");
if (scanner.scanErrorException == null)
println(" {");
else
println(" throws "+scanner.scanErrorException+" {");
}
private void emitMain() {
if ( !(scanner.standalone || scanner.debugOption || scanner.cupDebug) ) return;
if ( scanner.cupDebug ) {
println(" /**");
println(" * Converts an int token code into the name of the");
println(" * token by reflection on the cup symbol class/interface "+scanner.cupSymbol);
println(" *");
println(" * This code was contributed by Karl Meissner <[email protected]>");
println(" */");
println(" private String getTokenName(int token) {");
println(" try {");
println(" java.lang.reflect.Field [] classFields = " + scanner.cupSymbol + ".class.getFields();");
println(" for (int i = 0; i < classFields.length; i++) {");
println(" if (classFields[i].getInt(null) == token) {");
println(" return classFields[i].getName();");
println(" }");
println(" }");
println(" } catch (Exception e) {");
println(" e.printStackTrace(System.err);");
println(" }");
println("");
println(" return \"UNKNOWN TOKEN\";");
println(" }");
println("");
println(" /**");
println(" * Same as "+scanner.functionName+" but also prints the token to standard out");
println(" * for debugging.");
println(" *");
println(" * This code was contributed by Karl Meissner <[email protected]>");
println(" */");
print(" "+visibility+" ");
if ( scanner.tokenType == null ) {
if ( scanner.isInteger )
print( "int" );
else
if ( scanner.isIntWrap )
print( "Integer" );
else
print( "Yytoken" );
}
else
print( scanner.tokenType );
print(" debug_");
print(scanner.functionName);
print("() throws java.io.IOException");
if ( scanner.lexThrow != null ) {
print(", ");
print(scanner.lexThrow);
}
if ( scanner.scanErrorException != null ) {
print(", ");
print(scanner.scanErrorException);
}
println(" {");
println(" java_cup.runtime.Symbol s = "+scanner.functionName+"();");
print(" System.out.println( ");
if (scanner.lineCount) print("\"line:\" + (yyline+1) + ");
if (scanner.columnCount) print("\" col:\" + (yycolumn+1) + ");
println("\" --\"+ yytext() + \"--\" + getTokenName(s.sym) + \"--\");");
println(" return s;");
println(" }");
println("");
}
if ( scanner.standalone ) {
println(" /**");
println(" * Runs the scanner on input files.");
println(" *");
println(" * This is a standalone scanner, it will print any unmatched");
println(" * text to System.out unchanged.");
println(" *");
println(" * @param argv the command line, contains the filenames to run");
println(" * the scanner on.");
println(" */");
}
else {
println(" /**");
println(" * Runs the scanner on input files.");
println(" *");
println(" * This main method is the debugging routine for the scanner.");
println(" * It prints debugging information about each returned token to");
println(" * System.out until the end of file is reached, or an error occured.");
println(" *");
println(" * @param argv the command line, contains the filenames to run");
println(" * the scanner on.");
println(" */");
}
println(" public static void main(String argv[]) {");
println(" if (argv.length == 0) {");
println(" System.out.println(\"Usage : java "+scanner.className+" <inputfile>\");");
println(" }");
println(" else {");
println(" for (int i = 0; i < argv.length; i++) {");
println(" "+scanner.className+" scanner = null;");
println(" try {");
println(" scanner = new "+scanner.className+"( new java.io.FileReader(argv[i]) );");
if ( scanner.standalone ) {
println(" while ( !scanner.zzAtEOF ) scanner."+scanner.functionName+"();");
}
else if (scanner.cupDebug ) {
println(" while ( !scanner.zzAtEOF ) scanner.debug_"+scanner.functionName+"();");
}
else {
println(" do {");
println(" System.out.println(scanner."+scanner.functionName+"());");
println(" } while (!scanner.zzAtEOF);");
println("");
}
println(" }");
println(" catch (java.io.FileNotFoundException e) {");
println(" System.out.println(\"File not found : \\\"\"+argv[i]+\"\\\"\");");
println(" }");
println(" catch (java.io.IOException e) {");
println(" System.out.println(\"IO error scanning file \\\"\"+argv[i]+\"\\\"\");");
println(" System.out.println(e);");
println(" }");
println(" catch (Exception e) {");
println(" System.out.println(\"Unexpected exception:\");");
println(" e.printStackTrace();");
println(" }");
println(" }");
println(" }");
println(" }");
println("");
}
private void emitNoMatch() {
println(" zzScanError(ZZ_NO_MATCH);");
}
private void emitNextInput() {
println(" if (zzCurrentPosL < zzEndReadL)");
println(" zzInput = zzBufferL[zzCurrentPosL++];");
println(" else if (zzAtEOF) {");
println(" zzInput = YYEOF;");
println(" break zzForAction;");
println(" }");
println(" else {");
println(" // store back cached positions");
println(" zzCurrentPos = zzCurrentPosL;");
println(" zzMarkedPos = zzMarkedPosL;");
if ( scanner.lookAheadUsed )
println(" zzPushbackPos = zzPushbackPosL;");
println(" boolean eof = zzRefill();");
println(" // get translated positions and possibly new buffer");
println(" zzCurrentPosL = zzCurrentPos;");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzBufferL = zzBuffer;");
println(" zzEndReadL = zzEndRead;");
if ( scanner.lookAheadUsed )
println(" zzPushbackPosL = zzPushbackPos;");
println(" if (eof) {");
println(" zzInput = YYEOF;");
println(" break zzForAction;");
println(" }");
println(" else {");
println(" zzInput = zzBufferL[zzCurrentPosL++];");
println(" }");
println(" }");
}
private void emitHeader() {
println("/* The following code was generated by JFlex "+Main.version+" on "+date+" */");
println("");
}
private void emitUserCode() {
if ( scanner.userCode.length() > 0 )
println(scanner.userCode.toString());
}
private void emitClassName() {
if (!endsWithJavadoc(scanner.userCode)) {
String path = inputFile.toString();
// slashify path (avoid backslash u sequence = unicode escape)
if (File.separatorChar != '/') {
path = path.replace(File.separatorChar, '/');
}
println("/**");
println(" * This class is a scanner generated by ");
println(" * <a href=\"http://www.jflex.de/\">JFlex</a> "+Main.version);
println(" * on "+date+" from the specification file");
println(" * <tt>"+path+"</tt>");
println(" */");
}
if ( scanner.isPublic ) print("public ");
if ( scanner.isAbstract) print("abstract ");
if ( scanner.isFinal ) print("final ");
print("class ");
print(scanner.className);
if ( scanner.isExtending != null ) {
print(" extends ");
print(scanner.isExtending);
}
if ( scanner.isImplementing != null ) {
print(" implements ");
print(scanner.isImplementing);
}
println(" {");
}
/**
* Try to find out if user code ends with a javadoc comment
*
* @param buffer the user code
* @return true if it ends with a javadoc comment
*/
public static boolean endsWithJavadoc(StringBuffer usercode) {
String s = usercode.toString().trim();
if (!s.endsWith("*/")) return false;
// find beginning of javadoc comment
int i = s.lastIndexOf("/**");
if (i < 0) return false;
// javadoc comment shouldn't contain a comment end
return s.substring(i,s.length()-2).indexOf("*/") < 0;
}
private void emitLexicalStates() {
Enumeration stateNames = scanner.states.names();
while ( stateNames.hasMoreElements() ) {
String name = (String) stateNames.nextElement();
int num = scanner.states.getNumber(name).intValue();
if (scanner.bolUsed)
println(" "+visibility+" static final int "+name+" = "+2*num+";");
else
println(" "+visibility+" static final int "+name+" = "+dfa.lexState[2*num]+";");
}
if (scanner.bolUsed) {
println("");
println(" /**");
println(" * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l");
println(" * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l");
println(" * at the beginning of a line");
println(" * l is of the form l = 2*k, k a non negative integer");
println(" */");
println(" private static final int ZZ_LEXSTATE[] = { ");
int i, j = 0;
print(" ");
for (i = 0; i < dfa.lexState.length-1; i++) {
print( dfa.lexState[i], 2 );
print(", ");
if (++j >= 16) {
println();
print(" ");
j = 0;
}
}
println( dfa.lexState[i] );
println(" };");
}
}
private void emitDynamicInit() {
int count = 0;
int value = dfa.table[0][0];
println(" /** ");
println(" * The transition table of the DFA");
println(" */");
CountEmitter e = new CountEmitter("Trans");
e.setValTranslation(+1); // allow vals in [-1, 0xFFFE]
e.emitInit();
for (int i = 0; i < dfa.numStates; i++) {
if ( !rowKilled[i] ) {
for (int c = 0; c < dfa.numInput; c++) {
if ( !colKilled[c] ) {
if (dfa.table[i][c] == value) {
count++;
}
else {
e.emit(count, value);
count = 1;
value = dfa.table[i][c];
}
}
}
}
}
e.emit(count, value);
e.emitUnpack();
println(e.toString());
}
private void emitCharMapInitFunction() {
CharClasses cl = parser.getCharClasses();
if ( cl.getMaxCharCode() < 256 ) return;
println("");
println(" /** ");
println(" * Unpacks the compressed character translation table.");
println(" *");
println(" * @param packed the packed character translation table");
println(" * @return the unpacked character translation table");
println(" */");
println(" private static char [] zzUnpackCMap(String packed) {");
println(" char [] map = new char[0x10000];");
println(" int i = 0; /* index in packed string */");
println(" int j = 0; /* index in unpacked array */");
println(" while (i < "+2*intervalls.length+") {");
println(" int count = packed.charAt(i++);");
println(" char value = packed.charAt(i++);");
println(" do map[j++] = value; while (--count > 0);");
println(" }");
println(" return map;");
println(" }");
}
private void emitZZTrans() {
int i,c;
int n = 0;
println(" /** ");
println(" * The transition table of the DFA");
println(" */");
println(" private static final int ZZ_TRANS [] = {"); //XXX
print(" ");
for (i = 0; i < dfa.numStates; i++) {
if ( !rowKilled[i] ) {
for (c = 0; c < dfa.numInput; c++) {
if ( !colKilled[c] ) {
if (n >= 10) {
println();
print(" ");
n = 0;
}
print( dfa.table[i][c] );
if (i != dfa.numStates-1 || c != dfa.numInput-1)
print( ", ");
n++;
}
}
}
}
println();
println(" };");
}
private void emitCharMapArrayUnPacked() {
CharClasses cl = parser.getCharClasses();
intervalls = cl.getIntervalls();
println("");
println(" /** ");
println(" * Translates characters to character classes");
println(" */");
println(" private static final char [] ZZ_CMAP = {");
int n = 0; // numbers of entries in current line
print(" ");
int max = cl.getMaxCharCode();
int i = 0;
while ( i < intervalls.length && intervalls[i].start <= max ) {
int end = Math.min(intervalls[i].end, max);
for (int c = intervalls[i].start; c <= end; c++) {
print(colMap[intervalls[i].charClass], 2);
if (c < max) {
print(", ");
if ( ++n >= 16 ) {
println();
print(" ");
n = 0;
}
}
}
i++;
}
println();
println(" };");
println();
}
private void emitCharMapArray() {
CharClasses cl = parser.getCharClasses();
if ( cl.getMaxCharCode() < 256 ) {
emitCharMapArrayUnPacked();
return;
}
// ignores cl.getMaxCharCode(), emits all intervalls instead
intervalls = cl.getIntervalls();
println("");
println(" /** ");
println(" * Translates characters to character classes");
println(" */");
println(" private static final String ZZ_CMAP_PACKED = ");
int n = 0; // numbers of entries in current line
print(" \"");
int i = 0;
while ( i < intervalls.length-1 ) {
int count = intervalls[i].end-intervalls[i].start+1;
int value = colMap[intervalls[i].charClass];
printUC(count);
printUC(value);
if ( ++n >= 10 ) {
println("\"+");
print(" \"");
n = 0;
}
i++;
}
printUC(intervalls[i].end-intervalls[i].start+1);
printUC(colMap[intervalls[i].charClass]);
println("\";");
println();
println(" /** ");
println(" * Translates characters to character classes");
println(" */");
println(" private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);");
println();
}
/**
* Print number as octal/unicode escaped string character.
*
* @param c the value to print
* @prec 0 <= c <= 0xFFFF
*/
private void printUC(int c) {
if (c > 255) {
out.print("\\u");
if (c < 0x1000) out.print("0");
out.print(Integer.toHexString(c));
}
else {
out.print("\\");
out.print(Integer.toOctalString(c));
}
}
private void emitRowMapArray() {
println("");
println(" /** ");
println(" * Translates a state to a row index in the transition table");
println(" */");
HiLowEmitter e = new HiLowEmitter("RowMap");
e.emitInit();
for (int i = 0; i < dfa.numStates; i++) {
e.emit(rowMap[i]*numCols);
}
e.emitUnpack();
println(e.toString());
}
private void emitAttributes() {
println(" /**");
println(" * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>");
println(" */");
CountEmitter e = new CountEmitter("Attribute");
e.emitInit();
int count = 1;
int value = 0;
if ( dfa.isFinal[0] ) value = FINAL;
if ( dfa.isPushback[0] ) value|= PUSHBACK;
if ( dfa.isLookEnd[0] ) value|= LOOKEND;
if ( !isTransition[0] ) value|= NOLOOK;
for (int i = 1; i < dfa.numStates; i++) {
int attribute = 0;
if ( dfa.isFinal[i] ) attribute = FINAL;
if ( dfa.isPushback[i] ) attribute|= PUSHBACK;
if ( dfa.isLookEnd[i] ) attribute|= LOOKEND;
if ( !isTransition[i] ) attribute|= NOLOOK;
if (value == attribute) {
count++;
}
else {
e.emit(count, value);
count = 1;
value = attribute;
}
}
e.emit(count, value);
e.emitUnpack();
println(e.toString());
}
private void emitClassCode() {
if ( scanner.eofCode != null ) {
println(" /** denotes if the user-EOF-code has already been executed */");
println(" private boolean zzEOFDone;");
println("");
}
if ( scanner.classCode != null ) {
println(" /* user code: */");
println(scanner.classCode);
}
}
private void emitConstructorDecl() {
print(" ");
if ( scanner.isPublic ) print("public ");
print( scanner.className );
print("(java.io.Reader in)");
if ( scanner.initThrow != null ) {
print(" throws ");
print( scanner.initThrow );
}
println(" {");
if ( scanner.initCode != null ) {
print(" ");
print( scanner.initCode );
}
println(" this.zzReader = in;");
println(" }");
println();
println(" /**");
println(" * Creates a new scanner.");
println(" * There is also java.io.Reader version of this constructor.");
println(" *");
println(" * @param in the java.io.Inputstream to read input from.");
println(" */");
print(" ");
if ( scanner.isPublic ) print("public ");
print( scanner.className );
print("(java.io.InputStream in)");
if ( scanner.initThrow != null ) {
print(" throws ");
print( scanner.initThrow );
}
println(" {");
println(" this(new java.io.InputStreamReader(in));");
println(" }");
}
private void emitDoEOF() {
if ( scanner.eofCode == null ) return;
println(" /**");
println(" * Contains user EOF-code, which will be executed exactly once,");
println(" * when the end of file is reached");
println(" */");
print(" private void zzDoEOF()");
if ( scanner.eofThrow != null ) {
print(" throws ");
print(scanner.eofThrow);
}
println(" {");
println(" if (!zzEOFDone) {");
println(" zzEOFDone = true;");
println(" "+scanner.eofCode );
println(" }");
println(" }");
println("");
println("");
}
private void emitLexFunctHeader() {
if (scanner.cupCompatible) {
// force public, because we have to implement java_cup.runtime.Symbol
print(" public ");
}
else {
print(" "+visibility+" ");
}
if ( scanner.tokenType == null ) {
if ( scanner.isInteger )
print( "int" );
else
if ( scanner.isIntWrap )
print( "Integer" );
else
print( "Yytoken" );
}
else
print( scanner.tokenType );
print(" ");
print(scanner.functionName);
print("() throws java.io.IOException");
if ( scanner.lexThrow != null ) {
print(", ");
print(scanner.lexThrow);
}
if ( scanner.scanErrorException != null ) {
print(", ");
print(scanner.scanErrorException);
}
println(" {");
skel.emitNext();
if ( scanner.useRowMap ) {
println(" int [] zzTransL = ZZ_TRANS;");
println(" int [] zzRowMapL = ZZ_ROWMAP;");
println(" int [] zzAttrL = ZZ_ATTRIBUTE;");
}
if ( scanner.lookAheadUsed ) {
println(" int zzPushbackPosL = zzPushbackPos = -1;");
println(" boolean zzWasPushback;");
}
skel.emitNext();
if ( scanner.charCount ) {
println(" yychar+= zzMarkedPosL-zzStartRead;");
println("");
}
if ( scanner.lineCount || scanner.columnCount ) {
println(" boolean zzR = false;");
println(" for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL;");
println(" zzCurrentPosL++) {");
println(" switch (zzBufferL[zzCurrentPosL]) {");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = false;");
println(" break;");
println(" case '\\r':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = true;");
println(" break;");
println(" case '\\n':");
println(" if (zzR)");
println(" zzR = false;");
println(" else {");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" }");
println(" break;");
println(" default:");
println(" zzR = false;");
if ( scanner.columnCount )
println(" yycolumn++;");
println(" }");
println(" }");
println();
if ( scanner.lineCount ) {
println(" if (zzR) {");
println(" // peek one character ahead if it is \\n (if we have counted one line too much)");
println(" boolean zzPeek;");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" else if (zzAtEOF)");
println(" zzPeek = false;");
println(" else {");
println(" boolean eof = zzRefill();");
+ println(" zzEndReadL = zzEndRead;");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzPeek = false;");
println(" else ");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" }");
println(" if (zzPeek) yyline--;");
println(" }");
}
}
if ( scanner.bolUsed ) {
// zzMarkedPos > zzStartRead <=> last match was not empty
// if match was empty, last value of zzAtBOL can be used
// zzStartRead is always >= 0
println(" if (zzMarkedPosL > zzStartRead) {");
println(" switch (zzBufferL[zzMarkedPosL-1]) {");
println(" case '\\n':");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
println(" zzAtBOL = true;");
println(" break;");
println(" case '\\r': ");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" else if (zzAtEOF)");
println(" zzAtBOL = false;");
println(" else {");
println(" boolean eof = zzRefill();");
println(" zzMarkedPosL = zzMarkedPos;");
+ println(" zzEndReadL = zzEndRead;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzAtBOL = false;");
println(" else ");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" }");
println(" break;");
println(" default:");
println(" zzAtBOL = false;");
println(" }");
println(" }");
}
skel.emitNext();
if (scanner.bolUsed) {
println(" if (zzAtBOL)");
println(" zzState = ZZ_LEXSTATE[zzLexicalState+1];");
println(" else");
println(" zzState = ZZ_LEXSTATE[zzLexicalState];");
println();
}
else {
println(" zzState = zzLexicalState;");
println();
}
if (scanner.lookAheadUsed)
println(" zzWasPushback = false;");
skel.emitNext();
}
private void emitGetRowMapNext() {
println(" int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];");
println(" if (zzNext == "+DFA.NO_TARGET+") break zzForAction;");
println(" zzState = zzNext;");
println();
println(" int zzAttributes = zzAttrL[zzState];");
if ( scanner.lookAheadUsed ) {
println(" if ( (zzAttributes & "+PUSHBACK+") == "+PUSHBACK+" )");
println(" zzPushbackPosL = zzCurrentPosL;");
println();
}
println(" if ( (zzAttributes & "+FINAL+") == "+FINAL+" ) {");
if ( scanner.lookAheadUsed )
println(" zzWasPushback = (zzAttributes & "+LOOKEND+") == "+LOOKEND+";");
skel.emitNext();
println(" if ( (zzAttributes & "+NOLOOK+") == "+NOLOOK+" ) break zzForAction;");
skel.emitNext();
}
private void emitTransitionTable() {
transformTransitionTable();
println(" zzInput = zzCMapL[zzInput];");
println();
if ( scanner.lookAheadUsed )
println(" boolean zzPushback = false;");
println(" boolean zzIsFinal = false;");
println(" boolean zzNoLookAhead = false;");
println();
println(" zzForNext: { switch (zzState) {");
for (int state = 0; state < dfa.numStates; state++)
if (isTransition[state]) emitState(state);
println(" default:");
println(" // if this is ever reached, there is a serious bug in JFlex");
println(" zzScanError(ZZ_UNKNOWN_ERROR);");
println(" break;");
println(" } }");
println();
println(" if ( zzIsFinal ) {");
if ( scanner.lookAheadUsed )
println(" zzWasPushback = zzPushback;");
skel.emitNext();
println(" if ( zzNoLookAhead ) break zzForAction;");
skel.emitNext();
}
/**
* Escapes all " ' \ tabs and newlines
*/
private String escapify(String s) {
StringBuffer result = new StringBuffer(s.length()*2);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\'': result.append("\\\'"); break;
case '\"': result.append("\\\""); break;
case '\\': result.append("\\\\"); break;
case '\t': result.append("\\t"); break;
case '\r': if (i+1 == s.length() || s.charAt(i+1) != '\n') result.append("\"+ZZ_NL+\"");
break;
case '\n': result.append("\"+ZZ_NL+\""); break;
default: result.append(c);
}
}
return result.toString();
}
public void emitActionTable() {
int lastAction = 1;
int count = 0;
int value = 0;
println(" /** ");
println(" * Translates DFA states to action switch labels.");
println(" */");
CountEmitter e = new CountEmitter("Action");
e.emitInit();
for (int i = 0; i < dfa.numStates; i++) {
int newVal;
if ( dfa.isFinal[i] ) {
Action action = dfa.action[i];
Integer stored = (Integer) actionTable.get(action);
if ( stored == null ) {
stored = new Integer(lastAction++);
actionTable.put(action, stored);
}
newVal = stored.intValue();
}
else {
newVal = 0;
}
if (value == newVal) {
count++;
}
else {
if (count > 0) e.emit(count,value);
count = 1;
value = newVal;
}
}
if (count > 0) e.emit(count,value);
e.emitUnpack();
println(e.toString());
}
private void emitActions() {
println(" switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {");
int i = actionTable.size()+1;
Enumeration actions = actionTable.keys();
while ( actions.hasMoreElements() ) {
Action action = (Action) actions.nextElement();
int label = ((Integer) actionTable.get(action)).intValue();
println(" case "+label+": ");
if ( scanner.debugOption ) {
print(" System.out.println(");
if ( scanner.lineCount )
print("\"line: \"+(yyline+1)+\" \"+");
if ( scanner.columnCount )
print("\"col: \"+(yycolumn+1)+\" \"+");
println("\"match: --\"+yytext()+\"--\");");
print(" System.out.println(\"action ["+action.priority+"] { ");
print(escapify(action.content));
println(" }\");");
}
println(" { "+action.content);
println(" }");
println(" case "+(i++)+": break;");
}
}
private void emitEOFVal() {
EOFActions eofActions = parser.getEOFActions();
if ( scanner.eofCode != null )
println(" zzDoEOF();");
if ( eofActions.numActions() > 0 ) {
println(" switch (zzLexicalState) {");
Enumeration stateNames = scanner.states.names();
// record lex states already emitted:
Hashtable used = new Hashtable();
// pick a start value for break case labels.
// must be larger than any value of a lex state:
int last = dfa.numStates;
while ( stateNames.hasMoreElements() ) {
String name = (String) stateNames.nextElement();
int num = scanner.states.getNumber(name).intValue();
Action action = eofActions.getAction(num);
// only emit code if the lex state is not redundant, so
// that case labels don't overlap
// (redundant = points to the same dfa state as another one).
// applies only to scanners that don't use BOL, because
// in BOL scanners lex states get mapped at runtime, so
// case labels will always be unique.
boolean unused = true;
if (!scanner.bolUsed) {
Integer key = new Integer(dfa.lexState[2*num]);
unused = used.get(key) == null;
if (!unused)
Out.warning("Lexical states <"+name+"> and <"+used.get(key)+"> are equivalent.");
else
used.put(key,name);
}
if (action != null && unused) {
println(" case "+name+":");
println(" { "+action.content+" }");
println(" case "+(++last)+": break;");
}
}
println(" default:");
}
if (eofActions.getDefault() != null)
println(" { " + eofActions.getDefault().content + " }");
else if ( scanner.eofVal != null )
println(" { " + scanner.eofVal + " }");
else if ( scanner.isInteger )
println(" return YYEOF;");
else
println(" return null;");
if (eofActions.numActions() > 0)
println(" }");
}
private void emitState(int state) {
println(" case "+state+":");
println(" switch (zzInput) {");
int defaultTransition = getDefaultTransition(state);
for (int next = 0; next < dfa.numStates; next++) {
if ( next != defaultTransition && table[state][next] != null ) {
emitTransition(state, next);
}
}
if ( defaultTransition != DFA.NO_TARGET && noTarget[state] != null ) {
emitTransition(state, DFA.NO_TARGET);
}
emitDefaultTransition(state, defaultTransition);
println(" }");
println("");
}
private void emitTransition(int state, int nextState) {
CharSetEnumerator chars;
if (nextState != DFA.NO_TARGET)
chars = table[state][nextState].characters();
else
chars = noTarget[state].characters();
print(" case ");
print((int)chars.nextElement());
print(": ");
while ( chars.hasMoreElements() ) {
println();
print(" case ");
print((int)chars.nextElement());
print(": ");
}
if ( nextState != DFA.NO_TARGET ) {
if ( dfa.isFinal[nextState] )
print("zzIsFinal = true; ");
if ( dfa.isPushback[nextState] )
print("zzPushbackPosL = zzCurrentPosL; ");
if ( dfa.isLookEnd[nextState] )
print("zzPushback = true; ");
if ( !isTransition[nextState] )
print("zzNoLookAhead = true; ");
if ( nextState == state )
println("break zzForNext;");
else
println("zzState = "+nextState+"; break zzForNext;");
}
else
println("break zzForAction;");
}
private void emitDefaultTransition(int state, int nextState) {
print(" default: ");
if ( nextState != DFA.NO_TARGET ) {
if ( dfa.isFinal[nextState] )
print("zzIsFinal = true; ");
if ( dfa.isPushback[nextState] )
print("zzPushbackPosL = zzCurrentPosL; ");
if ( dfa.isLookEnd[nextState] )
print("zzPushback = true; ");
if ( !isTransition[nextState] )
print("zzNoLookAhead = true; ");
if ( nextState == state )
println("break zzForNext;");
else
println("zzState = "+nextState+"; break zzForNext;");
}
else
println( "break zzForAction;" );
}
private void emitPushback() {
println(" if (zzWasPushback)");
println(" zzMarkedPos = zzPushbackPosL;");
}
private int getDefaultTransition(int state) {
int max = 0;
for (int i = 0; i < dfa.numStates; i++) {
if ( table[state][max] == null )
max = i;
else
if ( table[state][i] != null && table[state][max].size() < table[state][i].size() )
max = i;
}
if ( table[state][max] == null ) return DFA.NO_TARGET;
if ( noTarget[state] == null ) return max;
if ( table[state][max].size() < noTarget[state].size() )
max = DFA.NO_TARGET;
return max;
}
// for switch statement:
private void transformTransitionTable() {
int numInput = parser.getCharClasses().getNumClasses()+1;
int i;
char j;
table = new CharSet[dfa.numStates][dfa.numStates];
noTarget = new CharSet[dfa.numStates];
for (i = 0; i < dfa.numStates; i++)
for (j = 0; j < dfa.numInput; j++) {
int nextState = dfa.table[i][j];
if ( nextState == DFA.NO_TARGET ) {
if ( noTarget[i] == null )
noTarget[i] = new CharSet(numInput, colMap[j]);
else
noTarget[i].add(colMap[j]);
}
else {
if ( table[i][nextState] == null )
table[i][nextState] = new CharSet(numInput, colMap[j]);
else
table[i][nextState].add(colMap[j]);
}
}
}
private void findActionStates() {
isTransition = new boolean [dfa.numStates];
for (int i = 0; i < dfa.numStates; i++) {
char j = 0;
while ( !isTransition[i] && j < dfa.numInput )
isTransition[i] = dfa.table[i][j++] != DFA.NO_TARGET;
}
}
private void reduceColumns() {
colMap = new int [dfa.numInput];
colKilled = new boolean [dfa.numInput];
int i,j,k;
int translate = 0;
boolean equal;
numCols = dfa.numInput;
for (i = 0; i < dfa.numInput; i++) {
colMap[i] = i-translate;
for (j = 0; j < i; j++) {
// test for equality:
k = -1;
equal = true;
while (equal && ++k < dfa.numStates)
equal = dfa.table[k][i] == dfa.table[k][j];
if (equal) {
translate++;
colMap[i] = colMap[j];
colKilled[i] = true;
numCols--;
break;
} // if
} // for j
} // for i
}
private void reduceRows() {
rowMap = new int [dfa.numStates];
rowKilled = new boolean [dfa.numStates];
int i,j,k;
int translate = 0;
boolean equal;
numRows = dfa.numStates;
// i is the state to add to the new table
for (i = 0; i < dfa.numStates; i++) {
rowMap[i] = i-translate;
// check if state i can be removed (i.e. already
// exists in entries 0..i-1)
for (j = 0; j < i; j++) {
// test for equality:
k = -1;
equal = true;
while (equal && ++k < dfa.numInput)
equal = dfa.table[i][k] == dfa.table[j][k];
if (equal) {
translate++;
rowMap[i] = rowMap[j];
rowKilled[i] = true;
numRows--;
break;
} // if
} // for j
} // for i
}
/**
* Set up EOF code sectioin according to scanner.eofcode
*/
private void setupEOFCode() {
if (scanner.eofclose) {
scanner.eofCode = LexScan.conc(scanner.eofCode, " yyclose();");
scanner.eofThrow = LexScan.concExc(scanner.eofThrow, "java.io.IOException");
}
}
/**
* Main Emitter method.
*/
public void emit() {
setupEOFCode();
if (scanner.functionName == null)
scanner.functionName = "yylex";
reduceColumns();
findActionStates();
emitHeader();
emitUserCode();
emitClassName();
skel.emitNext();
println(" private static final int ZZ_BUFFERSIZE = "+scanner.bufferSize+";");
if (scanner.debugOption) {
println(" private static final String ZZ_NL = System.getProperty(\"line.separator\");");
}
skel.emitNext();
emitLexicalStates();
emitCharMapArray();
emitActionTable();
if (scanner.useRowMap) {
reduceRows();
emitRowMapArray();
if (scanner.packed)
emitDynamicInit();
else
emitZZTrans();
}
skel.emitNext();
if (scanner.useRowMap)
emitAttributes();
skel.emitNext();
emitClassCode();
skel.emitNext();
emitConstructorDecl();
emitCharMapInitFunction();
skel.emitNext();
emitScanError();
skel.emitNext();
emitDoEOF();
skel.emitNext();
emitLexFunctHeader();
emitNextInput();
if (scanner.useRowMap)
emitGetRowMapNext();
else
emitTransitionTable();
if (scanner.lookAheadUsed)
emitPushback();
skel.emitNext();
emitActions();
skel.emitNext();
emitEOFVal();
skel.emitNext();
emitNoMatch();
skel.emitNext();
emitMain();
skel.emitNext();
out.close();
}
}
| false | true | private void emitLexFunctHeader() {
if (scanner.cupCompatible) {
// force public, because we have to implement java_cup.runtime.Symbol
print(" public ");
}
else {
print(" "+visibility+" ");
}
if ( scanner.tokenType == null ) {
if ( scanner.isInteger )
print( "int" );
else
if ( scanner.isIntWrap )
print( "Integer" );
else
print( "Yytoken" );
}
else
print( scanner.tokenType );
print(" ");
print(scanner.functionName);
print("() throws java.io.IOException");
if ( scanner.lexThrow != null ) {
print(", ");
print(scanner.lexThrow);
}
if ( scanner.scanErrorException != null ) {
print(", ");
print(scanner.scanErrorException);
}
println(" {");
skel.emitNext();
if ( scanner.useRowMap ) {
println(" int [] zzTransL = ZZ_TRANS;");
println(" int [] zzRowMapL = ZZ_ROWMAP;");
println(" int [] zzAttrL = ZZ_ATTRIBUTE;");
}
if ( scanner.lookAheadUsed ) {
println(" int zzPushbackPosL = zzPushbackPos = -1;");
println(" boolean zzWasPushback;");
}
skel.emitNext();
if ( scanner.charCount ) {
println(" yychar+= zzMarkedPosL-zzStartRead;");
println("");
}
if ( scanner.lineCount || scanner.columnCount ) {
println(" boolean zzR = false;");
println(" for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL;");
println(" zzCurrentPosL++) {");
println(" switch (zzBufferL[zzCurrentPosL]) {");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = false;");
println(" break;");
println(" case '\\r':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = true;");
println(" break;");
println(" case '\\n':");
println(" if (zzR)");
println(" zzR = false;");
println(" else {");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" }");
println(" break;");
println(" default:");
println(" zzR = false;");
if ( scanner.columnCount )
println(" yycolumn++;");
println(" }");
println(" }");
println();
if ( scanner.lineCount ) {
println(" if (zzR) {");
println(" // peek one character ahead if it is \\n (if we have counted one line too much)");
println(" boolean zzPeek;");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" else if (zzAtEOF)");
println(" zzPeek = false;");
println(" else {");
println(" boolean eof = zzRefill();");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzPeek = false;");
println(" else ");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" }");
println(" if (zzPeek) yyline--;");
println(" }");
}
}
if ( scanner.bolUsed ) {
// zzMarkedPos > zzStartRead <=> last match was not empty
// if match was empty, last value of zzAtBOL can be used
// zzStartRead is always >= 0
println(" if (zzMarkedPosL > zzStartRead) {");
println(" switch (zzBufferL[zzMarkedPosL-1]) {");
println(" case '\\n':");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
println(" zzAtBOL = true;");
println(" break;");
println(" case '\\r': ");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" else if (zzAtEOF)");
println(" zzAtBOL = false;");
println(" else {");
println(" boolean eof = zzRefill();");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzAtBOL = false;");
println(" else ");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" }");
println(" break;");
println(" default:");
println(" zzAtBOL = false;");
println(" }");
println(" }");
}
skel.emitNext();
if (scanner.bolUsed) {
println(" if (zzAtBOL)");
println(" zzState = ZZ_LEXSTATE[zzLexicalState+1];");
println(" else");
println(" zzState = ZZ_LEXSTATE[zzLexicalState];");
println();
}
else {
println(" zzState = zzLexicalState;");
println();
}
if (scanner.lookAheadUsed)
println(" zzWasPushback = false;");
skel.emitNext();
}
| private void emitLexFunctHeader() {
if (scanner.cupCompatible) {
// force public, because we have to implement java_cup.runtime.Symbol
print(" public ");
}
else {
print(" "+visibility+" ");
}
if ( scanner.tokenType == null ) {
if ( scanner.isInteger )
print( "int" );
else
if ( scanner.isIntWrap )
print( "Integer" );
else
print( "Yytoken" );
}
else
print( scanner.tokenType );
print(" ");
print(scanner.functionName);
print("() throws java.io.IOException");
if ( scanner.lexThrow != null ) {
print(", ");
print(scanner.lexThrow);
}
if ( scanner.scanErrorException != null ) {
print(", ");
print(scanner.scanErrorException);
}
println(" {");
skel.emitNext();
if ( scanner.useRowMap ) {
println(" int [] zzTransL = ZZ_TRANS;");
println(" int [] zzRowMapL = ZZ_ROWMAP;");
println(" int [] zzAttrL = ZZ_ATTRIBUTE;");
}
if ( scanner.lookAheadUsed ) {
println(" int zzPushbackPosL = zzPushbackPos = -1;");
println(" boolean zzWasPushback;");
}
skel.emitNext();
if ( scanner.charCount ) {
println(" yychar+= zzMarkedPosL-zzStartRead;");
println("");
}
if ( scanner.lineCount || scanner.columnCount ) {
println(" boolean zzR = false;");
println(" for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL;");
println(" zzCurrentPosL++) {");
println(" switch (zzBufferL[zzCurrentPosL]) {");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = false;");
println(" break;");
println(" case '\\r':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = true;");
println(" break;");
println(" case '\\n':");
println(" if (zzR)");
println(" zzR = false;");
println(" else {");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" }");
println(" break;");
println(" default:");
println(" zzR = false;");
if ( scanner.columnCount )
println(" yycolumn++;");
println(" }");
println(" }");
println();
if ( scanner.lineCount ) {
println(" if (zzR) {");
println(" // peek one character ahead if it is \\n (if we have counted one line too much)");
println(" boolean zzPeek;");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" else if (zzAtEOF)");
println(" zzPeek = false;");
println(" else {");
println(" boolean eof = zzRefill();");
println(" zzEndReadL = zzEndRead;");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzPeek = false;");
println(" else ");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" }");
println(" if (zzPeek) yyline--;");
println(" }");
}
}
if ( scanner.bolUsed ) {
// zzMarkedPos > zzStartRead <=> last match was not empty
// if match was empty, last value of zzAtBOL can be used
// zzStartRead is always >= 0
println(" if (zzMarkedPosL > zzStartRead) {");
println(" switch (zzBufferL[zzMarkedPosL-1]) {");
println(" case '\\n':");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
println(" zzAtBOL = true;");
println(" break;");
println(" case '\\r': ");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" else if (zzAtEOF)");
println(" zzAtBOL = false;");
println(" else {");
println(" boolean eof = zzRefill();");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzEndReadL = zzEndRead;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzAtBOL = false;");
println(" else ");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" }");
println(" break;");
println(" default:");
println(" zzAtBOL = false;");
println(" }");
println(" }");
}
skel.emitNext();
if (scanner.bolUsed) {
println(" if (zzAtBOL)");
println(" zzState = ZZ_LEXSTATE[zzLexicalState+1];");
println(" else");
println(" zzState = ZZ_LEXSTATE[zzLexicalState];");
println();
}
else {
println(" zzState = zzLexicalState;");
println();
}
if (scanner.lookAheadUsed)
println(" zzWasPushback = false;");
skel.emitNext();
}
|
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/DefaultEditorAdaptor.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/DefaultEditorAdaptor.java
index 1163080c..81298380 100644
--- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/DefaultEditorAdaptor.java
+++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/DefaultEditorAdaptor.java
@@ -1,578 +1,581 @@
package net.sourceforge.vrapper.vim;
import static java.lang.String.format;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import net.sourceforge.vrapper.keymap.KeyMap;
import net.sourceforge.vrapper.keymap.KeyStroke;
import net.sourceforge.vrapper.keymap.SpecialKey;
import net.sourceforge.vrapper.keymap.vim.SimpleKeyStroke;
import net.sourceforge.vrapper.log.VrapperLog;
import net.sourceforge.vrapper.platform.CommandLineUI;
import net.sourceforge.vrapper.platform.Configuration.Option;
import net.sourceforge.vrapper.platform.CursorService;
import net.sourceforge.vrapper.platform.FileService;
import net.sourceforge.vrapper.platform.HistoryService;
import net.sourceforge.vrapper.platform.KeyMapProvider;
import net.sourceforge.vrapper.platform.Platform;
import net.sourceforge.vrapper.platform.PlatformSpecificModeProvider;
import net.sourceforge.vrapper.platform.PlatformSpecificStateProvider;
import net.sourceforge.vrapper.platform.SearchAndReplaceService;
import net.sourceforge.vrapper.platform.SelectionService;
import net.sourceforge.vrapper.platform.ServiceProvider;
import net.sourceforge.vrapper.platform.TextContent;
import net.sourceforge.vrapper.platform.UnderlyingEditorSettings;
import net.sourceforge.vrapper.platform.UserInterfaceService;
import net.sourceforge.vrapper.platform.ViewportService;
import net.sourceforge.vrapper.utils.LineInformation;
import net.sourceforge.vrapper.utils.Position;
import net.sourceforge.vrapper.utils.SelectionArea;
import net.sourceforge.vrapper.vim.commands.Command;
import net.sourceforge.vrapper.vim.commands.CommandExecutionException;
import net.sourceforge.vrapper.vim.commands.Selection;
import net.sourceforge.vrapper.vim.modes.BlockwiseVisualMode;
import net.sourceforge.vrapper.vim.modes.ConfirmSubstitutionMode;
import net.sourceforge.vrapper.vim.modes.EditorMode;
import net.sourceforge.vrapper.vim.modes.InsertExpandMode;
import net.sourceforge.vrapper.vim.modes.InsertMode;
import net.sourceforge.vrapper.vim.modes.LinewiseVisualMode;
import net.sourceforge.vrapper.vim.modes.ModeSwitchHint;
import net.sourceforge.vrapper.vim.modes.NormalMode;
import net.sourceforge.vrapper.vim.modes.ReplaceMode;
import net.sourceforge.vrapper.vim.modes.VisualMode;
import net.sourceforge.vrapper.vim.modes.commandline.CommandLineMode;
import net.sourceforge.vrapper.vim.modes.commandline.CommandLineParser;
import net.sourceforge.vrapper.vim.modes.commandline.PasteRegisterMode;
import net.sourceforge.vrapper.vim.modes.commandline.SearchMode;
import net.sourceforge.vrapper.vim.register.DefaultRegisterManager;
import net.sourceforge.vrapper.vim.register.Register;
import net.sourceforge.vrapper.vim.register.RegisterManager;
import net.sourceforge.vrapper.vim.register.SimpleRegister;
public class DefaultEditorAdaptor implements EditorAdaptor {
// ugly global option, so unit tests can disable it
// in order to be .vrapperrc-agnostic
public static boolean SHOULD_READ_RC_FILE = true;
private static final String CONFIG_FILE_NAME = ".vrapperrc";
private static final String WINDOWS_CONFIG_FILE_NAME = "_vrapperrc";
private EditorMode currentMode;
private final Map<String, EditorMode> modeMap = new HashMap<String, EditorMode>();
private final TextContent modelContent;
private final TextContent viewContent;
private final CursorService cursorService;
private final SelectionService selectionService;
private final FileService fileService;
private RegisterManager registerManager;
private final RegisterManager globalRegisterManager;
private final ViewportService viewportService;
private final HistoryService historyService;
private final UserInterfaceService userInterfaceService;
private final ServiceProvider serviceProvider;
private final KeyStrokeTranslator keyStrokeTranslator;
private final KeyMapProvider keyMapProvider;
private final UnderlyingEditorSettings editorSettings;
private final LocalConfiguration configuration;
private final PlatformSpecificStateProvider platformSpecificStateProvider;
private final PlatformSpecificModeProvider platformSpecificModeProvider;
private final SearchAndReplaceService searchAndReplaceService;
private MacroRecorder macroRecorder;
private MacroPlayer macroPlayer;
private String lastModeName;
private String editorType;
public DefaultEditorAdaptor(final Platform editor, final RegisterManager registerManager, final boolean isActive) {
this.modelContent = editor.getModelContent();
this.viewContent = editor.getViewContent();
this.cursorService = editor.getCursorService();
this.selectionService = editor.getSelectionService();
this.historyService = editor.getHistoryService();
this.registerManager = registerManager;
this.globalRegisterManager = registerManager;
this.serviceProvider = editor.getServiceProvider();
this.editorSettings = editor.getUnderlyingEditorSettings();
this.configuration = new SimpleLocalConfiguration(editor.getConfiguration());
final LocalConfigurationListener listener = new LocalConfigurationListener() {
@Override
public <T> void optionChanged(final Option<T> option, final T oldValue, final T newValue) {
if("clipboard".equals(option.getId())) {
if("unnamed".equals(newValue)) {
final Register clipboardRegister = DefaultEditorAdaptor.this.getRegisterManager().getRegister(RegisterManager.REGISTER_NAME_CLIPBOARD);
DefaultEditorAdaptor.this.getRegisterManager().setDefaultRegister(clipboardRegister);
} else {
DefaultEditorAdaptor.this.getRegisterManager().setDefaultRegister(new SimpleRegister());
}
}
}
};
this.configuration.addListener(listener);
this.platformSpecificStateProvider = editor.getPlatformSpecificStateProvider();
this.platformSpecificModeProvider = editor.getPlatformSpecificModeProvider();
this.searchAndReplaceService = editor.getSearchAndReplaceService();
viewportService = editor.getViewportService();
userInterfaceService = editor.getUserInterfaceService();
keyMapProvider = editor.getKeyMapProvider();
keyStrokeTranslator = new KeyStrokeTranslator();
macroRecorder = new MacroRecorder(registerManager, userInterfaceService);
macroPlayer = null;
this.editorType = editor.getEditorType();
fileService = editor.getFileService();
__set_modes(this);
readConfiguration();
setNewLineFromFirstLine();
if (isActive) {
changeModeSafely(NormalMode.NAME);
}
}
public String getLastModeName() {
return lastModeName;
}
// this is public just for test purposes (Mockito spy as self)
public void __set_modes(final DefaultEditorAdaptor self) {
modeMap.clear();
final EditorMode[] modes = {
new NormalMode(self),
new VisualMode(self),
new LinewiseVisualMode(self),
new BlockwiseVisualMode(self),
new InsertMode(self),
new InsertExpandMode(self),
new ReplaceMode(self),
new CommandLineMode(self),
new SearchMode(self),
new ConfirmSubstitutionMode(self),
new PasteRegisterMode(self)};
for (final EditorMode mode: modes) {
modeMap.put(mode.getName(), mode);
}
}
@Override
public void changeModeSafely(final String name, final ModeSwitchHint... hints) {
try {
changeMode(name, hints);
} catch (final CommandExecutionException e) {
VrapperLog.error("exception when changing mode", e);
userInterfaceService.setErrorMessage(e.getMessage());
}
}
private void setNewLineFromFirstLine() {
if (modelContent.getNumberOfLines() > 1) {
final LineInformation first = modelContent.getLineInformation(0);
final LineInformation second = modelContent.getLineInformation(1);
final int start = first.getEndOffset();
final int end = second.getBeginOffset();
final String newLine = modelContent.getText(start, end-start);
configuration.setNewLine(newLine);
}
}
private void readConfiguration() {
if (!SHOULD_READ_RC_FILE) {
return;
}
String filename = CONFIG_FILE_NAME;
final File homeDir = new File(System.getProperty("user.home"));
File config = new File(homeDir, filename);
if( ! config.exists()) { //if no .vrapperrc, look for _vrapperrc
filename = WINDOWS_CONFIG_FILE_NAME;
config = new File(homeDir, filename);
}
if(config.exists()) {
sourceConfigurationFile(filename);
}
}
@Override
public boolean sourceConfigurationFile(final String filename) {
- final File homeDir = new File(System.getProperty("user.home"));
- final File config = new File(homeDir, filename);
+ File config = new File(filename);
+ if( ! config.isAbsolute()) {
+ final File homeDir = new File(System.getProperty("user.home"));
+ config = new File(homeDir, filename);
+ }
if(config.exists()) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(config));
String line;
final CommandLineParser parser = new CommandLineParser(this);
String trimmed;
while((line = reader.readLine()) != null) {
//*** skip over everything in a .vimrc file that we don't support ***//
trimmed = line.trim().toLowerCase();
//ignore comments and key mappings we don't support
if(trimmed.equals("") || trimmed.startsWith("\"") || trimmed.startsWith("let")
|| trimmed.contains("<leader>") || trimmed.contains("<silent>")) {
continue;
}
if(trimmed.startsWith("if")) {
//skip all conditional statements
while((line = reader.readLine()) != null) {
if(line.trim().toLowerCase().startsWith("endif")) {
break;
}
}
continue; //skip "endif" line
}
if(trimmed.startsWith("func")) {
//skip all function declarations
while((line = reader.readLine()) != null) {
if(line.trim().toLowerCase().startsWith("endfunc")) {
break;
}
}
continue; //skip "endfunction" line
}
if(trimmed.startsWith("try")) {
//skip all try declarations
while((line = reader.readLine()) != null) {
if(line.trim().toLowerCase().startsWith("endtry")) {
break;
}
}
continue; //skip "endtry" line
}
if(trimmed.startsWith(":")) {
//leading ':' is optional, skip it if it exists
line = line.substring(line.indexOf(':') +1);
}
//attempt to parse this line
Command c = parser.parseAndExecute(null, line.trim());
if (c != null) {
c.execute(this);
}
}
} catch (final FileNotFoundException e) {
// ignore
} catch (final IOException e) {
e.printStackTrace();
} catch (CommandExecutionException e) {
e.printStackTrace();
} finally {
if(reader != null) {
try {
reader.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
return true;
}
else {
return false;
}
}
@Override
public void changeMode(final String modeName, final ModeSwitchHint... args) throws CommandExecutionException {
EditorMode newMode = modeMap.get(modeName);
if (newMode == null) {
// Load extension modes
final List<EditorMode> modes = platformSpecificModeProvider.getModes(this);
for (final EditorMode mode : modes) {
if (modeMap.containsKey(mode.getName())) {
VrapperLog.error(format("Mode '%s' was already loaded!", mode.getName()));
} else {
modeMap.put(mode.getName(), mode);
}
}
newMode = modeMap.get(modeName);
if (newMode == null) {
VrapperLog.error(format("There is no mode named '%s'", modeName));
return;
}
}
if (currentMode != newMode) {
final EditorMode oldMode = currentMode;
if (currentMode != null) {
currentMode.leaveMode(args);
lastModeName = currentMode.getName();
}
try {
currentMode = newMode;
newMode.enterMode(args);
//EditorMode might have called changeMode again, so update UI with actual mode.
userInterfaceService.setEditorMode(currentMode.getDisplayName());
}
catch(final CommandExecutionException e) {
//failed to enter new mode, revert to previous mode
//then let Exception bubble up
currentMode = oldMode;
oldMode.enterMode();
//EditorMode might have called changeMode again, so update UI with actual mode.
userInterfaceService.setEditorMode(currentMode.getDisplayName());
throw e;
}
}
}
@Override
public boolean handleKey(final KeyStroke key) {
macroRecorder.handleKey(key);
return handleKeyOffRecord(key);
}
@Override
public boolean handleKeyOffRecord(final KeyStroke key) {
final boolean result = handleKey0(key);
if (macroPlayer != null) {
// while playing back one macro, another macro might be called
// recursively. we need a fresh macro player for that.
final MacroPlayer player = macroPlayer;
macroPlayer = null;
player.play();
}
return result;
}
@Override
public TextContent getModelContent() {
return modelContent;
}
@Override
public TextContent getViewContent() {
return viewContent;
}
@Override
public Position getPosition() {
return cursorService.getPosition();
}
@Override
public void setPosition(final Position destination, final boolean updateStickyColumn) {
cursorService.setPosition(destination, updateStickyColumn);
}
@Override
public Selection getSelection() {
return selectionService.getSelection();
}
@Override
public void setSelection(final Selection selection) {
selectionService.setSelection(selection);
}
@Override
public CursorService getCursorService() {
return cursorService;
}
@Override
public FileService getFileService() {
return fileService;
}
@Override
public ViewportService getViewportService() {
return viewportService;
}
@Override
public UserInterfaceService getUserInterfaceService() {
return userInterfaceService;
}
@Override
public RegisterManager getRegisterManager() {
return registerManager;
}
@Override
public HistoryService getHistory() {
return historyService;
}
@Override
public <T> T getService(final Class<T> serviceClass) {
return serviceProvider.getService(serviceClass);
}
@Override
public EditorMode getMode(final String name) {
return modeMap.get(name);
}
@Override
public KeyMapProvider getKeyMapProvider() {
return keyMapProvider;
}
@Override
public UnderlyingEditorSettings getEditorSettings() {
return editorSettings;
}
@Override
public PlatformSpecificStateProvider getPlatformSpecificStateProvider() {
return platformSpecificStateProvider;
}
@Override
public SearchAndReplaceService getSearchAndReplaceService() {
return searchAndReplaceService;
}
@Override
public void useGlobalRegisters() {
registerManager = globalRegisterManager;
swapMacroRecorder();
}
@Override
public void useLocalRegisters() {
registerManager = new DefaultRegisterManager();
swapMacroRecorder();
}
@Override
public LocalConfiguration getConfiguration() {
return configuration;
}
@Override
public MacroRecorder getMacroRecorder() {
return macroRecorder;
}
@Override
public MacroPlayer getMacroPlayer() {
if (macroPlayer == null) {
macroPlayer = new MacroPlayer(this);
}
return macroPlayer;
}
private void swapMacroRecorder() {
if (macroRecorder.isRecording()) {
macroRecorder.stopRecording();
}
macroRecorder = new MacroRecorder(registerManager, userInterfaceService);
}
/**
* Note from Kevin: This method is a major source of frustration for me.
* It has to handle the following scenarios but I can't unit test them:
* - multi-character mapping completed in InsertMode and NormalMode
* - multi-character mapping *not* completed in InsertMode and NormalMode
* - "nmap zx gg" and type 'zt'
* - "imap jj <ESC>" and type 'jk'
* - display pending character in InsertMode
* - and delete pending character when mapping completed
* - don't move cursor when not completing a multi-character mapping while inside parentheses
* - "for(int j=0)" when 'j' is part of a mapping ("imap jj <ESC>")
* - (Eclipse moves the cursor on me in its "Smart Insert" mode with auto-closing parentheses)
* - single-character mapping in InsertMode (perform mapping but don't display pending character)
*/
private boolean handleKey0(final KeyStroke key) {
if (currentMode != null) {
final KeyMap map = currentMode.resolveKeyMap(keyMapProvider);
if (map != null) {
final boolean inMapping = keyStrokeTranslator.processKeyStroke(map, key);
if (inMapping) {
final Queue<RemappedKeyStroke> resultingKeyStrokes =
keyStrokeTranslator.resultingKeyStrokes();
//if we're in a mapping in InsertMode, display the pending characters
//(we'll delete them if the user completes the mapping)
if(currentMode.getName() == InsertMode.NAME) {
//display pending character
if(resultingKeyStrokes.isEmpty()) {
return currentMode.handleKey(key);
}
//there are resulting key strokes,
//mapping exited either successfully or unsuccessfully
else if(keyStrokeTranslator.numUnconsumedKeys() > 0) {
if(keyStrokeTranslator.didMappingSucceed()) {
//delete all the pending characters we had displayed
for(int i=0; i < keyStrokeTranslator.numUnconsumedKeys(); i++) {
currentMode.handleKey(new RemappedKeyStroke(new SimpleKeyStroke(SpecialKey.BACKSPACE), false));
}
}
else {
//we've already displayed all but this most recent key
return currentMode.handleKey(key);
}
}
//else, mapping is only one character long (no pending characters to remove)
}
//play all resulting key strokes
while (!resultingKeyStrokes.isEmpty()) {
final RemappedKeyStroke next = resultingKeyStrokes.poll();
if (next.isRecursive()) {
handleKey(next);
} else {
currentMode.handleKey(next);
}
}
return true;
}
}
return currentMode.handleKey(key);
}
return false;
}
@Override
public void onChangeEnabled(final boolean enabled) {
if (enabled) {
// switch mode for set-up/tear-down
changeModeSafely(NormalMode.NAME, InsertMode.DONT_MOVE_CURSOR);
} else {
changeModeSafely(InsertMode.NAME, InsertMode.DONT_MOVE_CURSOR, InsertMode.DONT_LOCK_HISTORY);
userInterfaceService.setEditorMode(UserInterfaceService.VRAPPER_DISABLED);
}
}
@Override
public void rememberLastActiveSelection() {
Selection selection = selectionService.getSelection();
registerManager.setLastActiveSelection(selection, SelectionArea.getInstance(this));
cursorService.setMark(CursorService.LAST_SELECTION_START_MARK, selection.getStartMark(this));
cursorService.setMark(CursorService.LAST_SELECTION_END_MARK, selection.getEndMark(this));
}
@Override
public SelectionArea getLastActiveSelectionArea() {
return registerManager.getLastActiveSelectionArea();
}
@Override
public Selection getLastActiveSelection() {
return registerManager.getLastActiveSelection();
}
@Override
public String getCurrentModeName() {
return currentMode != null ? currentMode.getName() : null;
}
public String getEditorType() {
return editorType;
}
@Override
public CommandLineUI getCommandLine() {
return userInterfaceService.getCommandLineUI(this);
}
}
| true | true | public boolean sourceConfigurationFile(final String filename) {
final File homeDir = new File(System.getProperty("user.home"));
final File config = new File(homeDir, filename);
if(config.exists()) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(config));
String line;
final CommandLineParser parser = new CommandLineParser(this);
String trimmed;
while((line = reader.readLine()) != null) {
//*** skip over everything in a .vimrc file that we don't support ***//
trimmed = line.trim().toLowerCase();
//ignore comments and key mappings we don't support
if(trimmed.equals("") || trimmed.startsWith("\"") || trimmed.startsWith("let")
|| trimmed.contains("<leader>") || trimmed.contains("<silent>")) {
continue;
}
if(trimmed.startsWith("if")) {
//skip all conditional statements
while((line = reader.readLine()) != null) {
if(line.trim().toLowerCase().startsWith("endif")) {
break;
}
}
continue; //skip "endif" line
}
if(trimmed.startsWith("func")) {
//skip all function declarations
while((line = reader.readLine()) != null) {
if(line.trim().toLowerCase().startsWith("endfunc")) {
break;
}
}
continue; //skip "endfunction" line
}
if(trimmed.startsWith("try")) {
//skip all try declarations
while((line = reader.readLine()) != null) {
if(line.trim().toLowerCase().startsWith("endtry")) {
break;
}
}
continue; //skip "endtry" line
}
if(trimmed.startsWith(":")) {
//leading ':' is optional, skip it if it exists
line = line.substring(line.indexOf(':') +1);
}
//attempt to parse this line
Command c = parser.parseAndExecute(null, line.trim());
if (c != null) {
c.execute(this);
}
}
} catch (final FileNotFoundException e) {
// ignore
} catch (final IOException e) {
e.printStackTrace();
} catch (CommandExecutionException e) {
e.printStackTrace();
} finally {
if(reader != null) {
try {
reader.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
return true;
}
else {
return false;
}
}
| public boolean sourceConfigurationFile(final String filename) {
File config = new File(filename);
if( ! config.isAbsolute()) {
final File homeDir = new File(System.getProperty("user.home"));
config = new File(homeDir, filename);
}
if(config.exists()) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(config));
String line;
final CommandLineParser parser = new CommandLineParser(this);
String trimmed;
while((line = reader.readLine()) != null) {
//*** skip over everything in a .vimrc file that we don't support ***//
trimmed = line.trim().toLowerCase();
//ignore comments and key mappings we don't support
if(trimmed.equals("") || trimmed.startsWith("\"") || trimmed.startsWith("let")
|| trimmed.contains("<leader>") || trimmed.contains("<silent>")) {
continue;
}
if(trimmed.startsWith("if")) {
//skip all conditional statements
while((line = reader.readLine()) != null) {
if(line.trim().toLowerCase().startsWith("endif")) {
break;
}
}
continue; //skip "endif" line
}
if(trimmed.startsWith("func")) {
//skip all function declarations
while((line = reader.readLine()) != null) {
if(line.trim().toLowerCase().startsWith("endfunc")) {
break;
}
}
continue; //skip "endfunction" line
}
if(trimmed.startsWith("try")) {
//skip all try declarations
while((line = reader.readLine()) != null) {
if(line.trim().toLowerCase().startsWith("endtry")) {
break;
}
}
continue; //skip "endtry" line
}
if(trimmed.startsWith(":")) {
//leading ':' is optional, skip it if it exists
line = line.substring(line.indexOf(':') +1);
}
//attempt to parse this line
Command c = parser.parseAndExecute(null, line.trim());
if (c != null) {
c.execute(this);
}
}
} catch (final FileNotFoundException e) {
// ignore
} catch (final IOException e) {
e.printStackTrace();
} catch (CommandExecutionException e) {
e.printStackTrace();
} finally {
if(reader != null) {
try {
reader.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
return true;
}
else {
return false;
}
}
|
diff --git a/src/web/ScrimmagesServlet.java b/src/web/ScrimmagesServlet.java
index b9d266e..51fb778 100644
--- a/src/web/ScrimmagesServlet.java
+++ b/src/web/ScrimmagesServlet.java
@@ -1,191 +1,191 @@
package web;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import master.AbstractMaster;
import model.BSScrimmageSet;
import model.STATUS;
import model.TEAM;
import common.BSUtil;
import common.HibernateUtil;
public class ScrimmagesServlet extends HttpServlet {
private static final long serialVersionUID = -4741371113331532230L;
public static final String NAME = "/scrimmages.html";
private void warn(HttpServletResponse response, String warning) throws IOException {
response.getWriter().println("<p class='ui-state-error' style='padding:10px'>" + warning + "</p>");
}
private void highlight(HttpServletResponse response, String msg) throws IOException {
response.getWriter().println("<p class='ui-state-highlight' style='padding:10px'>" + msg + "</p>");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Send them to the upload servlet if they haven't uploaded battlecode files yet
if (!BSUtil.initializedBattlecode()) {
response.sendRedirect(UploadServlet.NAME);
return;
}
if (!request.getRequestURI().equals("/") && !request.getRequestURI().equals(NAME)) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println("<html><head>");
out.println("<title>Battlecode Tester</title>");
out.println("<link rel=\"stylesheet\" href=\"/css/table.css\" />");
out.println("</head>");
out.println("<body>");
WebUtil.writeTabs(request, response, NAME);
out.println("<script src='js/jquery.dataTables.min.js'></script>");
if (request.getParameter("submit-scrimmage") != null) {
File scrimmage = (File) request.getAttribute("scrimmage");
String scrimmageName = request.getParameter("scrimmageName").trim().replaceAll("\\s", "_");
if (scrimmage == null || !scrimmage.exists() || scrimmage.isDirectory()) {
warn(response, "Please select a valid map file");
} else if (scrimmageName == null || scrimmageName.isEmpty() || scrimmageName.contains("/")) {
warn(response, "Scrimmage file has invalid name");
} else {
BSScrimmageSet scrim = new BSScrimmageSet();
scrim.setFileName(scrimmageName);
scrim.setStatus(STATUS.QUEUED);
scrim.setPlayerA("");
scrim.setPlayerB("");
if (new File(scrim.toPath()).exists()) {
warn(response, "Scrimmage " + scrimmageName + " already exists!");
} else {
BSUtil.writeFileData(scrimmage, scrim.toPath());
highlight(response, "Successfully uploaded map: " + scrimmageName);
// Don't spawn a new thread because we *want* the new web thread to block
AbstractMaster.getMaster().analyzeScrimmageMatch(scrim);
}
}
}
EntityManager em = HibernateUtil.getEntityManager();
// Begin the upload form
out.println("<form id='scrimmageForm' action='" + response.encodeURL(NAME) + "' method='post' enctype='multipart/form-data'>");
out.println("<table>");
out.println("<tr>" +
"<td style='text-align:right'>Scrimmage:</td>" +
"<td><input type='file' name='scrimmage' id='scrimFile' /></td>" +
"</tr>");
out.println("<tr><td></td>" +
"<td><input type='submit' name='submit-scrimmage' value='Upload'/></td>" +
"</tr>");
out.println("</table>");
out.println("<input id='scrimmageName' type='hidden' name='scrimmageName' />");
out.println("</form>");
out.println("<table id=\"scrim_table\" class='datatable datatable-clickable'>" +
"<thead>" +
"<tr>" +
"<th>Scrimmage ID</th>" +
"<th>Name</th>" +
"<th>Team A</th>" +
"<th>Team B</th>" +
"<th>Status</th>" +
"<th>Control</th>" +
"</tr>" +
"</thead>" +
"<tbody>");
List<BSScrimmageSet> scrimmages = em.createQuery("from BSScrimmageSet", BSScrimmageSet.class).getResultList();
String myTeam = null;
// Try to find out what team we are
ArrayList<String> possibleTeams = new ArrayList<String>();
if (scrimmages.size() > 0) {
possibleTeams.add(scrimmages.get(0).getPlayerA());
possibleTeams.add(scrimmages.get(0).getPlayerB());
}
for (BSScrimmageSet s: scrimmages) {
if (possibleTeams.isEmpty())
break;
for (int i = 0; i < possibleTeams.size(); i++) {
boolean remove = true;
- if (s.getPlayerA().equals("") || s.getPlayerA().equals(possibleTeams.get(0))) {
+ if (s.getPlayerA().equals("") || s.getPlayerA().equals(possibleTeams.get(i))) {
remove = false;
}
- if (s.getPlayerB().equals("") || s.getPlayerB().equals(possibleTeams.get(0))) {
+ if (s.getPlayerB().equals("") || s.getPlayerB().equals(possibleTeams.get(i))) {
remove = false;
}
if (remove) {
possibleTeams.remove(i);
i--;
}
}
}
if (possibleTeams.size() == 1) {
myTeam = possibleTeams.get(0);
}
for (BSScrimmageSet s: scrimmages) {
String td;
// Make scrimmages with data clickable
//TODO: move this into js
if (s.getStatus() == STATUS.COMPLETE || s.getStatus() == STATUS.CANCELED)
td = "<td onClick='doNavMatches(" + s.getId() + ")'>";
else
td = "<td>";
if (myTeam == null || s.getPlayerA().equals("")) {
out.println("<tr>");
} else {
boolean won = (s.getPlayerA().equals(myTeam) && s.getWinner() == TEAM.A) ||
(s.getPlayerB().equals(myTeam) && s.getWinner() == TEAM.B);
out.println("<tr class='" + (won ? "win" : "loss") + "'>");
}
out.println(td + s.getId() + "</td>" +
td + s.getFileName() + "</td>" +
td + s.getPlayerA() + "</td>" +
td + s.getPlayerB() + "</td>" +
td + s.getStatus() + "</td>");
switch (s.getStatus()){
case QUEUED:
out.println("<td><input type=\"button\" value=\"dequeue\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
break;
case RUNNING:
out.println("<td><input type=\"button\" value=\"cancel\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
break;
case COMPLETE:
case CANCELED:
out.println("<td><input type=\"button\" value=\"delete\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
break;
default:
out.println("<td><input type=\"button\" value=\"delete\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
}
out.println("</tr>");
}
out.println("</tbody>");
out.println("</table>");
out.println("</div>");
out.println("<script type=\"text/javascript\">var myTeam = '" + myTeam + "'</script>");
out.println("<script type=\"text/javascript\" src=\"js/bsUtil.js\"></script>");
out.println("<script type=\"text/javascript\" src=\"js/scrimmage.js\"></script>");
out.println("</body></html>");
em.close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| false | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Send them to the upload servlet if they haven't uploaded battlecode files yet
if (!BSUtil.initializedBattlecode()) {
response.sendRedirect(UploadServlet.NAME);
return;
}
if (!request.getRequestURI().equals("/") && !request.getRequestURI().equals(NAME)) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println("<html><head>");
out.println("<title>Battlecode Tester</title>");
out.println("<link rel=\"stylesheet\" href=\"/css/table.css\" />");
out.println("</head>");
out.println("<body>");
WebUtil.writeTabs(request, response, NAME);
out.println("<script src='js/jquery.dataTables.min.js'></script>");
if (request.getParameter("submit-scrimmage") != null) {
File scrimmage = (File) request.getAttribute("scrimmage");
String scrimmageName = request.getParameter("scrimmageName").trim().replaceAll("\\s", "_");
if (scrimmage == null || !scrimmage.exists() || scrimmage.isDirectory()) {
warn(response, "Please select a valid map file");
} else if (scrimmageName == null || scrimmageName.isEmpty() || scrimmageName.contains("/")) {
warn(response, "Scrimmage file has invalid name");
} else {
BSScrimmageSet scrim = new BSScrimmageSet();
scrim.setFileName(scrimmageName);
scrim.setStatus(STATUS.QUEUED);
scrim.setPlayerA("");
scrim.setPlayerB("");
if (new File(scrim.toPath()).exists()) {
warn(response, "Scrimmage " + scrimmageName + " already exists!");
} else {
BSUtil.writeFileData(scrimmage, scrim.toPath());
highlight(response, "Successfully uploaded map: " + scrimmageName);
// Don't spawn a new thread because we *want* the new web thread to block
AbstractMaster.getMaster().analyzeScrimmageMatch(scrim);
}
}
}
EntityManager em = HibernateUtil.getEntityManager();
// Begin the upload form
out.println("<form id='scrimmageForm' action='" + response.encodeURL(NAME) + "' method='post' enctype='multipart/form-data'>");
out.println("<table>");
out.println("<tr>" +
"<td style='text-align:right'>Scrimmage:</td>" +
"<td><input type='file' name='scrimmage' id='scrimFile' /></td>" +
"</tr>");
out.println("<tr><td></td>" +
"<td><input type='submit' name='submit-scrimmage' value='Upload'/></td>" +
"</tr>");
out.println("</table>");
out.println("<input id='scrimmageName' type='hidden' name='scrimmageName' />");
out.println("</form>");
out.println("<table id=\"scrim_table\" class='datatable datatable-clickable'>" +
"<thead>" +
"<tr>" +
"<th>Scrimmage ID</th>" +
"<th>Name</th>" +
"<th>Team A</th>" +
"<th>Team B</th>" +
"<th>Status</th>" +
"<th>Control</th>" +
"</tr>" +
"</thead>" +
"<tbody>");
List<BSScrimmageSet> scrimmages = em.createQuery("from BSScrimmageSet", BSScrimmageSet.class).getResultList();
String myTeam = null;
// Try to find out what team we are
ArrayList<String> possibleTeams = new ArrayList<String>();
if (scrimmages.size() > 0) {
possibleTeams.add(scrimmages.get(0).getPlayerA());
possibleTeams.add(scrimmages.get(0).getPlayerB());
}
for (BSScrimmageSet s: scrimmages) {
if (possibleTeams.isEmpty())
break;
for (int i = 0; i < possibleTeams.size(); i++) {
boolean remove = true;
if (s.getPlayerA().equals("") || s.getPlayerA().equals(possibleTeams.get(0))) {
remove = false;
}
if (s.getPlayerB().equals("") || s.getPlayerB().equals(possibleTeams.get(0))) {
remove = false;
}
if (remove) {
possibleTeams.remove(i);
i--;
}
}
}
if (possibleTeams.size() == 1) {
myTeam = possibleTeams.get(0);
}
for (BSScrimmageSet s: scrimmages) {
String td;
// Make scrimmages with data clickable
//TODO: move this into js
if (s.getStatus() == STATUS.COMPLETE || s.getStatus() == STATUS.CANCELED)
td = "<td onClick='doNavMatches(" + s.getId() + ")'>";
else
td = "<td>";
if (myTeam == null || s.getPlayerA().equals("")) {
out.println("<tr>");
} else {
boolean won = (s.getPlayerA().equals(myTeam) && s.getWinner() == TEAM.A) ||
(s.getPlayerB().equals(myTeam) && s.getWinner() == TEAM.B);
out.println("<tr class='" + (won ? "win" : "loss") + "'>");
}
out.println(td + s.getId() + "</td>" +
td + s.getFileName() + "</td>" +
td + s.getPlayerA() + "</td>" +
td + s.getPlayerB() + "</td>" +
td + s.getStatus() + "</td>");
switch (s.getStatus()){
case QUEUED:
out.println("<td><input type=\"button\" value=\"dequeue\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
break;
case RUNNING:
out.println("<td><input type=\"button\" value=\"cancel\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
break;
case COMPLETE:
case CANCELED:
out.println("<td><input type=\"button\" value=\"delete\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
break;
default:
out.println("<td><input type=\"button\" value=\"delete\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
}
out.println("</tr>");
}
out.println("</tbody>");
out.println("</table>");
out.println("</div>");
out.println("<script type=\"text/javascript\">var myTeam = '" + myTeam + "'</script>");
out.println("<script type=\"text/javascript\" src=\"js/bsUtil.js\"></script>");
out.println("<script type=\"text/javascript\" src=\"js/scrimmage.js\"></script>");
out.println("</body></html>");
em.close();
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Send them to the upload servlet if they haven't uploaded battlecode files yet
if (!BSUtil.initializedBattlecode()) {
response.sendRedirect(UploadServlet.NAME);
return;
}
if (!request.getRequestURI().equals("/") && !request.getRequestURI().equals(NAME)) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println("<html><head>");
out.println("<title>Battlecode Tester</title>");
out.println("<link rel=\"stylesheet\" href=\"/css/table.css\" />");
out.println("</head>");
out.println("<body>");
WebUtil.writeTabs(request, response, NAME);
out.println("<script src='js/jquery.dataTables.min.js'></script>");
if (request.getParameter("submit-scrimmage") != null) {
File scrimmage = (File) request.getAttribute("scrimmage");
String scrimmageName = request.getParameter("scrimmageName").trim().replaceAll("\\s", "_");
if (scrimmage == null || !scrimmage.exists() || scrimmage.isDirectory()) {
warn(response, "Please select a valid map file");
} else if (scrimmageName == null || scrimmageName.isEmpty() || scrimmageName.contains("/")) {
warn(response, "Scrimmage file has invalid name");
} else {
BSScrimmageSet scrim = new BSScrimmageSet();
scrim.setFileName(scrimmageName);
scrim.setStatus(STATUS.QUEUED);
scrim.setPlayerA("");
scrim.setPlayerB("");
if (new File(scrim.toPath()).exists()) {
warn(response, "Scrimmage " + scrimmageName + " already exists!");
} else {
BSUtil.writeFileData(scrimmage, scrim.toPath());
highlight(response, "Successfully uploaded map: " + scrimmageName);
// Don't spawn a new thread because we *want* the new web thread to block
AbstractMaster.getMaster().analyzeScrimmageMatch(scrim);
}
}
}
EntityManager em = HibernateUtil.getEntityManager();
// Begin the upload form
out.println("<form id='scrimmageForm' action='" + response.encodeURL(NAME) + "' method='post' enctype='multipart/form-data'>");
out.println("<table>");
out.println("<tr>" +
"<td style='text-align:right'>Scrimmage:</td>" +
"<td><input type='file' name='scrimmage' id='scrimFile' /></td>" +
"</tr>");
out.println("<tr><td></td>" +
"<td><input type='submit' name='submit-scrimmage' value='Upload'/></td>" +
"</tr>");
out.println("</table>");
out.println("<input id='scrimmageName' type='hidden' name='scrimmageName' />");
out.println("</form>");
out.println("<table id=\"scrim_table\" class='datatable datatable-clickable'>" +
"<thead>" +
"<tr>" +
"<th>Scrimmage ID</th>" +
"<th>Name</th>" +
"<th>Team A</th>" +
"<th>Team B</th>" +
"<th>Status</th>" +
"<th>Control</th>" +
"</tr>" +
"</thead>" +
"<tbody>");
List<BSScrimmageSet> scrimmages = em.createQuery("from BSScrimmageSet", BSScrimmageSet.class).getResultList();
String myTeam = null;
// Try to find out what team we are
ArrayList<String> possibleTeams = new ArrayList<String>();
if (scrimmages.size() > 0) {
possibleTeams.add(scrimmages.get(0).getPlayerA());
possibleTeams.add(scrimmages.get(0).getPlayerB());
}
for (BSScrimmageSet s: scrimmages) {
if (possibleTeams.isEmpty())
break;
for (int i = 0; i < possibleTeams.size(); i++) {
boolean remove = true;
if (s.getPlayerA().equals("") || s.getPlayerA().equals(possibleTeams.get(i))) {
remove = false;
}
if (s.getPlayerB().equals("") || s.getPlayerB().equals(possibleTeams.get(i))) {
remove = false;
}
if (remove) {
possibleTeams.remove(i);
i--;
}
}
}
if (possibleTeams.size() == 1) {
myTeam = possibleTeams.get(0);
}
for (BSScrimmageSet s: scrimmages) {
String td;
// Make scrimmages with data clickable
//TODO: move this into js
if (s.getStatus() == STATUS.COMPLETE || s.getStatus() == STATUS.CANCELED)
td = "<td onClick='doNavMatches(" + s.getId() + ")'>";
else
td = "<td>";
if (myTeam == null || s.getPlayerA().equals("")) {
out.println("<tr>");
} else {
boolean won = (s.getPlayerA().equals(myTeam) && s.getWinner() == TEAM.A) ||
(s.getPlayerB().equals(myTeam) && s.getWinner() == TEAM.B);
out.println("<tr class='" + (won ? "win" : "loss") + "'>");
}
out.println(td + s.getId() + "</td>" +
td + s.getFileName() + "</td>" +
td + s.getPlayerA() + "</td>" +
td + s.getPlayerB() + "</td>" +
td + s.getStatus() + "</td>");
switch (s.getStatus()){
case QUEUED:
out.println("<td><input type=\"button\" value=\"dequeue\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
break;
case RUNNING:
out.println("<td><input type=\"button\" value=\"cancel\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
break;
case COMPLETE:
case CANCELED:
out.println("<td><input type=\"button\" value=\"delete\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
break;
default:
out.println("<td><input type=\"button\" value=\"delete\" onclick=\"delScrimmage(" + s.getId() + ")\"></td>");
}
out.println("</tr>");
}
out.println("</tbody>");
out.println("</table>");
out.println("</div>");
out.println("<script type=\"text/javascript\">var myTeam = '" + myTeam + "'</script>");
out.println("<script type=\"text/javascript\" src=\"js/bsUtil.js\"></script>");
out.println("<script type=\"text/javascript\" src=\"js/scrimmage.js\"></script>");
out.println("</body></html>");
em.close();
}
|
diff --git a/src/test/java/net/floodlightcontroller/debugevent/DebugEventTest.java b/src/test/java/net/floodlightcontroller/debugevent/DebugEventTest.java
index 1ceb2781..175b3d0d 100644
--- a/src/test/java/net/floodlightcontroller/debugevent/DebugEventTest.java
+++ b/src/test/java/net/floodlightcontroller/debugevent/DebugEventTest.java
@@ -1,107 +1,107 @@
package net.floodlightcontroller.debugevent;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.floodlightcontroller.debugevent.IDebugEventService.DebugEventInfo;
import net.floodlightcontroller.debugevent.IDebugEventService.EventColumn;
import net.floodlightcontroller.debugevent.IDebugEventService.EventFieldType;
import net.floodlightcontroller.debugevent.IDebugEventService.EventType;
import net.floodlightcontroller.debugevent.IDebugEventService.MaxEventsRegistered;
import net.floodlightcontroller.test.FloodlightTestCase;
public class DebugEventTest extends FloodlightTestCase {
DebugEvent debugEvent;
protected static Logger log = LoggerFactory.getLogger(DebugEventTest.class);
@Override
@Before
public void setUp() throws Exception {
debugEvent = new DebugEvent();
}
@Test
public void testRegisterAndUpdateEvent() {
assertEquals(0, debugEvent.currentEvents.size());
IEventUpdater<SwitchyEvent> event1 = null;
IEventUpdater<PacketyEvent> event2 = null;
try {
event1 = debugEvent.registerEvent("dbgevtest", "switchevent",
"switchtest", EventType.ALWAYS_LOG,
SwitchyEvent.class, 100);
event2 = debugEvent.registerEvent("dbgevtest", "pktinevent",
"pktintest", EventType.ALWAYS_LOG,
PacketyEvent.class, 100);
} catch (MaxEventsRegistered e) {
e.printStackTrace();
}
assertEquals(2, debugEvent.currentEvents.size());
assertTrue(null != debugEvent.moduleEvents.get("dbgevtest").
get("switchevent"));
int eventId1 = debugEvent.moduleEvents.get("dbgevtest").
get("switchevent");
assertTrue(null != debugEvent.moduleEvents.get("dbgevtest").
get("pktinevent"));
int eventId2 = debugEvent.moduleEvents.get("dbgevtest").
get("pktinevent");
assertEquals(true, debugEvent.containsModuleName("dbgevtest"));
assertEquals(true, debugEvent.containsModuleEventName("dbgevtest","switchevent"));
assertEquals(true, debugEvent.containsModuleEventName("dbgevtest","pktinevent"));
assertEquals(0, debugEvent.allEvents[eventId1].eventBuffer.size());
assertEquals(0, debugEvent.allEvents[eventId2].eventBuffer.size());
// update is immediately flushed to global store
event1.updateEventWithFlush(new SwitchyEvent(1L, "connected"));
assertEquals(1, debugEvent.allEvents[eventId1].eventBuffer.size());
// update is flushed only when flush is explicitly called
event2.updateEventNoFlush(new PacketyEvent(1L, 24L));
assertEquals(0, debugEvent.allEvents[eventId2].eventBuffer.size());
debugEvent.flushEvents();
assertEquals(1, debugEvent.allEvents[eventId1].eventBuffer.size());
assertEquals(1, debugEvent.allEvents[eventId2].eventBuffer.size());
DebugEventInfo de = debugEvent.getSingleEventHistory("dbgevtest","switchevent");
assertEquals(1, de.events.size());
- assertEquals(true, de.events.get(0)
- .contains("dpid=00:00:00:00:00:00:00:01, reason=connected"));
+ assertEquals(true, de.events.get(0).get("dpid").equals("00:00:00:00:00:00:00:01"));
+ assertEquals(true, de.events.get(0).get("reason").equals("connected"));
DebugEventInfo de2 = debugEvent.getSingleEventHistory("dbgevtest","pktinevent");
assertEquals(1, de2.events.size());
- assertEquals(true, de2.events.get(0)
- .contains("dpid=00:00:00:00:00:00:00:01, srcMac=00:00:00:00:00:18"));
+ assertEquals(true, de2.events.get(0).get("dpid").equals("00:00:00:00:00:00:00:01"));
+ assertEquals(true, de2.events.get(0).get("srcMac").equals("00:00:00:00:00:18"));
}
public class SwitchyEvent {
@EventColumn(name = "dpid", description = EventFieldType.DPID)
long dpid;
@EventColumn(name = "reason", description = EventFieldType.STRING)
String reason;
public SwitchyEvent(long dpid, String reason) {
this.dpid = dpid;
this.reason = reason;
}
}
public class PacketyEvent {
@EventColumn(name = "dpid", description = EventFieldType.DPID)
long dpid;
@EventColumn(name = "srcMac", description = EventFieldType.MAC)
long mac;
public PacketyEvent(long dpid, long mac) {
this.dpid = dpid;
this.mac = mac;
}
}
}
| false | true | public void testRegisterAndUpdateEvent() {
assertEquals(0, debugEvent.currentEvents.size());
IEventUpdater<SwitchyEvent> event1 = null;
IEventUpdater<PacketyEvent> event2 = null;
try {
event1 = debugEvent.registerEvent("dbgevtest", "switchevent",
"switchtest", EventType.ALWAYS_LOG,
SwitchyEvent.class, 100);
event2 = debugEvent.registerEvent("dbgevtest", "pktinevent",
"pktintest", EventType.ALWAYS_LOG,
PacketyEvent.class, 100);
} catch (MaxEventsRegistered e) {
e.printStackTrace();
}
assertEquals(2, debugEvent.currentEvents.size());
assertTrue(null != debugEvent.moduleEvents.get("dbgevtest").
get("switchevent"));
int eventId1 = debugEvent.moduleEvents.get("dbgevtest").
get("switchevent");
assertTrue(null != debugEvent.moduleEvents.get("dbgevtest").
get("pktinevent"));
int eventId2 = debugEvent.moduleEvents.get("dbgevtest").
get("pktinevent");
assertEquals(true, debugEvent.containsModuleName("dbgevtest"));
assertEquals(true, debugEvent.containsModuleEventName("dbgevtest","switchevent"));
assertEquals(true, debugEvent.containsModuleEventName("dbgevtest","pktinevent"));
assertEquals(0, debugEvent.allEvents[eventId1].eventBuffer.size());
assertEquals(0, debugEvent.allEvents[eventId2].eventBuffer.size());
// update is immediately flushed to global store
event1.updateEventWithFlush(new SwitchyEvent(1L, "connected"));
assertEquals(1, debugEvent.allEvents[eventId1].eventBuffer.size());
// update is flushed only when flush is explicitly called
event2.updateEventNoFlush(new PacketyEvent(1L, 24L));
assertEquals(0, debugEvent.allEvents[eventId2].eventBuffer.size());
debugEvent.flushEvents();
assertEquals(1, debugEvent.allEvents[eventId1].eventBuffer.size());
assertEquals(1, debugEvent.allEvents[eventId2].eventBuffer.size());
DebugEventInfo de = debugEvent.getSingleEventHistory("dbgevtest","switchevent");
assertEquals(1, de.events.size());
assertEquals(true, de.events.get(0)
.contains("dpid=00:00:00:00:00:00:00:01, reason=connected"));
DebugEventInfo de2 = debugEvent.getSingleEventHistory("dbgevtest","pktinevent");
assertEquals(1, de2.events.size());
assertEquals(true, de2.events.get(0)
.contains("dpid=00:00:00:00:00:00:00:01, srcMac=00:00:00:00:00:18"));
}
| public void testRegisterAndUpdateEvent() {
assertEquals(0, debugEvent.currentEvents.size());
IEventUpdater<SwitchyEvent> event1 = null;
IEventUpdater<PacketyEvent> event2 = null;
try {
event1 = debugEvent.registerEvent("dbgevtest", "switchevent",
"switchtest", EventType.ALWAYS_LOG,
SwitchyEvent.class, 100);
event2 = debugEvent.registerEvent("dbgevtest", "pktinevent",
"pktintest", EventType.ALWAYS_LOG,
PacketyEvent.class, 100);
} catch (MaxEventsRegistered e) {
e.printStackTrace();
}
assertEquals(2, debugEvent.currentEvents.size());
assertTrue(null != debugEvent.moduleEvents.get("dbgevtest").
get("switchevent"));
int eventId1 = debugEvent.moduleEvents.get("dbgevtest").
get("switchevent");
assertTrue(null != debugEvent.moduleEvents.get("dbgevtest").
get("pktinevent"));
int eventId2 = debugEvent.moduleEvents.get("dbgevtest").
get("pktinevent");
assertEquals(true, debugEvent.containsModuleName("dbgevtest"));
assertEquals(true, debugEvent.containsModuleEventName("dbgevtest","switchevent"));
assertEquals(true, debugEvent.containsModuleEventName("dbgevtest","pktinevent"));
assertEquals(0, debugEvent.allEvents[eventId1].eventBuffer.size());
assertEquals(0, debugEvent.allEvents[eventId2].eventBuffer.size());
// update is immediately flushed to global store
event1.updateEventWithFlush(new SwitchyEvent(1L, "connected"));
assertEquals(1, debugEvent.allEvents[eventId1].eventBuffer.size());
// update is flushed only when flush is explicitly called
event2.updateEventNoFlush(new PacketyEvent(1L, 24L));
assertEquals(0, debugEvent.allEvents[eventId2].eventBuffer.size());
debugEvent.flushEvents();
assertEquals(1, debugEvent.allEvents[eventId1].eventBuffer.size());
assertEquals(1, debugEvent.allEvents[eventId2].eventBuffer.size());
DebugEventInfo de = debugEvent.getSingleEventHistory("dbgevtest","switchevent");
assertEquals(1, de.events.size());
assertEquals(true, de.events.get(0).get("dpid").equals("00:00:00:00:00:00:00:01"));
assertEquals(true, de.events.get(0).get("reason").equals("connected"));
DebugEventInfo de2 = debugEvent.getSingleEventHistory("dbgevtest","pktinevent");
assertEquals(1, de2.events.size());
assertEquals(true, de2.events.get(0).get("dpid").equals("00:00:00:00:00:00:00:01"));
assertEquals(true, de2.events.get(0).get("srcMac").equals("00:00:00:00:00:18"));
}
|
diff --git a/src/com/example/wheresmystuff/Presenter/UnlockUser.java b/src/com/example/wheresmystuff/Presenter/UnlockUser.java
index f7e1765..e4d7664 100644
--- a/src/com/example/wheresmystuff/Presenter/UnlockUser.java
+++ b/src/com/example/wheresmystuff/Presenter/UnlockUser.java
@@ -1,33 +1,33 @@
package com.example.wheresmystuff.Presenter;
import com.example.wheresmystuff.Model.IModel;
import com.example.wheresmystuff.View.LockOrUnlock;
public class UnlockUser {
private final IModel myModel;
private final LockOrUnlock myView;
public UnlockUser(LockOrUnlock v, IModel m) {
myModel = m;
myView = v;
}
public void unlockUser(String username) {
myModel.open();
if (myModel.find_uid(username)) {
- myModel.setLocked(username);
+ myModel.unlockAccount(username);
myView.notify_of_error("Unlocked " + username);
}else{
myView.notify_of_error("User not Found");
}
myModel.close();
}
}
| true | true | public void unlockUser(String username) {
myModel.open();
if (myModel.find_uid(username)) {
myModel.setLocked(username);
myView.notify_of_error("Unlocked " + username);
}else{
myView.notify_of_error("User not Found");
}
myModel.close();
}
| public void unlockUser(String username) {
myModel.open();
if (myModel.find_uid(username)) {
myModel.unlockAccount(username);
myView.notify_of_error("Unlocked " + username);
}else{
myView.notify_of_error("User not Found");
}
myModel.close();
}
|
diff --git a/core/src/com/google/inject/internal/Nullability.java b/core/src/com/google/inject/internal/Nullability.java
index cd99579d..fe72f007 100644
--- a/core/src/com/google/inject/internal/Nullability.java
+++ b/core/src/com/google/inject/internal/Nullability.java
@@ -1,31 +1,33 @@
package com.google.inject.internal;
import java.lang.annotation.Annotation;
/**
* Whether a member supports null values injected.
*
* <p>Support for {@code Nullable} annotations in Guice is loose.
* Any annotation type whose simplename is "Nullable" is sufficient to indicate
* support for null values injected.
*
* <p>This allows support for JSR-305's
* <a href="http://groups.google.com/group/jsr-305/web/proposed-annotations">
* javax.annotation.meta.Nullable</a> annotation and IntelliJ IDEA's
* <a href="http://www.jetbrains.com/idea/documentation/howto.html">
* org.jetbrains.annotations.Nullable</a>.
*
* @author [email protected] (Jesse Wilson)
*/
public class Nullability {
private Nullability() {}
public static boolean allowsNull(Annotation[] annotations) {
for(Annotation a : annotations) {
- if ("Nullable".equals(a.annotationType().getSimpleName())) {
+ String name = a.annotationType().getSimpleName();
+ // Check for $Nullable also because jarjar renames it.
+ if ("Nullable".equals(name) || "$Nullable".equals(name)) {
return true;
}
}
return false;
}
}
| true | true | public static boolean allowsNull(Annotation[] annotations) {
for(Annotation a : annotations) {
if ("Nullable".equals(a.annotationType().getSimpleName())) {
return true;
}
}
return false;
}
| public static boolean allowsNull(Annotation[] annotations) {
for(Annotation a : annotations) {
String name = a.annotationType().getSimpleName();
// Check for $Nullable also because jarjar renames it.
if ("Nullable".equals(name) || "$Nullable".equals(name)) {
return true;
}
}
return false;
}
|
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/ChangeApi.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/ChangeApi.java
index 23cd917f0..10dac18c9 100644
--- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/ChangeApi.java
+++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/ChangeApi.java
@@ -1,44 +1,43 @@
// 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.google.gerrit.client.changes;
import com.google.gerrit.client.rpc.RestApi;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwtjsonrpc.common.AsyncCallback;
/**
* A collection of static methods which work on the Gerrit REST API for specific
* changes.
*/
public class ChangeApi {
private static final String URI = "/changes/";
private static class Message extends JavaScriptObject {
public final native void setMessage(String value) /*-{ this.message = value; }-*/;
}
/**
* Sends a REST call to abandon a change and notify a callback. TODO: switch
* to use the new id triplet (project~branch~change) once that data is
* available to the UI.
*/
public static void abandon(int changeId, String message,
AsyncCallback<ChangeInfo> callback) {
- RestApi call = new RestApi(URI + changeId + "/abandon");
Message msg = new Message();
msg.setMessage(message);
- call.post(msg, callback);
+ new RestApi(URI + changeId + "/abandon").data(msg).post(callback);
}
}
| false | true | public static void abandon(int changeId, String message,
AsyncCallback<ChangeInfo> callback) {
RestApi call = new RestApi(URI + changeId + "/abandon");
Message msg = new Message();
msg.setMessage(message);
call.post(msg, callback);
}
| public static void abandon(int changeId, String message,
AsyncCallback<ChangeInfo> callback) {
Message msg = new Message();
msg.setMessage(message);
new RestApi(URI + changeId + "/abandon").data(msg).post(callback);
}
|
diff --git a/src/main/java/com/reubenpeeris/maven/lombokeclipsecompiler/LombokEclipseCompiler.java b/src/main/java/com/reubenpeeris/maven/lombokeclipsecompiler/LombokEclipseCompiler.java
index af3a360..cf4bd28 100644
--- a/src/main/java/com/reubenpeeris/maven/lombokeclipsecompiler/LombokEclipseCompiler.java
+++ b/src/main/java/com/reubenpeeris/maven/lombokeclipsecompiler/LombokEclipseCompiler.java
@@ -1,119 +1,121 @@
package com.reubenpeeris.maven.lombokeclipsecompiler;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.codehaus.plexus.compiler.AbstractCompiler;
import org.codehaus.plexus.compiler.CompilerConfiguration;
import org.codehaus.plexus.compiler.CompilerException;
import org.codehaus.plexus.compiler.CompilerMessage;
import org.codehaus.plexus.compiler.CompilerOutputStyle;
import org.codehaus.plexus.compiler.CompilerResult;
import org.codehaus.plexus.util.IOUtil;
import org.eclipse.jdt.internal.compiler.batch.Main;
import static com.reubenpeeris.maven.lombokeclipsecompiler.Utils.findJava;
import static com.reubenpeeris.maven.lombokeclipsecompiler.Utils.getFromList;
import static com.reubenpeeris.maven.lombokeclipsecompiler.Utils.getJarFor;
import static com.reubenpeeris.maven.lombokeclipsecompiler.Utils.toPath;
public class LombokEclipseCompiler extends AbstractCompiler {
private static final String JVM_PROPERTY_PREFIX = "-J";
private static final String LOMBOK_JAR_PROPERTY = "-L-lombokjar";
public LombokEclipseCompiler() {
super(CompilerOutputStyle.ONE_OUTPUT_FILE_PER_INPUT_FILE, ".java",
".class", null);
}
@Override
public CompilerResult performCompile(CompilerConfiguration config)
throws CompilerException {
File javaExe = findJava();
String lombokJarRegex = config.getCustomCompilerArgumentsAsMap().get(LOMBOK_JAR_PROPERTY);
if (lombokJarRegex == null) {
lombokJarRegex = ".*/lombok-[^/]*\\.jar";
}
String lombokJar = getFromList(lombokJarRegex, config.getClasspathEntries(), "Lombok jars");
List<String> commandLine = new ArrayList<String>();
commandLine.add(javaExe.getAbsolutePath());
String jdtJar = getJarFor(org.eclipse.jdt.internal.compiler.Compiler.class);
for (Map.Entry<String, String> entry : config.getCustomCompilerArgumentsAsMap().entrySet()) {
if (entry.getKey().startsWith(JVM_PROPERTY_PREFIX)) {
commandLine.add(entry.getKey().substring(JVM_PROPERTY_PREFIX.length()));
if (entry.getValue() != null) {
commandLine.add(entry.getValue());
}
}
}
if (config.getMeminitial() != null) {
commandLine.add("-Xms" + config.getMeminitial());
}
if (config.getMaxmem() != null) {
commandLine.add("-Xmx" + config.getMaxmem());
}
commandLine.add("-Xbootclasspath/a:" + jdtJar);
if (lombokJar != null) {
//No Kind produces an INFO message in the output
// messages.add(new CompilerMessage("Using Lombok from '" + lombokJar + "'", Kind.NOTE));
System.out.println("[INFO] Using Lombok from '" + lombokJar + "'");
commandLine.add("-Xbootclasspath/a:" + lombokJar);
commandLine.add("-javaagent:" + lombokJar);
}
commandLine.add(Main.class.getCanonicalName());
commandLine.add("-source");
commandLine.add(config.getSourceVersion());
commandLine.add("-target");
commandLine.add(config.getTargetVersion());
commandLine.add("-encoding");
commandLine.add(config.getSourceEncoding());
commandLine.add("-cp");
commandLine.add(toPath(config.getClasspathEntries()));
commandLine.add("-d");
commandLine.add(config.getOutputLocation());
for (Map.Entry<String, String> entry : config.getCustomCompilerArgumentsAsMap().entrySet()) {
if (!entry.getKey().equals(LOMBOK_JAR_PROPERTY) && !entry.getKey().startsWith(JVM_PROPERTY_PREFIX)) {
commandLine.add(entry.getKey());
if (entry.getValue() != null) {
commandLine.add(entry.getValue());
}
}
}
commandLine.addAll(config.getSourceLocations());
ProcessBuilder pb = new ProcessBuilder(commandLine);
pb.redirectErrorStream(true);
pb.directory(config.getWorkingDirectory());
try {
Process process = pb.start();
IOUtil.copy(process.getInputStream(), System.out);
+ int result = process.waitFor();
System.out.println();
- int result = process.exitValue();
return new CompilerResult(result == 0, Collections.<CompilerMessage>emptyList());
} catch (IOException e) {
- throw new RuntimeException(e);
- }
+ throw new RuntimeException(e);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
}
@Override
public String[] createCommandLine(CompilerConfiguration config)
throws CompilerException {
return null;
}
}
| false | true | public CompilerResult performCompile(CompilerConfiguration config)
throws CompilerException {
File javaExe = findJava();
String lombokJarRegex = config.getCustomCompilerArgumentsAsMap().get(LOMBOK_JAR_PROPERTY);
if (lombokJarRegex == null) {
lombokJarRegex = ".*/lombok-[^/]*\\.jar";
}
String lombokJar = getFromList(lombokJarRegex, config.getClasspathEntries(), "Lombok jars");
List<String> commandLine = new ArrayList<String>();
commandLine.add(javaExe.getAbsolutePath());
String jdtJar = getJarFor(org.eclipse.jdt.internal.compiler.Compiler.class);
for (Map.Entry<String, String> entry : config.getCustomCompilerArgumentsAsMap().entrySet()) {
if (entry.getKey().startsWith(JVM_PROPERTY_PREFIX)) {
commandLine.add(entry.getKey().substring(JVM_PROPERTY_PREFIX.length()));
if (entry.getValue() != null) {
commandLine.add(entry.getValue());
}
}
}
if (config.getMeminitial() != null) {
commandLine.add("-Xms" + config.getMeminitial());
}
if (config.getMaxmem() != null) {
commandLine.add("-Xmx" + config.getMaxmem());
}
commandLine.add("-Xbootclasspath/a:" + jdtJar);
if (lombokJar != null) {
//No Kind produces an INFO message in the output
// messages.add(new CompilerMessage("Using Lombok from '" + lombokJar + "'", Kind.NOTE));
System.out.println("[INFO] Using Lombok from '" + lombokJar + "'");
commandLine.add("-Xbootclasspath/a:" + lombokJar);
commandLine.add("-javaagent:" + lombokJar);
}
commandLine.add(Main.class.getCanonicalName());
commandLine.add("-source");
commandLine.add(config.getSourceVersion());
commandLine.add("-target");
commandLine.add(config.getTargetVersion());
commandLine.add("-encoding");
commandLine.add(config.getSourceEncoding());
commandLine.add("-cp");
commandLine.add(toPath(config.getClasspathEntries()));
commandLine.add("-d");
commandLine.add(config.getOutputLocation());
for (Map.Entry<String, String> entry : config.getCustomCompilerArgumentsAsMap().entrySet()) {
if (!entry.getKey().equals(LOMBOK_JAR_PROPERTY) && !entry.getKey().startsWith(JVM_PROPERTY_PREFIX)) {
commandLine.add(entry.getKey());
if (entry.getValue() != null) {
commandLine.add(entry.getValue());
}
}
}
commandLine.addAll(config.getSourceLocations());
ProcessBuilder pb = new ProcessBuilder(commandLine);
pb.redirectErrorStream(true);
pb.directory(config.getWorkingDirectory());
try {
Process process = pb.start();
IOUtil.copy(process.getInputStream(), System.out);
System.out.println();
int result = process.exitValue();
return new CompilerResult(result == 0, Collections.<CompilerMessage>emptyList());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
| public CompilerResult performCompile(CompilerConfiguration config)
throws CompilerException {
File javaExe = findJava();
String lombokJarRegex = config.getCustomCompilerArgumentsAsMap().get(LOMBOK_JAR_PROPERTY);
if (lombokJarRegex == null) {
lombokJarRegex = ".*/lombok-[^/]*\\.jar";
}
String lombokJar = getFromList(lombokJarRegex, config.getClasspathEntries(), "Lombok jars");
List<String> commandLine = new ArrayList<String>();
commandLine.add(javaExe.getAbsolutePath());
String jdtJar = getJarFor(org.eclipse.jdt.internal.compiler.Compiler.class);
for (Map.Entry<String, String> entry : config.getCustomCompilerArgumentsAsMap().entrySet()) {
if (entry.getKey().startsWith(JVM_PROPERTY_PREFIX)) {
commandLine.add(entry.getKey().substring(JVM_PROPERTY_PREFIX.length()));
if (entry.getValue() != null) {
commandLine.add(entry.getValue());
}
}
}
if (config.getMeminitial() != null) {
commandLine.add("-Xms" + config.getMeminitial());
}
if (config.getMaxmem() != null) {
commandLine.add("-Xmx" + config.getMaxmem());
}
commandLine.add("-Xbootclasspath/a:" + jdtJar);
if (lombokJar != null) {
//No Kind produces an INFO message in the output
// messages.add(new CompilerMessage("Using Lombok from '" + lombokJar + "'", Kind.NOTE));
System.out.println("[INFO] Using Lombok from '" + lombokJar + "'");
commandLine.add("-Xbootclasspath/a:" + lombokJar);
commandLine.add("-javaagent:" + lombokJar);
}
commandLine.add(Main.class.getCanonicalName());
commandLine.add("-source");
commandLine.add(config.getSourceVersion());
commandLine.add("-target");
commandLine.add(config.getTargetVersion());
commandLine.add("-encoding");
commandLine.add(config.getSourceEncoding());
commandLine.add("-cp");
commandLine.add(toPath(config.getClasspathEntries()));
commandLine.add("-d");
commandLine.add(config.getOutputLocation());
for (Map.Entry<String, String> entry : config.getCustomCompilerArgumentsAsMap().entrySet()) {
if (!entry.getKey().equals(LOMBOK_JAR_PROPERTY) && !entry.getKey().startsWith(JVM_PROPERTY_PREFIX)) {
commandLine.add(entry.getKey());
if (entry.getValue() != null) {
commandLine.add(entry.getValue());
}
}
}
commandLine.addAll(config.getSourceLocations());
ProcessBuilder pb = new ProcessBuilder(commandLine);
pb.redirectErrorStream(true);
pb.directory(config.getWorkingDirectory());
try {
Process process = pb.start();
IOUtil.copy(process.getInputStream(), System.out);
int result = process.waitFor();
System.out.println();
return new CompilerResult(result == 0, Collections.<CompilerMessage>emptyList());
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/src/com/lge/app/floating/FloatingWindow.java b/src/com/lge/app/floating/FloatingWindow.java
index d84f0c4..e939ef4 100755
--- a/src/com/lge/app/floating/FloatingWindow.java
+++ b/src/com/lge/app/floating/FloatingWindow.java
@@ -1,1965 +1,1965 @@
package com.lge.app.floating;
import java.lang.reflect.*;
import android.animation.*;
import android.content.*;
import android.content.res.*;
import android.graphics.*;
import android.graphics.drawable.*;
import android.util.*;
import android.view.*;
import android.view.View.OnTouchListener;
import android.view.animation.*;
import android.widget.*;
import android.widget.SeekBar.OnSeekBarChangeListener;
/**
* Implements a window that can be floating around the screen. Instance of this class can be obtained
* by {@link FloatableActivity.getFloatingWindow}.
*
*/
public class FloatingWindow {
private final static String TAG = FloatingWindow.class.getSimpleName();
/**
* Determines how a floating window is laid out on the screen. Use
* {@link FloatingWindow.updateLayoutParams} to apply this information to a
* specific floating window.
*
*/
public static class LayoutParams implements Cloneable {
/**
* Information about whether the overlay slider is used or not. It is
* used to make the floating window to be semi-transparent. Default
* value is true.
*/
public boolean useOverlay = true;
/**
* Information about whether title and content area are overlapped or
* not. Default value is false.
*/
public boolean useOverlappingTitle = false;
/**
* Information about how the window is resized. See {@link ResizeOption}
* . Default value is {@link ResizeOption.ARBITRARY}.
*/
public int resizeOption = ResizeOption.CONTINUOUS | ResizeOption.ARBITRARY;
/**
* Information about how the window is moved on the screen. See
* {@link MoveOption}. Default value is {@link MoveOption.BOTH}.
*/
public int moveOption = MoveOption.BOTH;
/**
* Information about title bar is hidden or not. Default value is false.
*/
public boolean hideTitle = false;
/**
* Information about 'return to full screen' button is hidden or not.
* Default value is false.
*/
public boolean hideFullScreenButton = false;
/**
* Information about whether double tapping the title minimizes the
* window. Default value is false.
*/
public boolean useDoubleTapMinimize = false;
/**
* x position of the window on the screen in pixels.
*/
public int x;
/**
* y position of the window on the screen in pixels.
*/
public int y;
/**
* width of the window on the screen in pixels.
*/
public int width; // TODO: need to support WRAP_CONTENT, MATCH_PARENT,
// ...
/**
* height of the window on the screen in pixels.
*/
public int height; // TODO: need to support WRAP_CONTENT, MATCH_PARENT,
// ...
/**
* Ratio of the maximum height compared to the short axis of the screen
* Should be in between 0.0f and 1.0f.
*/
public float maxHeightWeight;
/**
* Ratio of the maximum height compared to the short axis of the screen
* Should be in between 0.0f and 1.0f.
*/
public float minHeightWeight;
/**
* Ratio of the maximum width compared to the short axis of the screen
* Should be in between 0.0f and 1.0f.
*/
public float maxWidthWeight;
/**
* Ratio of the minimum width compared to the short axis of the screen
* Should be in between 0.0f and 1.0f.
*/
public float minWidthWeight;
/**
* Creates layout parameters with default values.
*/
public LayoutParams(Context context) {
Resources res = context.getResources();
x = res.getDimensionPixelSize(R.dimen.floating_default_x);
y = res.getDimensionPixelSize(R.dimen.floating_default_y);
width = res.getDimensionPixelSize(R.dimen.floating_default_width);
height = res.getDimensionPixelSize(R.dimen.floating_default_height);
maxHeightWeight = res.getFraction(R.fraction.floating_max_height_percentage, 1, 1);
minHeightWeight = res.getFraction(R.fraction.floating_min_height_percentage, 1, 1);
maxWidthWeight = res.getFraction(R.fraction.floating_max_width_percentage, 1, 1);
minWidthWeight = res.getFraction(R.fraction.floating_min_width_percentage, 1, 1);
}
@Override
public LayoutParams clone() {
try {
return (LayoutParams) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
@Override
public String toString() {
//TODO: implement this
return "";
}
}
/**
* Interface definition for a callback to be invoked when a floating window
* status is changed. In order to register the listener, use
* {@link FloatingWindow.setOnUpdateListener}.
*/
public static interface OnUpdateListener {
/**
* Called when a floating window has been resized.
*
* @param window
* The window that has been resized.
* @param width
* The updated window width.
* @param height
* The updated window height.
*/
void onResizing(FloatingWindow window, int width, int height);
/**
* Called when user starts to drag the resize handle
*
* @param window
* the window that is being resized
*/
void onResizeStarted(FloatingWindow window);
/**
* Called when resize is canceled by rotating the phone or entering the
* keyguard
*
* @param window
* the window that was being resized
*/
void onResizeCanceled(FloatingWindow window);
// TODO: need to give the old width and height
/**
* Called when a floating window has been moved.
*
* @param window
* The window that has been moved.
* @param x
* The x coordinate of window left-top.
* @param y
* The y coordinate of window left-top.
*/
void onMoving(FloatingWindow window, int x, int y);
/**
* Called when the switch to full button is clicked. Returning true will
* make the window to return to full mode. Returning false will prevent
* the window from switching to full.
*
* @param window
* @return true for switching, false for preventing switching.
*/
boolean onSwitchFullRequested(FloatingWindow window);
// TODO: need to give the old x and y
/**
* Called when a floating window has switched to full mode.
*
* @param window
* The window that has switched to full mode.
*/
void onSwitchingFull(FloatingWindow window);
/**
* Called when a floating window has switched to/from minimized mode.
*
* @param window
* The window that has switched to full mode.
* @param flag
* True if the window has been minimized, false otherwise.
*/
void onSwitchingMinimized(FloatingWindow window, boolean flag);
/**
* Called when the close button is clicked. Returning true will make the
* window to be closed. Returning false will prevent the window from
* being closed.
*
* @param window
* @return true for closing, false for preventing closing.
*/
boolean onCloseRequested(FloatingWindow window);
/**
* Called when a floating window is about to be closed.
*
* @param window
* The window that is about to be closed.
*/
void onClosing(FloatingWindow window);
/**
* Called when a floating window is moved to the top
*
* @param window
* the window that is moved to the top
*/
void onMoveToTop(FloatingWindow window);
}
public static class DefaultOnUpdateListener implements OnUpdateListener {
@Override
public void onResizing(FloatingWindow window, int width, int height) {}
@Override
public void onResizeStarted(FloatingWindow window) {}
@Override
public void onResizeCanceled(FloatingWindow window) {}
@Override
public void onMoving(FloatingWindow window, int x, int y) {}
@Override
public boolean onSwitchFullRequested(FloatingWindow window) {return true;}
@Override
public void onSwitchingFull(FloatingWindow window) {}
@Override
public void onSwitchingMinimized(FloatingWindow window, boolean flag) {}
@Override
public boolean onCloseRequested(FloatingWindow window) {return true;}
@Override
public void onClosing(FloatingWindow window) {}
@Override
public void onMoveToTop(FloatingWindow window) {}
}
/**
* Determines how a user can resize a floating window. Note that setting
* this values does NOT affect the behavior of
* {@link FloatingWindow.setSize}. Even though {@link DISABLED} is used,
* <code>setSize</code> will alter the window size. This option only affects
* how the user is allowed to resize the window.
*/
public final static class ResizeOption {
/** Resize is not allowed */
public static final int DISABLED = 0x00;
/** Resize is allowed in horizontal direction */
public static final int HORIZONTAL = 0x01;
/** Resize is allowed in vertical direction */
public static final int VERTICAL = 0x02;
/** Resize is allowed in both vertical and horizontal direction */
public static final int ARBITRARY = HORIZONTAL | VERTICAL;
/**
* Resize is allowed in both directions but maintaining its aspect ratio
*/
public static final int PROPORTIONAL = 0x07;
/** User can resize the window continuously */
public static final int CONTINUOUS = 0x00;
/** User can resize the window discretely by one quarter of screen */
public static final int DISCRETE_QUARTER = 0x10;
private ResizeOption() {
// cannot create an instance of this class
}
}
/**
* Determines how a user can move a floating window. Note that setting this
* values does NOT affect the behavior of {@link FloatingWindow.move}. Even
* though {@link DISABLED} is used, <code>move</code> will alter the window
* position. This option only affects who the user is allowed to move the
* window.
*/
public final static class MoveOption {
/** move is not allowed */
public static final int DISABLED = 0x00;
/** Horizontal move only is allowed */
public static final int HORIZONTAL = 0x01;
/** Vertical move only is allowed */
public static final int VERTICAL = 0x02;
/** move in both directions are allowed */
public static final int BOTH = HORIZONTAL | VERTICAL;
private MoveOption() {
// cannot create an instance of this class
}
}
/**
* Determines how a user can customize title bar options. Use
* {@link FloatingWindow.getTitleViewTag} to apply this information to a
* specific title bar options.
*/
public final static class Tag {
/** customize layout background */
public static final String TITLE_BACKGROUND = "tag_layout";
/** customize full screen button */
public static final String FULLSCREEN_BUTTON = "tag_fullscreen_button";
/** customize overlay button */
public static final String OVERLAY_BUTTON = "tag_overlay_button";
/** customize title text */
public static final String TITLE_TEXT = "tag_textview";
/** customize seekbar */
public static final String SEEKBAR = "tag_seekbar";
/** customize close button */
public static final String CLOSE_BUTTON = "tag_close_button";
/** customize custom button */
public static final String CUSTOM_BUTTON = "tag_custom_button";
/** frame background */
public static final String MAIN_BACKGROUND = "tag_frame";
/** resize handle */
public static final String RESIZE_HANDLE = "tag_resize_handle";
private Tag() {
// cannot create an instance of this class
}
}
private final TitleView mTitleView;
private final FrameView mFrameView;
private ResizeFrame mResizeFrame; // not final
private final FloatableActivity mActivity;
private final String mActivityName;
private final FloatingWindowManager mFloatingWindowManager;
private final WindowManager mWindowManager;
private final LayoutInflater mInflater;
private LayoutParams mLayout;
private float mAlpha = 1.0f;
private boolean mIsInOverlayMode = false;
private boolean mIsMinimized = false;
private boolean mIsAttached = false;
private boolean mIsPortrait = true;
private boolean mLayoutLimit = false;
private boolean mIsMoving = false;
private boolean mIsResizing = false;
// layout parameters just before IME window is appeared
private WindowManager.LayoutParams mSavedParams;
private OnUpdateListener mUpdateListener;
private boolean mRedirectMoveToDown;
private int frameWindowX;
private int frameWindowY;
private int titleWindowX;
private int titleWindowY;
private int frameWindowH;
private int frameWindowW;
private int titleWindowH;
private int titleWindowW;
private Configuration mSavedConfig = new Configuration();
/**
* Creates a new floating window
*
* @param activity
* the activity that this floating window will be attached to
* @param windowManager
* the floating window manager that manages this window
* @param activityName
* the name of the activity
* @param params
* the initial layout parameter
*/
/* package */FloatingWindow(FloatableActivity activity, FloatingWindowManager windowManager, String activityName,
LayoutParams params) {
mFloatingWindowManager = windowManager;
mActivity = activity;
mActivityName = activityName;
mWindowManager = windowManager.getRealWindowManager();
mInflater = windowManager.getLayoutInflater();
mLayout = params.clone();
mFrameView = new FrameView();
mTitleView = new TitleView();
mFrameView.setTitleView(mTitleView);
mIsPortrait = activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
mSavedConfig.updateFrom(activity.getResources().getConfiguration());
}
/**
* Returns the view that renders the title area of this floating window
*
* @return the title view
*/
public TitleView getTitleView() {
return mTitleView;
}
/**
* Finds a view in the floating window with a tag. Refer {@link FloatingWindow.Tag}
*
* @return the View with the tag
*/
public View findViewWithTag(Object tag) {
View v = getTitleView().findViewWithTag(tag);
if (v != null) {
return v;
}
else {
return getFrameView().findViewWithTag(tag);
}
}
/**
* Returns the frame view which is the root view of this floating window
*
* @return the frame view
*/
public FrameView getFrameView() {
return mFrameView;
}
/**
* Returns the name of the activity that this floating window created for
*
* @return the name of the activity
*/
public String getActivityName() {
return mActivityName;
}
/**
* Returns the layout parameters for this floating window. Note that the
* returned layout parameter is a new copy of the existing one. Therefore,
* modifying the fields in the returned object does NOT affect the behavior
* of this floating window. In order to make the modified fields affective,
* you should call {@link updateLayoutParams}.
*
* @return the copy of the current layout parameters
*/
public LayoutParams getLayoutParams() {
return (LayoutParams) mLayout.clone();
}
/**
* Updates this floating window according to the new layout parameters.
*
* @param params
* the new layout parameters
* @param preferSavedRegion
* whether to prefer saved region
*/
public void updateLayoutParams(LayoutParams params, boolean preferSavedRegion) {
if (preferSavedRegion) {
SharedPreferences prefs = mActivity.getPreferences(Context.MODE_PRIVATE);
params.x = prefs.getInt("floating_x", params.x);
params.y = prefs.getInt("floating_y", params.y);
params.width = prefs.getInt("floating_w", params.width);
params.height = prefs.getInt("floating_h", params.height);
}
if (mLayout != params) {
mLayout = params.clone();
}
// calculate the window position and size
updateRealPositionAndSize();
// update the content of title and frame views
if (mIsAttached) {
getTitleView().update();
getFrameView().update();
}
// update the window position and size
move(params.x, params.y);
setSize(params.width, params.height);
}
/**
* Shortcut for updateLayoutParams(params, false);
*
* @param params
* the new layout parameters
*/
public void updateLayoutParams(LayoutParams params) {
updateLayoutParams(params, false);
}
/**
* Sets the content view of this floating window. Content view is actually
* inside the main view. If there already is a content view added, the old
* view is automatically removed prior to add the new view. Application
* should keep track of the view.
*
* @param v
* the root view of the new content that will be displayed in the
* floating window.
*/
public void setContentView(View v) {
if (v != null) {
setSurfaceViewBackgroundAsTransparentRecursively(v);
}
getFrameView().setContentView(v);
// FIXME: dirty hack
if (mIsAttached) {
setOpacity(mAlpha);
}
}
/**
* Returns the content view of this floating window.
*
* @return the root view of the content that is being displayed in the
* floating window.
*/
public View getContentView() {
return getFrameView().getContentView();
}
private void updateRealPositionAndSize() {
Rect padding = getFrameView().getPadding();
int titleHeight = getTitleView().measureAndGetHeight();
frameWindowX = titleWindowX = (mLayout.x - padding.left);
frameWindowW = titleWindowW = (mLayout.width + padding.left + padding.right);
// title is not shown
if (mLayout.useOverlappingTitle || (mLayout.hideTitle && !isInOverlay() && !mIsMoving && !mIsResizing)) {
frameWindowY = titleWindowY = (mLayout.y - padding.top);
titleWindowH = titleHeight + padding.top;
frameWindowH = mLayout.height + padding.top + padding.bottom;
}
// title is shown
else {
frameWindowY = titleWindowY = (mLayout.y - titleHeight - padding.top);
titleWindowH = titleHeight + padding.top;
frameWindowH = titleHeight + mLayout.height + padding.top + padding.bottom;
}
}
private int[] convertViewPositionToWindowPosition(View v, int x, int y) {
Rect padding = getFrameView().getPadding();
int[] positionInWindow = new int[2];
int viewLocation[] = new int[2];
v.getLocationInWindow(viewLocation);
positionInWindow[0] = viewLocation[0] + x - padding.left;
if ((mLayout.hideTitle && !isInOverlay() && !mIsMoving && !mIsResizing) || mLayout.useOverlappingTitle) {
positionInWindow[1] = viewLocation[1] + y - padding.top;
}
else {
positionInWindow[1] = viewLocation[1] + y - getTitleView().measureAndGetHeight() - padding.top;
}
return positionInWindow;
}
/**
* Add this floating window to the underlying window manager
*/
/* package */void attach() {
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.type = WindowManager.LayoutParams.TYPE_PHONE;
params.format = PixelFormat.TRANSLUCENT;
params.gravity = Gravity.LEFT | Gravity.TOP;
params.height = frameWindowH;
params.width = frameWindowW;
params.x = frameWindowX;
params.y = frameWindowY;
params.setTitle("Floating:" + mActivityName);
params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED;
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
params.windowAnimations = 0;//android.R.style.Animation_Dialog;
// if the activity inhibits IME, same as floating window
if ((mActivity.getWindow().getAttributes().flags
& WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM) != 0) {
params.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
}
mWindowManager.addView(mFrameView, params);
// mWindowManager.updateLayout() can be called from now on.
mIsAttached = true;
updateLayoutParams(mLayout);
// notify that this floating window becomes the top-most window (for now)
mFloatingWindowManager.moveToTop(this);
// callback to the app
mActivity.handleAttachToFloatingWindow(this);
}
/**
* Move this floating window to a new position on screen
*
* @param x
* x-coordinate of the window on the screen in pixels
* @param y
* y-coordinate of the window on the screen in pixels
*/
public void move(int x, int y) {
Log.i(TAG, "move to ("+x+", "+y+")");
mLayout.x = x;
mLayout.y = y;
updateRealPositionAndSize();
mSavedParams = null; // once window is explictly moved by user, we don't need to remember original position
if (mIsAttached) {
setLayoutLimit(false);
WindowManager.LayoutParams params = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
if (params.x != frameWindowX || params.y != frameWindowY) {
params.x = frameWindowX;
params.y = frameWindowY;
mWindowManager.updateViewLayout(getFrameView(), params);
}
// if this is in the overlay mode, the title view must be moved
// separately, since it is rendered on a separate window
if (mIsInOverlayMode || mIsMinimized) {
WindowManager.LayoutParams titleParams = (WindowManager.LayoutParams) getTitleView().getLayoutParams();
if (titleParams.x != titleWindowX || titleParams.y != titleWindowY) {
titleParams.x = titleWindowX;
titleParams.y = titleWindowY;
mWindowManager.updateViewLayout(getTitleView(), titleParams);
}
}
}
// callback listener.onMove()
if (mUpdateListener != null) {
mUpdateListener.onMoving(this, mLayout.x, mLayout.y);
}
}
/**
* Enlarge or shrink this floating window by a specific amount in width and
* height
*
* @param wDiff
* difference in width
* @param hDiff
* difference in height
*/
public void resize(int wDiff, int hDiff) {
setSize(mLayout.width + wDiff, mLayout.height + hDiff);
}
/**
* Set the size of this floating window
*
* @param width
* the new width in pixels
* @param height
* the new height in pixels
*/
public void setSize(int width, int height) {
Log.i(TAG, "set size to ("+width+", "+height+")");
mLayout.width = width;
mLayout.height = height;
updateRealPositionAndSize();
mSavedParams = null; // if window is moved, saved params has no value
if (mIsAttached) {
WindowManager.LayoutParams params = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
if (params.width != frameWindowW || params.height != frameWindowH) {
params.width = frameWindowW;
params.height = frameWindowH;
mWindowManager.updateViewLayout(getFrameView(), params);
}
// if this is in the overlay mode, the title view must be moved
// separately, since it is rendered on a separate window
if (mIsInOverlayMode || mIsMinimized) {
WindowManager.LayoutParams titleParams = (WindowManager.LayoutParams) getTitleView().getLayoutParams();
if (titleParams.width != titleWindowW || titleParams.height != titleWindowH) {
titleParams.width = titleWindowW;
titleParams.height = titleWindowH;
mWindowManager.updateViewLayout(getTitleView(), titleParams);
}
}
}
// callback listener.onMove()
if (mUpdateListener != null) {
mUpdateListener.onResizing(this, mLayout.width, mLayout.height);
}
}
/**
* Close this floating window immediately. This is equivalent to calling
* <code>close(false)</code>
*/
public void close() {
close(false);
}
/**
* Close this floating window immediately
*
* @param isReturningToFullscreen
* true if closing this window is for returning to the full
* screen mode. false if not.
*/
public void close(boolean isReturningToFullscreen) {
Log.i(TAG, "floating window for " + mActivityName + " is being closed.");
if (mIsAttached) {
mWindowManager.removeView(getFrameView());
if (mIsInOverlayMode || mIsMinimized) {
mWindowManager.removeView(getTitleView());
}
if (mResizeFrame != null) {
mResizeFrame.dismiss();
mResizeFrame = null;
}
mFloatingWindowManager.removeFloatingWindow(this);
mIsAttached = false;
mActivity.handleDetachFromFloatingWindow(this, isReturningToFullscreen);
if (mUpdateListener != null) {
if (isReturningToFullscreen) {
mUpdateListener.onSwitchingFull(this);
} else {
mUpdateListener.onClosing(this);
}
}
}
}
/**
* Switch to overlay mode, in which the windows becomes semi-transparent and
* only the title is touchable.
*
* @param enable
* true to switch to overlay mode, false to switch back to the
* normal mode.
*/
public void setOverlay(boolean enable) {
Log.i(TAG, "set overlay = " + enable);
if (mIsInOverlayMode != enable) {
mIsInOverlayMode = enable;
if (enable) {
// in overlay mode, this floating window becomes
// semi-transparent, and is neither touchable nor focusable
WindowManager.LayoutParams params = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mWindowManager.updateViewLayout(getFrameView(), params);
if (!mIsMinimized) {
// remove title view from the frame view and make it as a new
// separate window, which is touchable and opaque
getFrameView().removeTitleView();
WindowManager.LayoutParams titleParams = new WindowManager.LayoutParams();
titleParams.copyFrom(params);
titleParams.height = titleWindowH;
titleParams.alpha = 1.0f;
titleParams.setTitle("Floating title:" + mActivityName);
titleParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
titleParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
titleParams.windowAnimations = 0;
Rect padding = getFrameView().getPadding();
getTitleView().setPadding(padding.left, padding.top, padding.right, 0);
mWindowManager.addView(getTitleView(), titleParams);
}
} else {
// do the exactly opposite
if (!mIsMinimized) {
mWindowManager.removeViewImmediate(getTitleView());
getTitleView().setPadding(0, 0, 0, 0); // TODO: dirty
getFrameView().setTitleView(getTitleView());
}
setOpacity(1.0f);
WindowManager.LayoutParams params = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
params.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
params.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mWindowManager.updateViewLayout(getFrameView(), params);
}
updateLayoutParams(mLayout);
}
}
/**
* Tests whether this floating window is in overlay mode or not.
*
* @return true if this floating window is in overlay mode. false otherwise.
*/
public boolean isInOverlay() {
return mIsInOverlayMode;
}
/**
* Changes the opacity of this floating window. If this floating window is
* NOT in overlay mode, the opacity of the entire window is changed.
* However, if this floating window is IN overlay mode, the title area is
* not affected.
*
* @param alpha
* 0 is completely transparent. 1.0f is completely opaque.
*/
public void setOpacity(float alpha) {
WindowManager.LayoutParams params = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
params.alpha = alpha;
setSurfaceViewAlphaRecursively(getFrameView(), alpha);
mWindowManager.updateViewLayout(getFrameView(), params);
mAlpha = alpha;
}
/**
* Returns the current opacity of this floating window
*
* @return 0 is completely transparent. 1.0f is completely opaque.
*/
public float getOpacity() {
WindowManager.LayoutParams params = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
return params.alpha;
}
/**
* Force this floating window to loose input focus.
*/
public void looseFocus() {
if (mIsAttached) {
WindowManager.LayoutParams contentParams = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
contentParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mWindowManager.updateViewLayout(getFrameView(), contentParams);
if (mIsInOverlayMode || mIsMinimized) {
WindowManager.LayoutParams titleParams = (WindowManager.LayoutParams) getTitleView().getLayoutParams();
titleParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mWindowManager.updateViewLayout(getTitleView(), titleParams);
}
}
}
/**
* Force this floating window to gain input focus.
*/
public void gainFocus() {
if (mIsAttached) {
WindowManager.LayoutParams contentParams = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
if ((contentParams.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0) {
Log.i(TAG, "gaining focus");
contentParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mWindowManager.updateViewLayout(getFrameView(), contentParams);
}
if (mIsInOverlayMode || mIsMinimized) {
WindowManager.LayoutParams titleParams = (WindowManager.LayoutParams) getTitleView().getLayoutParams();
if ((titleParams.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0) {
titleParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mWindowManager.updateViewLayout(getTitleView(), titleParams);
}
}
}
}
/**
* Make this floating window the top-most window among all floating windows
* in the system
*/
public void moveToTop() {
if (!mFloatingWindowManager.isTopWindow(this) && mIsAttached) {
Log.i(TAG, "move to top");
WindowManager.LayoutParams params = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
mWindowManager.removeViewImmediate(getFrameView());
mWindowManager.addView(getFrameView(), params);
if (mIsInOverlayMode || mIsMinimized) {
WindowManager.LayoutParams titleParams = (WindowManager.LayoutParams) getTitleView().getLayoutParams();
mWindowManager.removeViewImmediate(getTitleView());
mWindowManager.addView(getTitleView(), titleParams);
}
// notify to the window manager that this floating window becomes
// the top-most window. the window manager will then broadcast this
// event to other floating apps
mFloatingWindowManager.moveToTop(this);
if (mUpdateListener != null) {
mUpdateListener.onMoveToTop(this);
}
}
}
//TODO: need to expose this as an API?
public boolean isPortrait() {
return mIsPortrait;
}
//TODO: need to expose this as an API?
public void setLayoutLimit(boolean limit) {
if (mLayoutLimit == limit) {
return;
} else {
mLayoutLimit = limit;
}
if (mIsAttached) {
WindowManager.LayoutParams params = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
if (limit) {
// before limiting the layout, save the current layout
mSavedParams = new WindowManager.LayoutParams();
mSavedParams.copyFrom(params);
params.flags &= ~WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
params.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
params.y = 50; //TODO: externalize hard-coded value
params.x = 0;
} else {
if (mSavedParams != null) {
params = mSavedParams;
mSavedParams = null;
} else {
params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
params.flags &= ~WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
params.gravity = Gravity.LEFT | Gravity.TOP;
Rect padding = getFrameView().getPadding();
params.x = mLayout.x - padding.left;
params.y = mLayout.y - padding.top;
}
// if the title view is in a separate window (minimized or in overlay mode),
// then recover the layout params of the separate window as well
if (mIsMinimized || mIsInOverlayMode) {
WindowManager.LayoutParams titleParams = (WindowManager.LayoutParams) getTitleView().getLayoutParams();
titleParams.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
titleParams.flags &= ~WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
titleParams.gravity = params.gravity;
titleParams.x = params.x;
titleParams.y = params.y;
mWindowManager.updateViewLayout(getTitleView(), titleParams);
}
}
mWindowManager.updateViewLayout(getFrameView(), params);
}
}
/**
* Set this floating window to the minimized state. In the state, the main
* area is hidden and only the title area is visible.
*
* @param minimized
* true to minimize, false to not to minimize
*/
public void setMinimized(boolean minimized) {
boolean curState = isMinimized();
Log.i(TAG, "minimized. current=" + curState + " new=" + minimized);
if (curState != minimized) {
if (minimized) {
if (!mIsInOverlayMode) {
WindowManager.LayoutParams params = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
// remove title view from the frame view and make it as a new
// separate window, which is touchable and opaque
getFrameView().removeTitleView();
WindowManager.LayoutParams titleParams = new WindowManager.LayoutParams();
titleParams.copyFrom(params);
titleParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
titleParams.alpha = 1.0f;
titleParams.setTitle("Floating title:" + mActivityName);
titleParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
titleParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
titleParams.windowAnimations = 0;
Rect padding = getFrameView().getPadding();
getTitleView().setPadding(padding.left, padding.top, padding.right, padding.bottom);// TODO:
// dirty
mWindowManager.addView(getTitleView(), titleParams);
}
getFrameView().setVisibility(View.GONE);
} else {
if (!mIsInOverlayMode) {
mWindowManager.removeViewImmediate(getTitleView());
getFrameView().setTitleView(getTitleView());
getTitleView().setPadding(0, 0, 0, 0);// TODO: dirty
}
getFrameView().setVisibility(View.VISIBLE);
}
mIsMinimized = minimized;
if (mUpdateListener != null) {
mUpdateListener.onSwitchingMinimized(this, this.isMinimized());
}
}
}
/**
* Returns if this floating window is minimized
*
* @return true if minimized, false it not minimized
*/
public boolean isMinimized() {
return mIsMinimized;
}
/**
* Sets OnFloatingWindowUpdateListener of current window.
*
* @param listener
* The listener to be invoked on floating window's update.
*/
public void setOnUpdateListener(OnUpdateListener listener) {
mUpdateListener = listener;
}
public void configurationChangeforWindow (Configuration newConfig) {
if (newConfig.fontScale != mSavedConfig.fontScale || !newConfig.locale.equals(mSavedConfig.locale)) {
//Log.w(TAG, "setViewForConfigChanged");
mActivity.setViewForConfigChanged();
}
mSavedConfig.updateFrom(newConfig);
}
private boolean isInCorrectPositionAndSize(Rect rect) {
return rect.left == mLayout.x && rect.top == mLayout.y && rect.width() == mLayout.width
&& rect.height() == mLayout.height;
}
private Rect calculateCorrectPosition() {
DisplayMetrics dm = mActivity.getResources().getDisplayMetrics();
int correctWidth = mLayout.width;
int correctHeight = mLayout.height;
int minY = 0;
if (mLayout.hideTitle) {
minY = 0 - (int) ((mActivity.getResources()
.getFraction(R.fraction.floating_max_top_margin_percentabe, 1, 1)) * (float) correctHeight);
} else {
minY = mActivity.getResources().getDimensionPixelSize(R.dimen.floating_title_height);
}
int maxY = dm.heightPixels
- (int) ((mActivity.getResources().getFraction(R.fraction.floating_max_bottom_margin_percentabe, 1, 1)) * (float) correctHeight);
int minX = 0 - (int) ((mActivity.getResources().getFraction(R.fraction.floating_max_left_margin_percentabe, 1,
1)) * (float) correctWidth);
int maxX = dm.widthPixels
- (int) ((mActivity.getResources().getFraction(R.fraction.floating_max_right_margin_percentabe, 1, 1)) * (float) correctWidth);
int currentX = mLayout.x;
int currentY = mLayout.y;
int correctX = currentX > maxX ? maxX : (currentX < minX ? minX : currentX);
int correctY = currentY > maxY ? maxY : (currentY < minY ? minY : currentY);
Rect rect = new Rect();
rect.left = correctX;
rect.top = correctY;
rect.right = correctX + correctWidth;
rect.bottom = correctY + correctHeight;
return rect;
}
private ValueAnimator getBounceAnimator(Rect end) {
Rect start = new Rect();
int frameViewLocation[] = new int[2];
getFrameView().getLocationOnScreen(frameViewLocation);
start.left = frameViewLocation[0];
start.top = frameViewLocation[1];
start.right = start.left + mLayout.width;
start.bottom = start.top + mLayout.height;
ValueAnimator anim = ValueAnimator.ofObject(new RectEvaluator(), start, end);
BounceAnimationListener listener = new BounceAnimationListener();
anim.setInterpolator(new DecelerateInterpolator());
anim.addUpdateListener(listener);
anim.addListener(listener);
return anim;
}
private static class RectEvaluator implements TypeEvaluator<Rect> {
@Override
public android.graphics.Rect evaluate(float fraction, android.graphics.Rect startValue,
android.graphics.Rect endValue) {
android.graphics.Rect r = new android.graphics.Rect();
r.left = startValue.left + (int) (fraction * (float) (endValue.left - startValue.left));
r.right = startValue.right + (int) (fraction * (float) (endValue.right - startValue.right));
r.top = startValue.top + (int) (fraction * (float) (endValue.top - startValue.top));
r.bottom = startValue.bottom + (int) (fraction * (float) (endValue.bottom - startValue.bottom));
return r;
}
}
private class BounceAnimationListener extends AnimatorListenerAdapter implements
ValueAnimator.AnimatorUpdateListener {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Rect r = (Rect) animation.getAnimatedValue();
FloatingWindow.this.move(r.left, r.top);
FloatingWindow.this.setSize(r.width(), r.height());
}
@Override
public void onAnimationEnd(Animator animation) {
FloatingWindow.this.moveToTop();
}
}
/**
* TitleView implements title of a floating window
*
*/
private class TitleView extends RelativeLayout implements OnTouchListener, OnSeekBarChangeListener {
private final ImageButton mCloseButton;
private final ImageButton mOverlayButton;
private final SeekBar mOpacitySlider;
private final ImageButton mFullscreenButton;
private final GestureDetector mGestureDetector;
private final int mOpacitySteps;
private final boolean mSupportsQuickOverlay;
// x, y coordinate of the initial touch down. (inside the window)
private int xDown;
private int yDown;
private TitleView() {
super(mActivity);
mInflater.inflate(R.layout.floating_window_title, this);
setOnTouchListener(this);
mCloseButton = (ImageButton) this.findViewById(R.id.imageButton1);
mCloseButton.setOnTouchListener(this);
mOverlayButton = (ImageButton) this.findViewById(R.id.overlayButton);
mOverlayButton.setOnTouchListener(this);
mOpacitySlider = (SeekBar) this.findViewById(R.id.opacitySlider);
mOpacitySlider.setOnSeekBarChangeListener(this);
mOpacitySlider.setOnTouchListener(this);
mFullscreenButton = (ImageButton) this.findViewById(R.id.fullscreenButton);
mFullscreenButton.setOnTouchListener(this);
mOpacitySteps = mActivity.getResources().getInteger(R.integer.floating_overlay_steps);
mSupportsQuickOverlay = mActivity.getResources().getBoolean(R.bool.floating_use_instantoverlay);
mGestureDetector = new GestureDetector(mActivity, new MyGestureListener());
update();
}
private FloatingWindow getWindow() {
return FloatingWindow.this;
}
private int measureAndGetHeight() {
getTitleView().measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
return getChildAt(0).getMeasuredHeight();
}
/**
* Update the UI of title view according to the current status
*/
private void update() {
if (mSupportsQuickOverlay) {
mFullscreenButton.setVisibility(mLayout.hideFullScreenButton ? View.INVISIBLE : View.VISIBLE);
mOverlayButton.setVisibility(GONE);
mOpacitySlider.setVisibility(mLayout.useOverlay ? View.VISIBLE : View.GONE);
} else {
if (getWindow().isInOverlay()) {
mFullscreenButton.setVisibility(GONE);
mOpacitySlider.setVisibility(VISIBLE);
mOpacitySlider.setProgress((int) (getWindow().getOpacity() * mOpacitySteps));
mOverlayButton.setImageResource(R.drawable.floating_ic_btn_overlay_off);
} else {
mFullscreenButton.setVisibility(mLayout.hideFullScreenButton ? View.INVISIBLE : View.VISIBLE);
mOpacitySlider.setVisibility(INVISIBLE);
mOverlayButton.setImageResource(R.drawable.floating_ic_btn_overlay_on);
mOverlayButton.setVisibility(mLayout.useOverlay ? View.VISIBLE : View.GONE);
}
}
this.setVisibility((mLayout.hideTitle && !isInOverlay() && !mIsMoving && !mIsResizing)? View.GONE : View.VISIBLE);
}
private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDoubleTap(MotionEvent e) {
if (mLayout.useDoubleTapMinimize) {
// toggle the minimized status
getWindow().setMinimized(!getWindow().isMinimized());
return true;
} else {
return false;
}
}
}
private boolean mTouchOnSliderIgnored = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i(TAG, "on touch " + v + " " + event.toString());
boolean returnCode = false;
if (v == this) {
// if this is NOT the first-finger touch, don't handle it.
if (event.getPointerId(0) != 0) {
return false;
}
// ACTION_DOWN is handled in dispatchTouchEvent in order to
// intercept motion event delivered to button controls on the
// title
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int xMove = mLayout.x;
int yMove = mLayout.y;
if ((mLayout.moveOption & MoveOption.HORIZONTAL) != 0) {
xMove = (int) event.getRawX() - xDown;
}
if ((mLayout.moveOption & MoveOption.VERTICAL) != 0) {
yMove = (int) event.getRawY() - yDown;
}
mIsMoving = true;
getWindow().move(xMove, yMove);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
Rect r = getWindow().calculateCorrectPosition();
if (!getWindow().isInCorrectPositionAndSize(r)) {
getWindow().getBounceAnimator(r).start();
}
mIsMoving = false;
updateLayoutParams(mLayout);
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
mIsMoving = false;
updateLayoutParams(mLayout);
}
return mGestureDetector.onTouchEvent(event);
} else if (v == mOpacitySlider) {
if (event.getAction() == MotionEvent.ACTION_CANCEL) {
if (mTouchOnSliderIgnored) {
return true;
}
mRedirectMoveToDown = true;
Log.i(TAG, "cancel on slider");
} else if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mOpacitySlider.getProgress() == 100) {
int diff = mOpacitySlider.getWidth() - (int) event.getX();
if (diff > mOpacitySlider.getThumbOffset()*2) {
mTouchOnSliderIgnored = true;
Log.i(TAG, "down on slider is ignored");
return true;
}
else {
Log.i(TAG, "slider touch is NOT ignored");
mTouchOnSliderIgnored = false;
}
}
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (mTouchOnSliderIgnored) {
return true;
}
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
if (mTouchOnSliderIgnored) {
return true;
}
}
}
else if (v == mCloseButton) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.isPressed()) {
- if (mUpdateListener != null && mUpdateListener.onCloseRequested(getWindow())) {
+ if (mUpdateListener == null || mUpdateListener.onCloseRequested(getWindow())) {
getWindow().close();
}
return true;
}
}
}
else if (v == mOverlayButton) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.isPressed()) {
getWindow().setOverlay(!getWindow().isInOverlay());
return true;
}
}
}
else if (v == mFullscreenButton) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.isPressed()) {
- if (mUpdateListener != null && mUpdateListener.onSwitchFullRequested(getWindow())) {
+ if (mUpdateListener == null || mUpdateListener.onSwitchFullRequested(getWindow())) {
getWindow().close(true);
}
return true;
}
}
}
return returnCode;
}
// initial x, y coordinate in the screen
private float mDownX;
private float mDownY;
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// record the initial x, y coordinate of the touch down event
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mDownX = event.getRawX();
mDownY = event.getRawY();
}
// if touch moves greater than 5 pixels, move the window itself.
// Otherwise, deliver the event to child views
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int xMove = (int) Math.abs(event.getRawX() - mDownX);
int yMove = (int) Math.abs(event.getRawY() - mDownY);
final int slop = mActivity.getResources().getDimensionPixelSize(R.dimen.floating_title_touch_slop);
if (xMove > slop || yMove > slop) {
return true; // true means this should be intercepted.
}
}
return false; // false means this should not be intercepted.
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.i(TAG, "dispatch at title. " + event.toString());
// convert MOVE to DOWN event
if (mRedirectMoveToDown) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
MotionEvent event2 = MotionEvent.obtainNoHistory(event);
event2.setAction(MotionEvent.ACTION_DOWN);
event = event2;
}
mRedirectMoveToDown = false;
}
super.dispatchTouchEvent(event);
// record the initial touch down coordinate here
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int [] ret = convertViewPositionToWindowPosition(this, (int)event.getX(), (int)event.getY());
xDown = ret[0];
yDown = ret[1];
}
if (event.getAction() == MotionEvent.ACTION_UP) {
Rect r = getWindow().calculateCorrectPosition();
if (getWindow().isInCorrectPositionAndSize(r)) {
getWindow().moveToTop();
}
}
// return true means that any touch event directed to title view is
// completely handled by title view itself.
return true;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
boolean isPortrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT;
if (isPortrait != getWindow().isPortrait()) {
Rect r = getWindow().calculateCorrectPosition();
if (!getWindow().isInCorrectPositionAndSize(r)) {
getWindow().getBounceAnimator(r).start();
}
if (mResizeFrame != null) {
mResizeFrame.dismiss();
mResizeFrame = null;
getFrameView().mResizeHandle.setVisibility(View.VISIBLE);
}
}
mIsPortrait = mActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
}
@Override
public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
if (progress < mOpacitySteps
&& progress > mActivity.getResources().getInteger(R.integer.floating_overlay_max)) {
seekbar.setProgress(100);
return;
}
if (progress < mActivity.getResources().getInteger(R.integer.floating_overlay_min)) {
seekbar.setProgress(mActivity.getResources().getInteger(R.integer.floating_overlay_min));
return;
}
if (mSupportsQuickOverlay) {
if (progress < mOpacitySteps && !getWindow().isInOverlay()) {
Log.i(TAG, "entering overlay");
getWindow().setOverlay(true);
seekbar.requestFocus();
}
}
getWindow().setOpacity(progress / (float) mOpacitySteps);
Log.i(TAG, "slider " + seekbar.getProgress() + " " + seekbar.getThumbOffset() + " " + fromUser);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Drawable d = mActivity.getResources().getDrawable(R.drawable.floating_seekbar_progress_active);
seekBar.setProgressDrawable(d);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (seekBar.getProgress() == mOpacitySteps) {
getWindow().setOverlay(false);
}
//fix: remove the progress inactive
//Drawable d = mActivity.getResources().getDrawable(R.drawable.floating_seekbar_progress_inactive);
//seekBar.setProgressDrawable(d);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean result = super.dispatchKeyEvent(event);
// back/menu key will make this window to loose focus
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
getWindow().looseFocus();
}
}
return result;
}
}
/**
* FrameView implements the top-level container of a floating window.
*
*/
private class FrameView extends RelativeLayout implements OnTouchListener {
private final View mResizeHandle;
private final ViewGroup mContentParent;
private final Rect mPadding;
private View mContent;
private int xDown;
private int yDown;
private int wDown;
private int hDown;
private FrameView() {
super(mActivity);
mInflater.inflate(R.layout.floating_window_frame, this);
mContentParent = (ViewGroup) findViewById(R.id.main_area);
mResizeHandle = findViewById(R.id.resize_handle);
mResizeHandle.setOnTouchListener(this);
mPadding = new Rect();
findViewById(R.id.content_parent).getBackground().getPadding(mPadding);
this.setOnTouchListener(this);
update();
}
private void setTitleView(TitleView tv) {
ViewGroup vg = (ViewGroup) findViewById(R.id.title_area);
tv.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
vg.addView(tv);
}
private TitleView removeTitleView() {
ViewGroup vg = (ViewGroup) findViewById(R.id.title_area);
TitleView tv = (TitleView) vg.getChildAt(0);
if (tv != null) {
vg.removeViewAt(0);
}
return tv;
}
private FloatingWindow getWindow() {
return FloatingWindow.this;
}
private void setContentView(View v) {
if (mContent != null) {
mContentParent.removeView(mContent);
}
if (v != null) {
mContentParent.addView(v);
mResizeHandle.bringToFront();
mContent = v;
}
}
private View getContentView() {
return mContent;
}
private void update() {
setOverlappingTitle(mLayout.useOverlappingTitle);
updateResizeHandle();
findViewById(R.id.title_area).setVisibility((mLayout.hideTitle && !isInOverlay() && !mIsMoving && !mIsResizing) ? View.GONE : View.VISIBLE);
}
private void setOverlappingTitle(boolean enable) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) findViewById(R.id.main_area)
.getLayoutParams();
if (enable) {
// if overlapping is enabled, main area is aligned with the
// top-edge of window
params.addRule(RelativeLayout.BELOW, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
} else {
// if overlapping is disabled, main area is aligned with the
// bottom-edge of the title
params.addRule(RelativeLayout.BELOW, R.id.title_area);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
}
findViewById(R.id.main_area).setLayoutParams(params);
findViewById(R.id.title_area).bringToFront();
}
private void updateResizeHandle() {
if ((mLayout.resizeOption & ResizeOption.ARBITRARY) != 0) {
mResizeHandle.setVisibility(mIsInOverlayMode ? View.GONE : View.VISIBLE);
} else {
mResizeHandle.setVisibility(View.GONE);
}
}
/**
* Return the padding around frameview. The padding is used usually for
* shadow effect.
*/
private Rect getPadding() {
return mPadding;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// v == this means that touch event is not handled by any child
// view. Then, move the floating window itself according to the touch
if (v == this) {
// give a chance to the activity-level touch handler
if (mActivity.onTouchEvent(event)) {
return true;
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int [] ret = convertViewPositionToWindowPosition(this, (int)event.getX(), (int)event.getY());
xDown = ret[0];
yDown = ret[1];
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
int xMove = mLayout.x;
int yMove = mLayout.y;
if ((mLayout.moveOption & MoveOption.HORIZONTAL) != 0) {
xMove = (int) event.getRawX() - xDown;
}
if ((mLayout.moveOption & MoveOption.VERTICAL) != 0) {
yMove = (int) event.getRawY() - yDown;
}
mIsMoving = true;
getWindow().move(xMove, yMove);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
Rect r = getWindow().calculateCorrectPosition();
if (!getWindow().isInCorrectPositionAndSize(r)) {
getWindow().getBounceAnimator(r).start();
}
mIsMoving = false;
updateLayoutParams(mLayout);
} else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
if (mFloatingWindowManager.isTopWindow(getWindow())){
Log.i(TAG, "touch outside");
getWindow().looseFocus();
}
mIsMoving = false;
updateLayoutParams(mLayout);
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
mIsMoving = false;
updateLayoutParams(mLayout);
}
} else if (v == mResizeHandle) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
wDown = (int) event.getRawX();
hDown = (int) event.getRawY();
mResizeFrame = new ResizeFrame();
mResizeHandle.setVisibility(View.INVISIBLE);
if (mUpdateListener != null) {
mUpdateListener.onResizeStarted(getWindow());
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (mResizeFrame != null) {
mResizeFrame.setSize(mLayout.width + (int) event.getRawX() - wDown,
mLayout.height + (int) event.getRawY() - hDown);
}
mIsResizing = true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (mResizeFrame != null) {
Point newSize = mResizeFrame.getRefinedSize();
if (newSize != null) {
getWindow().setSize(newSize.x, newSize.y);
}
mResizeFrame.dismiss();
mResizeFrame = null;
}
Rect r = getWindow().calculateCorrectPosition();
if (!getWindow().isInCorrectPositionAndSize(r)) {
getWindow().getBounceAnimator(r).start();
}
mIsResizing = false;
updateLayoutParams(mLayout);
updateResizeHandle();
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
updateResizeHandle();
if (mResizeFrame != null) {
mResizeFrame.dismiss();
mResizeFrame = null;
}
if (mUpdateListener != null) {
mUpdateListener.onResizeCanceled(getWindow());
}
mIsResizing = false;
updateLayoutParams(mLayout);
}
}
return true;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// if back of menu key is pressed, floating window looses focus
// so that further pressing the keys are delivered to the
// full-screen app
// just beneath the floating window
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
getWindow().looseFocus();
return false; // return here so that key event is not
// handled by any view
}
}
return super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
// if IME keyboard is about to be dismissed, stop limiting the
// layout of
// floating window inside the screen
if (event.getAction() == KeyEvent.ACTION_UP) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
View v = this.findFocus();
if (v != null && v instanceof EditText && ((EditText) v).isInputMethodTarget()) {
Log.i(TAG, "dispatchKeyEventPreIme");
getWindow().setLayoutLimit(false);
}
}
}
return super.dispatchKeyEventPreIme(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.i(TAG, "dispatch at frame. " + event.toString());
// every touch event is first dispatched to child views
boolean result = super.dispatchTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mFloatingWindowManager.isTopWindow(getWindow())) {
boolean imeAllowed = true;
WindowManager.LayoutParams params = (WindowManager.LayoutParams) getFrameView().getLayoutParams();
if (((params.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0)
&& ((params.flags & WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM) != 0)) {
imeAllowed = false;
}
// if user has pressed the edit text, then limit the layout of
// this window inside the screen so that the window
// is not obscured by the IME keyboard
View v = this.findFocus();
if (imeAllowed && v != null && v instanceof EditText && ((EditText) v).isInputMethodTarget() && mResizeFrame == null) {
int location[] = new int[2];
v.getLocationInWindow(location);
Rect r = new Rect();
r.left = location[0];
r.top = location[1];
r.right = r.left + v.getWidth();
r.bottom = r.top + v.getHeight();
if (r.contains((int) event.getX(), (int) event.getY())) {
Log.i(TAG, "touched edit text");
getWindow().setLayoutLimit(true);
}
}
}
if (!getWindow().isInOverlay()) {
getWindow().gainFocus();
}
// moveToTop should be performed after all other actions
Rect r = getWindow().calculateCorrectPosition();
if (getWindow().isInCorrectPositionAndSize(r)) {
getWindow().moveToTop();
}
}
return result;
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
if (!hasWindowFocus) {
Log.w(TAG, "onWindowFocusChanged - setLayoutLimit(false)");
//getWindow().setLayoutLimit(false);
}
}
}
/**
* ResizeFrame implements window frame during resizing a floating window.
* Note that ResizeFrame only exists during resizing.
*
*/
private class ResizeFrame extends RelativeLayout {
private Point mRefinedSize; //TODO: should not use Point class for size
private final int mMinHeight;
private final int mMaxHeight;
private final int mMinWidth;
private final int mMaxWidth;
private final float mCurrentRatio;
private final int mResizeOption;
public ResizeFrame() {
super(mActivity);
mResizeOption = mLayout.resizeOption;
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
// x, y position of resize frame is same as that of floating window
int frameViewLocation[] = new int[2];
getFrameView().getLocationOnScreen(frameViewLocation);
params.gravity = Gravity.LEFT | Gravity.TOP;
params.x = frameViewLocation[0];
params.y = frameViewLocation[1];
params.type = WindowManager.LayoutParams.TYPE_PHONE;
params.format = PixelFormat.TRANSLUCENT;
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
params.setTitle("Floating resize:" + mActivityName);
// make a new window for resize frame
mInflater.inflate(R.layout.floating_window_resize, this);
mWindowManager.addView(this, params);
// apply the same amount of padding as the floating window
Rect padding = new Rect();
getFrameView().findViewById(R.id.content_parent).getBackground().getPadding(padding);
setPadding(padding.left, padding.top, padding.right, padding.bottom);
//update size according to the ResizeOption
DisplayMetrics dm = mActivity.getResources().getDisplayMetrics();
final int shortPixels = Math.min(dm.heightPixels, dm.widthPixels);
if ((mResizeOption & ResizeOption.PROPORTIONAL) == ResizeOption.PROPORTIONAL) {
mCurrentRatio = (float)(mLayout.height)/mLayout.width;
int oldMinHeight = (int) (mLayout.minHeightWeight * shortPixels);
int oldMinWidth = (int) (mLayout.minWidthWeight * shortPixels);
int oldMaxHeight = (int) (mLayout.maxHeightWeight * shortPixels);
int oldMaxWidth = (int) (mLayout.maxWidthWeight * shortPixels);
mMinHeight = Math.max(oldMinHeight, (int)(oldMinWidth*mCurrentRatio));
mMinWidth = (mMinHeight > oldMinHeight) ? oldMinWidth : (int)(mMinHeight/mCurrentRatio);
mMaxHeight = Math.min(oldMaxHeight, (int)(oldMaxWidth*mCurrentRatio));
mMaxWidth = (mMaxHeight < oldMaxHeight) ? oldMaxWidth : (int)(mMaxHeight/mCurrentRatio);
}
else {
mCurrentRatio = .0f;
mMaxHeight = (int) (mLayout.maxHeightWeight * shortPixels);
mMinHeight = (int) (mLayout.minHeightWeight * shortPixels);
mMaxWidth = (int) (mLayout.maxWidthWeight * shortPixels);
mMinWidth = (int) (mLayout.minWidthWeight * shortPixels);
}
}
public void setSize(int width, int height) {
WindowManager.LayoutParams params = (WindowManager.LayoutParams) getLayoutParams();
mRefinedSize = refineSize(width, height);
Rect padding = getFrameView().getPadding();
params.width = mRefinedSize.x + padding.left + padding.right;
params.height = mRefinedSize.y + padding.top + padding.bottom;
mWindowManager.updateViewLayout(this, params);
}
public void dismiss() {
mWindowManager.removeViewImmediate(this);
}
public Point getRefinedSize() {
return mRefinedSize;
}
private Point refineSize(int width, int height) {
Point refinedSize = new Point(mLayout.width, mLayout.height);
//update size according to the ResizeOption
if ((mResizeOption & ResizeOption.PROPORTIONAL) == ResizeOption.PROPORTIONAL) {
final float targetRatio = (float)(height)/width;
if(targetRatio < mCurrentRatio) {
height = (int)(width * mCurrentRatio);
}
else {
width = (int)(height / mCurrentRatio);
}
}
if((mResizeOption & ResizeOption.HORIZONTAL) != 0) {
//horizontally resizable -> update width
refinedSize.x = width > mMaxWidth ? mMaxWidth
: width < mMinWidth ? mMinWidth : width;
}
if((mResizeOption & ResizeOption.VERTICAL) != 0) {
//vertically resizable -> update height
refinedSize.y = height > mMaxHeight ? mMaxHeight
: height < mMinHeight ? mMinHeight : height;
}
//turn on edge glow if width or height reached min/max resize bounds
if(refinedSize.x >= mMaxWidth || refinedSize.x <= mMinWidth) {
findViewById(R.id.resize_bound_right).setVisibility(VISIBLE);
}
else {
findViewById(R.id.resize_bound_right).setVisibility(INVISIBLE);
}
if(refinedSize.y >= mMaxHeight || refinedSize.y <= mMinHeight) {
findViewById(R.id.resize_bound_bottom).setVisibility(VISIBLE);
}
else {
findViewById(R.id.resize_bound_bottom).setVisibility(INVISIBLE);
}
return refinedSize;
}
}
// //////////////////////////////////////////////////////////////////
// utility methods
// //////////////////////////////////////////////////////////////////
// used to access SurfaceView.mLayout field, which is hidden API
private static Field sLayoutField;
// used to access SurfaceView.updateWindow method, which is hidden API
private static Method sUpdateWindowMethod;
static {
try {
sLayoutField = SurfaceView.class.getDeclaredField("mLayout");
if (sLayoutField != null) {
sLayoutField.setAccessible(true);
}
sUpdateWindowMethod = SurfaceView.class.getDeclaredMethod("updateWindow", boolean.class, boolean.class);
if (sUpdateWindowMethod != null) {
sUpdateWindowMethod.setAccessible(true);
}
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
/**
* Find all SurfaceViews and set their background as transparent
*
* @param aView
*/
private static void setSurfaceViewBackgroundAsTransparentRecursively(View aView) {
// TODO: performance optimization
if (aView.getVisibility() != View.VISIBLE) {
return;
}
if (aView instanceof SurfaceView) {
aView.setBackgroundColor(Color.TRANSPARENT);
return;
}
if (aView instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) aView;
for (int i = 0; i < vg.getChildCount(); i++) {
setSurfaceViewBackgroundAsTransparentRecursively(vg.getChildAt(i));
}
}
}
/**
* Find all SurfaceViews and set their alpha as specified
*
* @param aView
* @param alpha
*/
private static void setSurfaceViewAlphaRecursively(View aView, float alpha) {
// TODO: performance optimization
if (aView.getVisibility() != View.VISIBLE) {
return;
}
if (aView instanceof SurfaceView) {
try {
// TODO: is this needed?
((SurfaceView) aView).getHolder().setFormat(PixelFormat.RGBA_8888);
WindowManager.LayoutParams params = (WindowManager.LayoutParams) sLayoutField.get(aView);
if (params != null) {
params.alpha = alpha;
sUpdateWindowMethod.invoke(aView, true, true);
}
} catch (Exception e) {
Log.e(TAG, "cannot set alpha for view: " + aView);
}
return;
}
if (aView instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) aView;
for (int i = 0; i < vg.getChildCount(); i++) {
setSurfaceViewAlphaRecursively(vg.getChildAt(i), alpha);
}
}
}
}
| false | true | public boolean onTouch(View v, MotionEvent event) {
Log.i(TAG, "on touch " + v + " " + event.toString());
boolean returnCode = false;
if (v == this) {
// if this is NOT the first-finger touch, don't handle it.
if (event.getPointerId(0) != 0) {
return false;
}
// ACTION_DOWN is handled in dispatchTouchEvent in order to
// intercept motion event delivered to button controls on the
// title
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int xMove = mLayout.x;
int yMove = mLayout.y;
if ((mLayout.moveOption & MoveOption.HORIZONTAL) != 0) {
xMove = (int) event.getRawX() - xDown;
}
if ((mLayout.moveOption & MoveOption.VERTICAL) != 0) {
yMove = (int) event.getRawY() - yDown;
}
mIsMoving = true;
getWindow().move(xMove, yMove);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
Rect r = getWindow().calculateCorrectPosition();
if (!getWindow().isInCorrectPositionAndSize(r)) {
getWindow().getBounceAnimator(r).start();
}
mIsMoving = false;
updateLayoutParams(mLayout);
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
mIsMoving = false;
updateLayoutParams(mLayout);
}
return mGestureDetector.onTouchEvent(event);
} else if (v == mOpacitySlider) {
if (event.getAction() == MotionEvent.ACTION_CANCEL) {
if (mTouchOnSliderIgnored) {
return true;
}
mRedirectMoveToDown = true;
Log.i(TAG, "cancel on slider");
} else if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mOpacitySlider.getProgress() == 100) {
int diff = mOpacitySlider.getWidth() - (int) event.getX();
if (diff > mOpacitySlider.getThumbOffset()*2) {
mTouchOnSliderIgnored = true;
Log.i(TAG, "down on slider is ignored");
return true;
}
else {
Log.i(TAG, "slider touch is NOT ignored");
mTouchOnSliderIgnored = false;
}
}
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (mTouchOnSliderIgnored) {
return true;
}
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
if (mTouchOnSliderIgnored) {
return true;
}
}
}
else if (v == mCloseButton) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.isPressed()) {
if (mUpdateListener != null && mUpdateListener.onCloseRequested(getWindow())) {
getWindow().close();
}
return true;
}
}
}
else if (v == mOverlayButton) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.isPressed()) {
getWindow().setOverlay(!getWindow().isInOverlay());
return true;
}
}
}
else if (v == mFullscreenButton) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.isPressed()) {
if (mUpdateListener != null && mUpdateListener.onSwitchFullRequested(getWindow())) {
getWindow().close(true);
}
return true;
}
}
}
return returnCode;
}
| public boolean onTouch(View v, MotionEvent event) {
Log.i(TAG, "on touch " + v + " " + event.toString());
boolean returnCode = false;
if (v == this) {
// if this is NOT the first-finger touch, don't handle it.
if (event.getPointerId(0) != 0) {
return false;
}
// ACTION_DOWN is handled in dispatchTouchEvent in order to
// intercept motion event delivered to button controls on the
// title
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int xMove = mLayout.x;
int yMove = mLayout.y;
if ((mLayout.moveOption & MoveOption.HORIZONTAL) != 0) {
xMove = (int) event.getRawX() - xDown;
}
if ((mLayout.moveOption & MoveOption.VERTICAL) != 0) {
yMove = (int) event.getRawY() - yDown;
}
mIsMoving = true;
getWindow().move(xMove, yMove);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
Rect r = getWindow().calculateCorrectPosition();
if (!getWindow().isInCorrectPositionAndSize(r)) {
getWindow().getBounceAnimator(r).start();
}
mIsMoving = false;
updateLayoutParams(mLayout);
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
mIsMoving = false;
updateLayoutParams(mLayout);
}
return mGestureDetector.onTouchEvent(event);
} else if (v == mOpacitySlider) {
if (event.getAction() == MotionEvent.ACTION_CANCEL) {
if (mTouchOnSliderIgnored) {
return true;
}
mRedirectMoveToDown = true;
Log.i(TAG, "cancel on slider");
} else if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mOpacitySlider.getProgress() == 100) {
int diff = mOpacitySlider.getWidth() - (int) event.getX();
if (diff > mOpacitySlider.getThumbOffset()*2) {
mTouchOnSliderIgnored = true;
Log.i(TAG, "down on slider is ignored");
return true;
}
else {
Log.i(TAG, "slider touch is NOT ignored");
mTouchOnSliderIgnored = false;
}
}
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (mTouchOnSliderIgnored) {
return true;
}
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
if (mTouchOnSliderIgnored) {
return true;
}
}
}
else if (v == mCloseButton) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.isPressed()) {
if (mUpdateListener == null || mUpdateListener.onCloseRequested(getWindow())) {
getWindow().close();
}
return true;
}
}
}
else if (v == mOverlayButton) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.isPressed()) {
getWindow().setOverlay(!getWindow().isInOverlay());
return true;
}
}
}
else if (v == mFullscreenButton) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.isPressed()) {
if (mUpdateListener == null || mUpdateListener.onSwitchFullRequested(getWindow())) {
getWindow().close(true);
}
return true;
}
}
}
return returnCode;
}
|
diff --git a/java/src/org/broadinstitute/sting/playground/gatk/walkers/variants/VariantFiltrationWalker.java b/java/src/org/broadinstitute/sting/playground/gatk/walkers/variants/VariantFiltrationWalker.java
index 8835d91bc..d484b231d 100755
--- a/java/src/org/broadinstitute/sting/playground/gatk/walkers/variants/VariantFiltrationWalker.java
+++ b/java/src/org/broadinstitute/sting/playground/gatk/walkers/variants/VariantFiltrationWalker.java
@@ -1,225 +1,225 @@
package org.broadinstitute.sting.playground.gatk.walkers.variants;
import org.broadinstitute.sting.gatk.LocusContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.refdata.rodVariants;
import org.broadinstitute.sting.gatk.walkers.DataSource;
import org.broadinstitute.sting.gatk.walkers.LocusWalker;
import org.broadinstitute.sting.gatk.walkers.RMD;
import org.broadinstitute.sting.gatk.walkers.Requires;
import org.broadinstitute.sting.playground.utils.AlleleFrequencyEstimate;
import org.broadinstitute.sting.utils.BaseUtils;
import org.broadinstitute.sting.utils.PackageUtils;
import org.broadinstitute.sting.utils.StingException;
import org.broadinstitute.sting.utils.cmdLine.Argument;
import org.broadinstitute.sting.playground.gatk.walkers.variants.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
/**
* VariantFiltrationWalker applies specified conditionally independent features to pre-called variants, thus modifying
* the likelihoods of each genotype. At the moment, the variants are expected to be in gelitext format.
*/
@Requires(value={DataSource.READS, DataSource.REFERENCE},referenceMetaData=@RMD(name="variant",type=rodVariants.class))
public class VariantFiltrationWalker extends LocusWalker<Integer, Integer> {
@Argument(fullName="features", shortName="F", doc="Feature test (optionally with arguments) to apply to genotype posteriors. Syntax: 'testname[:arguments]'") public String[] FEATURES;
@Argument(fullName="exclusion_criterion", shortName="X", doc="Exclusion test (optionally with arguments) to apply to variant call. Syntax: 'testname[:arguments]'") public String[] EXCLUSIONS;
@Argument(fullName="variants_out", shortName="VO", doc="File to which modified variants should be written") public File VARIANTS_OUT;
@Argument(fullName="verbose", shortName="V", doc="Show how the variant likelihoods are changing with the application of each feature") public Boolean VERBOSE = false;
@Argument(fullName="list", shortName="ls", doc="List the available features and exclusion criteria and exit") public Boolean LIST = false;
private ArrayList<Class> featureClasses;
private ArrayList<Class> exclusionClasses;
private PrintWriter vwriter;
/**
* Prepare the output file and the list of available features.
*/
public void initialize() {
featureClasses = PackageUtils.getClassesImplementingInterface(IndependentVariantFeature.class);
exclusionClasses = PackageUtils.getClassesImplementingInterface(VariantExclusionCriterion.class);
if (LIST) {
out.println("\nAvailable features: " + getAvailableClasses(featureClasses) + "\n");
out.println("\nAvailable exclusion criteria: " + getAvailableClasses(exclusionClasses) + "\n");
System.exit(0);
}
try {
vwriter = new PrintWriter(VARIANTS_OUT);
vwriter.println(AlleleFrequencyEstimate.geliHeaderString());
} catch (FileNotFoundException e) {
throw new StingException(String.format("Could not open file '%s' for writing", VARIANTS_OUT.getAbsolutePath()));
}
}
/**
* Trim the 'IVF' or 'VEC' off the feature/exclusion name so the user needn't specify that on the command-line.
*
* @param featureClass the feature class whose name we should rationalize
* @return the class name, minus 'IVF'
*/
private String rationalizeClassName(Class featureClass) {
String featureClassName = featureClass.getSimpleName();
String newName = featureClassName.replaceFirst("IVF", "");
newName = newName.replaceFirst("VEC", "");
return newName;
}
/**
* Returns a comma-separated list of available classes the user may specify at the command-line.
*
* @param classes an ArrayList of classes
* @return String of available classes
*/
private String getAvailableClasses(ArrayList<Class> classes) {
String availableString = "";
for (int classIndex = 0; classIndex < classes.size(); classIndex++) {
availableString += rationalizeClassName(classes.get(classIndex)) + (classIndex == classes.size() - 1 ? "" : ",");
}
return availableString;
}
/**
* Initialize the number of loci processed to zero.
*
* @return 0
*/
public Integer reduceInit() { return 0; }
/**
* For each site of interest, rescore the genotype likelihoods by applying the specified feature set.
*
* @param tracker the meta-data tracker
* @param ref the reference base
* @param context the context for the given locus
* @return 1 if the locus was successfully processed, 0 if otherwise
*/
public Integer map(RefMetaDataTracker tracker, char ref, LocusContext context) {
rodVariants variant = (rodVariants) tracker.lookup("variant", null);
// Ignore places where we don't have a variant or where the reference base is ambiguous.
if (variant != null && BaseUtils.simpleBaseToBaseIndex(ref) != -1) {
if (VERBOSE) { out.println("Original:\n " + variant); }
// Apply features that modify the likelihoods and LOD scores
for (String requestedFeatureString : FEATURES) {
String[] requestedFeaturePieces = requestedFeatureString.split(":");
String requestedFeatureName = requestedFeaturePieces[0];
String requestedFeatureArgs = (requestedFeaturePieces.length == 2) ? requestedFeaturePieces[1] : "";
int notYetSeenFeature = 0;
for ( Class featureClass : featureClasses ) {
String featureClassName = rationalizeClassName(featureClass);
if (requestedFeatureName.equalsIgnoreCase(featureClassName)) {
try {
IndependentVariantFeature ivf = (IndependentVariantFeature) featureClass.newInstance();
ivf.initialize(requestedFeatureArgs);
variant.adjustLikelihoods(ivf.compute(ref, context));
if (VERBOSE) { out.println(featureClassName + ":\n " + variant); }
} catch (InstantiationException e) {
throw new StingException(String.format("Cannot instantiate feature class '%s': must be concrete class", featureClass.getSimpleName()));
} catch (IllegalAccessException e) {
throw new StingException(String.format("Cannot instantiate feature class '%s': must have no-arg constructor", featureClass.getSimpleName()));
}
} else {
notYetSeenFeature++;
}
}
if (notYetSeenFeature == featureClasses.size()) {
throw new StingException(String.format("Unknown feature '%s'. Valid features are '%s'", requestedFeatureName, getAvailableClasses(featureClasses)));
}
}
// Apply exclusion tests that accept or reject the variant call
ArrayList<String> exclusionResults = new ArrayList<String>();
for (String requestedExclusionString : EXCLUSIONS) {
String[] requestedExclusionPieces = requestedExclusionString.split(":");
String requestedExclusionName = requestedExclusionPieces[0];
String requestedExclusionArgs = (requestedExclusionPieces.length == 2) ? requestedExclusionPieces[1] : "";
int notYetSeenExclusion = 0;
for ( Class exclusionClass : exclusionClasses ) {
String exclusionClassName = rationalizeClassName(exclusionClass);
if (requestedExclusionName.equalsIgnoreCase(exclusionClassName)) {
try {
VariantExclusionCriterion vec = (VariantExclusionCriterion) exclusionClass.newInstance();
vec.initialize(requestedExclusionArgs);
boolean excludeResult = vec.exclude(ref, context, variant);
if (excludeResult) {
exclusionResults.add(exclusionClassName);
}
} catch (InstantiationException e) {
throw new StingException(String.format("Cannot instantiate exclusion class '%s': must be concrete class", exclusionClass.getSimpleName()));
} catch (IllegalAccessException e) {
throw new StingException(String.format("Cannot instantiate exclusion class '%s': must have no-arg constructor", exclusionClass.getSimpleName()));
}
} else {
notYetSeenExclusion++;
}
}
if (notYetSeenExclusion == exclusionClasses.size()) {
- throw new StingException(String.format("Unknown exclusion '%s'. Valid features are '%s'", requestedExclusionName, getAvailableClasses(exclusionClasses)));
+ throw new StingException(String.format("Unknown exclusion '%s'. Valid exclusions are '%s'", requestedExclusionName, getAvailableClasses(exclusionClasses)));
}
}
if (exclusionResults.size() > 0) {
if (VERBOSE) {
String exclusions = "";
for (int i = 0; i < exclusionResults.size(); i++) {
exclusions += exclusionResults.get(i) + (i == exclusionResults.size() - 1 ? "" : ",");
}
out.printf("Exclusions: %s\n", exclusions);
}
} else {
vwriter.println(variant);
}
if (VERBOSE) { out.println(); }
return 1;
}
return 0;
}
/**
* Increment the number of loci processed.
*
* @param value result of the map.
* @param sum accumulator for the reduce.
* @return the new number of loci processed.
*/
public Integer reduce(Integer value, Integer sum) {
return sum + value;
}
/**
* Tell the user the number of loci processed and close out the new variants file.
*
* @param result the number of loci seen.
*/
public void onTraversalDone(Integer result) {
out.printf("Processed %d loci.\n", result);
vwriter.close();
}
}
| true | true | public Integer map(RefMetaDataTracker tracker, char ref, LocusContext context) {
rodVariants variant = (rodVariants) tracker.lookup("variant", null);
// Ignore places where we don't have a variant or where the reference base is ambiguous.
if (variant != null && BaseUtils.simpleBaseToBaseIndex(ref) != -1) {
if (VERBOSE) { out.println("Original:\n " + variant); }
// Apply features that modify the likelihoods and LOD scores
for (String requestedFeatureString : FEATURES) {
String[] requestedFeaturePieces = requestedFeatureString.split(":");
String requestedFeatureName = requestedFeaturePieces[0];
String requestedFeatureArgs = (requestedFeaturePieces.length == 2) ? requestedFeaturePieces[1] : "";
int notYetSeenFeature = 0;
for ( Class featureClass : featureClasses ) {
String featureClassName = rationalizeClassName(featureClass);
if (requestedFeatureName.equalsIgnoreCase(featureClassName)) {
try {
IndependentVariantFeature ivf = (IndependentVariantFeature) featureClass.newInstance();
ivf.initialize(requestedFeatureArgs);
variant.adjustLikelihoods(ivf.compute(ref, context));
if (VERBOSE) { out.println(featureClassName + ":\n " + variant); }
} catch (InstantiationException e) {
throw new StingException(String.format("Cannot instantiate feature class '%s': must be concrete class", featureClass.getSimpleName()));
} catch (IllegalAccessException e) {
throw new StingException(String.format("Cannot instantiate feature class '%s': must have no-arg constructor", featureClass.getSimpleName()));
}
} else {
notYetSeenFeature++;
}
}
if (notYetSeenFeature == featureClasses.size()) {
throw new StingException(String.format("Unknown feature '%s'. Valid features are '%s'", requestedFeatureName, getAvailableClasses(featureClasses)));
}
}
// Apply exclusion tests that accept or reject the variant call
ArrayList<String> exclusionResults = new ArrayList<String>();
for (String requestedExclusionString : EXCLUSIONS) {
String[] requestedExclusionPieces = requestedExclusionString.split(":");
String requestedExclusionName = requestedExclusionPieces[0];
String requestedExclusionArgs = (requestedExclusionPieces.length == 2) ? requestedExclusionPieces[1] : "";
int notYetSeenExclusion = 0;
for ( Class exclusionClass : exclusionClasses ) {
String exclusionClassName = rationalizeClassName(exclusionClass);
if (requestedExclusionName.equalsIgnoreCase(exclusionClassName)) {
try {
VariantExclusionCriterion vec = (VariantExclusionCriterion) exclusionClass.newInstance();
vec.initialize(requestedExclusionArgs);
boolean excludeResult = vec.exclude(ref, context, variant);
if (excludeResult) {
exclusionResults.add(exclusionClassName);
}
} catch (InstantiationException e) {
throw new StingException(String.format("Cannot instantiate exclusion class '%s': must be concrete class", exclusionClass.getSimpleName()));
} catch (IllegalAccessException e) {
throw new StingException(String.format("Cannot instantiate exclusion class '%s': must have no-arg constructor", exclusionClass.getSimpleName()));
}
} else {
notYetSeenExclusion++;
}
}
if (notYetSeenExclusion == exclusionClasses.size()) {
throw new StingException(String.format("Unknown exclusion '%s'. Valid features are '%s'", requestedExclusionName, getAvailableClasses(exclusionClasses)));
}
}
if (exclusionResults.size() > 0) {
if (VERBOSE) {
String exclusions = "";
for (int i = 0; i < exclusionResults.size(); i++) {
exclusions += exclusionResults.get(i) + (i == exclusionResults.size() - 1 ? "" : ",");
}
out.printf("Exclusions: %s\n", exclusions);
}
} else {
vwriter.println(variant);
}
if (VERBOSE) { out.println(); }
return 1;
}
return 0;
}
| public Integer map(RefMetaDataTracker tracker, char ref, LocusContext context) {
rodVariants variant = (rodVariants) tracker.lookup("variant", null);
// Ignore places where we don't have a variant or where the reference base is ambiguous.
if (variant != null && BaseUtils.simpleBaseToBaseIndex(ref) != -1) {
if (VERBOSE) { out.println("Original:\n " + variant); }
// Apply features that modify the likelihoods and LOD scores
for (String requestedFeatureString : FEATURES) {
String[] requestedFeaturePieces = requestedFeatureString.split(":");
String requestedFeatureName = requestedFeaturePieces[0];
String requestedFeatureArgs = (requestedFeaturePieces.length == 2) ? requestedFeaturePieces[1] : "";
int notYetSeenFeature = 0;
for ( Class featureClass : featureClasses ) {
String featureClassName = rationalizeClassName(featureClass);
if (requestedFeatureName.equalsIgnoreCase(featureClassName)) {
try {
IndependentVariantFeature ivf = (IndependentVariantFeature) featureClass.newInstance();
ivf.initialize(requestedFeatureArgs);
variant.adjustLikelihoods(ivf.compute(ref, context));
if (VERBOSE) { out.println(featureClassName + ":\n " + variant); }
} catch (InstantiationException e) {
throw new StingException(String.format("Cannot instantiate feature class '%s': must be concrete class", featureClass.getSimpleName()));
} catch (IllegalAccessException e) {
throw new StingException(String.format("Cannot instantiate feature class '%s': must have no-arg constructor", featureClass.getSimpleName()));
}
} else {
notYetSeenFeature++;
}
}
if (notYetSeenFeature == featureClasses.size()) {
throw new StingException(String.format("Unknown feature '%s'. Valid features are '%s'", requestedFeatureName, getAvailableClasses(featureClasses)));
}
}
// Apply exclusion tests that accept or reject the variant call
ArrayList<String> exclusionResults = new ArrayList<String>();
for (String requestedExclusionString : EXCLUSIONS) {
String[] requestedExclusionPieces = requestedExclusionString.split(":");
String requestedExclusionName = requestedExclusionPieces[0];
String requestedExclusionArgs = (requestedExclusionPieces.length == 2) ? requestedExclusionPieces[1] : "";
int notYetSeenExclusion = 0;
for ( Class exclusionClass : exclusionClasses ) {
String exclusionClassName = rationalizeClassName(exclusionClass);
if (requestedExclusionName.equalsIgnoreCase(exclusionClassName)) {
try {
VariantExclusionCriterion vec = (VariantExclusionCriterion) exclusionClass.newInstance();
vec.initialize(requestedExclusionArgs);
boolean excludeResult = vec.exclude(ref, context, variant);
if (excludeResult) {
exclusionResults.add(exclusionClassName);
}
} catch (InstantiationException e) {
throw new StingException(String.format("Cannot instantiate exclusion class '%s': must be concrete class", exclusionClass.getSimpleName()));
} catch (IllegalAccessException e) {
throw new StingException(String.format("Cannot instantiate exclusion class '%s': must have no-arg constructor", exclusionClass.getSimpleName()));
}
} else {
notYetSeenExclusion++;
}
}
if (notYetSeenExclusion == exclusionClasses.size()) {
throw new StingException(String.format("Unknown exclusion '%s'. Valid exclusions are '%s'", requestedExclusionName, getAvailableClasses(exclusionClasses)));
}
}
if (exclusionResults.size() > 0) {
if (VERBOSE) {
String exclusions = "";
for (int i = 0; i < exclusionResults.size(); i++) {
exclusions += exclusionResults.get(i) + (i == exclusionResults.size() - 1 ? "" : ",");
}
out.printf("Exclusions: %s\n", exclusions);
}
} else {
vwriter.println(variant);
}
if (VERBOSE) { out.println(); }
return 1;
}
return 0;
}
|
diff --git a/tests/test.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java b/tests/test.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java
index 9f22a9ae..d38d61c7 100644
--- a/tests/test.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java
+++ b/tests/test.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java
@@ -1,36 +1,36 @@
package org.cocos2dx.lib;
import org.cocos2dx.lib.touch.MultiTouchFilter;
import org.cocos2dx.lib.touch.SingleTouchFilter;
import org.cocos2dx.lib.touch.TouchFilter;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.util.Log;
import android.view.MotionEvent;
public class Cocos2dxGLSurfaceView extends GLSurfaceView {
private static final String TAG = "Cocos2dxGLSurfaceView";
private TouchFilter mTouchFilter;
private Cocos2dxRenderer mRenderer;
public Cocos2dxGLSurfaceView(Context context) {
super(context);
mRenderer = new Cocos2dxRenderer();
setRenderer(mRenderer);
final int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
if (sdkVersion < Build.VERSION_CODES.ECLAIR) {
mTouchFilter = new SingleTouchFilter(this, mRenderer);
Log.i(TAG, "using SingleTouchFilter");
} else {
- mTouchFilter = new SingleTouchFilter(this, mRenderer);
+ mTouchFilter = new MultiTouchFilter(this, mRenderer);
Log.i(TAG, "using MultiTouchFilter");
}
}
public boolean onTouchEvent(final MotionEvent event) {
return mTouchFilter.updateTouch(event);
}
}
| true | true | public Cocos2dxGLSurfaceView(Context context) {
super(context);
mRenderer = new Cocos2dxRenderer();
setRenderer(mRenderer);
final int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
if (sdkVersion < Build.VERSION_CODES.ECLAIR) {
mTouchFilter = new SingleTouchFilter(this, mRenderer);
Log.i(TAG, "using SingleTouchFilter");
} else {
mTouchFilter = new SingleTouchFilter(this, mRenderer);
Log.i(TAG, "using MultiTouchFilter");
}
}
| public Cocos2dxGLSurfaceView(Context context) {
super(context);
mRenderer = new Cocos2dxRenderer();
setRenderer(mRenderer);
final int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
if (sdkVersion < Build.VERSION_CODES.ECLAIR) {
mTouchFilter = new SingleTouchFilter(this, mRenderer);
Log.i(TAG, "using SingleTouchFilter");
} else {
mTouchFilter = new MultiTouchFilter(this, mRenderer);
Log.i(TAG, "using MultiTouchFilter");
}
}
|
diff --git a/tests/com/splunk/IndexTest.java b/tests/com/splunk/IndexTest.java
index 430135d..318998a 100644
--- a/tests/com/splunk/IndexTest.java
+++ b/tests/com/splunk/IndexTest.java
@@ -1,651 +1,647 @@
/*
* Copyright 2012 Splunk, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"): you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.splunk;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.*;
import java.net.Socket;
import junit.framework.AssertionFailedError;
public class IndexTest extends SDKTestCase {
private String indexName;
private Index index;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
indexName = createTemporaryName();
index = service.getIndexes().create(indexName);
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
return service.getIndexes().containsKey(indexName);
}
});
}
@After
@Override
public void tearDown() throws Exception {
if (service.versionIsAtLeast("5.0.0")) {
if (service.getIndexes().containsKey(indexName)) {
index.remove();
}
} else {
// Can't delete indexes via the REST API. Just let them build up.
}
super.tearDown();
}
@Test
public void testDeletion() {
if (service.versionIsEarlierThan("5.0.0")) {
// Can't delete indexes via the REST API.
return;
}
assertTrue(service.getIndexes().containsKey(indexName));
index.remove();
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
return !service.getIndexes().containsKey(indexName);
}
});
}
@Test
public void testDeletionFromCollection() {
if (service.versionIsEarlierThan("5.0.0")) {
// Can't delete indexes via the REST API.
return;
}
assertTrue(service.getIndexes().containsKey(indexName));
service.getIndexes().remove(indexName);
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
return !service.getIndexes().containsKey(indexName);
}
});
}
@Test
public void testAttachWith() throws IOException {
final int originalEventCount = index.getTotalEventCount();
index.attachWith(new ReceiverBehavior() {
public void run(OutputStream stream) throws IOException {
String s = createTimestamp() + " Boris the mad baboon!\r\n";
stream.write(s.getBytes("UTF8"));
}
});
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
index.refresh();
return index.getTotalEventCount() == originalEventCount + 1;
}
});
}
@Test
@SuppressWarnings("deprecation")
public void testIndexGettersThrowNoErrors() {
index.getAssureUTF8();
index.getBlockSignatureDatabase();
index.getBlockSignSize();
index.getBloomfilterTotalSizeKB();
index.getColdPath();
index.getColdPathExpanded();
index.getColdToFrozenDir();
index.getColdToFrozenScript();
index.getCompressRawdata();
index.getCurrentDBSizeMB();
index.getDefaultDatabase();
index.getEnableRealtimeSearch();
index.getFrozenTimePeriodInSecs();
index.getHomePath();
index.getHomePathExpanded();
index.getIndexThreads();
index.getLastInitTime();
index.getMaxBloomBackfillBucketAge();
index.getMaxConcurrentOptimizes();
index.getMaxDataSize();
index.getMaxHotBuckets();
index.getMaxHotIdleSecs();
index.getMaxHotSpanSecs();
index.getMaxMemMB();
index.getMaxMetaEntries();
index.getMaxRunningProcessGroups();
index.getMaxTime();
index.getMaxTotalDataSizeMB();
index.getMaxWarmDBCount();
index.getMemPoolMB();
index.getMinRawFileSyncSecs();
index.getMinTime();
index.getNumBloomfilters();
index.getNumHotBuckets();
index.getNumWarmBuckets();
index.getPartialServiceMetaPeriod();
index.getQuarantineFutureSecs();
index.getQuarantinePastSecs();
index.getRawChunkSizeBytes();
index.getRotatePeriodInSecs();
index.getServiceMetaPeriod();
index.getSuppressBannerList();
index.getSync();
index.getSyncMeta();
index.getThawedPath();
index.getThawedPathExpanded();
index.getThrottleCheckPeriod();
index.getTotalEventCount();
index.isDisabled();
index.isInternal();
// Fields only available from 5.0 on.
if (service.versionIsAtLeast("5.0.0")) {
index.getBucketRebuildMemoryHint();
index.getMaxTimeUnreplicatedNoAcks();
index.getMaxTimeUnreplicatedWithAcks();
}
}
@Test
public void testSetters() {
int newBlockSignSize = index.getBlockSignSize() + 1;
index.setBlockSignSize(newBlockSignSize);
int newFrozenTimePeriodInSecs = index.getFrozenTimePeriodInSecs()+1;
index.setFrozenTimePeriodInSecs(newFrozenTimePeriodInSecs);
int newMaxConcurrentOptimizes = index.getMaxConcurrentOptimizes()+1;
index.setMaxConcurrentOptimizes(newMaxConcurrentOptimizes);
String newMaxDataSize = "auto";
index.setMaxDataSize(newMaxDataSize);
int newMaxHotBuckets = index.getMaxHotBuckets()+1;
index.setMaxHotBuckets(newMaxHotBuckets);
int newMaxHotIdleSecs = index.getMaxHotIdleSecs()+1;
index.setMaxHotIdleSecs(newMaxHotIdleSecs);
int newMaxMemMB = index.getMaxMemMB()+1;
index.setMaxMemMB(newMaxMemMB);
int newMaxMetaEntries = index.getMaxMetaEntries()+1;
index.setMaxMetaEntries(newMaxMetaEntries);
int newMaxTotalDataSizeMB = index.getMaxTotalDataSizeMB()+1;
index.setMaxTotalDataSizeMB(newMaxTotalDataSizeMB);
int newMaxWarmDBCount = index.getMaxWarmDBCount()+1;
index.setMaxWarmDBCount(newMaxWarmDBCount);
String newMinRawFileSyncSecs = "disable";
index.setMinRawFileSyncSecs(newMinRawFileSyncSecs);
int newPartialServiceMetaPeriod = index.getPartialServiceMetaPeriod()+1;
index.setPartialServiceMetaPeriod(newPartialServiceMetaPeriod);
int newQuarantineFutureSecs = index.getQuarantineFutureSecs()+1;
index.setQuarantineFutureSecs(newQuarantineFutureSecs);
int newQuarantinePastSecs = index.getQuarantinePastSecs()+1;
index.setQuarantinePastSecs(newQuarantinePastSecs);
int newRawChunkSizeBytes = index.getRawChunkSizeBytes()+1;
index.setRawChunkSizeBytes(newRawChunkSizeBytes);
int newRotatePeriodInSecs = index.getRotatePeriodInSecs()+1;
index.setRotatePeriodInSecs(newRotatePeriodInSecs);
int newServiceMetaPeriod = index.getServiceMetaPeriod()+1;
index.setServiceMetaPeriod(newServiceMetaPeriod);
boolean newSyncMeta = !index.getSyncMeta();
index.setSyncMeta(newSyncMeta);
int newThrottleCheckPeriod = index.getThrottleCheckPeriod()+1;
index.setThrottleCheckPeriod(newThrottleCheckPeriod);
String coldToFrozenDir = index.getColdToFrozenDir();
index.setColdToFrozenDir("/tmp/foobar" + index.getName());
boolean newEnableOnlineBucketRepair = false;
String newMaxBloomBackfillBucketAge = null;
if (service.versionIsAtLeast("4.3")) {
newEnableOnlineBucketRepair = !index.getEnableOnlineBucketRepair();
index.setEnableOnlineBucketRepair(newEnableOnlineBucketRepair);
newMaxBloomBackfillBucketAge = "20d";
index.setMaxBloomBackfillBucketAge(newMaxBloomBackfillBucketAge);
}
String newBucketRebuildMemoryHint = null;
int newMaxTimeUnreplicatedNoAcks = -1;
int newMaxTimeUnreplicatedWithAcks = -1;
if (service.versionIsAtLeast("5.0")) {
newBucketRebuildMemoryHint = "auto";
index.setBucketRebuildMemoryHint(newBucketRebuildMemoryHint);
newMaxTimeUnreplicatedNoAcks = 300;
index.setMaxTimeUnreplicatedNoAcks(newMaxTimeUnreplicatedNoAcks);
newMaxTimeUnreplicatedWithAcks = 60;
index.setMaxTimeUnreplicatedWithAcks(newMaxTimeUnreplicatedWithAcks);
}
index.update();
index.refresh();
assertEquals(newBlockSignSize, index.getBlockSignSize());
assertEquals(newFrozenTimePeriodInSecs, index.getFrozenTimePeriodInSecs());
assertEquals(newMaxConcurrentOptimizes, index.getMaxConcurrentOptimizes());
assertEquals(newMaxDataSize, index.getMaxDataSize());
assertEquals(newMaxHotBuckets, index.getMaxHotBuckets());
assertEquals(newMaxHotIdleSecs, index.getMaxHotIdleSecs());
assertEquals(newMaxMemMB, index.getMaxMemMB());
assertEquals(newMaxMetaEntries, index.getMaxMetaEntries());
assertEquals(newMaxTotalDataSizeMB, index.getMaxTotalDataSizeMB());
assertEquals(newMaxWarmDBCount, index.getMaxWarmDBCount());
assertEquals(newMinRawFileSyncSecs, index.getMinRawFileSyncSecs());
assertEquals(newPartialServiceMetaPeriod, index.getPartialServiceMetaPeriod());
assertEquals(newQuarantineFutureSecs, index.getQuarantineFutureSecs());
assertEquals(newQuarantinePastSecs, index.getQuarantinePastSecs());
assertEquals(newRawChunkSizeBytes, index.getRawChunkSizeBytes());
assertEquals(newRotatePeriodInSecs, index.getRotatePeriodInSecs());
assertEquals(newServiceMetaPeriod, index.getServiceMetaPeriod());
assertEquals(newSyncMeta, index.getSyncMeta());
assertEquals(newThrottleCheckPeriod, index.getThrottleCheckPeriod());
assertEquals("/tmp/foobar" + index.getName(), index.getColdToFrozenDir());
if (service.versionIsAtLeast("4.3")) {
assertEquals(
newEnableOnlineBucketRepair,
index.getEnableOnlineBucketRepair()
);
assertEquals(
newMaxBloomBackfillBucketAge,
index.getMaxBloomBackfillBucketAge()
);
}
if (service.versionIsAtLeast("5.0")) {
assertEquals(
newBucketRebuildMemoryHint,
index.getBucketRebuildMemoryHint()
);
assertEquals(
newMaxTimeUnreplicatedNoAcks,
index.getMaxTimeUnreplicatedNoAcks()
);
assertEquals(
newMaxTimeUnreplicatedWithAcks,
index.getMaxTimeUnreplicatedWithAcks()
);
}
index.setColdToFrozenDir(coldToFrozenDir == null ? "" : coldToFrozenDir);
index.update();
String coldToFrozenScript = index.getColdToFrozenScript();
index.setColdToFrozenScript("/bin/sh");
index.update();
assertEquals("/bin/sh", index.getColdToFrozenScript());
index.setColdToFrozenScript(coldToFrozenScript == null ? "" : coldToFrozenScript);
index.update();
//index.setColdToFrozenScript(coldToFrozenScript);
- // TODO: Figure out which of the above setters is forcing
- // causing a restart request.
- if (service.versionIsEarlierThan("6.0.0")) {
- clearRestartMessage();
- } else {
- splunkRestart(); // In Splunk 6, you actually need the restart or it won't let you delete the index.
+ if (restartRequired()) {
+ splunkRestart();
}
}
@Test
public void testEnable() {
assertFalse(index.isDisabled());
// Force the index to be disabled
index.disable();
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override public boolean predicate() {
index.refresh();
return index.isDisabled();
}
});
// Disabling an index before Splunk 6 puts Splunk into a weird state that actually
// requires a restart to get out of.
if (service.versionIsEarlierThan("6.0.0")) {
splunkRestart();
}
// And then enable it
index.enable();
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override public boolean predicate() {
index.refresh();
return !index.isDisabled();
}
});
}
@Test
public void testSubmitOne() throws Exception {
try {
tryTestSubmitOne();
} catch (AssertionFailedError e) {
if (e.getMessage().contains("Test timed out before true.") &&
restartRequired()) {
System.out.println(
"WARNING: Splunk indicated restart required while " +
"running a test. Trying to recover...");
splunkRestart();
tryTestSubmitOne();
} else {
throw e;
}
}
}
private void tryTestSubmitOne() {
assertTrue(getResultCountOfIndex() == 0);
assertTrue(index.getTotalEventCount() == 0);
index.submit(createTimestamp() + " This is a test of the emergency broadcasting system.");
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
return getResultCountOfIndex() == 1;
}
});
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
index.refresh();
return index.getTotalEventCount() == 1;
}
});
}
@Test
public void testSubmitOneArgs() throws Exception {
try {
tryTestSubmitOneArgs();
} catch (AssertionFailedError e) {
if (e.getMessage().contains("Test timed out before true.") &&
restartRequired()) {
System.out.println(
"WARNING: Splunk indicated restart required while " +
"running a test. Trying to recover...");
splunkRestart();
tryTestSubmitOne();
} else {
throw e;
}
}
}
private void tryTestSubmitOneArgs() {
assertTrue(getResultCountOfIndex() == 0);
assertTrue(index.getTotalEventCount() == 0);
Args args = Args.create("sourcetype", "mysourcetype");
index.submit(args, createTimestamp() + " This is a test of the emergency broadcasting system.");
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
return getResultCountOfIndex() == 1;
}
});
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
index.refresh();
return index.getTotalEventCount() == 1;
}
});
}
@Test
public void testSubmitOneInEachCall() {
assertTrue(getResultCountOfIndex() == 0);
assertTrue(index.getTotalEventCount() == 0);
index.submit(createTimestamp() + " Hello world!\u0150");
index.submit(createTimestamp() + " Goodbye world!\u0150");
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
return getResultCountOfIndex() == 2;
}
});
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
index.refresh();
// Some versions of Splunk only increase event count by 1.
// Event count should never go up by more than the result count.
int tec = index.getTotalEventCount();
return (1 <= tec) && (tec <= 2);
}
});
}
@Test
public void testSubmitMultipleInOneCall() {
assertTrue(getResultCountOfIndex() == 0);
assertTrue(index.getTotalEventCount() == 0);
index.submit(
createTimestamp() + " Hello world!\u0150" + "\r\n" +
createTimestamp() + " Goodbye world!\u0150");
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
return getResultCountOfIndex() == 2;
}
});
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
index.refresh();
// Some versions of Splunk only increase event count by 1.
// Event count should never go up by more than the result count.
int tec = index.getTotalEventCount();
return (1 <= tec) && (tec <= 2);
}
});
}
@Test
public void testAttach() throws IOException {
assertTrue(getResultCountOfIndex() == 0);
assertTrue(index.getTotalEventCount() == 0);
Socket socket = index.attach();
OutputStream ostream = socket.getOutputStream();
Writer out = new OutputStreamWriter(ostream, "UTF8");
out.write(createTimestamp() + " Hello world!\u0150\r\n");
out.write(createTimestamp() + " Goodbye world!\u0150\r\n");
out.flush();
socket.close();
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
return getResultCountOfIndex() == 2;
}
});
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
index.refresh();
// Some versions of Splunk only increase event count by 1.
// Event count should never go up by more than the result count.
int tec = index.getTotalEventCount();
return (1 <= tec) && (tec <= 2);
}
});
}
@Test
public void testAttachArgs() throws IOException {
assertTrue(getResultCountOfIndex() == 0);
assertTrue(index.getTotalEventCount() == 0);
Args args = Args.create("sourcetype", "mysourcetype");
Socket socket = index.attach(args);
OutputStream ostream = socket.getOutputStream();
Writer out = new OutputStreamWriter(ostream, "UTF8");
out.write(createTimestamp() + " Hello world!\u0150\r\n");
out.write(createTimestamp() + " Goodbye world!\u0150\r\n");
out.write(createTimestamp() + " Goodbye world again!\u0150\r\n");
out.flush();
socket.close();
assertEventuallyTrue(new EventuallyTrueBehavior() {
{ tries = 60; }
@Override
public boolean predicate() {
return getResultCountOfIndex() == 3;
}
});
assertEventuallyTrue(new EventuallyTrueBehavior() {
{ tries = 60; }
@Override
public boolean predicate() {
index.refresh();
// Some versions of Splunk only increase event count by 1.
// Event count should never go up by more than the result count.
int tec = index.getTotalEventCount();
return (1 <= tec) && (tec <= 3);
}
});
}
@Test
public void testUpload() throws Exception {
if (!hasTestData()) {
System.out.println("WARNING: sdk-app-collection not installed in Splunk; skipping test.");
return;
}
installApplicationFromTestData("file_to_upload");
assertTrue(getResultCountOfIndex() == 0);
assertTrue(index.getTotalEventCount() == 0);
String fileToUpload = joinServerPath(new String[] {
service.getSettings().getSplunkHome(),
"etc", "apps", "file_to_upload", "log.txt"});
index.upload(fileToUpload);
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
return getResultCountOfIndex() == 4;
}
});
assertEventuallyTrue(new EventuallyTrueBehavior() {
@Override
public boolean predicate() {
index.refresh();
// Some versions of Splunk only increase event count by 1.
// Event count should never go up by more than the result count.
int tec = index.getTotalEventCount();
return (1 <= tec) && (tec <= 4);
}
});
}
@Test
public void testSubmitAndClean() throws InterruptedException {
try {
tryTestSubmitAndClean();
} catch (SplunkException e) {
if (e.getCode() == SplunkException.TIMEOUT) {
// Due to flakiness of the underlying implementation,
// this index clean method doesn't always work on a "dirty"
// Splunk instance. Try again on a "clean" instance.
System.out.println(
"WARNING: Index clean timed out. Trying again on a " +
"freshly restarted Splunk instance...");
uncheckedSplunkRestart();
tryTestSubmitAndClean();
} else {
throw e;
}
}
}
private void tryTestSubmitAndClean() throws InterruptedException {
assertTrue(getResultCountOfIndex() == 0);
// Make sure the index is not empty.
index.submit("Hello world");
assertEventuallyTrue(new EventuallyTrueBehavior() {
{
tries = 50;
}
@Override
public boolean predicate() {
return getResultCountOfIndex() == 1;
}
});
// Clean the index and make sure it's empty.
// NOTE: Average time for this is 65s (!!!). Have seen 110+.
index.clean(150);
assertTrue(getResultCountOfIndex() == 0);
}
@Test
public void testUpdateNameShouldFail() {
try {
index.update(new Args("name", createTemporaryName()));
fail("Expected IllegalStateException.");
}
catch (IllegalStateException e) {
// Good
}
}
// === Utility ===
private int getResultCountOfIndex() {
InputStream results = service.oneshotSearch("search index=" + indexName);
try {
ResultsReaderXml resultsReader = new ResultsReaderXml(results);
int numEvents = 0;
while (resultsReader.getNextEvent() != null) {
numEvents++;
}
return numEvents;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| true | true | public void testSetters() {
int newBlockSignSize = index.getBlockSignSize() + 1;
index.setBlockSignSize(newBlockSignSize);
int newFrozenTimePeriodInSecs = index.getFrozenTimePeriodInSecs()+1;
index.setFrozenTimePeriodInSecs(newFrozenTimePeriodInSecs);
int newMaxConcurrentOptimizes = index.getMaxConcurrentOptimizes()+1;
index.setMaxConcurrentOptimizes(newMaxConcurrentOptimizes);
String newMaxDataSize = "auto";
index.setMaxDataSize(newMaxDataSize);
int newMaxHotBuckets = index.getMaxHotBuckets()+1;
index.setMaxHotBuckets(newMaxHotBuckets);
int newMaxHotIdleSecs = index.getMaxHotIdleSecs()+1;
index.setMaxHotIdleSecs(newMaxHotIdleSecs);
int newMaxMemMB = index.getMaxMemMB()+1;
index.setMaxMemMB(newMaxMemMB);
int newMaxMetaEntries = index.getMaxMetaEntries()+1;
index.setMaxMetaEntries(newMaxMetaEntries);
int newMaxTotalDataSizeMB = index.getMaxTotalDataSizeMB()+1;
index.setMaxTotalDataSizeMB(newMaxTotalDataSizeMB);
int newMaxWarmDBCount = index.getMaxWarmDBCount()+1;
index.setMaxWarmDBCount(newMaxWarmDBCount);
String newMinRawFileSyncSecs = "disable";
index.setMinRawFileSyncSecs(newMinRawFileSyncSecs);
int newPartialServiceMetaPeriod = index.getPartialServiceMetaPeriod()+1;
index.setPartialServiceMetaPeriod(newPartialServiceMetaPeriod);
int newQuarantineFutureSecs = index.getQuarantineFutureSecs()+1;
index.setQuarantineFutureSecs(newQuarantineFutureSecs);
int newQuarantinePastSecs = index.getQuarantinePastSecs()+1;
index.setQuarantinePastSecs(newQuarantinePastSecs);
int newRawChunkSizeBytes = index.getRawChunkSizeBytes()+1;
index.setRawChunkSizeBytes(newRawChunkSizeBytes);
int newRotatePeriodInSecs = index.getRotatePeriodInSecs()+1;
index.setRotatePeriodInSecs(newRotatePeriodInSecs);
int newServiceMetaPeriod = index.getServiceMetaPeriod()+1;
index.setServiceMetaPeriod(newServiceMetaPeriod);
boolean newSyncMeta = !index.getSyncMeta();
index.setSyncMeta(newSyncMeta);
int newThrottleCheckPeriod = index.getThrottleCheckPeriod()+1;
index.setThrottleCheckPeriod(newThrottleCheckPeriod);
String coldToFrozenDir = index.getColdToFrozenDir();
index.setColdToFrozenDir("/tmp/foobar" + index.getName());
boolean newEnableOnlineBucketRepair = false;
String newMaxBloomBackfillBucketAge = null;
if (service.versionIsAtLeast("4.3")) {
newEnableOnlineBucketRepair = !index.getEnableOnlineBucketRepair();
index.setEnableOnlineBucketRepair(newEnableOnlineBucketRepair);
newMaxBloomBackfillBucketAge = "20d";
index.setMaxBloomBackfillBucketAge(newMaxBloomBackfillBucketAge);
}
String newBucketRebuildMemoryHint = null;
int newMaxTimeUnreplicatedNoAcks = -1;
int newMaxTimeUnreplicatedWithAcks = -1;
if (service.versionIsAtLeast("5.0")) {
newBucketRebuildMemoryHint = "auto";
index.setBucketRebuildMemoryHint(newBucketRebuildMemoryHint);
newMaxTimeUnreplicatedNoAcks = 300;
index.setMaxTimeUnreplicatedNoAcks(newMaxTimeUnreplicatedNoAcks);
newMaxTimeUnreplicatedWithAcks = 60;
index.setMaxTimeUnreplicatedWithAcks(newMaxTimeUnreplicatedWithAcks);
}
index.update();
index.refresh();
assertEquals(newBlockSignSize, index.getBlockSignSize());
assertEquals(newFrozenTimePeriodInSecs, index.getFrozenTimePeriodInSecs());
assertEquals(newMaxConcurrentOptimizes, index.getMaxConcurrentOptimizes());
assertEquals(newMaxDataSize, index.getMaxDataSize());
assertEquals(newMaxHotBuckets, index.getMaxHotBuckets());
assertEquals(newMaxHotIdleSecs, index.getMaxHotIdleSecs());
assertEquals(newMaxMemMB, index.getMaxMemMB());
assertEquals(newMaxMetaEntries, index.getMaxMetaEntries());
assertEquals(newMaxTotalDataSizeMB, index.getMaxTotalDataSizeMB());
assertEquals(newMaxWarmDBCount, index.getMaxWarmDBCount());
assertEquals(newMinRawFileSyncSecs, index.getMinRawFileSyncSecs());
assertEquals(newPartialServiceMetaPeriod, index.getPartialServiceMetaPeriod());
assertEquals(newQuarantineFutureSecs, index.getQuarantineFutureSecs());
assertEquals(newQuarantinePastSecs, index.getQuarantinePastSecs());
assertEquals(newRawChunkSizeBytes, index.getRawChunkSizeBytes());
assertEquals(newRotatePeriodInSecs, index.getRotatePeriodInSecs());
assertEquals(newServiceMetaPeriod, index.getServiceMetaPeriod());
assertEquals(newSyncMeta, index.getSyncMeta());
assertEquals(newThrottleCheckPeriod, index.getThrottleCheckPeriod());
assertEquals("/tmp/foobar" + index.getName(), index.getColdToFrozenDir());
if (service.versionIsAtLeast("4.3")) {
assertEquals(
newEnableOnlineBucketRepair,
index.getEnableOnlineBucketRepair()
);
assertEquals(
newMaxBloomBackfillBucketAge,
index.getMaxBloomBackfillBucketAge()
);
}
if (service.versionIsAtLeast("5.0")) {
assertEquals(
newBucketRebuildMemoryHint,
index.getBucketRebuildMemoryHint()
);
assertEquals(
newMaxTimeUnreplicatedNoAcks,
index.getMaxTimeUnreplicatedNoAcks()
);
assertEquals(
newMaxTimeUnreplicatedWithAcks,
index.getMaxTimeUnreplicatedWithAcks()
);
}
index.setColdToFrozenDir(coldToFrozenDir == null ? "" : coldToFrozenDir);
index.update();
String coldToFrozenScript = index.getColdToFrozenScript();
index.setColdToFrozenScript("/bin/sh");
index.update();
assertEquals("/bin/sh", index.getColdToFrozenScript());
index.setColdToFrozenScript(coldToFrozenScript == null ? "" : coldToFrozenScript);
index.update();
//index.setColdToFrozenScript(coldToFrozenScript);
// TODO: Figure out which of the above setters is forcing
// causing a restart request.
if (service.versionIsEarlierThan("6.0.0")) {
clearRestartMessage();
} else {
splunkRestart(); // In Splunk 6, you actually need the restart or it won't let you delete the index.
}
}
| public void testSetters() {
int newBlockSignSize = index.getBlockSignSize() + 1;
index.setBlockSignSize(newBlockSignSize);
int newFrozenTimePeriodInSecs = index.getFrozenTimePeriodInSecs()+1;
index.setFrozenTimePeriodInSecs(newFrozenTimePeriodInSecs);
int newMaxConcurrentOptimizes = index.getMaxConcurrentOptimizes()+1;
index.setMaxConcurrentOptimizes(newMaxConcurrentOptimizes);
String newMaxDataSize = "auto";
index.setMaxDataSize(newMaxDataSize);
int newMaxHotBuckets = index.getMaxHotBuckets()+1;
index.setMaxHotBuckets(newMaxHotBuckets);
int newMaxHotIdleSecs = index.getMaxHotIdleSecs()+1;
index.setMaxHotIdleSecs(newMaxHotIdleSecs);
int newMaxMemMB = index.getMaxMemMB()+1;
index.setMaxMemMB(newMaxMemMB);
int newMaxMetaEntries = index.getMaxMetaEntries()+1;
index.setMaxMetaEntries(newMaxMetaEntries);
int newMaxTotalDataSizeMB = index.getMaxTotalDataSizeMB()+1;
index.setMaxTotalDataSizeMB(newMaxTotalDataSizeMB);
int newMaxWarmDBCount = index.getMaxWarmDBCount()+1;
index.setMaxWarmDBCount(newMaxWarmDBCount);
String newMinRawFileSyncSecs = "disable";
index.setMinRawFileSyncSecs(newMinRawFileSyncSecs);
int newPartialServiceMetaPeriod = index.getPartialServiceMetaPeriod()+1;
index.setPartialServiceMetaPeriod(newPartialServiceMetaPeriod);
int newQuarantineFutureSecs = index.getQuarantineFutureSecs()+1;
index.setQuarantineFutureSecs(newQuarantineFutureSecs);
int newQuarantinePastSecs = index.getQuarantinePastSecs()+1;
index.setQuarantinePastSecs(newQuarantinePastSecs);
int newRawChunkSizeBytes = index.getRawChunkSizeBytes()+1;
index.setRawChunkSizeBytes(newRawChunkSizeBytes);
int newRotatePeriodInSecs = index.getRotatePeriodInSecs()+1;
index.setRotatePeriodInSecs(newRotatePeriodInSecs);
int newServiceMetaPeriod = index.getServiceMetaPeriod()+1;
index.setServiceMetaPeriod(newServiceMetaPeriod);
boolean newSyncMeta = !index.getSyncMeta();
index.setSyncMeta(newSyncMeta);
int newThrottleCheckPeriod = index.getThrottleCheckPeriod()+1;
index.setThrottleCheckPeriod(newThrottleCheckPeriod);
String coldToFrozenDir = index.getColdToFrozenDir();
index.setColdToFrozenDir("/tmp/foobar" + index.getName());
boolean newEnableOnlineBucketRepair = false;
String newMaxBloomBackfillBucketAge = null;
if (service.versionIsAtLeast("4.3")) {
newEnableOnlineBucketRepair = !index.getEnableOnlineBucketRepair();
index.setEnableOnlineBucketRepair(newEnableOnlineBucketRepair);
newMaxBloomBackfillBucketAge = "20d";
index.setMaxBloomBackfillBucketAge(newMaxBloomBackfillBucketAge);
}
String newBucketRebuildMemoryHint = null;
int newMaxTimeUnreplicatedNoAcks = -1;
int newMaxTimeUnreplicatedWithAcks = -1;
if (service.versionIsAtLeast("5.0")) {
newBucketRebuildMemoryHint = "auto";
index.setBucketRebuildMemoryHint(newBucketRebuildMemoryHint);
newMaxTimeUnreplicatedNoAcks = 300;
index.setMaxTimeUnreplicatedNoAcks(newMaxTimeUnreplicatedNoAcks);
newMaxTimeUnreplicatedWithAcks = 60;
index.setMaxTimeUnreplicatedWithAcks(newMaxTimeUnreplicatedWithAcks);
}
index.update();
index.refresh();
assertEquals(newBlockSignSize, index.getBlockSignSize());
assertEquals(newFrozenTimePeriodInSecs, index.getFrozenTimePeriodInSecs());
assertEquals(newMaxConcurrentOptimizes, index.getMaxConcurrentOptimizes());
assertEquals(newMaxDataSize, index.getMaxDataSize());
assertEquals(newMaxHotBuckets, index.getMaxHotBuckets());
assertEquals(newMaxHotIdleSecs, index.getMaxHotIdleSecs());
assertEquals(newMaxMemMB, index.getMaxMemMB());
assertEquals(newMaxMetaEntries, index.getMaxMetaEntries());
assertEquals(newMaxTotalDataSizeMB, index.getMaxTotalDataSizeMB());
assertEquals(newMaxWarmDBCount, index.getMaxWarmDBCount());
assertEquals(newMinRawFileSyncSecs, index.getMinRawFileSyncSecs());
assertEquals(newPartialServiceMetaPeriod, index.getPartialServiceMetaPeriod());
assertEquals(newQuarantineFutureSecs, index.getQuarantineFutureSecs());
assertEquals(newQuarantinePastSecs, index.getQuarantinePastSecs());
assertEquals(newRawChunkSizeBytes, index.getRawChunkSizeBytes());
assertEquals(newRotatePeriodInSecs, index.getRotatePeriodInSecs());
assertEquals(newServiceMetaPeriod, index.getServiceMetaPeriod());
assertEquals(newSyncMeta, index.getSyncMeta());
assertEquals(newThrottleCheckPeriod, index.getThrottleCheckPeriod());
assertEquals("/tmp/foobar" + index.getName(), index.getColdToFrozenDir());
if (service.versionIsAtLeast("4.3")) {
assertEquals(
newEnableOnlineBucketRepair,
index.getEnableOnlineBucketRepair()
);
assertEquals(
newMaxBloomBackfillBucketAge,
index.getMaxBloomBackfillBucketAge()
);
}
if (service.versionIsAtLeast("5.0")) {
assertEquals(
newBucketRebuildMemoryHint,
index.getBucketRebuildMemoryHint()
);
assertEquals(
newMaxTimeUnreplicatedNoAcks,
index.getMaxTimeUnreplicatedNoAcks()
);
assertEquals(
newMaxTimeUnreplicatedWithAcks,
index.getMaxTimeUnreplicatedWithAcks()
);
}
index.setColdToFrozenDir(coldToFrozenDir == null ? "" : coldToFrozenDir);
index.update();
String coldToFrozenScript = index.getColdToFrozenScript();
index.setColdToFrozenScript("/bin/sh");
index.update();
assertEquals("/bin/sh", index.getColdToFrozenScript());
index.setColdToFrozenScript(coldToFrozenScript == null ? "" : coldToFrozenScript);
index.update();
//index.setColdToFrozenScript(coldToFrozenScript);
if (restartRequired()) {
splunkRestart();
}
}
|
diff --git a/src/com/android/browser/preferences/WebViewPreview.java b/src/com/android/browser/preferences/WebViewPreview.java
index 41173883..a3c19a45 100644
--- a/src/com/android/browser/preferences/WebViewPreview.java
+++ b/src/com/android/browser/preferences/WebViewPreview.java
@@ -1,94 +1,101 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser.preferences;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import com.android.browser.R;
public abstract class WebViewPreview extends Preference
implements OnSharedPreferenceChangeListener {
protected WebView mWebView;
public WebViewPreview(
Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public WebViewPreview(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public WebViewPreview(Context context) {
super(context);
init(context);
}
protected void init(Context context) {
setLayoutResource(R.layout.webview_preview);
}
protected abstract void updatePreview();
protected void setupWebView(WebView view) {}
@Override
protected View onCreateView(ViewGroup parent) {
View root = super.onCreateView(parent);
WebView webView = (WebView) root.findViewById(R.id.webview);
+ // Tell WebView to really, truly ignore all touch events. No, seriously,
+ // ignore them all. And don't show scrollbars.
webView.setFocusable(false);
+ webView.setFocusableInTouchMode(false);
+ webView.setClickable(false);
+ webView.setLongClickable(false);
+ webView.setHorizontalScrollBarEnabled(false);
+ webView.setVerticalScrollBarEnabled(false);
setupWebView(webView);
return root;
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
mWebView = (WebView) view.findViewById(R.id.webview);
updatePreview();
}
@Override
protected void onAttachedToHierarchy(PreferenceManager preferenceManager) {
super.onAttachedToHierarchy(preferenceManager);
getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPrepareForRemoval() {
getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPrepareForRemoval();
}
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
updatePreview();
}
}
| false | true | protected View onCreateView(ViewGroup parent) {
View root = super.onCreateView(parent);
WebView webView = (WebView) root.findViewById(R.id.webview);
webView.setFocusable(false);
setupWebView(webView);
return root;
}
| protected View onCreateView(ViewGroup parent) {
View root = super.onCreateView(parent);
WebView webView = (WebView) root.findViewById(R.id.webview);
// Tell WebView to really, truly ignore all touch events. No, seriously,
// ignore them all. And don't show scrollbars.
webView.setFocusable(false);
webView.setFocusableInTouchMode(false);
webView.setClickable(false);
webView.setLongClickable(false);
webView.setHorizontalScrollBarEnabled(false);
webView.setVerticalScrollBarEnabled(false);
setupWebView(webView);
return root;
}
|
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/ca/uoguelph/lib/app/xmlui/aspect/general/PendingSubmissionsTransformer.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/ca/uoguelph/lib/app/xmlui/aspect/general/PendingSubmissionsTransformer.java
index a758002..6774ec5 100644
--- a/dspace-xmlui/dspace-xmlui-api/src/main/java/ca/uoguelph/lib/app/xmlui/aspect/general/PendingSubmissionsTransformer.java
+++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/ca/uoguelph/lib/app/xmlui/aspect/general/PendingSubmissionsTransformer.java
@@ -1,115 +1,115 @@
/**
* PendingSubmissionsTransformer.java
*
* This file is released under the same license as DSpace itself.
*
* @author Chris Charles [email protected]
*/
package ca.uoguelph.lib.app.xmlui.aspect.general;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.eperson.EPerson;
/**
* Add a div to the DRI document notifying the user that there are pending
* submissions.
*
* Pending submissions are items which have been submitted but have not yet
* been accepted into any collections due to workflow restrictions.
*/
public class PendingSubmissionsTransformer extends AbstractDSpaceTransformer
{
private static final Message T_pending_submissions_intro =
message("xmlui.general.pending_submissions.intro");
private static final Message T_one_pending_submission =
message("xmlui.general.pending_submissions.link_single");
private static final Message T_multiple_pending_submissions =
message("xmlui.general.pending_submissions.link_multiple");
private static final Message T_pending_submissions_outtro_single =
message("xmlui.general.pending_submissions.outtro_single");
private static final Message T_pending_submissions_outtro_multiple =
message("xmlui.general.pending_submissions.outtro_multiple");
/**
* Add a new pending-submissions div and table to the DRI body and
* populate from the database.
*
* @param body The DRI document's body element.
*/
public void addBody(Body body) throws WingException, SQLException
{
EPerson currentUser = context.getCurrentUser();
if (currentUser != null)
{
Statement statement = context.getDBConnection().createStatement();
// Find out which metadata_field_id represents dc.title
String title_field_query =
"SELECT metadata_field_id" +
" FROM metadatafieldregistry AS fields," +
" metadataschemaregistry AS schemas" +
" WHERE fields.metadata_schema_id" +
" = schemas.metadata_schema_id" +
" AND schemas.short_id = 'dc'" +
" AND fields.element = 'title'" +
" AND fields.qualifier IS NULL" +
" LIMIT 1;";
ResultSet dcTitleField = statement.executeQuery(title_field_query);
dcTitleField.next();
String dcTitleID = dcTitleField.getString("metadata_field_id");
// Retrieve the number of pending submissions
String submissions_query =
"SELECT COUNT(metadatavalue.text_value)" +
" FROM workflowitem, item, metadatavalue" +
" WHERE workflowitem.item_id = item.item_id" +
" AND item.item_id = metadatavalue.item_id" +
" AND metadatavalue.metadata_field_id = " + dcTitleID +
" AND item.submitter_id = " + currentUser.getID() + ";";
ResultSet submissions = statement.executeQuery(submissions_query);
// Advance to the first record and get its value
submissions.next();
int rowCount = submissions.getInt(1);
// Add the pending-submissions div if pending submissions exist.
if (rowCount > 0)
{
Message T_link;
Message T_outtro;
if (rowCount == 1)
{
T_link = T_one_pending_submission;
T_outtro = T_pending_submissions_outtro_single;
}
else
{
T_link =
T_multiple_pending_submissions.parameterize(rowCount);
T_outtro = T_pending_submissions_outtro_multiple;
}
Division pending = body.addDivision("pending-submissions");
Para para = pending.addPara();
para.addContent(T_pending_submissions_intro);
- para.addXref("submissions", T_link);
+ para.addXref("/xmlui/submissions", T_link);
para.addContent(T_outtro);
}
}
}
}
| true | true | public void addBody(Body body) throws WingException, SQLException
{
EPerson currentUser = context.getCurrentUser();
if (currentUser != null)
{
Statement statement = context.getDBConnection().createStatement();
// Find out which metadata_field_id represents dc.title
String title_field_query =
"SELECT metadata_field_id" +
" FROM metadatafieldregistry AS fields," +
" metadataschemaregistry AS schemas" +
" WHERE fields.metadata_schema_id" +
" = schemas.metadata_schema_id" +
" AND schemas.short_id = 'dc'" +
" AND fields.element = 'title'" +
" AND fields.qualifier IS NULL" +
" LIMIT 1;";
ResultSet dcTitleField = statement.executeQuery(title_field_query);
dcTitleField.next();
String dcTitleID = dcTitleField.getString("metadata_field_id");
// Retrieve the number of pending submissions
String submissions_query =
"SELECT COUNT(metadatavalue.text_value)" +
" FROM workflowitem, item, metadatavalue" +
" WHERE workflowitem.item_id = item.item_id" +
" AND item.item_id = metadatavalue.item_id" +
" AND metadatavalue.metadata_field_id = " + dcTitleID +
" AND item.submitter_id = " + currentUser.getID() + ";";
ResultSet submissions = statement.executeQuery(submissions_query);
// Advance to the first record and get its value
submissions.next();
int rowCount = submissions.getInt(1);
// Add the pending-submissions div if pending submissions exist.
if (rowCount > 0)
{
Message T_link;
Message T_outtro;
if (rowCount == 1)
{
T_link = T_one_pending_submission;
T_outtro = T_pending_submissions_outtro_single;
}
else
{
T_link =
T_multiple_pending_submissions.parameterize(rowCount);
T_outtro = T_pending_submissions_outtro_multiple;
}
Division pending = body.addDivision("pending-submissions");
Para para = pending.addPara();
para.addContent(T_pending_submissions_intro);
para.addXref("submissions", T_link);
para.addContent(T_outtro);
}
}
}
| public void addBody(Body body) throws WingException, SQLException
{
EPerson currentUser = context.getCurrentUser();
if (currentUser != null)
{
Statement statement = context.getDBConnection().createStatement();
// Find out which metadata_field_id represents dc.title
String title_field_query =
"SELECT metadata_field_id" +
" FROM metadatafieldregistry AS fields," +
" metadataschemaregistry AS schemas" +
" WHERE fields.metadata_schema_id" +
" = schemas.metadata_schema_id" +
" AND schemas.short_id = 'dc'" +
" AND fields.element = 'title'" +
" AND fields.qualifier IS NULL" +
" LIMIT 1;";
ResultSet dcTitleField = statement.executeQuery(title_field_query);
dcTitleField.next();
String dcTitleID = dcTitleField.getString("metadata_field_id");
// Retrieve the number of pending submissions
String submissions_query =
"SELECT COUNT(metadatavalue.text_value)" +
" FROM workflowitem, item, metadatavalue" +
" WHERE workflowitem.item_id = item.item_id" +
" AND item.item_id = metadatavalue.item_id" +
" AND metadatavalue.metadata_field_id = " + dcTitleID +
" AND item.submitter_id = " + currentUser.getID() + ";";
ResultSet submissions = statement.executeQuery(submissions_query);
// Advance to the first record and get its value
submissions.next();
int rowCount = submissions.getInt(1);
// Add the pending-submissions div if pending submissions exist.
if (rowCount > 0)
{
Message T_link;
Message T_outtro;
if (rowCount == 1)
{
T_link = T_one_pending_submission;
T_outtro = T_pending_submissions_outtro_single;
}
else
{
T_link =
T_multiple_pending_submissions.parameterize(rowCount);
T_outtro = T_pending_submissions_outtro_multiple;
}
Division pending = body.addDivision("pending-submissions");
Para para = pending.addPara();
para.addContent(T_pending_submissions_intro);
para.addXref("/xmlui/submissions", T_link);
para.addContent(T_outtro);
}
}
}
|
diff --git a/core/tests/org.eclipse.dltk.debug.tests/src/org/eclipse/dltk/debug/dbgp/tests/DbgpBase64Tests.java b/core/tests/org.eclipse.dltk.debug.tests/src/org/eclipse/dltk/debug/dbgp/tests/DbgpBase64Tests.java
index 6a1b3e26e..c4405de94 100644
--- a/core/tests/org.eclipse.dltk.debug.tests/src/org/eclipse/dltk/debug/dbgp/tests/DbgpBase64Tests.java
+++ b/core/tests/org.eclipse.dltk.debug.tests/src/org/eclipse/dltk/debug/dbgp/tests/DbgpBase64Tests.java
@@ -1,63 +1,64 @@
/*******************************************************************************
* Copyright (c) 2008 xored software, 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:
* xored software, Inc. - initial API and Implementation (Alex Panchenko)
*******************************************************************************/
package org.eclipse.dltk.debug.dbgp.tests;
import org.eclipse.dltk.dbgp.internal.utils.Base64Helper;
import junit.framework.TestCase;
public class DbgpBase64Tests extends TestCase {
public void testNullAndEmpty() {
assertEquals("", Base64Helper.encodeString(null));
assertEquals("", Base64Helper.encodeString(""));
assertEquals("", Base64Helper.decodeString(null));
assertEquals("", Base64Helper.decodeString(""));
assertEquals("", Base64Helper.decodeString("\r\n"));
}
public void testEndode() {
assertEquals("MTIz", Base64Helper.encodeString("123"));
assertEquals("MTIzNDU2Nzg5", Base64Helper.encodeString("123456789"));
}
public void testDecode() {
assertEquals("123", Base64Helper.decodeString("MTIz"));
assertEquals("123456789", Base64Helper.decodeString("MTIzNDU2Nzg5"));
}
public void testDecodeChunked() {
assertEquals("123", Base64Helper.decodeString("MTIz"));
assertEquals("123456789", Base64Helper.decodeString("MTIz" + "\n"
+ "NDU2" + "\n" + "Nzg5"));
}
public void testLongString() {
char[] c = new char[256];
for (int i = 0; i < c.length; ++i) {
c[i] = (char) i;
}
final String input = new String(c);
final String encoded = Base64Helper.encodeString(input);
final int chunkSize = 64;
final int chunkCount = (encoded.length() + chunkSize - 1) / chunkSize;
final StringBuffer chunked = new StringBuffer();
for (int i = 0; i < chunkCount; ++i) {
final int beginIndex = i * chunkSize;
final int endIndex = Math.min(encoded.length(), beginIndex
+ chunkSize);
chunked.append(encoded.substring(beginIndex, endIndex));
+ chunked.append("\r\n");
}
final String output = Base64Helper.decodeString(chunked.toString());
assertEquals(input, output);
}
}
| true | true | public void testLongString() {
char[] c = new char[256];
for (int i = 0; i < c.length; ++i) {
c[i] = (char) i;
}
final String input = new String(c);
final String encoded = Base64Helper.encodeString(input);
final int chunkSize = 64;
final int chunkCount = (encoded.length() + chunkSize - 1) / chunkSize;
final StringBuffer chunked = new StringBuffer();
for (int i = 0; i < chunkCount; ++i) {
final int beginIndex = i * chunkSize;
final int endIndex = Math.min(encoded.length(), beginIndex
+ chunkSize);
chunked.append(encoded.substring(beginIndex, endIndex));
}
final String output = Base64Helper.decodeString(chunked.toString());
assertEquals(input, output);
}
| public void testLongString() {
char[] c = new char[256];
for (int i = 0; i < c.length; ++i) {
c[i] = (char) i;
}
final String input = new String(c);
final String encoded = Base64Helper.encodeString(input);
final int chunkSize = 64;
final int chunkCount = (encoded.length() + chunkSize - 1) / chunkSize;
final StringBuffer chunked = new StringBuffer();
for (int i = 0; i < chunkCount; ++i) {
final int beginIndex = i * chunkSize;
final int endIndex = Math.min(encoded.length(), beginIndex
+ chunkSize);
chunked.append(encoded.substring(beginIndex, endIndex));
chunked.append("\r\n");
}
final String output = Base64Helper.decodeString(chunked.toString());
assertEquals(input, output);
}
|
diff --git a/src/java/org/wings/plaf/css/FrameCG.java b/src/java/org/wings/plaf/css/FrameCG.java
index 351ab459..7badb742 100644
--- a/src/java/org/wings/plaf/css/FrameCG.java
+++ b/src/java/org/wings/plaf/css/FrameCG.java
@@ -1,376 +1,376 @@
/*
* $Id$
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://www.j-wings.org).
*
* wingS is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* Please see COPYING for the complete licence.
*/
package org.wings.plaf.css;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wings.*;
import org.wings.externalizer.ExternalizeManager;
import org.wings.header.Link;
import org.wings.header.Script;
import org.wings.io.Device;
import org.wings.plaf.CGManager;
import org.wings.resource.ClassPathStylesheetResource;
import org.wings.resource.ClasspathResource;
import org.wings.resource.DefaultURLResource;
import org.wings.resource.DynamicCodeResource;
import org.wings.script.DynamicScriptResource;
import org.wings.script.JavaScriptListener;
import org.wings.script.ScriptListener;
import org.wings.session.Browser;
import org.wings.session.BrowserType;
import org.wings.session.SessionManager;
import org.wings.style.CSSSelector;
import org.wings.style.DynamicStyleSheetResource;
import java.io.IOException;
import java.util.*;
public class FrameCG implements org.wings.plaf.FrameCG {
private final transient static Log log = LogFactory.getLog(FrameCG.class);
/**
* The default DOCTYPE enforcing standard (non-quirks mode) in all current browsers.
* Please be aware, that changing the DOCTYPE may change the way how browser renders the generate
* document i.e. esp. the CSS attribute inheritance does not work correctly on <code>table</code> elements.
* See i.e. http://www.ericmeyeroncss.com/bonus/render-mode.html
*/
public final static String STRICT_DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" " +
"\"http://www.w3.org/TR/REC-html40/strict.dtd\">";
/**
* The HTML DOCTYPE setting all browsers to Quirks mode.
* We need this to force IE to use the correct box rendering model. It's the only browser
* you cannot reconfigure via an CSS tag.
*/
public final static String QUIRKS_DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">";
private String documentType = STRICT_DOCTYPE;
private Boolean renderXmlDeclaration = Boolean.FALSE;
/**
* Initialize properties from config
*/
public FrameCG() {
final CGManager manager = SessionManager.getSession().getCGManager();
final String userDocType = (String) manager.getObject("FrameCG.userDocType", String.class);
final Boolean userRenderXmlDecl = (Boolean) manager.getObject("FrameCG.renderXmlDeclaration", Boolean.class);
if (userDocType != null)
setDocumentType(userDocType);
if (userRenderXmlDecl != null)
setRenderXmlDeclaration(userRenderXmlDecl);
}
private static final String PROPERTY_STYLESHEET = "Stylesheet.";
private static final String BROWSER_DEFAULT = "default";
private final static Set javascriptResourceKeys;
static {
javascriptResourceKeys = new HashSet();
javascriptResourceKeys.add("JScripts.domlib");
javascriptResourceKeys.add("JScripts.domtt");
}
/**
* Externalizes the style sheet(s) for this session.
* Look up according style sheet file name in org.wings.plaf.css.properties file under Stylesheet.BROWSERNAME.
* The style sheet is loaded from the class path.
* @return the URLs under which the css file(s) was externalized
*/
private List externalizeBrowserStylesheets() {
final ExternalizeManager extManager = SessionManager.getSession().getExternalizeManager();
final CGManager manager = SessionManager.getSession().getCGManager();
final String browserName = SessionManager.getSession().getUserAgent().getBrowserType().getShortName();
final String cssResource = PROPERTY_STYLESHEET + browserName;
String cssClassPaths = (String)manager.getObject(cssResource, String.class);
// catch missing browser entry in properties file
if (cssClassPaths == null) {
cssClassPaths = (String)manager.getObject(PROPERTY_STYLESHEET + BROWSER_DEFAULT, String.class);
}
StringTokenizer tokenizer = new StringTokenizer(cssClassPaths,",");
ArrayList cssUrls = new ArrayList();
while (tokenizer.hasMoreTokens()) {
String cssClassPath = tokenizer.nextToken();
ClassPathStylesheetResource res = new ClassPathStylesheetResource(cssClassPath, "text/css");
String cssUrl = extManager.externalize(res, ExternalizeManager.GLOBAL);
if (cssUrl != null)
cssUrls.add(cssUrl);
}
return cssUrls;
}
/**
* @param jsResKey
* @return
*/
private String externalizeJavaScript(String jsResKey) {
final ExternalizeManager extManager = SessionManager.getSession().getExternalizeManager();
final CGManager manager = SessionManager.getSession().getCGManager();
String jsClassPath = (String)manager.getObject(jsResKey, String.class);
// catch missing script entry in properties file
if (jsClassPath != null) {
ClasspathResource res = new ClasspathResource(jsClassPath, "text/javascript");
return extManager.externalize(res, ExternalizeManager.GLOBAL);
}
return null;
}
public static final String UTILS_SCRIPT = (String) SessionManager
.getSession().getCGManager().getObject("JScripts.utils",
String.class);
public static final String FORM_SCRIPT = (String) SessionManager
.getSession().getCGManager().getObject("JScripts.form",
String.class);
public static final JavaScriptListener FOCUS_SCRIPT =
new JavaScriptListener("onfocus", "storeFocus(event)");
public static final JavaScriptListener SCROLL_POSITION_SCRIPT =
new JavaScriptListener("onscroll", "storeScrollPosition(event)");
public void installCG(final SComponent comp) {
final SFrame component = (SFrame) comp;
DynamicCodeResource dynamicCodeRessource;
DynamicStyleSheetResource styleSheetResource;
DynamicScriptResource scriptResource;
Link stylesheetLink;
// dynamic code resource.
dynamicCodeRessource = new DynamicCodeResource(component);
component.addDynamicResource(dynamicCodeRessource);
// dynamic stylesheet resource.
styleSheetResource = new DynamicStyleSheetResource(component);
stylesheetLink = new Link("stylesheet", null, "text/css", null, styleSheetResource);
component.addDynamicResource(styleSheetResource);
component.addHeader(stylesheetLink);
// dynamic java script resource.
scriptResource = new DynamicScriptResource(component);
component.addDynamicResource(scriptResource);
component.addHeader(new Script("text/javascript", scriptResource));
Iterator iter = javascriptResourceKeys.iterator();
while (iter.hasNext()) {
String jsResKey = (String) iter.next();
String jScriptUrl = externalizeJavaScript(jsResKey);
if (jScriptUrl != null) {
component.addHeader(new Script("text/javascript", new DefaultURLResource(jScriptUrl)));
}
}
final List externalizedBrowserCssUrls = externalizeBrowserStylesheets();
for (int i = 0; i < externalizedBrowserCssUrls.size(); i++) {
component.headers().add(i, new Link("stylesheet", null, "text/css", null, new DefaultURLResource((String) externalizedBrowserCssUrls.get(i))));;
}
addExternalizedHeader(component, UTILS_SCRIPT, "text/javascript");
addExternalizedHeader(component, FORM_SCRIPT, "text/javascript");
component.addScriptListener(FOCUS_SCRIPT);
component.addScriptListener(SCROLL_POSITION_SCRIPT);
CaptureDefaultBindingsScriptListener.install(component);
}
/**
* adds the file found at the classPath to the parentFrame header with
* the specified mimeType
* @param classPath the classPath to look in for the file
* @param mimeType the mimetype of the file
*/
private void addExternalizedHeader(SFrame parentFrame, String classPath, String mimeType) {
ClasspathResource res = new ClasspathResource(classPath, mimeType);
String jScriptUrl = SessionManager.getSession().getExternalizeManager().externalize(res, ExternalizeManager.GLOBAL);
parentFrame.addHeader(new Script(mimeType, new DefaultURLResource(jScriptUrl)));
}
public void uninstallCG(final SComponent comp) {
final SFrame component = (SFrame) comp;
component.removeDynamicResource(DynamicCodeResource.class);
component.removeDynamicResource(DynamicStyleSheetResource.class);
component.removeDynamicResource(DynamicScriptResource.class);
component.clearHeaders();
}
public void write(final Device device, final SComponent _c)
throws IOException {
if (!_c.isVisible()) return;
_c.fireRenderEvent(SComponent.START_RENDERING);
final SFrame component = (SFrame) _c;
Browser browser = SessionManager.getSession().getUserAgent();
SFrame frame = (SFrame) component;
String language = SessionManager.getSession().getLocale().getLanguage();
String title = frame.getTitle();
List headers = frame.headers();
String encoding = SessionManager.getSession().getCharacterEncoding();
/**
* We need to put IE6 into quirks mode
* for box model compatibility. (border-box).
* For that we make use of a comment in the first line.
* This is a known bug in IE6
*/
if (BrowserType.IE.equals(browser.getBrowserType())) {
if (browser.getMajorVersion() == 6) {
device.print("<!-- IE6 quirks mode switch -->\n");
}
}
if (renderXmlDeclaration == null || renderXmlDeclaration.booleanValue()) {
device.print("<?xml version=\"1.0\" encoding=\"");
Utils.write(device, encoding);
device.print("\"?>\n");
}
Utils.writeRaw(device, documentType);
device.print("\n");
device.print("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"");
Utils.write(device, language);
device.print("\" lang=\"");
Utils.write(device, language);
- device.print("\" />\n");
+ device.print("\">\n");
/* Insert version and compile time.
* Since the Version Class is generated on compile time, build errors
* in SDK's are quite normal. Just run the Version.java ant task.
*/
device.print("<!-- This is wingS (http://www.j-wings.org) version ");
device.print(Version.getVersion());
device.print(" (Build date: ");
device.print(Version.getCompileTime());
device.print(") -->\n");
device.print("<head>");
if (title != null) {
device.print("<title>");
Utils.write(device, title);
device.print("</title>\n");
}
device.print("<meta http-equiv=\"Content-type\" content=\"text/html; charset=");
Utils.write(device, encoding);
device.print("\"/>\n");
for (Iterator iterator = headers.iterator(); iterator.hasNext();) {
Object next = iterator.next();
if (next instanceof Renderable) {
((Renderable) next).write(device);
} else {
Utils.write(device, next.toString());
}
device.print("\n");
}
SComponent focus = frame.getFocus();
Object lastFocus = frame.getClientProperty("focus");
if (focus != lastFocus) {
if (lastFocus != null) {
ScriptListener[] scriptListeners = frame.getScriptListeners();
for (int i = 0; i < scriptListeners.length; i++) {
ScriptListener scriptListener = scriptListeners[i];
if (scriptListener instanceof FocusScriptListener)
component.removeScriptListener(scriptListener);
}
}
if (focus != null) {
FocusScriptListener listener = new FocusScriptListener("onload", "requestFocus('" + focus.getName() + "')");
frame.addScriptListener(listener);
}
frame.putClientProperty("focus", focus);
}
// let ie understand hover css styles on elements other than anchors
if (BrowserType.IE.equals(browser.getBrowserType())) {
// externalize hover behavior
final String classPath = (String)SessionManager.getSession().getCGManager().getObject("Behaviors.ieHover", String.class);
ClasspathResource res = new ClasspathResource(classPath, "text/x-component");
String behaviorUrl = SessionManager.getSession().getExternalizeManager().externalize(res, ExternalizeManager.GLOBAL);
device.print("<style type=\"text/css\" media=\"screen\">\n");
device.print("body{behavior:url(");
device.print(behaviorUrl);
device.print(");}\n");
device.print("</style>\n");
}
// TODO: move this to a dynamic script resource
SToolTipManager toolTipManager = component.getSession().getToolTipManager();
device
.print("<script type=\"text/javascript\">\n")
.print("domTT_addPredefined('default', 'caption', false");
if (toolTipManager.isFollowMouse())
device.print(", 'trail', true");
device.print(", 'delay', ").print(toolTipManager.getInitialDelay());
device.print(", 'lifetime', ").print(toolTipManager.getDismissDelay());
device
.print(");\n")
.print("</script>\n");
device.print("</head>\n");
device.print("<body");
Utils.optAttribute(device, "id", frame.getName());
Utils.optAttribute(device, "class", frame.getStyle());
Utils.writeEvents(device, frame);
device.print(">\n");
if (frame.isVisible()) {
frame.getLayout().write(device);
device.print("\n");
// now add all menus
Iterator iter = frame.getMenus().iterator();
while (iter.hasNext()) {
SComponent menu = (SComponent)iter.next();
menu.write(device);
}
}
device.print("\n</body></html>\n");
_c.fireRenderEvent(SComponent.DONE_RENDERING);
}
public String getDocumentType() {
return documentType;
}
public void setDocumentType(String documentType) {
this.documentType = documentType;
}
/**
* @return The current rendered DOCTYPE of this document. {@link #STRICT_DOCTYPE}
*/
public Boolean getRenderXmlDeclaration() {
return renderXmlDeclaration;
}
public void setRenderXmlDeclaration(Boolean renderXmlDeclaration) {
this.renderXmlDeclaration = renderXmlDeclaration;
}
public CSSSelector mapSelector(SComponent addressedComponent, CSSSelector selector) {
// Default: Do not map/modify the passed CSS selector.
return selector;
}
}
| true | true | public void write(final Device device, final SComponent _c)
throws IOException {
if (!_c.isVisible()) return;
_c.fireRenderEvent(SComponent.START_RENDERING);
final SFrame component = (SFrame) _c;
Browser browser = SessionManager.getSession().getUserAgent();
SFrame frame = (SFrame) component;
String language = SessionManager.getSession().getLocale().getLanguage();
String title = frame.getTitle();
List headers = frame.headers();
String encoding = SessionManager.getSession().getCharacterEncoding();
/**
* We need to put IE6 into quirks mode
* for box model compatibility. (border-box).
* For that we make use of a comment in the first line.
* This is a known bug in IE6
*/
if (BrowserType.IE.equals(browser.getBrowserType())) {
if (browser.getMajorVersion() == 6) {
device.print("<!-- IE6 quirks mode switch -->\n");
}
}
if (renderXmlDeclaration == null || renderXmlDeclaration.booleanValue()) {
device.print("<?xml version=\"1.0\" encoding=\"");
Utils.write(device, encoding);
device.print("\"?>\n");
}
Utils.writeRaw(device, documentType);
device.print("\n");
device.print("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"");
Utils.write(device, language);
device.print("\" lang=\"");
Utils.write(device, language);
device.print("\" />\n");
/* Insert version and compile time.
* Since the Version Class is generated on compile time, build errors
* in SDK's are quite normal. Just run the Version.java ant task.
*/
device.print("<!-- This is wingS (http://www.j-wings.org) version ");
device.print(Version.getVersion());
device.print(" (Build date: ");
device.print(Version.getCompileTime());
device.print(") -->\n");
device.print("<head>");
if (title != null) {
device.print("<title>");
Utils.write(device, title);
device.print("</title>\n");
}
device.print("<meta http-equiv=\"Content-type\" content=\"text/html; charset=");
Utils.write(device, encoding);
device.print("\"/>\n");
for (Iterator iterator = headers.iterator(); iterator.hasNext();) {
Object next = iterator.next();
if (next instanceof Renderable) {
((Renderable) next).write(device);
} else {
Utils.write(device, next.toString());
}
device.print("\n");
}
SComponent focus = frame.getFocus();
Object lastFocus = frame.getClientProperty("focus");
if (focus != lastFocus) {
if (lastFocus != null) {
ScriptListener[] scriptListeners = frame.getScriptListeners();
for (int i = 0; i < scriptListeners.length; i++) {
ScriptListener scriptListener = scriptListeners[i];
if (scriptListener instanceof FocusScriptListener)
component.removeScriptListener(scriptListener);
}
}
if (focus != null) {
FocusScriptListener listener = new FocusScriptListener("onload", "requestFocus('" + focus.getName() + "')");
frame.addScriptListener(listener);
}
frame.putClientProperty("focus", focus);
}
// let ie understand hover css styles on elements other than anchors
if (BrowserType.IE.equals(browser.getBrowserType())) {
// externalize hover behavior
final String classPath = (String)SessionManager.getSession().getCGManager().getObject("Behaviors.ieHover", String.class);
ClasspathResource res = new ClasspathResource(classPath, "text/x-component");
String behaviorUrl = SessionManager.getSession().getExternalizeManager().externalize(res, ExternalizeManager.GLOBAL);
device.print("<style type=\"text/css\" media=\"screen\">\n");
device.print("body{behavior:url(");
device.print(behaviorUrl);
device.print(");}\n");
device.print("</style>\n");
}
// TODO: move this to a dynamic script resource
SToolTipManager toolTipManager = component.getSession().getToolTipManager();
device
.print("<script type=\"text/javascript\">\n")
.print("domTT_addPredefined('default', 'caption', false");
if (toolTipManager.isFollowMouse())
device.print(", 'trail', true");
device.print(", 'delay', ").print(toolTipManager.getInitialDelay());
device.print(", 'lifetime', ").print(toolTipManager.getDismissDelay());
device
.print(");\n")
.print("</script>\n");
device.print("</head>\n");
device.print("<body");
Utils.optAttribute(device, "id", frame.getName());
Utils.optAttribute(device, "class", frame.getStyle());
Utils.writeEvents(device, frame);
device.print(">\n");
if (frame.isVisible()) {
frame.getLayout().write(device);
device.print("\n");
// now add all menus
Iterator iter = frame.getMenus().iterator();
while (iter.hasNext()) {
SComponent menu = (SComponent)iter.next();
menu.write(device);
}
}
device.print("\n</body></html>\n");
_c.fireRenderEvent(SComponent.DONE_RENDERING);
}
| public void write(final Device device, final SComponent _c)
throws IOException {
if (!_c.isVisible()) return;
_c.fireRenderEvent(SComponent.START_RENDERING);
final SFrame component = (SFrame) _c;
Browser browser = SessionManager.getSession().getUserAgent();
SFrame frame = (SFrame) component;
String language = SessionManager.getSession().getLocale().getLanguage();
String title = frame.getTitle();
List headers = frame.headers();
String encoding = SessionManager.getSession().getCharacterEncoding();
/**
* We need to put IE6 into quirks mode
* for box model compatibility. (border-box).
* For that we make use of a comment in the first line.
* This is a known bug in IE6
*/
if (BrowserType.IE.equals(browser.getBrowserType())) {
if (browser.getMajorVersion() == 6) {
device.print("<!-- IE6 quirks mode switch -->\n");
}
}
if (renderXmlDeclaration == null || renderXmlDeclaration.booleanValue()) {
device.print("<?xml version=\"1.0\" encoding=\"");
Utils.write(device, encoding);
device.print("\"?>\n");
}
Utils.writeRaw(device, documentType);
device.print("\n");
device.print("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"");
Utils.write(device, language);
device.print("\" lang=\"");
Utils.write(device, language);
device.print("\">\n");
/* Insert version and compile time.
* Since the Version Class is generated on compile time, build errors
* in SDK's are quite normal. Just run the Version.java ant task.
*/
device.print("<!-- This is wingS (http://www.j-wings.org) version ");
device.print(Version.getVersion());
device.print(" (Build date: ");
device.print(Version.getCompileTime());
device.print(") -->\n");
device.print("<head>");
if (title != null) {
device.print("<title>");
Utils.write(device, title);
device.print("</title>\n");
}
device.print("<meta http-equiv=\"Content-type\" content=\"text/html; charset=");
Utils.write(device, encoding);
device.print("\"/>\n");
for (Iterator iterator = headers.iterator(); iterator.hasNext();) {
Object next = iterator.next();
if (next instanceof Renderable) {
((Renderable) next).write(device);
} else {
Utils.write(device, next.toString());
}
device.print("\n");
}
SComponent focus = frame.getFocus();
Object lastFocus = frame.getClientProperty("focus");
if (focus != lastFocus) {
if (lastFocus != null) {
ScriptListener[] scriptListeners = frame.getScriptListeners();
for (int i = 0; i < scriptListeners.length; i++) {
ScriptListener scriptListener = scriptListeners[i];
if (scriptListener instanceof FocusScriptListener)
component.removeScriptListener(scriptListener);
}
}
if (focus != null) {
FocusScriptListener listener = new FocusScriptListener("onload", "requestFocus('" + focus.getName() + "')");
frame.addScriptListener(listener);
}
frame.putClientProperty("focus", focus);
}
// let ie understand hover css styles on elements other than anchors
if (BrowserType.IE.equals(browser.getBrowserType())) {
// externalize hover behavior
final String classPath = (String)SessionManager.getSession().getCGManager().getObject("Behaviors.ieHover", String.class);
ClasspathResource res = new ClasspathResource(classPath, "text/x-component");
String behaviorUrl = SessionManager.getSession().getExternalizeManager().externalize(res, ExternalizeManager.GLOBAL);
device.print("<style type=\"text/css\" media=\"screen\">\n");
device.print("body{behavior:url(");
device.print(behaviorUrl);
device.print(");}\n");
device.print("</style>\n");
}
// TODO: move this to a dynamic script resource
SToolTipManager toolTipManager = component.getSession().getToolTipManager();
device
.print("<script type=\"text/javascript\">\n")
.print("domTT_addPredefined('default', 'caption', false");
if (toolTipManager.isFollowMouse())
device.print(", 'trail', true");
device.print(", 'delay', ").print(toolTipManager.getInitialDelay());
device.print(", 'lifetime', ").print(toolTipManager.getDismissDelay());
device
.print(");\n")
.print("</script>\n");
device.print("</head>\n");
device.print("<body");
Utils.optAttribute(device, "id", frame.getName());
Utils.optAttribute(device, "class", frame.getStyle());
Utils.writeEvents(device, frame);
device.print(">\n");
if (frame.isVisible()) {
frame.getLayout().write(device);
device.print("\n");
// now add all menus
Iterator iter = frame.getMenus().iterator();
while (iter.hasNext()) {
SComponent menu = (SComponent)iter.next();
menu.write(device);
}
}
device.print("\n</body></html>\n");
_c.fireRenderEvent(SComponent.DONE_RENDERING);
}
|
diff --git a/src/amidst/map/widget/CursorInformationWidget.java b/src/amidst/map/widget/CursorInformationWidget.java
index 05714b6..4a198ca 100644
--- a/src/amidst/map/widget/CursorInformationWidget.java
+++ b/src/amidst/map/widget/CursorInformationWidget.java
@@ -1,36 +1,37 @@
package amidst.map.widget;
import java.awt.Graphics2D;
import java.awt.Point;
import MoF.MapViewer;
public class CursorInformationWidget extends PanelWidget {
private String message = "";
public CursorInformationWidget(MapViewer mapViewer) {
super(mapViewer);
setDimensions(20, 30);
forceVisibility(false);
}
@Override
public void draw(Graphics2D g2d, float time) {
- if (targetVisibility) {
- Point mouseLocation = map.screenToLocal(mapViewer.getMousePosition());
+ Point mouseLocation = null;
+ if ((mouseLocation = mapViewer.getMousePosition()) != null) {
+ mouseLocation = map.screenToLocal(mouseLocation);
String biomeName = map.getBiomeAliasAt(mouseLocation);
message = biomeName + " [ " + mouseLocation.x + ", " + mouseLocation.y + " ]";
}
int stringWidth = mapViewer.getFontMetrics().stringWidth(message);
setWidth(stringWidth + 20);
super.draw(g2d, time);
g2d.setColor(textColor);
g2d.drawString(message, x + 10, y + 20);
}
@Override
protected boolean onVisibilityCheck() {
return (mapViewer.getMousePosition() != null);
}
}
| true | true | public void draw(Graphics2D g2d, float time) {
if (targetVisibility) {
Point mouseLocation = map.screenToLocal(mapViewer.getMousePosition());
String biomeName = map.getBiomeAliasAt(mouseLocation);
message = biomeName + " [ " + mouseLocation.x + ", " + mouseLocation.y + " ]";
}
int stringWidth = mapViewer.getFontMetrics().stringWidth(message);
setWidth(stringWidth + 20);
super.draw(g2d, time);
g2d.setColor(textColor);
g2d.drawString(message, x + 10, y + 20);
}
| public void draw(Graphics2D g2d, float time) {
Point mouseLocation = null;
if ((mouseLocation = mapViewer.getMousePosition()) != null) {
mouseLocation = map.screenToLocal(mouseLocation);
String biomeName = map.getBiomeAliasAt(mouseLocation);
message = biomeName + " [ " + mouseLocation.x + ", " + mouseLocation.y + " ]";
}
int stringWidth = mapViewer.getFontMetrics().stringWidth(message);
setWidth(stringWidth + 20);
super.draw(g2d, time);
g2d.setColor(textColor);
g2d.drawString(message, x + 10, y + 20);
}
|
diff --git a/src/com/github/Holyvirus/Blacksmith/core/Eco/Engines/Material_Engine.java b/src/com/github/Holyvirus/Blacksmith/core/Eco/Engines/Material_Engine.java
index c7e5c26..fe635dc 100644
--- a/src/com/github/Holyvirus/Blacksmith/core/Eco/Engines/Material_Engine.java
+++ b/src/com/github/Holyvirus/Blacksmith/core/Eco/Engines/Material_Engine.java
@@ -1,126 +1,126 @@
package com.github.Holyvirus.Blacksmith.core.Eco.Engines;
import com.github.Holyvirus.Blacksmith.BlackSmith;
import com.github.Holyvirus.Blacksmith.core.Eco.mEco;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
public class Material_Engine extends mEco {
BlackSmith plugin;
private int hasAmount(Inventory inv, ItemStack item) {
MaterialData type = item.getData();
ArrayList<ItemStack> properStack = new ArrayList<ItemStack>();
int amount = 0;
HashMap<Integer, ? extends ItemStack> stacky = inv.all(item.getType());
for(Map.Entry<Integer, ? extends ItemStack> stack : stacky.entrySet()) {
ItemStack tmp = stack.getValue();
if(type == null && tmp.getData() == null) {
properStack.add(tmp);
amount += tmp.getAmount();
- }else if(type != null && tmp.getData() != null && type.toString().equalsIgnoreCase(tmp.getData().toString())) {
+ }else if(type != null && tmp.getData() != null && item.getDurability() == tmp.getDurability()) {
properStack.add(tmp);
amount += tmp.getAmount();
}
}
return amount;
}
private void removeItem(Inventory inventory, ItemStack item, int amt) {
ItemStack[] items = inventory.getContents();
for (int i = 0; i < items.length; i++) {
if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) {
if (items[i].getAmount() > amt) {
items[i].setAmount(items[i].getAmount() - amt);
break;
} else if (items[i].getAmount() == amt) {
items[i] = null;
break;
} else {
amt -= items[i].getAmount();
items[i] = null;
}
}
}
inventory.setContents(items);
}
public Material_Engine(BlackSmith plugin) {
this.plugin = plugin;
plugin.getLogger().log(Level.INFO, "Now using materials!");
}
@Override
public int getBalance(String player, ItemStack i) {
Player p = plugin.getServer().getPlayer(player);
if(p == null)
return 0;
return this.getBalance(player, i);
}
@Override
public int getBalance(Player player, ItemStack i) {
return this.hasAmount(player.getInventory(), i);
}
@Override
public boolean withdraw(String player, ItemStack i, int amount) {
Player p = plugin.getServer().getPlayer(player);
if(p == null)
return false;
return this.withdraw(player, i, amount);
}
@Override
public boolean withdraw(Player player, ItemStack i, int amount) {
int has = this.hasAmount(player.getInventory(), i);
if(has > amount) {
this.removeItem(player.getInventory(), i, amount);
}
return false;
}
@Override
public boolean deposit(String player, ItemStack i, int amount) {
Player p = plugin.getServer().getPlayer(player);
if(p == null)
return false;
return this.deposit(player, i, amount);
}
@Override
public boolean deposit(Player player, ItemStack i, int amount) {
HashMap<Integer, ItemStack> left;
i.setAmount(amount);
left = player.getInventory().addItem(i);
if(!left.isEmpty()) {
player.sendMessage(ChatColor.DARK_PURPLE + "You inventory is full dropping remaining contents!");
for(Map.Entry<Integer, ItemStack> stack : left.entrySet()) {
player.getWorld().dropItem(player.getLocation(), stack.getValue());
}
}
return true;
}
@Override
public boolean isLoaded() {
return true;
}
}
| true | true | private int hasAmount(Inventory inv, ItemStack item) {
MaterialData type = item.getData();
ArrayList<ItemStack> properStack = new ArrayList<ItemStack>();
int amount = 0;
HashMap<Integer, ? extends ItemStack> stacky = inv.all(item.getType());
for(Map.Entry<Integer, ? extends ItemStack> stack : stacky.entrySet()) {
ItemStack tmp = stack.getValue();
if(type == null && tmp.getData() == null) {
properStack.add(tmp);
amount += tmp.getAmount();
}else if(type != null && tmp.getData() != null && type.toString().equalsIgnoreCase(tmp.getData().toString())) {
properStack.add(tmp);
amount += tmp.getAmount();
}
}
return amount;
}
| private int hasAmount(Inventory inv, ItemStack item) {
MaterialData type = item.getData();
ArrayList<ItemStack> properStack = new ArrayList<ItemStack>();
int amount = 0;
HashMap<Integer, ? extends ItemStack> stacky = inv.all(item.getType());
for(Map.Entry<Integer, ? extends ItemStack> stack : stacky.entrySet()) {
ItemStack tmp = stack.getValue();
if(type == null && tmp.getData() == null) {
properStack.add(tmp);
amount += tmp.getAmount();
}else if(type != null && tmp.getData() != null && item.getDurability() == tmp.getDurability()) {
properStack.add(tmp);
amount += tmp.getAmount();
}
}
return amount;
}
|
diff --git a/com.buglabs.common/com/buglabs/bug/sysfs/BMIDevice.java b/com.buglabs.common/com/buglabs/bug/sysfs/BMIDevice.java
index 2dc7e4a..8d7a30c 100644
--- a/com.buglabs.common/com/buglabs/bug/sysfs/BMIDevice.java
+++ b/com.buglabs.common/com/buglabs/bug/sysfs/BMIDevice.java
@@ -1,188 +1,188 @@
package com.buglabs.bug.sysfs;
import java.io.File;
import java.io.IOException;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.sprinkles.Fn;
import com.buglabs.util.osgi.OSGiServiceLoader;
/**
* A for properties associated with a BMI module attached to
* BUG. This class is designed to be subclassed for specific modules.
*
* @author kgilmer
*
*/
public class BMIDevice extends SysfsNode {
/**
* Total number of possible BMI devices.
*/
public static final int MAX_BMI_SLOTS = 4;
private static final String SUSPEND_FILENAME = "suspend";
private String description;
private int gpioUsage;
private int powerUse;
private int revision;
private int vendor;
private int busUsage;
private int memorySize;
private int powerCharging;
private String productId;
private String serialNum;
private final int slot;
/**
* @param root of sysfs directory for bmi device
* @param slot slot index for bmi device
*/
public BMIDevice(File root, int slot) {
super(root);
this.slot = slot;
this.description = getFirstLineofFile(new File(root, "description"));
this.gpioUsage = parseInt(getFirstLineofFile(new File(root, "gpio_usage")));
this.powerUse = parseInt(getFirstLineofFile(new File(root, "power_use")));
this.revision = parseInt(getFirstLineofFile(new File(root, "revision")));
this.vendor = parseInt(getFirstLineofFile(new File(root, "vendor")));
this.busUsage = parseInt(getFirstLineofFile(new File(root, "bus_usage")));
this.memorySize = parseInt(getFirstLineofFile(new File(root, "memory_size")));
this.powerCharging = parseInt(getFirstLineofFile(new File(root, "power_charging")));
this.productId = parseHexInt(getFirstLineofFile(new File(root, "product")));
this.serialNum = parseMultiInt(getFirstLineofFile(new File(root, "serial_num")));
}
/**
* Create an instance of BMIModuleProperties class using the base BMI /sys
* filesystem directory, for example /sys/devices/conn-m1.
*
* @param directory of BMI sysfs entry
* @param slot slot index
* @return BMIDevice
*/
protected static BMIDevice createFromSYSDirectory(final BundleContext context, File directory, int slot) {
if (directory == null || !directory.exists() || !directory.isDirectory()) {
return null;
}
final String productId = parseHexInt(getFirstLineofFile(new File(directory, "product")));
BMIDeviceNodeFactory factory;
try {
factory = Fn.find(new Fn.Function<ServiceReference, BMIDeviceNodeFactory>() {
@Override
public BMIDeviceNodeFactory apply(ServiceReference element) {
if (element.getProperty("PRODUCT.ID") != null && element.getProperty("PRODUCT.ID").equals(productId))
- return context.getService(element);
+ return (BMIDeviceNodeFactory) context.getService(element);
return null;
}
}, context.getAllServiceReferences(BMIDeviceNodeFactory.class.getName(), null));
if (factory != null)
return factory.createBMIDeviceNode(directory, slot);
} catch (InvalidSyntaxException e) {
//Ignore
}
return new BMIDevice(directory, slot);
}
/**
* @return Slot device is attached to
*/
public int getSlot() {
return slot;
}
/**
* @return Description of device provided in EEPROM
*/
public String getDescription() {
return description;
}
/**
* @return GPIO Usage
*/
public int getGpioUsage() {
return gpioUsage;
}
/**
* @return Power Usage
*/
public int getPowerUse() {
return powerUse;
}
/**
* @return Module hardware revision number
*/
public int getRevision() {
return revision;
}
/**
* @return Vendor of hardware module
*/
public int getVendor() {
return vendor;
}
/**
* @return Hardware bus usage
*/
public int getBusUsage() {
return busUsage;
}
/**
* @return Memory usage
*/
public int getMemorySize() {
return memorySize;
}
/**
* @return power charging status
*/
public int getPowerCharging() {
return powerCharging;
}
/**
* @return Product ID of hardware module
*/
public String getProductId() {
return productId;
}
/**
* @return Serial number of hardware module
*/
public String getSerialNum() {
return serialNum;
}
/**
* @return true if device was successfully suspended, false otherwise.
* @throws IOException
*/
public void suspend() throws IOException {
println(new File(root, SUSPEND_FILENAME), "1");
}
/**
* @return true if device was successfully resumed, false otherwise.
* @throws IOException
*/
public void resume() throws IOException {
println(new File(root, SUSPEND_FILENAME), "0");
}
}
| true | true | protected static BMIDevice createFromSYSDirectory(final BundleContext context, File directory, int slot) {
if (directory == null || !directory.exists() || !directory.isDirectory()) {
return null;
}
final String productId = parseHexInt(getFirstLineofFile(new File(directory, "product")));
BMIDeviceNodeFactory factory;
try {
factory = Fn.find(new Fn.Function<ServiceReference, BMIDeviceNodeFactory>() {
@Override
public BMIDeviceNodeFactory apply(ServiceReference element) {
if (element.getProperty("PRODUCT.ID") != null && element.getProperty("PRODUCT.ID").equals(productId))
return context.getService(element);
return null;
}
}, context.getAllServiceReferences(BMIDeviceNodeFactory.class.getName(), null));
if (factory != null)
return factory.createBMIDeviceNode(directory, slot);
} catch (InvalidSyntaxException e) {
//Ignore
}
return new BMIDevice(directory, slot);
}
| protected static BMIDevice createFromSYSDirectory(final BundleContext context, File directory, int slot) {
if (directory == null || !directory.exists() || !directory.isDirectory()) {
return null;
}
final String productId = parseHexInt(getFirstLineofFile(new File(directory, "product")));
BMIDeviceNodeFactory factory;
try {
factory = Fn.find(new Fn.Function<ServiceReference, BMIDeviceNodeFactory>() {
@Override
public BMIDeviceNodeFactory apply(ServiceReference element) {
if (element.getProperty("PRODUCT.ID") != null && element.getProperty("PRODUCT.ID").equals(productId))
return (BMIDeviceNodeFactory) context.getService(element);
return null;
}
}, context.getAllServiceReferences(BMIDeviceNodeFactory.class.getName(), null));
if (factory != null)
return factory.createBMIDeviceNode(directory, slot);
} catch (InvalidSyntaxException e) {
//Ignore
}
return new BMIDevice(directory, slot);
}
|
diff --git a/gnu/testlet/java/beans/beancontext/InstantiateChild.java b/gnu/testlet/java/beans/beancontext/InstantiateChild.java
index 0106d9d3..4ae37688 100644
--- a/gnu/testlet/java/beans/beancontext/InstantiateChild.java
+++ b/gnu/testlet/java/beans/beancontext/InstantiateChild.java
@@ -1,57 +1,56 @@
// Tags: JDK1.2
/*
Copyright (C) 2006 Andrew John Hughes ([email protected])
This file is part of Mauve.
Mauve is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
Mauve 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 Mauve; see the file COPYING. If not, write to
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
package gnu.testlet.java.beans.beancontext;
import gnu.testlet.Testlet;
import gnu.testlet.TestHarness;
import java.beans.beancontext.BeanContextSupport;
public class InstantiateChild
implements Testlet
{
private static BeanContextSupport context = new BeanContextSupport();
public void test(TestHarness h)
{
try
{
/* Check initial empty status of context */
h.check(context.isEmpty(), "Empty check");
h.check(context.size() == 0, "Size of 0 check");
/* Add child */
- h.check(context.instantiateChild("java.beans.beancontext.BeanContextChildSupport"),
- "Child instantiated addition check");
+ context.instantiateChild("java.beans.beancontext.BeanContextChildSupport");
/* Check child is added to context */
h.check(context.isEmpty() == false, "Non-empty check");
h.check(context.size() == 1, "Size of 1 check");
}
catch (Exception e)
{
h.debug(e);
}
}
}
| true | true | public void test(TestHarness h)
{
try
{
/* Check initial empty status of context */
h.check(context.isEmpty(), "Empty check");
h.check(context.size() == 0, "Size of 0 check");
/* Add child */
h.check(context.instantiateChild("java.beans.beancontext.BeanContextChildSupport"),
"Child instantiated addition check");
/* Check child is added to context */
h.check(context.isEmpty() == false, "Non-empty check");
h.check(context.size() == 1, "Size of 1 check");
}
catch (Exception e)
{
h.debug(e);
}
}
| public void test(TestHarness h)
{
try
{
/* Check initial empty status of context */
h.check(context.isEmpty(), "Empty check");
h.check(context.size() == 0, "Size of 0 check");
/* Add child */
context.instantiateChild("java.beans.beancontext.BeanContextChildSupport");
/* Check child is added to context */
h.check(context.isEmpty() == false, "Non-empty check");
h.check(context.size() == 1, "Size of 1 check");
}
catch (Exception e)
{
h.debug(e);
}
}
|
diff --git a/src/java/org/jivesoftware/openfire/nio/XMLLightweightParser.java b/src/java/org/jivesoftware/openfire/nio/XMLLightweightParser.java
index 866d0115..d694fed1 100644
--- a/src/java/org/jivesoftware/openfire/nio/XMLLightweightParser.java
+++ b/src/java/org/jivesoftware/openfire/nio/XMLLightweightParser.java
@@ -1,330 +1,329 @@
/**
* $Revision: $
* $Date: $
*
* Copyright (C) 2007 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.openfire.nio;
import org.apache.mina.common.ByteBuffer;
import org.jivesoftware.util.Log;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* This is a Light-Weight XML Parser.
* It read data from a channel and collect data until data are available in
* the channel.
* When a message is complete you can retrieve messages invoking the method
* getMsgs() and you can invoke the method areThereMsgs() to know if at least
* an message is presents.
*
* @author Daniele Piras
* @author Gaston Dombiak
*/
class XMLLightweightParser {
// Chars that rappresent CDATA section start
protected static char[] CDATA_START = {'<', '!', '[', 'C', 'D', 'A', 'T', 'A', '['};
// Chars that rappresent CDATA section end
protected static char[] CDATA_END = {']', ']', '>'};
// Buffer with all data retrieved
protected StringBuilder buffer = new StringBuilder();
// ---- INTERNAL STATUS -------
// Initial status
protected static final int INIT = 0;
// Status used when the first tag name is retrieved
protected static final int HEAD = 2;
// Status used when robot is inside the xml and it looking for the tag conclusion
protected static final int INSIDE = 3;
// Status used when a '<' is found and try to find the conclusion tag.
protected static final int PRETAIL = 4;
// Status used when the ending tag is equal to the head tag
protected static final int TAIL = 5;
// Status used when robot is inside the main tag and found an '/' to check '/>'.
protected static final int VERIFY_CLOSE_TAG = 6;
// Status used when you are inside a parameter
protected static final int INSIDE_PARAM_VALUE = 7;
// Status used when you are inside a cdata section
protected static final int INSIDE_CDATA = 8;
// Status used when you are outside a tag/reading text
protected static final int OUTSIDE = 9;
final String[] sstatus = {"INIT", "", "HEAD", "INSIDE", "PRETAIL", "TAIL", "VERIFY", "INSIDE_PARAM", "INSIDE_CDATA", "OUTSIDE"};
// Current robot status
protected int status = XMLLightweightParser.INIT;
// Index to looking for a CDATA section start or end.
protected int cdataOffset = 0;
// Number of chars that machs with the head tag. If the tailCount is equal to
// the head length so a close tag is found.
protected int tailCount = 0;
// Indicate the starting point in the buffer for the next message.
protected int startLastMsg = 0;
// Flag used to discover tag in the form <tag />.
protected boolean insideRootTag = false;
// Object conteining the head tag
protected StringBuilder head = new StringBuilder(5);
// List with all finished messages found.
protected List<String> msgs = new ArrayList<String>();
private int depth = 0;
protected boolean insideChildrenTag = false;
Charset encoder;
public XMLLightweightParser(String charset) {
encoder = Charset.forName(charset);
}
/*
* true if the parser has found some complete xml message.
*/
public boolean areThereMsgs() {
return (msgs.size() > 0);
}
/*
* @return an array with all messages found
*/
public String[] getMsgs() {
String[] res = new String[msgs.size()];
for (int i = 0; i < res.length; i++) {
res[i] = msgs.get(i);
}
msgs.clear();
invalidateBuffer();
return res;
}
/*
* Method use to re-initialize the buffer
*/
protected void invalidateBuffer() {
if (buffer.length() > 0) {
String str = buffer.substring(startLastMsg);
buffer.delete(0, buffer.length());
buffer.append(str);
buffer.trimToSize();
}
startLastMsg = 0;
}
/*
* Method that add a message to the list and reinit parser.
*/
protected void foundMsg(String msg) {
// Add message to the complete message list
if (msg != null) {
msgs.add(msg);
}
// Move the position into the buffer
status = XMLLightweightParser.INIT;
tailCount = 0;
cdataOffset = 0;
head.setLength(0);
insideRootTag = false;
insideChildrenTag = false;
depth = 0;
}
/*
* Main reading method
*/
public void read(ByteBuffer byteBuffer) throws Exception {
invalidateBuffer();
// Check that the buffer is not bigger than 1 Megabyte. For security reasons
// we will abort parsing when 1 Mega of queued chars was found.
if (buffer.length() > 1048576) {
throw new Exception("Stopped parsing never ending stanza");
}
CharBuffer charBuffer = encoder.decode(byteBuffer.buf());
char[] buf = charBuffer.array();
int readByte = charBuffer.remaining();
// Verify if the last received byte is an incomplete double byte character
char lastChar = buf[readByte-1];
- //if (Character.isISOControl(lastChar) || lastChar >= 0xfff0) {
if (lastChar >= 0xfff0) {
if (Log.isDebugEnabled()) {
Log.debug("Waiting to get complete char: " + String.valueOf(buf));
}
// Rewind the position one place so the last byte stays in the buffer
// The missing byte should arrive in the next iteration. Once we have both
// of bytes we will have the correct character
byteBuffer.position(byteBuffer.position()-1);
// Decrease the number of bytes read by one
readByte--;
}
buffer.append(buf, 0, readByte);
// Do nothing if the buffer only contains white spaces
if (buffer.charAt(0) <= ' ' && buffer.charAt(buffer.length()-1) <= ' ') {
if ("".equals(buffer.toString().trim())) {
// Empty the buffer so there is no memory leak
buffer.delete(0, buffer.length());
return;
}
}
// Robot.
char ch;
for (int i = 0; i < readByte; i++) {
ch = buf[i];
if (status == XMLLightweightParser.TAIL) {
// Looking for the close tag
if (depth < 1 && ch == head.charAt(tailCount)) {
tailCount++;
if (tailCount == head.length()) {
// Close stanza found!
// Calculate the correct start,end position of the message into the buffer
int end = buffer.length() - readByte + (i + 1);
String msg = buffer.substring(startLastMsg, end);
// Add message to the list
foundMsg(msg);
startLastMsg = end;
}
} else {
tailCount = 0;
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.PRETAIL) {
if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_START.length) {
status = XMLLightweightParser.INSIDE_CDATA;
cdataOffset = 0;
continue;
}
} else {
cdataOffset = 0;
status = XMLLightweightParser.INSIDE;
}
if (ch == '/') {
status = XMLLightweightParser.TAIL;
depth--;
}
else if (ch == '!') {
// This is a <! (comment) so ignore it
status = XMLLightweightParser.INSIDE;
}
else {
depth++;
}
} else if (status == XMLLightweightParser.VERIFY_CLOSE_TAG) {
if (ch == '>') {
depth--;
status = XMLLightweightParser.OUTSIDE;
if (depth < 1) {
// Found a tag in the form <tag />
int end = buffer.length() - readByte + (i + 1);
String msg = buffer.substring(startLastMsg, end);
// Add message to the list
foundMsg(msg);
startLastMsg = end;
}
} else if (ch == '<') {
status = XMLLightweightParser.PRETAIL;
insideChildrenTag = true;
} else {
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.INSIDE_PARAM_VALUE) {
if (ch == '"') {
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.INSIDE_CDATA) {
if (ch == XMLLightweightParser.CDATA_END[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_END.length) {
status = XMLLightweightParser.OUTSIDE;
cdataOffset = 0;
}
} else {
cdataOffset = 0;
}
} else if (status == XMLLightweightParser.INSIDE) {
if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_START.length) {
status = XMLLightweightParser.INSIDE_CDATA;
cdataOffset = 0;
continue;
}
} else {
cdataOffset = 0;
status = XMLLightweightParser.INSIDE;
}
if (ch == '"') {
status = XMLLightweightParser.INSIDE_PARAM_VALUE;
} else if (ch == '>') {
status = XMLLightweightParser.OUTSIDE;
if (insideRootTag && ("stream:stream>".equals(head.toString()) ||
("?xml>".equals(head.toString())) || ("flash:stream>".equals(head.toString())))) {
// Found closing stream:stream
int end = buffer.length() - readByte + (i + 1);
// Skip LF, CR and other "weird" characters that could appear
while (startLastMsg < end && '<' != buffer.charAt(startLastMsg)) {
startLastMsg++;
}
String msg = buffer.substring(startLastMsg, end);
foundMsg(msg);
startLastMsg = end;
}
insideRootTag = false;
} else if (ch == '/') {
status = XMLLightweightParser.VERIFY_CLOSE_TAG;
}
} else if (status == XMLLightweightParser.HEAD) {
if (ch == ' ' || ch == '>') {
// Append > to head to allow searching </tag>
head.append(">");
if(ch == '>')
status = XMLLightweightParser.OUTSIDE;
else
status = XMLLightweightParser.INSIDE;
insideRootTag = true;
insideChildrenTag = false;
continue;
}
else if (ch == '/' && head.length() > 0) {
status = XMLLightweightParser.VERIFY_CLOSE_TAG;
depth--;
}
head.append(ch);
} else if (status == XMLLightweightParser.INIT) {
if (ch == '<') {
status = XMLLightweightParser.HEAD;
depth = 1;
}
else {
startLastMsg++;
}
} else if (status == XMLLightweightParser.OUTSIDE) {
if (ch == '<') {
status = XMLLightweightParser.PRETAIL;
cdataOffset = 1;
insideChildrenTag = true;
}
}
}
if (head.length() > 0 &&
("/stream:stream>".equals(head.toString()) || ("/flash:stream>".equals(head.toString())))) {
// Found closing stream:stream
foundMsg("</stream:stream>");
}
}
}
| true | true | public void read(ByteBuffer byteBuffer) throws Exception {
invalidateBuffer();
// Check that the buffer is not bigger than 1 Megabyte. For security reasons
// we will abort parsing when 1 Mega of queued chars was found.
if (buffer.length() > 1048576) {
throw new Exception("Stopped parsing never ending stanza");
}
CharBuffer charBuffer = encoder.decode(byteBuffer.buf());
char[] buf = charBuffer.array();
int readByte = charBuffer.remaining();
// Verify if the last received byte is an incomplete double byte character
char lastChar = buf[readByte-1];
//if (Character.isISOControl(lastChar) || lastChar >= 0xfff0) {
if (lastChar >= 0xfff0) {
if (Log.isDebugEnabled()) {
Log.debug("Waiting to get complete char: " + String.valueOf(buf));
}
// Rewind the position one place so the last byte stays in the buffer
// The missing byte should arrive in the next iteration. Once we have both
// of bytes we will have the correct character
byteBuffer.position(byteBuffer.position()-1);
// Decrease the number of bytes read by one
readByte--;
}
buffer.append(buf, 0, readByte);
// Do nothing if the buffer only contains white spaces
if (buffer.charAt(0) <= ' ' && buffer.charAt(buffer.length()-1) <= ' ') {
if ("".equals(buffer.toString().trim())) {
// Empty the buffer so there is no memory leak
buffer.delete(0, buffer.length());
return;
}
}
// Robot.
char ch;
for (int i = 0; i < readByte; i++) {
ch = buf[i];
if (status == XMLLightweightParser.TAIL) {
// Looking for the close tag
if (depth < 1 && ch == head.charAt(tailCount)) {
tailCount++;
if (tailCount == head.length()) {
// Close stanza found!
// Calculate the correct start,end position of the message into the buffer
int end = buffer.length() - readByte + (i + 1);
String msg = buffer.substring(startLastMsg, end);
// Add message to the list
foundMsg(msg);
startLastMsg = end;
}
} else {
tailCount = 0;
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.PRETAIL) {
if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_START.length) {
status = XMLLightweightParser.INSIDE_CDATA;
cdataOffset = 0;
continue;
}
} else {
cdataOffset = 0;
status = XMLLightweightParser.INSIDE;
}
if (ch == '/') {
status = XMLLightweightParser.TAIL;
depth--;
}
else if (ch == '!') {
// This is a <! (comment) so ignore it
status = XMLLightweightParser.INSIDE;
}
else {
depth++;
}
} else if (status == XMLLightweightParser.VERIFY_CLOSE_TAG) {
if (ch == '>') {
depth--;
status = XMLLightweightParser.OUTSIDE;
if (depth < 1) {
// Found a tag in the form <tag />
int end = buffer.length() - readByte + (i + 1);
String msg = buffer.substring(startLastMsg, end);
// Add message to the list
foundMsg(msg);
startLastMsg = end;
}
} else if (ch == '<') {
status = XMLLightweightParser.PRETAIL;
insideChildrenTag = true;
} else {
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.INSIDE_PARAM_VALUE) {
if (ch == '"') {
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.INSIDE_CDATA) {
if (ch == XMLLightweightParser.CDATA_END[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_END.length) {
status = XMLLightweightParser.OUTSIDE;
cdataOffset = 0;
}
} else {
cdataOffset = 0;
}
} else if (status == XMLLightweightParser.INSIDE) {
if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_START.length) {
status = XMLLightweightParser.INSIDE_CDATA;
cdataOffset = 0;
continue;
}
} else {
cdataOffset = 0;
status = XMLLightweightParser.INSIDE;
}
if (ch == '"') {
status = XMLLightweightParser.INSIDE_PARAM_VALUE;
} else if (ch == '>') {
status = XMLLightweightParser.OUTSIDE;
if (insideRootTag && ("stream:stream>".equals(head.toString()) ||
("?xml>".equals(head.toString())) || ("flash:stream>".equals(head.toString())))) {
// Found closing stream:stream
int end = buffer.length() - readByte + (i + 1);
// Skip LF, CR and other "weird" characters that could appear
while (startLastMsg < end && '<' != buffer.charAt(startLastMsg)) {
startLastMsg++;
}
String msg = buffer.substring(startLastMsg, end);
foundMsg(msg);
startLastMsg = end;
}
insideRootTag = false;
} else if (ch == '/') {
status = XMLLightweightParser.VERIFY_CLOSE_TAG;
}
} else if (status == XMLLightweightParser.HEAD) {
if (ch == ' ' || ch == '>') {
// Append > to head to allow searching </tag>
head.append(">");
if(ch == '>')
status = XMLLightweightParser.OUTSIDE;
else
status = XMLLightweightParser.INSIDE;
insideRootTag = true;
insideChildrenTag = false;
continue;
}
else if (ch == '/' && head.length() > 0) {
status = XMLLightweightParser.VERIFY_CLOSE_TAG;
depth--;
}
head.append(ch);
} else if (status == XMLLightweightParser.INIT) {
if (ch == '<') {
status = XMLLightweightParser.HEAD;
depth = 1;
}
else {
startLastMsg++;
}
} else if (status == XMLLightweightParser.OUTSIDE) {
if (ch == '<') {
status = XMLLightweightParser.PRETAIL;
cdataOffset = 1;
insideChildrenTag = true;
}
}
}
if (head.length() > 0 &&
("/stream:stream>".equals(head.toString()) || ("/flash:stream>".equals(head.toString())))) {
// Found closing stream:stream
foundMsg("</stream:stream>");
}
}
| public void read(ByteBuffer byteBuffer) throws Exception {
invalidateBuffer();
// Check that the buffer is not bigger than 1 Megabyte. For security reasons
// we will abort parsing when 1 Mega of queued chars was found.
if (buffer.length() > 1048576) {
throw new Exception("Stopped parsing never ending stanza");
}
CharBuffer charBuffer = encoder.decode(byteBuffer.buf());
char[] buf = charBuffer.array();
int readByte = charBuffer.remaining();
// Verify if the last received byte is an incomplete double byte character
char lastChar = buf[readByte-1];
if (lastChar >= 0xfff0) {
if (Log.isDebugEnabled()) {
Log.debug("Waiting to get complete char: " + String.valueOf(buf));
}
// Rewind the position one place so the last byte stays in the buffer
// The missing byte should arrive in the next iteration. Once we have both
// of bytes we will have the correct character
byteBuffer.position(byteBuffer.position()-1);
// Decrease the number of bytes read by one
readByte--;
}
buffer.append(buf, 0, readByte);
// Do nothing if the buffer only contains white spaces
if (buffer.charAt(0) <= ' ' && buffer.charAt(buffer.length()-1) <= ' ') {
if ("".equals(buffer.toString().trim())) {
// Empty the buffer so there is no memory leak
buffer.delete(0, buffer.length());
return;
}
}
// Robot.
char ch;
for (int i = 0; i < readByte; i++) {
ch = buf[i];
if (status == XMLLightweightParser.TAIL) {
// Looking for the close tag
if (depth < 1 && ch == head.charAt(tailCount)) {
tailCount++;
if (tailCount == head.length()) {
// Close stanza found!
// Calculate the correct start,end position of the message into the buffer
int end = buffer.length() - readByte + (i + 1);
String msg = buffer.substring(startLastMsg, end);
// Add message to the list
foundMsg(msg);
startLastMsg = end;
}
} else {
tailCount = 0;
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.PRETAIL) {
if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_START.length) {
status = XMLLightweightParser.INSIDE_CDATA;
cdataOffset = 0;
continue;
}
} else {
cdataOffset = 0;
status = XMLLightweightParser.INSIDE;
}
if (ch == '/') {
status = XMLLightweightParser.TAIL;
depth--;
}
else if (ch == '!') {
// This is a <! (comment) so ignore it
status = XMLLightweightParser.INSIDE;
}
else {
depth++;
}
} else if (status == XMLLightweightParser.VERIFY_CLOSE_TAG) {
if (ch == '>') {
depth--;
status = XMLLightweightParser.OUTSIDE;
if (depth < 1) {
// Found a tag in the form <tag />
int end = buffer.length() - readByte + (i + 1);
String msg = buffer.substring(startLastMsg, end);
// Add message to the list
foundMsg(msg);
startLastMsg = end;
}
} else if (ch == '<') {
status = XMLLightweightParser.PRETAIL;
insideChildrenTag = true;
} else {
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.INSIDE_PARAM_VALUE) {
if (ch == '"') {
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.INSIDE_CDATA) {
if (ch == XMLLightweightParser.CDATA_END[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_END.length) {
status = XMLLightweightParser.OUTSIDE;
cdataOffset = 0;
}
} else {
cdataOffset = 0;
}
} else if (status == XMLLightweightParser.INSIDE) {
if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_START.length) {
status = XMLLightweightParser.INSIDE_CDATA;
cdataOffset = 0;
continue;
}
} else {
cdataOffset = 0;
status = XMLLightweightParser.INSIDE;
}
if (ch == '"') {
status = XMLLightweightParser.INSIDE_PARAM_VALUE;
} else if (ch == '>') {
status = XMLLightweightParser.OUTSIDE;
if (insideRootTag && ("stream:stream>".equals(head.toString()) ||
("?xml>".equals(head.toString())) || ("flash:stream>".equals(head.toString())))) {
// Found closing stream:stream
int end = buffer.length() - readByte + (i + 1);
// Skip LF, CR and other "weird" characters that could appear
while (startLastMsg < end && '<' != buffer.charAt(startLastMsg)) {
startLastMsg++;
}
String msg = buffer.substring(startLastMsg, end);
foundMsg(msg);
startLastMsg = end;
}
insideRootTag = false;
} else if (ch == '/') {
status = XMLLightweightParser.VERIFY_CLOSE_TAG;
}
} else if (status == XMLLightweightParser.HEAD) {
if (ch == ' ' || ch == '>') {
// Append > to head to allow searching </tag>
head.append(">");
if(ch == '>')
status = XMLLightweightParser.OUTSIDE;
else
status = XMLLightweightParser.INSIDE;
insideRootTag = true;
insideChildrenTag = false;
continue;
}
else if (ch == '/' && head.length() > 0) {
status = XMLLightweightParser.VERIFY_CLOSE_TAG;
depth--;
}
head.append(ch);
} else if (status == XMLLightweightParser.INIT) {
if (ch == '<') {
status = XMLLightweightParser.HEAD;
depth = 1;
}
else {
startLastMsg++;
}
} else if (status == XMLLightweightParser.OUTSIDE) {
if (ch == '<') {
status = XMLLightweightParser.PRETAIL;
cdataOffset = 1;
insideChildrenTag = true;
}
}
}
if (head.length() > 0 &&
("/stream:stream>".equals(head.toString()) || ("/flash:stream>".equals(head.toString())))) {
// Found closing stream:stream
foundMsg("</stream:stream>");
}
}
|
diff --git a/src/main/java/org/dequis/anherobridge/AnHeroEndPoint.java b/src/main/java/org/dequis/anherobridge/AnHeroEndPoint.java
index 7147754..1778a7b 100644
--- a/src/main/java/org/dequis/anherobridge/AnHeroEndPoint.java
+++ b/src/main/java/org/dequis/anherobridge/AnHeroEndPoint.java
@@ -1,68 +1,68 @@
package org.dequis.anherobridge;
import java.util.List;
import org.bukkit.plugin.Plugin;
import com.dthielke.herochat.Herochat;
import com.dthielke.herochat.Channel;
import com.ensifera.animosity.craftirc.CraftIRC;
import com.ensifera.animosity.craftirc.EndPoint;
import com.ensifera.animosity.craftirc.RelayedMessage;
public class AnHeroEndPoint implements EndPoint {
private CraftIRC craftirc;
public String herotag;
public String irctag;
private Channel herochatChannel;
public AnHeroEndPoint(CraftIRC craftirc, String herotag, String irctag) {
this.craftirc = craftirc;
this.herotag = herotag;
this.irctag = irctag;
- this.herochatChannel = Herochat.getChannelManager().getChannel(herotag);
+ this.herochatChannel = Herochat.getChannelManager().getChannel(herotag);
}
public void register() {
this.craftirc.registerEndPoint(this.irctag, this);
}
public void unregister() {
this.craftirc.unregisterEndPoint(this.irctag);
}
@Override
public Type getType() {
return EndPoint.Type.MINECRAFT;
}
@Override
public void messageIn(RelayedMessage msg) {
// msg.getEvent() == "action", herochatChannel.emote?
this.herochatChannel.announce(msg.getMessage(this));
}
@Override
public boolean userMessageIn(String username, RelayedMessage msg) {
return false;
}
@Override
public boolean adminMessageIn(RelayedMessage msg) {
return false;
}
@Override
public List<String> listUsers() {
return null;
}
@Override
public List<String> listDisplayUsers() {
return null;
}
}
| true | true | public AnHeroEndPoint(CraftIRC craftirc, String herotag, String irctag) {
this.craftirc = craftirc;
this.herotag = herotag;
this.irctag = irctag;
this.herochatChannel = Herochat.getChannelManager().getChannel(herotag);
}
| public AnHeroEndPoint(CraftIRC craftirc, String herotag, String irctag) {
this.craftirc = craftirc;
this.herotag = herotag;
this.irctag = irctag;
this.herochatChannel = Herochat.getChannelManager().getChannel(herotag);
}
|
diff --git a/atlas-web/src/main/java/ae3/service/AtlasPlotter.java b/atlas-web/src/main/java/ae3/service/AtlasPlotter.java
index 1d0b9739f..034c85f04 100644
--- a/atlas-web/src/main/java/ae3/service/AtlasPlotter.java
+++ b/atlas-web/src/main/java/ae3/service/AtlasPlotter.java
@@ -1,207 +1,209 @@
package ae3.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.core.io.DescriptiveResource;
import ae3.model.AtlasTuple;
import ds.server.DataServerAPI;
import ds.server.ExpressionDataSet;
public class AtlasPlotter {
private AtlasPlotter() {};
private static AtlasPlotter _instance = null;
private static final String[] altColors= {"#D8D8D8","#F2F2F2"};
final java.util.regex.Pattern startsOrEndsWithDigits = java.util.regex.Pattern.compile("^\\d+|\\d+$");
public static AtlasPlotter instance() {
if(null == _instance) {
_instance = new AtlasPlotter();
}
return _instance;
}
public JSONObject getGeneInExpPlotData(String geneIdKey, String expIdKey, String EF) throws Exception{
AtlasRanker ranker = new AtlasRanker();
if(EF.equals("default")){
HashMap rankInfo = ranker.getHighestRankEF(expIdKey, geneIdKey);
EF = "ba_"+rankInfo.get("expfactor").toString();
}
System.out.println(EF);
ArrayList<String> topFVs = new ArrayList<String>();
List<AtlasTuple> atlusTuples = AtlasGeneService.getAtlasResult(geneIdKey, expIdKey);
for(int i=0; i<atlusTuples.size(); i++){
if(i>10)
break;
AtlasTuple at = atlusTuples.get(i);
if(at.getEf().equalsIgnoreCase(EF.substring(3)) && !at.getEfv().equals("V1")){
topFVs.add(at.getEfv().toLowerCase());
}
}
ExpressionDataSet ds = DataServerAPI.retrieveExpressionDataSet(geneIdKey, expIdKey, EF);
// double[][] data = ds.getSortedExpressionMatrix().get("ba_"+EF);
JSONObject jsonString = createJSON(ds,EF,geneIdKey, expIdKey, topFVs);
return jsonString;
}
private JSONObject createJSON(ExpressionDataSet eds, String EF, String gid, String eid, ArrayList<String> topFVs){
JSONObject plotData = new JSONObject();
try {
JSONObject series = new JSONObject();
JSONArray seriesList = new JSONArray();
JSONArray seriesData = new JSONArray();
Set<String> fvs = eds.getFactorValues(EF);
final Object[] fvs_arr = fvs.toArray();
Integer[] sortedFVindexes = sortFVs(fvs_arr);
JSONObject meanSeries = new JSONObject();
JSONArray meanSeriesData = new JSONArray();
HashMap<String, Double> fvMean_map = new HashMap<String, Double>();
int sampleIndex=1;
int c=0;
+ boolean unDiffPresent = false;
for (int i=0; i<fvs_arr.length; i++){
String fv = fvs_arr[sortedFVindexes[i]].toString();
ArrayList[] DEdata = eds.getDataByFV(EF, fv);
series = new JSONObject();
seriesData = new JSONArray();
for(int j=0; j<DEdata[0].size(); j++){//columns <==> samples with the same FV
for(int k=0; k<DEdata.length; k++){//rows <==> DEs
JSONArray point = new JSONArray();
point.put(sampleIndex);
point.put(DEdata[k].get(j));// loop over available DEs and add data points to the same x point
seriesData.put(point);
if(!fvMean_map.containsKey(fv+"_de"))
fvMean_map.put(fv+"_de",getMean(DEdata[k]));
double fvMean = fvMean_map.get(fv+"_de");
point = new JSONArray();
point.put(sampleIndex);
point.put(fvMean);
meanSeriesData.put(point);
}
sampleIndex++;
}
series.put("data", seriesData);
series.put("bars", new JSONObject("{show:true, align: \"center\", fill:true}"));
series.put("lines", new JSONObject("{show:false,lineWidth:2, fill:true}"));
series.put("points", new JSONObject("{show:false,radius:1}"));
series.put("label", fv);
series.put("legend",new JSONObject("{show:true}"));
//Choose series color
if(!topFVs.contains(fv.toLowerCase())){
series.put("color", altColors[c%2]);
series.put("legend",new JSONObject("{show:false}"));
c++;
}
if(EF.equals("ba_time")){
series.put("bars", new JSONObject("{show:false, align: \"center\", fill:true}"));
series.put("lines", new JSONObject("{show:true,lineWidth:2, fill:false}"));
}
seriesList.put(series);
}
//Create mean series
meanSeries.put("data", meanSeriesData);
meanSeries.put("lines", new JSONObject("{show:true,lineWidth:1.0}"));
meanSeries.put("points", new JSONObject("{show:false}"));
- meanSeries.put("color", "#1f1f1f");
+ meanSeries.put("color", "#bfbfbf");
meanSeries.put("label", "Mean");
meanSeries.put("legend",new JSONObject("{show:false}"));
+ meanSeries.put("hoverable", "false");
meanSeries.put("shadowSize","0");
seriesList.put(meanSeries);
plotData.put("series", seriesList);
int noOfCols = (fvs.size()>=5)? 2: fvs.size();
// JSONObject options = new JSONObject("{ xaxis:{ticks:0}, " +
// " legend:{ position:\"sw\", container: \"#"+gid+"_"+eid+"_legend\", extContainer: \"#"+gid+"_"+eid+"_legend_ext\" }," +
// " grid:{ backgroundColor: '#fafafa', autoHighlight: true, hoverable: true }," +
// " bars:{fill:0.7}," +
// " selection: { mode: \"x\" } }");
// JSONObject legend = new JSONObject();
//// legend.put("container", "#"+gid+"_"+eid+"_legend");
//// options.put("legend", legend);
// plotData.put("options", options);
} catch (JSONException e) {
e.printStackTrace();
}
return plotData;
}
private Integer[] sortFVs(final Object[] fvs){
Integer[] fso = new Integer[fvs.length];
for (int i = 0; i < fvs.length; i++) {
fso[i] = i;
}
Arrays.sort(fso,
new Comparator() {
public int compare(Object o1, Object o2) {
String s1 = fvs[((Integer) o1).intValue()].toString();
String s2 = fvs[((Integer) o2).intValue()].toString();
// want to make sure that empty strings are pushed to the back
if (s1.equals("") && s2.equals("")) return 0;
if (s1.equals("") && !s2.equals("")) return 1;
if (!s1.equals("") && s2.equals("")) return -1;
java.util.regex.Matcher m1 = startsOrEndsWithDigits.matcher(s1);
java.util.regex.Matcher m2 = startsOrEndsWithDigits.matcher(s2);
if (m1.find() && m2.find()) {
Long i1 = new Long(s1.substring(m1.start(), m1.end()));
Long i2 = new Long(s2.substring(m2.start(), m2.end()));
if (i1.compareTo(i2) == 0)
return s1.compareToIgnoreCase(s2);
else
return i1.compareTo(i2);
}
return s1.compareToIgnoreCase(s2);
}
});
return fso;
}
private double getMean(ArrayList<Double> test ){
double sum=0.0;
for(int i=0; i<test.size(); i++){
sum+= test.get(i);
}
return sum/test.size();
}
}
| false | true | private JSONObject createJSON(ExpressionDataSet eds, String EF, String gid, String eid, ArrayList<String> topFVs){
JSONObject plotData = new JSONObject();
try {
JSONObject series = new JSONObject();
JSONArray seriesList = new JSONArray();
JSONArray seriesData = new JSONArray();
Set<String> fvs = eds.getFactorValues(EF);
final Object[] fvs_arr = fvs.toArray();
Integer[] sortedFVindexes = sortFVs(fvs_arr);
JSONObject meanSeries = new JSONObject();
JSONArray meanSeriesData = new JSONArray();
HashMap<String, Double> fvMean_map = new HashMap<String, Double>();
int sampleIndex=1;
int c=0;
for (int i=0; i<fvs_arr.length; i++){
String fv = fvs_arr[sortedFVindexes[i]].toString();
ArrayList[] DEdata = eds.getDataByFV(EF, fv);
series = new JSONObject();
seriesData = new JSONArray();
for(int j=0; j<DEdata[0].size(); j++){//columns <==> samples with the same FV
for(int k=0; k<DEdata.length; k++){//rows <==> DEs
JSONArray point = new JSONArray();
point.put(sampleIndex);
point.put(DEdata[k].get(j));// loop over available DEs and add data points to the same x point
seriesData.put(point);
if(!fvMean_map.containsKey(fv+"_de"))
fvMean_map.put(fv+"_de",getMean(DEdata[k]));
double fvMean = fvMean_map.get(fv+"_de");
point = new JSONArray();
point.put(sampleIndex);
point.put(fvMean);
meanSeriesData.put(point);
}
sampleIndex++;
}
series.put("data", seriesData);
series.put("bars", new JSONObject("{show:true, align: \"center\", fill:true}"));
series.put("lines", new JSONObject("{show:false,lineWidth:2, fill:true}"));
series.put("points", new JSONObject("{show:false,radius:1}"));
series.put("label", fv);
series.put("legend",new JSONObject("{show:true}"));
//Choose series color
if(!topFVs.contains(fv.toLowerCase())){
series.put("color", altColors[c%2]);
series.put("legend",new JSONObject("{show:false}"));
c++;
}
if(EF.equals("ba_time")){
series.put("bars", new JSONObject("{show:false, align: \"center\", fill:true}"));
series.put("lines", new JSONObject("{show:true,lineWidth:2, fill:false}"));
}
seriesList.put(series);
}
//Create mean series
meanSeries.put("data", meanSeriesData);
meanSeries.put("lines", new JSONObject("{show:true,lineWidth:1.0}"));
meanSeries.put("points", new JSONObject("{show:false}"));
meanSeries.put("color", "#1f1f1f");
meanSeries.put("label", "Mean");
meanSeries.put("legend",new JSONObject("{show:false}"));
meanSeries.put("shadowSize","0");
seriesList.put(meanSeries);
plotData.put("series", seriesList);
int noOfCols = (fvs.size()>=5)? 2: fvs.size();
// JSONObject options = new JSONObject("{ xaxis:{ticks:0}, " +
// " legend:{ position:\"sw\", container: \"#"+gid+"_"+eid+"_legend\", extContainer: \"#"+gid+"_"+eid+"_legend_ext\" }," +
// " grid:{ backgroundColor: '#fafafa', autoHighlight: true, hoverable: true }," +
// " bars:{fill:0.7}," +
// " selection: { mode: \"x\" } }");
// JSONObject legend = new JSONObject();
//// legend.put("container", "#"+gid+"_"+eid+"_legend");
//// options.put("legend", legend);
// plotData.put("options", options);
} catch (JSONException e) {
e.printStackTrace();
}
return plotData;
}
| private JSONObject createJSON(ExpressionDataSet eds, String EF, String gid, String eid, ArrayList<String> topFVs){
JSONObject plotData = new JSONObject();
try {
JSONObject series = new JSONObject();
JSONArray seriesList = new JSONArray();
JSONArray seriesData = new JSONArray();
Set<String> fvs = eds.getFactorValues(EF);
final Object[] fvs_arr = fvs.toArray();
Integer[] sortedFVindexes = sortFVs(fvs_arr);
JSONObject meanSeries = new JSONObject();
JSONArray meanSeriesData = new JSONArray();
HashMap<String, Double> fvMean_map = new HashMap<String, Double>();
int sampleIndex=1;
int c=0;
boolean unDiffPresent = false;
for (int i=0; i<fvs_arr.length; i++){
String fv = fvs_arr[sortedFVindexes[i]].toString();
ArrayList[] DEdata = eds.getDataByFV(EF, fv);
series = new JSONObject();
seriesData = new JSONArray();
for(int j=0; j<DEdata[0].size(); j++){//columns <==> samples with the same FV
for(int k=0; k<DEdata.length; k++){//rows <==> DEs
JSONArray point = new JSONArray();
point.put(sampleIndex);
point.put(DEdata[k].get(j));// loop over available DEs and add data points to the same x point
seriesData.put(point);
if(!fvMean_map.containsKey(fv+"_de"))
fvMean_map.put(fv+"_de",getMean(DEdata[k]));
double fvMean = fvMean_map.get(fv+"_de");
point = new JSONArray();
point.put(sampleIndex);
point.put(fvMean);
meanSeriesData.put(point);
}
sampleIndex++;
}
series.put("data", seriesData);
series.put("bars", new JSONObject("{show:true, align: \"center\", fill:true}"));
series.put("lines", new JSONObject("{show:false,lineWidth:2, fill:true}"));
series.put("points", new JSONObject("{show:false,radius:1}"));
series.put("label", fv);
series.put("legend",new JSONObject("{show:true}"));
//Choose series color
if(!topFVs.contains(fv.toLowerCase())){
series.put("color", altColors[c%2]);
series.put("legend",new JSONObject("{show:false}"));
c++;
}
if(EF.equals("ba_time")){
series.put("bars", new JSONObject("{show:false, align: \"center\", fill:true}"));
series.put("lines", new JSONObject("{show:true,lineWidth:2, fill:false}"));
}
seriesList.put(series);
}
//Create mean series
meanSeries.put("data", meanSeriesData);
meanSeries.put("lines", new JSONObject("{show:true,lineWidth:1.0}"));
meanSeries.put("points", new JSONObject("{show:false}"));
meanSeries.put("color", "#bfbfbf");
meanSeries.put("label", "Mean");
meanSeries.put("legend",new JSONObject("{show:false}"));
meanSeries.put("hoverable", "false");
meanSeries.put("shadowSize","0");
seriesList.put(meanSeries);
plotData.put("series", seriesList);
int noOfCols = (fvs.size()>=5)? 2: fvs.size();
// JSONObject options = new JSONObject("{ xaxis:{ticks:0}, " +
// " legend:{ position:\"sw\", container: \"#"+gid+"_"+eid+"_legend\", extContainer: \"#"+gid+"_"+eid+"_legend_ext\" }," +
// " grid:{ backgroundColor: '#fafafa', autoHighlight: true, hoverable: true }," +
// " bars:{fill:0.7}," +
// " selection: { mode: \"x\" } }");
// JSONObject legend = new JSONObject();
//// legend.put("container", "#"+gid+"_"+eid+"_legend");
//// options.put("legend", legend);
// plotData.put("options", options);
} catch (JSONException e) {
e.printStackTrace();
}
return plotData;
}
|
diff --git a/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/SanitizingRequestRewriter.java b/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/SanitizingRequestRewriter.java
index 8c353297f..f24472713 100644
--- a/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/SanitizingRequestRewriter.java
+++ b/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/SanitizingRequestRewriter.java
@@ -1,147 +1,150 @@
/*
* 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.shindig.gadgets.render;
import org.apache.sanselan.ImageFormat;
import org.apache.sanselan.ImageReadException;
import org.apache.sanselan.Sanselan;
import org.apache.sanselan.common.byteSources.ByteSourceInputStream;
import org.apache.shindig.gadgets.http.HttpRequest;
import org.apache.shindig.gadgets.http.HttpResponse;
import org.apache.shindig.gadgets.parse.caja.CajaCssSanitizer;
import org.apache.shindig.gadgets.render.SanitizingGadgetRewriter.SanitizingProxyingLinkRewriter;
import org.apache.shindig.gadgets.rewrite.ContentRewriterFeature;
import org.apache.shindig.gadgets.rewrite.ContentRewriterFeatureFactory;
import org.apache.shindig.gadgets.rewrite.ContentRewriterUris;
import org.apache.shindig.gadgets.rewrite.MutableContent;
import org.apache.shindig.gadgets.rewrite.RequestRewriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.inject.Inject;
/**
* Rewriter that sanitizes CSS and image content.
*/
public class SanitizingRequestRewriter implements RequestRewriter {
private static final Logger logger =
Logger.getLogger(SanitizingRequestRewriter.class.getName());
private final CajaCssSanitizer cssSanitizer;
private final ContentRewriterFeatureFactory rewriterFeatureFactory;
private final ContentRewriterUris rewriterUris;
@Inject
public SanitizingRequestRewriter(
ContentRewriterFeatureFactory rewriterFeatureFactory,
ContentRewriterUris rewriterUris,
CajaCssSanitizer cssSanitizer) {
this.rewriterUris = rewriterUris;
this.cssSanitizer = cssSanitizer;
this.rewriterFeatureFactory = rewriterFeatureFactory;
}
public boolean rewrite(HttpRequest request, HttpResponse resp, MutableContent content) {
// Content fetched through the proxy can stipulate that it must be sanitized.
if (request.isSanitizationRequested()) {
ContentRewriterFeature rewriterFeature =
rewriterFeatureFactory.createRewriteAllFeature(request.getCacheTtl());
if (request.getRewriteMimeType().equalsIgnoreCase("text/css")) {
return rewriteProxiedCss(request, resp, content, rewriterFeature);
} else if (request.getRewriteMimeType().toLowerCase().startsWith("image/")) {
return rewriteProxiedImage(request, resp, content);
} else {
logger.log(Level.WARNING, "Request to sanitize unknown content type "
+ request.getRewriteMimeType()
+ " for " + request.getUri().toString());
content.setContent("");
return true;
}
} else {
// No Op
return false;
}
}
/**
* We don't actually rewrite the image we just ensure that it is in fact a valid
* and known image type.
*/
private boolean rewriteProxiedImage(HttpRequest request, HttpResponse resp,
MutableContent content) {
boolean imageIsSafe = false;
try {
String contentType = resp.getHeader("Content-Type");
if (contentType == null || contentType.toLowerCase().startsWith("image/")) {
// Unspecified or unknown image mime type.
try {
ImageFormat imageFormat = Sanselan
.guessFormat(new ByteSourceInputStream(resp.getResponse(),
request.getUri().getPath()));
if (imageFormat == ImageFormat.IMAGE_FORMAT_UNKNOWN) {
logger.log(Level.INFO, "Unable to sanitize unknown image type "
+ request.getUri().toString());
return true;
}
imageIsSafe = true;
// Return false to indicate that no rewriting occurred
return false;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} catch (ImageReadException ire) {
- throw new RuntimeException(ire);
+ // Unable to read the image so its not safe
+ logger.log(Level.INFO, "Unable to detect image type for " +request.getUri().toString() +
+ " for sanitized content", ire);
+ return true;
}
} else {
return true;
}
} finally {
if (!imageIsSafe) {
content.setContent("");
}
}
}
/**
* Sanitize a CSS file.
*/
private boolean rewriteProxiedCss(HttpRequest request, HttpResponse response,
MutableContent content, ContentRewriterFeature rewriterFeature) {
String sanitized = "";
try {
String contentType = response.getHeader("Content-Type");
if (contentType == null || contentType.toLowerCase().startsWith("text/")) {
String proxyBaseNoGadget = rewriterUris.getProxyBase(request.getContainer());
SanitizingProxyingLinkRewriter cssImportRewriter = new SanitizingProxyingLinkRewriter(
request.getGadget(), rewriterFeature, proxyBaseNoGadget, "text/css");
SanitizingProxyingLinkRewriter cssImageRewriter = new SanitizingProxyingLinkRewriter(
request.getGadget(), rewriterFeature, proxyBaseNoGadget, "image/*");
sanitized = cssSanitizer.sanitize(content.getContent(), request.getUri(), cssImportRewriter,
cssImageRewriter);
}
return true;
} finally {
// Set sanitized content in finally to ensure it is always cleared in
// the case of errors
content.setContent(sanitized);
}
}
}
| true | true | private boolean rewriteProxiedImage(HttpRequest request, HttpResponse resp,
MutableContent content) {
boolean imageIsSafe = false;
try {
String contentType = resp.getHeader("Content-Type");
if (contentType == null || contentType.toLowerCase().startsWith("image/")) {
// Unspecified or unknown image mime type.
try {
ImageFormat imageFormat = Sanselan
.guessFormat(new ByteSourceInputStream(resp.getResponse(),
request.getUri().getPath()));
if (imageFormat == ImageFormat.IMAGE_FORMAT_UNKNOWN) {
logger.log(Level.INFO, "Unable to sanitize unknown image type "
+ request.getUri().toString());
return true;
}
imageIsSafe = true;
// Return false to indicate that no rewriting occurred
return false;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} catch (ImageReadException ire) {
throw new RuntimeException(ire);
}
} else {
return true;
}
} finally {
if (!imageIsSafe) {
content.setContent("");
}
}
}
| private boolean rewriteProxiedImage(HttpRequest request, HttpResponse resp,
MutableContent content) {
boolean imageIsSafe = false;
try {
String contentType = resp.getHeader("Content-Type");
if (contentType == null || contentType.toLowerCase().startsWith("image/")) {
// Unspecified or unknown image mime type.
try {
ImageFormat imageFormat = Sanselan
.guessFormat(new ByteSourceInputStream(resp.getResponse(),
request.getUri().getPath()));
if (imageFormat == ImageFormat.IMAGE_FORMAT_UNKNOWN) {
logger.log(Level.INFO, "Unable to sanitize unknown image type "
+ request.getUri().toString());
return true;
}
imageIsSafe = true;
// Return false to indicate that no rewriting occurred
return false;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} catch (ImageReadException ire) {
// Unable to read the image so its not safe
logger.log(Level.INFO, "Unable to detect image type for " +request.getUri().toString() +
" for sanitized content", ire);
return true;
}
} else {
return true;
}
} finally {
if (!imageIsSafe) {
content.setContent("");
}
}
}
|
diff --git a/ActiveObjects/src/net/java/ao/schema/UnderscoreFieldNameConverter.java b/ActiveObjects/src/net/java/ao/schema/UnderscoreFieldNameConverter.java
index 25716a7..7b3b02c 100644
--- a/ActiveObjects/src/net/java/ao/schema/UnderscoreFieldNameConverter.java
+++ b/ActiveObjects/src/net/java/ao/schema/UnderscoreFieldNameConverter.java
@@ -1,111 +1,111 @@
/*
* Copyright 2007 Daniel Spiewak
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.java.ao.schema;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>Imposes an underscore word-separation convention upon field names.
* This will convert field in the following way:</p>
*
* <table border="1">
* <tr>
* <td><b>Method Name</b></td>
* <td><b>Returns Entity?</b></td>
* <td><b>Field Name</b></td>
* </tr>
*
* <tr>
* <td>getFirstName</td>
* <td><code>false</code></td>
* <td>first_name</td>
* </tr>
*
* <tr>
* <td>setLastName</td>
* <td><code>false</code></td>
* <td>last_name</td>
* </tr>
*
* <tr>
* <td>getCompany</td>
* <td><code>true</code></td>
* <td>company_id</td>
* </tr>
*
* <tr>
* <td>isCool</td>
* <td><code>false</code></td>
* <td>cool</td>
* </tr>
* </table>
*
* <p>This converter allows for both all-lowercase and all-uppercase
* field name conventions. For example, depending on the configuration,
* <code>getLastName</code> may convert to "LAST_NAME".</p>
*
* <p>This converter is all that is required to emulate the ActiveRecord
* field name conversion.</p>
*
* @author Daniel Spiewak
*/
public class UnderscoreFieldNameConverter extends AbstractFieldNameConverter {
private static final Pattern WORD_PATTERN = Pattern.compile("([a-z\\d])([A-Z\\d])");
private boolean uppercase;
/**
* Creates a new field name converter in which all field names will
* be either fully uppercase or fully lowercase.
*
* @param uppercase <code>true</code> if field names should be all
* uppercase, <code>false</code> if field names should be all
* lowercase.
*/
public UnderscoreFieldNameConverter(boolean uppercase) {
this.uppercase = uppercase;
}
/**
* Returns whether or not resulting field names will be entirely
* uppercase. If <code>false</code>, field names will be entirely
* lowercase.
*/
public boolean isUppercase() {
return uppercase;
}
@Override
protected String convertName(String name, boolean entity, boolean polyType) {
Matcher matcher = WORD_PATTERN.matcher(name);
String back = matcher.replaceAll("$1_$2");
if (polyType) {
- name += "_type";
+ back += "_type";
} else if (entity) {
- name += "_id";
+ back += "_id";
}
if (uppercase) {
back = back.toUpperCase();
} else {
back = back.toLowerCase();
}
return back.toString();
}
}
| false | true | protected String convertName(String name, boolean entity, boolean polyType) {
Matcher matcher = WORD_PATTERN.matcher(name);
String back = matcher.replaceAll("$1_$2");
if (polyType) {
name += "_type";
} else if (entity) {
name += "_id";
}
if (uppercase) {
back = back.toUpperCase();
} else {
back = back.toLowerCase();
}
return back.toString();
}
| protected String convertName(String name, boolean entity, boolean polyType) {
Matcher matcher = WORD_PATTERN.matcher(name);
String back = matcher.replaceAll("$1_$2");
if (polyType) {
back += "_type";
} else if (entity) {
back += "_id";
}
if (uppercase) {
back = back.toUpperCase();
} else {
back = back.toLowerCase();
}
return back.toString();
}
|
diff --git a/test/server/j2se/com/sun/sgs/test/impl/service/session/TestClientSessionServiceImpl.java b/test/server/j2se/com/sun/sgs/test/impl/service/session/TestClientSessionServiceImpl.java
index 6e1d30719..86e4fc968 100644
--- a/test/server/j2se/com/sun/sgs/test/impl/service/session/TestClientSessionServiceImpl.java
+++ b/test/server/j2se/com/sun/sgs/test/impl/service/session/TestClientSessionServiceImpl.java
@@ -1,1571 +1,1571 @@
/*
* Copyright 2007-2008 Sun Microsystems, Inc.
*
* This file is part of Project Darkstar Server.
*
* Project Darkstar Server 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 and
* distributed hereunder to you.
*
* Project Darkstar Server is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sun.sgs.test.impl.service.session;
import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.AppListener;
import com.sun.sgs.app.ClientSession;
import com.sun.sgs.app.ClientSessionListener;
import com.sun.sgs.app.DataManager;
import com.sun.sgs.app.ExceptionRetryStatus;
import com.sun.sgs.app.ManagedObject;
import com.sun.sgs.app.ManagedReference;
import com.sun.sgs.app.MessageRejectedException;
import com.sun.sgs.app.NameNotBoundException;
import com.sun.sgs.app.ObjectNotFoundException;
import com.sun.sgs.auth.Identity;
import com.sun.sgs.impl.io.SocketEndpoint;
import com.sun.sgs.impl.io.TransportType;
import com.sun.sgs.impl.kernel.StandardProperties;
import com.sun.sgs.impl.service.session.ClientSessionServer;
import com.sun.sgs.impl.service.session.ClientSessionServiceImpl;
import com.sun.sgs.impl.sharedutil.HexDumper;
import com.sun.sgs.impl.sharedutil.MessageBuffer;
import com.sun.sgs.impl.util.AbstractKernelRunnable;
import com.sun.sgs.impl.util.AbstractService.Version;
import com.sun.sgs.impl.util.ManagedSerializable;
import com.sun.sgs.io.Connector;
import com.sun.sgs.io.Connection;
import com.sun.sgs.io.ConnectionListener;
import com.sun.sgs.kernel.TransactionScheduler;
import com.sun.sgs.protocol.simple.SimpleSgsProtocol;
import com.sun.sgs.service.DataService;
import com.sun.sgs.test.util.SgsTestNode;
import com.sun.sgs.test.util.SimpleTestIdentityAuthenticator;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Properties;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import static com.sun.sgs.test.util.UtilProperties.createProperties;
public class TestClientSessionServiceImpl extends TestCase {
/** If this property is set, then only run the single named test method. */
private static final String testMethod = System.getProperty("test.method");
/**
* Specify the test suite to include all tests, or just a single method if
* specified.
*/
public static TestSuite suite() throws Exception {
if (testMethod == null) {
return new TestSuite(TestClientSessionServiceImpl.class);
}
TestSuite suite = new TestSuite();
suite.addTest(new TestClientSessionServiceImpl(testMethod));
return suite;
}
private static final String APP_NAME = "TestClientSessionServiceImpl";
private static final String LOGIN_FAILED_MESSAGE = "login failed";
private static final int WAIT_TIME = 5000;
private static final String RETURN_NULL = "return null";
private static final String NON_SERIALIZABLE = "non-serializable";
private static final String THROW_RUNTIME_EXCEPTION =
"throw RuntimeException";
private static final String DISCONNECT_THROWS_NONRETRYABLE_EXCEPTION =
"disconnect throws non-retryable exception";
private static final String SESSION_PREFIX =
"com.sun.sgs.impl.service.session.impl";
private static final String SESSION_NODE_PREFIX =
"com.sun.sgs.impl.service.session.node";
private static final String LISTENER_PREFIX =
"com.sun.sgs.impl.service.session.listener";
private static final String NODE_PREFIX =
"com.sun.sgs.impl.service.watchdog.node";
/** The ClientSession service properties. */
private static final Properties serviceProps =
createProperties(
StandardProperties.APP_NAME, APP_NAME,
StandardProperties.APP_PORT, "20000");
/** The node that creates the servers. */
private SgsTestNode serverNode;
/** Any additional nodes, keyed by node hostname (for tests
* needing more than one node). */
private Map<String,SgsTestNode> additionalNodes;
/** Version information from ClientSessionServiceImpl class. */
private final String VERSION_KEY;
private final int MAJOR_VERSION;
private final int MINOR_VERSION;
/** If {@code true}, shuts off some printing during performance tests. */
private boolean isPerformanceTest = false;
/** The transaction scheduler. */
private TransactionScheduler txnScheduler;
/** The owner for tasks I initiate. */
private Identity taskOwner;
/** The shared data service. */
private DataService dataService;
/** The test clients, keyed by user name. */
private static Map<String, DummyClient> dummyClients;
private static Field getField(Class cl, String name) throws Exception {
Field field = cl.getDeclaredField(name);
field.setAccessible(true);
return field;
}
/** Constructs a test instance. */
public TestClientSessionServiceImpl(String name) throws Exception {
super(name);
Class cl = ClientSessionServiceImpl.class;
VERSION_KEY = (String) getField(cl, "VERSION_KEY").get(null);
MAJOR_VERSION = getField(cl, "MAJOR_VERSION").getInt(null);
MINOR_VERSION = getField(cl, "MINOR_VERSION").getInt(null);
}
protected void setUp() throws Exception {
dummyClients = new HashMap<String, DummyClient>();
System.err.println("Testcase: " + getName());
setUp(true);
}
/** Creates and configures the session service. */
protected void setUp(boolean clean) throws Exception {
Properties props =
SgsTestNode.getDefaultProperties(APP_NAME, null,
DummyAppListener.class);
props.setProperty(StandardProperties.AUTHENTICATORS,
"com.sun.sgs.test.util.SimpleTestIdentityAuthenticator");
serverNode =
new SgsTestNode(APP_NAME, DummyAppListener.class, props, clean);
txnScheduler =
serverNode.getSystemRegistry().
getComponent(TransactionScheduler.class);
taskOwner = serverNode.getProxy().getCurrentOwner();
dataService = serverNode.getDataService();
}
/**
* Add additional nodes. We only do this as required by the tests.
*
* @param hosts contains a host name for each additional node
*/
private void addNodes(String... hosts) throws Exception {
// Create the other nodes
additionalNodes = new HashMap<String, SgsTestNode>();
for (String host : hosts) {
Properties props = SgsTestNode.getDefaultProperties(
APP_NAME, serverNode, DummyAppListener.class);
props.put("com.sun.sgs.impl.service.watchdog.client.host", host);
SgsTestNode node =
new SgsTestNode(serverNode, DummyAppListener.class, props);
additionalNodes.put(host, node);
}
}
/** Sets passed if the test passes. */
protected void runTest() throws Throwable {
super.runTest();
Thread.sleep(100);
}
protected void tearDown() throws Exception {
tearDown(true);
}
protected void tearDown(boolean clean) throws Exception {
Thread.sleep(100);
if (additionalNodes != null) {
for (SgsTestNode node : additionalNodes.values()) {
node.shutdown(false);
}
additionalNodes = null;
}
serverNode.shutdown(clean);
serverNode = null;
}
/* -- Test constructor -- */
public void testConstructorNullProperties() throws Exception {
try {
new ClientSessionServiceImpl(
null, serverNode.getSystemRegistry(),
serverNode.getProxy());
fail("Expected NullPointerException");
} catch (NullPointerException e) {
System.err.println(e);
}
}
public void testConstructorNullComponentRegistry() throws Exception {
try {
new ClientSessionServiceImpl(serviceProps, null,
serverNode.getProxy());
fail("Expected NullPointerException");
} catch (NullPointerException e) {
System.err.println(e);
}
}
public void testConstructorNullTransactionProxy() throws Exception {
try {
new ClientSessionServiceImpl(serviceProps,
serverNode.getSystemRegistry(), null);
fail("Expected NullPointerException");
} catch (NullPointerException e) {
System.err.println(e);
}
}
public void testConstructorNoAppName() throws Exception {
try {
new ClientSessionServiceImpl(
new Properties(), serverNode.getSystemRegistry(),
serverNode.getProxy());
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
System.err.println(e);
}
}
public void testConstructorNoPort() throws Exception {
try {
Properties props =
createProperties(
StandardProperties.APP_NAME, APP_NAME);
new ClientSessionServiceImpl(
props, serverNode.getSystemRegistry(),
serverNode.getProxy());
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
System.err.println(e);
}
}
public void testConstructedVersion() throws Exception {
txnScheduler.runTask(new AbstractKernelRunnable() {
public void run() {
Version version = (Version)
dataService.getServiceBinding(VERSION_KEY);
if (version.getMajorVersion() != MAJOR_VERSION ||
version.getMinorVersion() != MINOR_VERSION)
{
fail("Expected service version (major=" +
MAJOR_VERSION + ", minor=" + MINOR_VERSION +
"), got:" + version);
}
}}, taskOwner);
}
public void testConstructorWithCurrentVersion() throws Exception {
txnScheduler.runTask(new AbstractKernelRunnable() {
public void run() {
Version version = new Version(MAJOR_VERSION, MINOR_VERSION);
dataService.setServiceBinding(VERSION_KEY, version);
}}, taskOwner);
new ClientSessionServiceImpl(
serviceProps, serverNode.getSystemRegistry(),
serverNode.getProxy());
}
public void testConstructorWithMajorVersionMismatch() throws Exception {
txnScheduler.runTask(new AbstractKernelRunnable() {
public void run() {
Version version =
new Version(MAJOR_VERSION + 1, MINOR_VERSION);
dataService.setServiceBinding(VERSION_KEY, version);
}}, taskOwner);
try {
new ClientSessionServiceImpl(
serviceProps, serverNode.getSystemRegistry(),
serverNode.getProxy());
fail("Expected IllegalStateException");
} catch (IllegalStateException e) {
System.err.println(e);
}
}
public void testConstructorWithMinorVersionMismatch() throws Exception {
txnScheduler.runTask(new AbstractKernelRunnable() {
public void run() {
Version version =
new Version(MAJOR_VERSION, MINOR_VERSION + 1);
dataService.setServiceBinding(VERSION_KEY, version);
}}, taskOwner);
try {
new ClientSessionServiceImpl(
serviceProps, serverNode.getSystemRegistry(),
serverNode.getProxy());
fail("Expected IllegalStateException");
} catch (IllegalStateException e) {
System.err.println(e);
}
}
/* -- Test connecting, logging in, logging out with server -- */
public void testConnection() throws Exception {
DummyClient client = new DummyClient("foo");
try {
client.connect(serverNode.getAppPort());
} catch (Exception e) {
System.err.println("Exception: " + e);
Throwable t = e.getCause();
System.err.println("caused by: " + t);
System.err.println("detail message: " + t.getMessage());
throw e;
} finally {
client.disconnect();
}
}
public void testLoginSuccess() throws Exception {
DummyClient client = new DummyClient("success");
try {
client.connect(serverNode.getAppPort());
client.login();
} finally {
client.disconnect();
}
}
public void testLoginRedirect() throws Exception {
int serverAppPort = serverNode.getAppPort();
String[] hosts = new String[] { "one", "two", "three", "four"};
String[] users = new String[] { "sleepy", "bashful", "dopey", "doc" };
Set<DummyClient> clients = new HashSet<DummyClient>();
addNodes(hosts);
boolean failed = false;
int redirectCount = 0;
try {
for (String user : users) {
DummyClient client = new DummyClient(user);
client.connect(serverAppPort);
if (! client.login()) {
// login redirected
redirectCount++;
int port = client.redirectPort;
client = new DummyClient(user);
client.connect(port);
if (!client.login()) {
failed = true;
System.err.println("login for user: " + user +
" redirected twice");
}
}
clients.add(client);
}
int expectedRedirects = users.length;
if (redirectCount != expectedRedirects) {
failed = true;
System.err.println("Expected " + expectedRedirects +
" redirects, got " + redirectCount);
} else {
System.err.println(
"Number of redirected users: " + redirectCount);
}
if (failed) {
fail("test failed (see output)");
}
} finally {
for (DummyClient client : clients) {
try {
client.disconnect();
} catch (Exception e) {
System.err.println(
"Exception disconnecting client: " + client);
}
}
}
}
public void testLoginSuccessAndNotifyLoggedInCallback() throws Exception {
String name = "success";
DummyClient client = new DummyClient(name);
try {
client.connect(serverNode.getAppPort());
client.login();
if (SimpleTestIdentityAuthenticator.allIdentities.
getNotifyLoggedIn(name)) {
System.err.println(
"notifyLoggedIn invoked for identity: " + name);
} else {
fail("notifyLoggedIn not invoked for identity: " + name);
}
} finally {
client.disconnect();
}
}
public void testLoggedInReturningNonSerializableClientSessionListener()
throws Exception
{
DummyClient client = new DummyClient(NON_SERIALIZABLE);
try {
client.connect(serverNode.getAppPort());
client.login();
fail("expected login failure");
} catch (RuntimeException e) {
if (e.getMessage().equals(LOGIN_FAILED_MESSAGE)) {
System.err.println("login refused");
if (SimpleTestIdentityAuthenticator.allIdentities.
getNotifyLoggedIn(NON_SERIALIZABLE))
{
fail("unexpected notifyLoggedIn invoked on identity: " +
NON_SERIALIZABLE);
}
return;
} else {
fail("unexpected login failure: " + e);
}
} finally {
client.disconnect();
}
}
public void testLoggedInReturningNullClientSessionListener()
throws Exception
{
DummyClient client = new DummyClient(RETURN_NULL);
try {
client.connect(serverNode.getAppPort());
client.login();
fail("expected login failure");
} catch (RuntimeException e) {
if (e.getMessage().equals(LOGIN_FAILED_MESSAGE)) {
System.err.println("login refused");
if (SimpleTestIdentityAuthenticator.allIdentities.
getNotifyLoggedIn(NON_SERIALIZABLE))
{
fail("unexpected notifyLoggedIn invoked on identity: " +
NON_SERIALIZABLE);
}
return;
} else {
fail("unexpected login failure: " + e);
}
} finally {
client.disconnect();
}
}
public void testLoggedInThrowingRuntimeException()
throws Exception
{
DummyClient client = new DummyClient(THROW_RUNTIME_EXCEPTION);
try {
client.connect(serverNode.getAppPort());
client.login();
fail("expected login failure");
} catch (RuntimeException e) {
if (e.getMessage().equals(LOGIN_FAILED_MESSAGE)) {
System.err.println("login refused");
if (SimpleTestIdentityAuthenticator.allIdentities.
getNotifyLoggedIn(NON_SERIALIZABLE))
{
fail("unexpected notifyLoggedIn invoked on identity: " +
NON_SERIALIZABLE);
}
return;
} else {
fail("unexpected login failure: " + e);
}
} finally {
client.disconnect();
}
}
public void testLogoutRequestAndDisconnectedCallback() throws Exception {
final String name = "logout";
DummyClient client = new DummyClient(name);
try {
client.connect(serverNode.getAppPort());
client.login();
checkBindings(1);
client.logout();
client.checkDisconnected(true);
checkBindings(0);
// check that client session was removed after disconnected callback
// returned
txnScheduler.runTask(new AbstractKernelRunnable() {
public void run() {
try {
dataService.getBinding(name);
fail("expected ObjectNotFoundException: " +
"object not removed");
} catch (ObjectNotFoundException e) {
}
}
}, taskOwner);
} catch (InterruptedException e) {
e.printStackTrace();
fail("testLogout interrupted");
} finally {
client.disconnect();
}
}
public void testDisconnectedCallbackThrowingNonRetryableException()
throws Exception
{
DummyClient client =
new DummyClient(DISCONNECT_THROWS_NONRETRYABLE_EXCEPTION);
try {
client.connect(serverNode.getAppPort());
client.login();
checkBindings(1);
client.logout();
client.checkDisconnected(true);
// give scheduled task a chance to clean up...
Thread.sleep(250);
checkBindings(0);
} finally {
client.disconnect();
}
}
public void testLogoutAndNotifyLoggedOutCallback() throws Exception {
String name = "logout";
DummyClient client = new DummyClient(name);
try {
client.connect(serverNode.getAppPort()).login();
client.logout();
if (SimpleTestIdentityAuthenticator.allIdentities.
getNotifyLoggedIn(name)) {
System.err.println(
"notifyLoggedIn invoked for identity: " + name);
} else {
fail("notifyLoggedIn not invoked for identity: " + name);
}
if (SimpleTestIdentityAuthenticator.allIdentities.
getNotifyLoggedOut(name)) {
System.err.println(
"notifyLoggedOut invoked for identity: " + name);
} else {
fail("notifyLoggedOut not invoked for identity: " + name);
}
} finally {
client.disconnect();
}
}
public void testNotifyClientSessionListenerAfterCrash() throws Exception {
int numClients = 4;
try {
List<String> nodeKeys = getServiceBindingKeys(NODE_PREFIX);
System.err.println("Node keys: " + nodeKeys);
if (nodeKeys.isEmpty()) {
fail("no node keys");
} else if (nodeKeys.size() > 1) {
fail("more than one node key");
}
int appPort = serverNode.getAppPort();
for (int i = 0; i < numClients; i++) {
/*
* Create half of the clients with a name that starts with
* "badClient" which will cause the associated session's
* ClientSessionListener's 'disconnected' method to throw a
* non-retryable exception. We want to make sure that all the
* client sessions are cleaned up after a crash, even if
* invoking a session's listener's 'disconnected' callback
* throws a non-retryable exception.
*/
String name = (i % 2 == 0) ? "client" : "badClient";
DummyClient client = new DummyClient(name + String.valueOf(i));
client.connect(appPort).login();
}
checkBindings(numClients);
// Simulate "crash"
tearDown(false);
String failedNodeKey = nodeKeys.get(0);
setUp(false);
for (DummyClient client : dummyClients.values()) {
client.checkDisconnected(false);
}
// Wait to make sure that bindings and node key are cleaned up.
// Some extra time is needed when a ClientSessionListener throws a
// non-retryable exception because a separate task is scheduled to
// clean up the client session and bindings.
Thread.sleep(WAIT_TIME);
System.err.println("check for session bindings being removed.");
checkBindings(0);
nodeKeys = getServiceBindingKeys(NODE_PREFIX);
System.err.println("Node keys: " + nodeKeys);
if (nodeKeys.contains(failedNodeKey)) {
fail("failed node key not removed: " + failedNodeKey);
}
} finally {
for (DummyClient client : dummyClients.values()) {
try {
client.disconnect();
} catch (Exception e) {
// ignore
}
}
}
}
/**
* Check that the session bindings are the expected number and throw an
* exception if they aren't.
*/
private void checkBindings(int numExpected) throws Exception {
List<String> listenerKeys = getServiceBindingKeys(LISTENER_PREFIX);
System.err.println("Listener keys: " + listenerKeys);
if (listenerKeys.size() != numExpected) {
fail("expected " + numExpected + " listener keys, got " +
listenerKeys.size());
}
List<String> sessionKeys = getServiceBindingKeys(SESSION_PREFIX);
System.err.println("Session keys: " + sessionKeys);
if (sessionKeys.size() != numExpected) {
fail("expected " + numExpected + " session keys, got " +
sessionKeys.size());
}
List<String> sessionNodeKeys =
getServiceBindingKeys(SESSION_NODE_PREFIX);
System.err.println("Session node keys: " + sessionNodeKeys);
if (sessionNodeKeys.size() != numExpected) {
fail("expected " + numExpected + " session node keys, got " +
sessionNodeKeys.size());
}
}
private List<String> getServiceBindingKeys(String prefix) throws Exception {
GetKeysTask task = new GetKeysTask(prefix);
txnScheduler.runTask(task, taskOwner);
return task.getKeys();
}
private class GetKeysTask extends AbstractKernelRunnable {
private List<String> keys = new ArrayList<String>();
private final String prefix;
GetKeysTask(String prefix) {
this.prefix = prefix;
}
public void run() throws Exception {
String key = prefix;
for (;;) {
key = dataService.nextServiceBoundName(key);
if (key == null ||
! key.regionMatches(
0, prefix, 0, prefix.length()))
{
break;
}
keys.add(key);
}
}
public List<String> getKeys() { return keys;}
}
/* -- test ClientSession -- */
public void testClientSessionIsConnected() throws Exception {
DummyClient client = new DummyClient("clientname");
try {
client.connect(serverNode.getAppPort());
client.login();
txnScheduler.runTask(new AbstractKernelRunnable() {
public void run() {
DummyAppListener appListener = getAppListener();
Set<ClientSession> sessions = appListener.getSessions();
if (sessions.isEmpty()) {
fail("appListener contains no client sessions!");
}
for (ClientSession session : appListener.getSessions()) {
if (session.isConnected() == true) {
System.err.println("session is connected");
return;
} else {
fail("Expected connected session: " + session);
}
}
fail("expected a connected session");
}
}, taskOwner);
} finally {
client.disconnect();
}
}
public void testClientSessionGetName() throws Exception {
final String name = "clientname";
DummyClient client = new DummyClient(name);
try {
client.connect(serverNode.getAppPort());
client.login();
txnScheduler.runTask(new AbstractKernelRunnable() {
public void run() {
DummyAppListener appListener = getAppListener();
Set<ClientSession> sessions = appListener.getSessions();
if (sessions.isEmpty()) {
fail("appListener contains no client sessions!");
}
for (ClientSession session : appListener.getSessions()) {
if (session.getName().equals(name)) {
System.err.println("names match");
return;
} else {
fail("Expected session name: " + name +
", got: " + session.getName());
}
}
fail("expected disconnected session");
}
}, taskOwner);
} finally {
client.disconnect();
}
}
public void testClientSessionSend() throws Exception {
final String name = "dummy";
DummyClient client = new DummyClient(name);
try {
final String counterName = "counter";
client.connect(serverNode.getAppPort());
client.login();
- addNodes("a", "b", "c", "d");
+ addNodes("a", "b");
- int iterations = 4;
+ int iterations = 3;
final List<SgsTestNode> nodes = new ArrayList<SgsTestNode>();
nodes.add(serverNode);
nodes.addAll(additionalNodes.values());
/*
* Replace each node's ClientSessionServer, bound in the data
* service, with a wrapped server that delays before sending
* the message.
*/
final DataService ds = dataService;
TransactionScheduler txnScheduler =
serverNode.getSystemRegistry().
getComponent(TransactionScheduler.class);
txnScheduler.runTask(new AbstractKernelRunnable() {
@SuppressWarnings("unchecked")
public void run() {
for (SgsTestNode node : nodes) {
String key = "com.sun.sgs.impl.service.session.server." +
node.getNodeId();
ManagedSerializable<ClientSessionServer> managedServer =
(ManagedSerializable<ClientSessionServer>)
dataService.getServiceBinding(key);
DelayingInvocationHandler handler =
new DelayingInvocationHandler(managedServer.get());
ClientSessionServer delayingServer =
(ClientSessionServer)
Proxy.newProxyInstance(
ClientSessionServer.class.getClassLoader(),
new Class[] { ClientSessionServer.class },
handler);
dataService.setServiceBinding(
key, new ManagedSerializable(delayingServer));
}
}}, taskOwner);
for (int i = 0; i < iterations; i++) {
for (SgsTestNode node : nodes) {
TransactionScheduler localTxnScheduler =
node.getSystemRegistry().
getComponent(TransactionScheduler.class);
Identity identity = node.getProxy().getCurrentOwner();
localTxnScheduler.scheduleTask(
new AbstractKernelRunnable() {
public void run() {
DataManager dataManager =
AppContext.getDataManager();
Counter counter;
try {
counter = (Counter)
dataManager.getBinding(counterName);
} catch (NameNotBoundException e) {
throw new MaybeRetryException("retry", true);
}
ClientSession session = (ClientSession)
dataManager.getBinding(name);
MessageBuffer buf = new MessageBuffer(4);
buf.putInt(counter.getAndIncrement());
session.send(ByteBuffer.wrap(buf.getBuffer()));
}},
identity);
}
}
txnScheduler.runTask(new AbstractKernelRunnable() {
public void run() {
AppContext.getDataManager().
setBinding(counterName, new Counter());
}}, taskOwner);
client.checkMessagesReceived(nodes.size() * iterations);
} finally {
client.disconnect();
}
}
private static class Counter implements ManagedObject, Serializable {
private static final long serialVersionUID = 1L;
private int value = 0;
int getAndIncrement() {
AppContext.getDataManager().markForUpdate(this);
return value++;
}
}
/**
* Test sending from the server to the client session in a transaction that
* aborts with a retryable exception to make sure that message buffers are
* reclaimed. Try sending 4K bytes, and have the task abort 100 times with
* a retryable exception so the task is retried. If the buffers are not
* being reclaimed then the sends will eventually fail because the buffer
* space is used up. Note that this test assumes that sending 400 KB of
* data will surpass the I/O throttling limit.
*/
public void testClientSessionSendAbortRetryable() throws Exception {
DummyClient client = new DummyClient("clientname");
try {
client.connect(serverNode.getAppPort());
client.login();
txnScheduler.runTask(
new AbstractKernelRunnable() {
int tryCount = 0;
public void run() {
Set<ClientSession> sessions =
getAppListener().getSessions();
ClientSession session = sessions.iterator().next();
try {
session.send(ByteBuffer.wrap(new byte[4096]));
} catch (MessageRejectedException e) {
fail("Should not run out of buffer space: " + e);
}
if (++tryCount < 100) {
throw new MaybeRetryException("Retryable", true);
}
}
}, taskOwner);
} finally {
client.disconnect();
}
}
public void testClientSend() throws Exception {
sendMessagesAndCheck(5, 5, null);
}
public void testClientSendWithListenerThrowingRetryableException()
throws Exception
{
sendMessagesAndCheck(
5, 5, new MaybeRetryException("retryable", true));
}
public void testClientSendWithListenerThrowingNonRetryableException()
throws Exception
{
sendMessagesAndCheck(
5, 4, new MaybeRetryException("non-retryable", false));
}
public void testLocalSendPerformance() throws Exception {
final String user = "dummy";
DummyClient client = (new DummyClient(user)).connect(serverNode.getAppPort());
client.login();
isPerformanceTest = true;
int numIterations = 1000;
final ByteBuffer msg = ByteBuffer.allocate(0);
long startTime = System.currentTimeMillis();
for (int i = 0; i < numIterations; i++) {
txnScheduler.runTask(new AbstractKernelRunnable() {
public void run() {
DataManager dataManager = AppContext.getDataManager();
ClientSession session = (ClientSession)
dataManager.getBinding(user);
session.send(msg);
}}, taskOwner);
}
long endTime = System.currentTimeMillis();
System.err.println("send, iterations: " + numIterations +
", elapsed time: " + (endTime - startTime) +
" ms.");
}
private void sendMessagesAndCheck(
int numMessages, int expectedMessages, RuntimeException exception)
throws Exception
{
String name = "clientname";
DummyClient client = new DummyClient(name);
try {
client.connect(serverNode.getAppPort());
client.login();
client.sendMessages(numMessages, expectedMessages, exception);
} finally {
client.disconnect();
}
}
/* -- other methods -- */
private void printIt(String line) {
if (! isPerformanceTest) {
System.err.println(line);
}
}
/** Find the app listener */
private DummyAppListener getAppListener() {
return (DummyAppListener) dataService.getServiceBinding(
StandardProperties.APP_LISTENER);
}
/**
* Dummy client code for testing purposes.
*/
private class DummyClient {
private String name;
private String password;
private Connector<SocketAddress> connector;
private Listener listener;
private Connection connection;
private boolean connected = false;
private final Object lock = new Object();
private final Object disconnectedCallbackLock = new Object();
private final Object receivedAllMessagesLock = new Object();
private boolean loginAck = false;
private boolean loginSuccess = false;
private boolean loginRedirect = false;
private boolean logoutAck = false;
private boolean awaitGraceful = false;
private boolean awaitLoginFailure = false;
private String reason;
private String redirectHost;
private int redirectPort;
private byte[] reconnectKey;
volatile boolean receivedDisconnectedCallback = false;
volatile boolean graceful = false;
volatile RuntimeException throwException;
volatile int expectedMessages;
Queue<byte[]> messages = new ConcurrentLinkedQueue<byte[]>();
DummyClient(String name) {
this.name = name;
dummyClients.put(name, this);
}
DummyClient connect(int port) {
connected = false;
listener = new Listener();
try {
SocketEndpoint endpoint =
new SocketEndpoint(
new InetSocketAddress(InetAddress.getLocalHost(), port),
TransportType.RELIABLE);
connector = endpoint.createConnector();
connector.connect(listener);
} catch (Exception e) {
System.err.println(toString() + " connect throws: " + e);
e.printStackTrace();
throw new RuntimeException("DummyClient.connect failed", e);
}
synchronized (lock) {
try {
if (connected == false) {
lock.wait(WAIT_TIME);
}
if (connected != true) {
throw new RuntimeException(
toString() + " connect timed out to " + port);
}
} catch (InterruptedException e) {
throw new RuntimeException(
toString() + " connect timed out to " + port, e);
}
}
return this;
}
void disconnect() {
System.err.println(toString() + " disconnecting");
synchronized (lock) {
if (connected == false) {
return;
}
connected = false;
}
try {
connection.close();
} catch (IOException e) {
System.err.println(toString() + " disconnect exception:" + e);
}
synchronized (lock) {
lock.notifyAll();
}
}
/**
* Returns {@code true} if login was successful, and returns
* {@code false} if login was redirected.
*/
boolean login() {
synchronized (lock) {
if (connected == false) {
throw new RuntimeException(toString() + " not connected");
}
}
this.password = "password";
MessageBuffer buf =
new MessageBuffer(2 + MessageBuffer.getSize(name) +
MessageBuffer.getSize(password));
buf.putByte(SimpleSgsProtocol.LOGIN_REQUEST).
putByte(SimpleSgsProtocol.VERSION).
putString(name).
putString(password);
loginAck = false;
try {
connection.sendBytes(buf.getBuffer());
} catch (IOException e) {
throw new RuntimeException(e);
}
synchronized (lock) {
try {
if (loginAck == false) {
lock.wait(WAIT_TIME);
}
if (loginAck != true) {
throw new RuntimeException(
toString() + " login timed out");
}
if (loginRedirect == true) {
return false;
}
if (!loginSuccess) {
throw new RuntimeException(LOGIN_FAILED_MESSAGE);
}
} catch (InterruptedException e) {
throw new RuntimeException(
toString() + " login timed out", e);
}
}
return true;
}
/**
* Throws a {@code RuntimeException} if this session is not
* logged in.
*/
private void checkLoggedIn() {
synchronized (lock) {
if (!connected || !loginSuccess) {
throw new RuntimeException(
toString() + " not connected or loggedIn");
}
}
}
/**
* Sends a SESSION_MESSAGE.
*/
void sendMessage(byte[] message) {
checkLoggedIn();
MessageBuffer buf =
new MessageBuffer(1+ message.length);
buf.putByte(SimpleSgsProtocol.SESSION_MESSAGE).
putBytes(message);
try {
connection.sendBytes(buf.getBuffer());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
void sendMessages(
int numMessages, int expectedMessages, RuntimeException re)
{
this.expectedMessages = expectedMessages;
this.throwException = re;
for (int i = 0; i < numMessages; i++) {
MessageBuffer buf = new MessageBuffer(4);
buf.putInt(i);
sendMessage(buf.getBuffer());
}
synchronized (receivedAllMessagesLock) {
if (messages.size() != expectedMessages) {
try {
receivedAllMessagesLock.wait(WAIT_TIME);
} catch (InterruptedException e) {
}
int receivedMessages = messages.size();
if (receivedMessages != expectedMessages) {
fail(toString() + " expected " + expectedMessages +
", received " + receivedMessages);
}
}
}
}
void checkMessagesReceived(int expectedMessages) {
this.expectedMessages = expectedMessages;
synchronized (receivedAllMessagesLock) {
if (listener.messageList.size() != expectedMessages) {
try {
receivedAllMessagesLock.wait(WAIT_TIME);
} catch (InterruptedException e) {
}
int receivedMessages = listener.messageList.size();
if (receivedMessages != expectedMessages) {
fail(toString() + " expected " + expectedMessages +
", received " + receivedMessages);
}
}
}
int i = 0;
for (byte[] message : listener.messageList) {
MessageBuffer buf = new MessageBuffer(message);
int value = buf.getInt();
System.err.println(toString() + " received message " + value);
if (value != i) {
fail("expected message " + i + ", got " + value);
}
i++;
}
}
void logout() {
synchronized (lock) {
if (connected == false) {
return;
}
logoutAck = false;
awaitGraceful = true;
}
MessageBuffer buf = new MessageBuffer(1);
buf.putByte(SimpleSgsProtocol.LOGOUT_REQUEST);
try {
connection.sendBytes(buf.getBuffer());
} catch (IOException e) {
throw new RuntimeException(e);
}
synchronized (lock) {
try {
if (logoutAck == false) {
lock.wait(WAIT_TIME);
}
if (logoutAck != true) {
throw new RuntimeException(
toString() + " disconnect timed out");
}
} catch (InterruptedException e) {
throw new RuntimeException(
toString() + " disconnect timed out", e);
} finally {
if (! logoutAck)
disconnect();
}
}
}
void checkDisconnected(boolean graceful) throws Exception {
synchronized (disconnectedCallbackLock) {
if (!receivedDisconnectedCallback) {
disconnectedCallbackLock.wait(WAIT_TIME);
}
}
if (!receivedDisconnectedCallback) {
fail(toString() + " disconnected callback not invoked");
} else if (this.graceful != graceful) {
fail(toString() + " graceful was: " + this.graceful +
", expected: " + graceful);
}
System.err.println(toString() + " disconnect successful");
}
public String toString() {
return "[" + name + "]";
}
private class Listener implements ConnectionListener {
List<byte[]> messageList = new ArrayList<byte[]>();
/** {@inheritDoc} */
public void bytesReceived(Connection conn, byte[] buffer) {
if (connection != conn) {
System.err.println(
"DummyClient.Listener connected wrong handle, got:" +
conn + ", expected:" + connection);
return;
}
MessageBuffer buf = new MessageBuffer(buffer);
byte opcode = buf.getByte();
switch (opcode) {
case SimpleSgsProtocol.LOGIN_SUCCESS:
reconnectKey = buf.getBytes(buf.limit() - buf.position());
synchronized (lock) {
loginAck = true;
loginSuccess = true;
System.err.println("login succeeded: " + name);
lock.notifyAll();
}
break;
case SimpleSgsProtocol.LOGIN_FAILURE:
reason = buf.getString();
synchronized (lock) {
loginAck = true;
loginSuccess = false;
System.err.println("login failed: " + name +
", reason:" + reason);
lock.notifyAll();
}
break;
case SimpleSgsProtocol.LOGIN_REDIRECT:
redirectHost = buf.getString();
redirectPort = buf.getInt();
synchronized (lock) {
loginAck = true;
loginRedirect = true;
System.err.println("login redirected: " + name +
", host:" + redirectHost +
", port:" + redirectPort);
lock.notifyAll();
} break;
case SimpleSgsProtocol.LOGOUT_SUCCESS:
synchronized (lock) {
logoutAck = true;
System.err.println("logout succeeded: " + name);
// let disconnect do the lock notification
}
break;
case SimpleSgsProtocol.SESSION_MESSAGE:
byte[] message = buf.getBytes(buf.limit() - buf.position());
synchronized (lock) {
messageList.add(message);
printIt("[" + name + "] received SESSION_MESSAGE: " +
HexDumper.toHexString(message));
lock.notifyAll();
}
break;
default:
System.err.println(
"bytesReceived: unknown op code: " + opcode);
break;
}
}
/** {@inheritDoc} */
public void connected(Connection conn) {
System.err.println("DummyClient.Listener.connected");
if (connection != null) {
System.err.println(
"DummyClient.Listener.already connected handle: " +
connection);
return;
}
connection = conn;
synchronized (lock) {
connected = true;
lock.notifyAll();
}
}
/** {@inheritDoc} */
public void disconnected(Connection conn) {
synchronized (lock) {
// Hack since client might not get last msg
if (awaitGraceful) {
// Pretend they logged out gracefully
logoutAck = true;
} else if (! loginAck) {
// Pretend they got a login failure message
loginAck = true;
loginSuccess = false;
reason = "disconnected before login ack";
}
connected = false;
lock.notifyAll();
}
}
/** {@inheritDoc} */
public void exceptionThrown(Connection conn, Throwable exception) {
System.err.println("DummyClient.Listener.exceptionThrown " +
"exception:" + exception);
exception.printStackTrace();
}
}
}
public static class DummyAppListener implements AppListener, Serializable {
private final static long serialVersionUID = 1L;
private final Map<ManagedReference<ClientSession>,
ManagedReference<DummyClientSessionListener>>
sessions = Collections.synchronizedMap(
new HashMap<ManagedReference<ClientSession>,
ManagedReference<DummyClientSessionListener>>());
/** {@inheritDoc} */
public ClientSessionListener loggedIn(ClientSession session) {
String name = session.getName();
DummyClientSessionListener listener;
if (name.equals(RETURN_NULL)) {
return null;
} else if (name.equals(NON_SERIALIZABLE)) {
return new NonSerializableClientSessionListener();
} else if (name.equals(THROW_RUNTIME_EXCEPTION)) {
throw new RuntimeException("loggedIn throwing an exception");
} else if (name.equals(DISCONNECT_THROWS_NONRETRYABLE_EXCEPTION) ||
name.startsWith("badClient")) {
listener = new DummyClientSessionListener(name, true);
} else {
listener = new DummyClientSessionListener(name, false);
}
DataManager dataManager = AppContext.getDataManager();
ManagedReference<ClientSession> sessionRef =
dataManager.createReference(session);
ManagedReference<DummyClientSessionListener> listenerRef =
dataManager.createReference(listener);
dataManager.markForUpdate(this);
sessions.put(sessionRef, listenerRef);
dataManager.setBinding(session.getName(), session);
System.err.println("DummyAppListener.loggedIn: session:" + session);
return listener;
}
/** {@inheritDoc} */
public void initialize(Properties props) {
}
private Set<ClientSession> getSessions() {
Set<ClientSession> sessionSet =
new HashSet<ClientSession>();
for (ManagedReference<ClientSession> sessionRef
: sessions.keySet())
{
sessionSet.add(sessionRef.get());
}
return sessionSet;
}
}
private static class NonSerializableClientSessionListener
implements ClientSessionListener
{
/** {@inheritDoc} */
public void disconnected(boolean graceful) {
}
/** {@inheritDoc} */
public void receivedMessage(ByteBuffer message) {
}
}
private static class DummyClientSessionListener
implements ClientSessionListener, Serializable, ManagedObject
{
private final static long serialVersionUID = 1L;
private final String name;
private final boolean disconnectedThrowsException;
private int seq = -1;
DummyClientSessionListener(
String name, boolean disconnectedThrowsException)
{
this.name = name;
this.disconnectedThrowsException = disconnectedThrowsException;
}
/** {@inheritDoc} */
public void disconnected(boolean graceful) {
System.err.println("DummyClientSessionListener[" + name +
"] disconnected invoked with " + graceful);
AppContext.getDataManager().markForUpdate(this);
DummyClient client = dummyClients.get(name);
client.receivedDisconnectedCallback = true;
client.graceful = graceful;
synchronized (client.disconnectedCallbackLock) {
client.disconnectedCallbackLock.notifyAll();
}
if (disconnectedThrowsException) {
throw new RuntimeException(
"disconnected throws non-retryable exception");
}
}
/** {@inheritDoc} */
public void receivedMessage(ByteBuffer message) {
byte[] bytes = new byte[message.remaining()];
message.asReadOnlyBuffer().get(bytes);
int num = message.getInt();
DummyClient client = dummyClients.get(name);
System.err.println("receivedMessage: " + num +
"\nthrowException: " + client.throwException);
if (num <= seq) {
throw new RuntimeException(
"expected message greater than " + seq + ", got " + num);
}
AppContext.getDataManager().markForUpdate(this);
client.messages.add(bytes);
seq = num;
if (client.throwException != null) {
RuntimeException re = client.throwException;
client.throwException = null;
throw re;
}
if (client.messages.size() == client.expectedMessages) {
synchronized (client.receivedAllMessagesLock) {
client.receivedAllMessagesLock.notifyAll();
}
}
}
}
private static class MaybeRetryException
extends RuntimeException implements ExceptionRetryStatus
{
private static final long serialVersionUID = 1L;
private boolean retry;
public MaybeRetryException(String s, boolean retry) {
super(s);
this.retry = retry;
}
public boolean shouldRetry() {
return retry;
}
}
private static class DelayingInvocationHandler
implements InvocationHandler, Serializable
{
private final static long serialVersionUID = 1L;
private Object obj;
DelayingInvocationHandler(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Exception
{
Thread.sleep(100);
try {
return method.invoke(obj, args);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
throw (Exception) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else {
throw new RuntimeException(
"Unexpected exception:" + cause, cause);
}
}
}
}
}
| false | true | public void testClientSessionSend() throws Exception {
final String name = "dummy";
DummyClient client = new DummyClient(name);
try {
final String counterName = "counter";
client.connect(serverNode.getAppPort());
client.login();
addNodes("a", "b", "c", "d");
int iterations = 4;
final List<SgsTestNode> nodes = new ArrayList<SgsTestNode>();
nodes.add(serverNode);
nodes.addAll(additionalNodes.values());
/*
* Replace each node's ClientSessionServer, bound in the data
* service, with a wrapped server that delays before sending
* the message.
*/
final DataService ds = dataService;
TransactionScheduler txnScheduler =
serverNode.getSystemRegistry().
getComponent(TransactionScheduler.class);
txnScheduler.runTask(new AbstractKernelRunnable() {
@SuppressWarnings("unchecked")
public void run() {
for (SgsTestNode node : nodes) {
String key = "com.sun.sgs.impl.service.session.server." +
node.getNodeId();
ManagedSerializable<ClientSessionServer> managedServer =
(ManagedSerializable<ClientSessionServer>)
dataService.getServiceBinding(key);
DelayingInvocationHandler handler =
new DelayingInvocationHandler(managedServer.get());
ClientSessionServer delayingServer =
(ClientSessionServer)
Proxy.newProxyInstance(
ClientSessionServer.class.getClassLoader(),
new Class[] { ClientSessionServer.class },
handler);
dataService.setServiceBinding(
key, new ManagedSerializable(delayingServer));
}
}}, taskOwner);
for (int i = 0; i < iterations; i++) {
for (SgsTestNode node : nodes) {
TransactionScheduler localTxnScheduler =
node.getSystemRegistry().
getComponent(TransactionScheduler.class);
Identity identity = node.getProxy().getCurrentOwner();
localTxnScheduler.scheduleTask(
new AbstractKernelRunnable() {
public void run() {
DataManager dataManager =
AppContext.getDataManager();
Counter counter;
try {
counter = (Counter)
dataManager.getBinding(counterName);
} catch (NameNotBoundException e) {
throw new MaybeRetryException("retry", true);
}
ClientSession session = (ClientSession)
dataManager.getBinding(name);
MessageBuffer buf = new MessageBuffer(4);
buf.putInt(counter.getAndIncrement());
session.send(ByteBuffer.wrap(buf.getBuffer()));
}},
identity);
}
}
txnScheduler.runTask(new AbstractKernelRunnable() {
public void run() {
AppContext.getDataManager().
setBinding(counterName, new Counter());
}}, taskOwner);
client.checkMessagesReceived(nodes.size() * iterations);
} finally {
client.disconnect();
}
}
| public void testClientSessionSend() throws Exception {
final String name = "dummy";
DummyClient client = new DummyClient(name);
try {
final String counterName = "counter";
client.connect(serverNode.getAppPort());
client.login();
addNodes("a", "b");
int iterations = 3;
final List<SgsTestNode> nodes = new ArrayList<SgsTestNode>();
nodes.add(serverNode);
nodes.addAll(additionalNodes.values());
/*
* Replace each node's ClientSessionServer, bound in the data
* service, with a wrapped server that delays before sending
* the message.
*/
final DataService ds = dataService;
TransactionScheduler txnScheduler =
serverNode.getSystemRegistry().
getComponent(TransactionScheduler.class);
txnScheduler.runTask(new AbstractKernelRunnable() {
@SuppressWarnings("unchecked")
public void run() {
for (SgsTestNode node : nodes) {
String key = "com.sun.sgs.impl.service.session.server." +
node.getNodeId();
ManagedSerializable<ClientSessionServer> managedServer =
(ManagedSerializable<ClientSessionServer>)
dataService.getServiceBinding(key);
DelayingInvocationHandler handler =
new DelayingInvocationHandler(managedServer.get());
ClientSessionServer delayingServer =
(ClientSessionServer)
Proxy.newProxyInstance(
ClientSessionServer.class.getClassLoader(),
new Class[] { ClientSessionServer.class },
handler);
dataService.setServiceBinding(
key, new ManagedSerializable(delayingServer));
}
}}, taskOwner);
for (int i = 0; i < iterations; i++) {
for (SgsTestNode node : nodes) {
TransactionScheduler localTxnScheduler =
node.getSystemRegistry().
getComponent(TransactionScheduler.class);
Identity identity = node.getProxy().getCurrentOwner();
localTxnScheduler.scheduleTask(
new AbstractKernelRunnable() {
public void run() {
DataManager dataManager =
AppContext.getDataManager();
Counter counter;
try {
counter = (Counter)
dataManager.getBinding(counterName);
} catch (NameNotBoundException e) {
throw new MaybeRetryException("retry", true);
}
ClientSession session = (ClientSession)
dataManager.getBinding(name);
MessageBuffer buf = new MessageBuffer(4);
buf.putInt(counter.getAndIncrement());
session.send(ByteBuffer.wrap(buf.getBuffer()));
}},
identity);
}
}
txnScheduler.runTask(new AbstractKernelRunnable() {
public void run() {
AppContext.getDataManager().
setBinding(counterName, new Counter());
}}, taskOwner);
client.checkMessagesReceived(nodes.size() * iterations);
} finally {
client.disconnect();
}
}
|
diff --git a/src/main/java/org/jenkinsci/plugins/urltrigger/URLTrigger.java b/src/main/java/org/jenkinsci/plugins/urltrigger/URLTrigger.java
index 7228b85..7a8dbbf 100644
--- a/src/main/java/org/jenkinsci/plugins/urltrigger/URLTrigger.java
+++ b/src/main/java/org/jenkinsci/plugins/urltrigger/URLTrigger.java
@@ -1,336 +1,331 @@
package org.jenkinsci.plugins.urltrigger;
import antlr.ANTLRException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.Util;
import hudson.model.*;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.FormValidation;
import hudson.util.SequentialExecutionQueue;
import hudson.util.StreamTaskListener;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.jenkinsci.plugins.urltrigger.content.URLTriggerContentType;
import org.jenkinsci.plugins.urltrigger.content.URLTriggerContentTypeDescriptor;
import org.jenkinsci.plugins.urltrigger.service.URLTriggerService;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.io.File;
import java.io.Serializable;
import java.text.DateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Gregory Boissinot
*/
public class URLTrigger extends Trigger<BuildableItem> implements Serializable {
private static Logger LOGGER = Logger.getLogger(URLTrigger.class.getName());
private List<URLTriggerEntry> entries = new ArrayList<URLTriggerEntry>();
@DataBoundConstructor
public URLTrigger(String cronTabSpec, List<URLTriggerEntry> entries) throws ANTLRException {
super(cronTabSpec);
this.entries = entries;
}
@SuppressWarnings("unused")
public List<URLTriggerEntry> getEntries() {
return entries;
}
@Override
public Collection<? extends Action> getProjectActions() {
Map<String, String> subActionTitles = null;
for (URLTriggerEntry entry : entries) {
String url = entry.getUrl();
URLTriggerContentType[] urlTriggerContentTypes = entry.getContentTypes();
if (entry.getContentTypes() != null) {
subActionTitles = new HashMap<String, String>(urlTriggerContentTypes.length);
for (int i = 0; i < urlTriggerContentTypes.length; i++) {
URLTriggerContentType fsTriggerContentFileType = urlTriggerContentTypes[i];
if (fsTriggerContentFileType != null) {
Descriptor<URLTriggerContentType> descriptor = fsTriggerContentFileType.getDescriptor();
if (descriptor instanceof URLTriggerContentTypeDescriptor) {
subActionTitles.put(url, ((URLTriggerContentTypeDescriptor) descriptor).getLabel());
}
}
}
}
}
URLTriggerAction action = new URLTriggerAction((AbstractProject) job, getLogFile(), this.getDescriptor().getDisplayName(), subActionTitles);
return Collections.singleton(action);
}
private boolean checkForScheduling(URLTriggerLog log) throws URLTriggerException {
if (entries == null || entries.size() == 0) {
log.info("No URLs to poll.");
return false;
}
ClientConfig cc = new DefaultClientConfig();
Client client = Client.create(cc);
for (URLTriggerEntry entry : entries) {
String url = entry.getUrl();
log.info(String.format("Invoking the url: \n %s", url));
ClientResponse clientResponse = client.resource(url).get(ClientResponse.class);
URLTriggerService urlTriggerService = URLTriggerService.getInstance();
if (urlTriggerService.isSchedulingForURLEntry(clientResponse, entry, log)) {
urlTriggerService.refreshContent(clientResponse, entry);
return true;
}
}
return false;
}
/**
* Asynchronous task
*/
protected class Runner implements Runnable, Serializable {
private AbstractProject project;
private URLTriggerLog log;
Runner(AbstractProject project, URLTriggerLog log) {
this.project = project;
this.log = log;
}
public void run() {
try {
long start = System.currentTimeMillis();
log.info("Polling started on " + DateFormat.getDateTimeInstance().format(new Date(start)));
boolean scheduling = checkForScheduling(log);
log.info("Polling complete. Took " + Util.getTimeSpanString(System.currentTimeMillis() - start));
if (scheduling) {
log.info("There are changes. Scheduling a build.");
project.scheduleBuild(new URLTriggerCause());
} else {
log.info("No changes.");
}
} catch (URLTriggerException e) {
log.error("Polling error " + e.getMessage());
} catch (Throwable e) {
log.error("SEVERE - Polling error " + e.getMessage());
}
}
}
/**
* Gets the triggering log file
*
* @return the trigger log
*/
private File getLogFile() {
return new File(job.getRootDir(), "trigger-script-polling.log");
}
@Override
public void start(BuildableItem project, boolean newInstance) {
super.start(project, newInstance);
URLTriggerService service = URLTriggerService.getInstance();
try {
ClientConfig cc = new DefaultClientConfig();
Client client = Client.create(cc);
for (URLTriggerEntry entry : entries) {
String url = entry.getUrl();
ClientResponse clientResponse = client.resource(url).get(ClientResponse.class);
service.initContent(clientResponse, entry);
}
} catch (URLTriggerException urle) {
LOGGER.log(Level.SEVERE, "Error on trigger startup " + urle.getMessage());
urle.printStackTrace();
} catch (Throwable t) {
LOGGER.log(Level.SEVERE, "Severe error on trigger startup " + t.getMessage());
t.printStackTrace();
}
}
@Override
public void run() {
if (!Hudson.getInstance().isQuietingDown() && ((AbstractProject) this.job).isBuildable()) {
URLScriptTriggerDescriptor descriptor = getDescriptor();
ExecutorService executorService = descriptor.getExecutor();
StreamTaskListener listener;
try {
listener = new StreamTaskListener(getLogFile());
URLTriggerLog log = new URLTriggerLog(listener);
if (job instanceof AbstractProject) {
Runner runner = new Runner((AbstractProject) job, log);
executorService.execute(runner);
}
} catch (Throwable t) {
LOGGER.log(Level.SEVERE, "Severe Error during the trigger execution " + t.getMessage());
t.printStackTrace();
}
}
}
@Override
public URLScriptTriggerDescriptor getDescriptor() {
return (URLScriptTriggerDescriptor) Hudson.getInstance().getDescriptorOrDie(getClass());
}
@Extension
@SuppressWarnings("unused")
public static class URLScriptTriggerDescriptor extends TriggerDescriptor {
private transient final SequentialExecutionQueue queue = new SequentialExecutionQueue(Executors.newSingleThreadExecutor());
public ExecutorService getExecutor() {
return queue.getExecutors();
}
@Override
public boolean isApplicable(Item item) {
return true;
}
@Override
public URLTrigger newInstance(StaplerRequest req, JSONObject formData) throws FormException {
String cronTabSpec = formData.getString("cronTabSpec");
Object entryObject = formData.get("urlElements");
List<URLTriggerEntry> entries = new ArrayList<URLTriggerEntry>();
if (entryObject instanceof JSONObject) {
entries.add(fillAndGetEntry(req, (JSONObject) entryObject));
} else {
JSONArray jsonArray = (JSONArray) entryObject;
if (jsonArray != null) {
Iterator it = jsonArray.iterator();
while (it.hasNext()) {
entries.add(fillAndGetEntry(req, (JSONObject) it.next()));
}
}
}
URLTrigger urlTrigger;
try {
urlTrigger = new URLTrigger(cronTabSpec, entries);
} catch (ANTLRException e) {
throw new RuntimeException(e.getMessage());
}
return urlTrigger;
}
private URLTriggerEntry fillAndGetEntry(StaplerRequest req, JSONObject entryObject) {
URLTriggerEntry urlTriggerEntry = new URLTriggerEntry();
urlTriggerEntry.setUrl(entryObject.getString("url"));
//Process checkStatus
Object checkStatusObject = entryObject.get("checkStatus");
if (checkStatusObject != null) {
urlTriggerEntry.setCheckStatus(true);
try {
JSONObject statusJSONObject = (JSONObject) checkStatusObject;
urlTriggerEntry.setStatusCode(statusJSONObject.getInt("statusCode"));
} catch (JSONException jsne) {
urlTriggerEntry.setStatusCode(URLTriggerEntry.DEFAULT_STATUS_CODE);
}
} else {
urlTriggerEntry.setCheckStatus(false);
urlTriggerEntry.setStatusCode(URLTriggerEntry.DEFAULT_STATUS_CODE);
}
//Process checkLastModifiedDate
- Object checkLastModifiedDateObject = entryObject.get("checkLastModificationDate");
- if (checkLastModifiedDateObject != null) {
- urlTriggerEntry.setCheckLastModificationDate(true);
- } else {
- urlTriggerEntry.setCheckLastModificationDate(false);
- }
+ urlTriggerEntry.setCheckLastModificationDate(entryObject.getBoolean("checkLastModificationDate"));
//Process inspectingContent
Object inspectingContentObject = entryObject.get("inspectingContent");
if (inspectingContentObject == null) {
urlTriggerEntry.setInspectingContent(false);
urlTriggerEntry.setContentTypes(new URLTriggerContentType[0]);
} else {
urlTriggerEntry.setInspectingContent(true);
JSONObject inspectingContentJSONObject = entryObject.getJSONObject("inspectingContent");
JSON contentTypesJsonElt;
try {
contentTypesJsonElt = inspectingContentJSONObject.getJSONArray("contentTypes");
} catch (JSONException jsone) {
contentTypesJsonElt = inspectingContentJSONObject.getJSONObject("contentTypes");
}
List<URLTriggerContentType> types = req.bindJSONToList(URLTriggerContentType.class, contentTypesJsonElt);
urlTriggerEntry.setContentTypes(types.toArray(new URLTriggerContentType[types.size()]));
}
return urlTriggerEntry;
}
@Override
public String getDisplayName() {
return Messages.urltrigger_displayName();
}
@Override
public String getHelpFile() {
return "/plugin/urltrigger/help.html";
}
@SuppressWarnings("unchecked")
public DescriptorExtensionList getListURLTriggerDescriptors() {
return DescriptorExtensionList.createDescriptorList(Hudson.getInstance(), URLTriggerContentType.class);
}
public FormValidation doCheckStatus(@QueryParameter String value) {
if (value == null || value.trim().isEmpty()) {
return FormValidation.ok();
}
try {
Integer.parseInt(value);
return FormValidation.ok();
} catch (Exception e) {
return FormValidation.error("You must provide a valid number status such as 200, 301, ...");
}
}
public FormValidation doCheckURL(@QueryParameter String value) {
if (value == null || value.trim().isEmpty()) {
return FormValidation.error("The url field is mandatory.");
}
try {
ClientConfig cc = new DefaultClientConfig();
Client client = Client.create(cc);
client.resource(value).get(ClientResponse.class);
return FormValidation.ok();
} catch (Exception e) {
return FormValidation.error(e.getMessage());
}
}
}
}
| true | true | private URLTriggerEntry fillAndGetEntry(StaplerRequest req, JSONObject entryObject) {
URLTriggerEntry urlTriggerEntry = new URLTriggerEntry();
urlTriggerEntry.setUrl(entryObject.getString("url"));
//Process checkStatus
Object checkStatusObject = entryObject.get("checkStatus");
if (checkStatusObject != null) {
urlTriggerEntry.setCheckStatus(true);
try {
JSONObject statusJSONObject = (JSONObject) checkStatusObject;
urlTriggerEntry.setStatusCode(statusJSONObject.getInt("statusCode"));
} catch (JSONException jsne) {
urlTriggerEntry.setStatusCode(URLTriggerEntry.DEFAULT_STATUS_CODE);
}
} else {
urlTriggerEntry.setCheckStatus(false);
urlTriggerEntry.setStatusCode(URLTriggerEntry.DEFAULT_STATUS_CODE);
}
//Process checkLastModifiedDate
Object checkLastModifiedDateObject = entryObject.get("checkLastModificationDate");
if (checkLastModifiedDateObject != null) {
urlTriggerEntry.setCheckLastModificationDate(true);
} else {
urlTriggerEntry.setCheckLastModificationDate(false);
}
//Process inspectingContent
Object inspectingContentObject = entryObject.get("inspectingContent");
if (inspectingContentObject == null) {
urlTriggerEntry.setInspectingContent(false);
urlTriggerEntry.setContentTypes(new URLTriggerContentType[0]);
} else {
urlTriggerEntry.setInspectingContent(true);
JSONObject inspectingContentJSONObject = entryObject.getJSONObject("inspectingContent");
JSON contentTypesJsonElt;
try {
contentTypesJsonElt = inspectingContentJSONObject.getJSONArray("contentTypes");
} catch (JSONException jsone) {
contentTypesJsonElt = inspectingContentJSONObject.getJSONObject("contentTypes");
}
List<URLTriggerContentType> types = req.bindJSONToList(URLTriggerContentType.class, contentTypesJsonElt);
urlTriggerEntry.setContentTypes(types.toArray(new URLTriggerContentType[types.size()]));
}
return urlTriggerEntry;
}
| private URLTriggerEntry fillAndGetEntry(StaplerRequest req, JSONObject entryObject) {
URLTriggerEntry urlTriggerEntry = new URLTriggerEntry();
urlTriggerEntry.setUrl(entryObject.getString("url"));
//Process checkStatus
Object checkStatusObject = entryObject.get("checkStatus");
if (checkStatusObject != null) {
urlTriggerEntry.setCheckStatus(true);
try {
JSONObject statusJSONObject = (JSONObject) checkStatusObject;
urlTriggerEntry.setStatusCode(statusJSONObject.getInt("statusCode"));
} catch (JSONException jsne) {
urlTriggerEntry.setStatusCode(URLTriggerEntry.DEFAULT_STATUS_CODE);
}
} else {
urlTriggerEntry.setCheckStatus(false);
urlTriggerEntry.setStatusCode(URLTriggerEntry.DEFAULT_STATUS_CODE);
}
//Process checkLastModifiedDate
urlTriggerEntry.setCheckLastModificationDate(entryObject.getBoolean("checkLastModificationDate"));
//Process inspectingContent
Object inspectingContentObject = entryObject.get("inspectingContent");
if (inspectingContentObject == null) {
urlTriggerEntry.setInspectingContent(false);
urlTriggerEntry.setContentTypes(new URLTriggerContentType[0]);
} else {
urlTriggerEntry.setInspectingContent(true);
JSONObject inspectingContentJSONObject = entryObject.getJSONObject("inspectingContent");
JSON contentTypesJsonElt;
try {
contentTypesJsonElt = inspectingContentJSONObject.getJSONArray("contentTypes");
} catch (JSONException jsone) {
contentTypesJsonElt = inspectingContentJSONObject.getJSONObject("contentTypes");
}
List<URLTriggerContentType> types = req.bindJSONToList(URLTriggerContentType.class, contentTypesJsonElt);
urlTriggerEntry.setContentTypes(types.toArray(new URLTriggerContentType[types.size()]));
}
return urlTriggerEntry;
}
|
diff --git a/ExperienceMod/src/com/comphenix/xp/messages/HeroService.java b/ExperienceMod/src/com/comphenix/xp/messages/HeroService.java
index c392d04..c89e444 100644
--- a/ExperienceMod/src/com/comphenix/xp/messages/HeroService.java
+++ b/ExperienceMod/src/com/comphenix/xp/messages/HeroService.java
@@ -1,81 +1,81 @@
package com.comphenix.xp.messages;
import org.bukkit.entity.Player;
import com.dthielke.herochat.Channel;
import com.dthielke.herochat.Chatter;
import com.dthielke.herochat.Herochat;
public class HeroService implements ChannelService {
public static final String NAME = "HEROCHAT";
public HeroService() {
// Make sure we haven't screwed up
if (!exists())
throw new IllegalArgumentException("HeroChat hasn't been enabled.");
}
/**
* Determines whether or not the HeroChat plugin is loaded AND enabled.
* @return TRUE if it is, FALSE otherwise.
*/
public static boolean exists() {
try {
// Make sure
if (Herochat.getPlugin().isEnabled())
return true;
else
return false;
// Cannot load plugin
- } catch (Exception e) {
+ } catch (NoClassDefFoundError e) {
return false;
}
}
@Override
public boolean hasChannel(String channelID) {
// See if this channel exists
return Herochat.getChannelManager().hasChannel(channelID);
}
@Override
public void announce(String channelID, String message) {
// Stores channels in a HashMap, so it should return NULL if the channel doesn't exist
Channel channel = Herochat.getChannelManager().getChannel(channelID);
if (channel == null) {
throw new IllegalArgumentException("Channel doesn't exist.");
}
channel.announce(message);
}
@Override
public void emote(String channelID, String message, Player sender) {
Chatter playerChatter = Herochat.getChatterManager().getChatter(sender);
// Emote for this character
getChannel(channelID).emote(playerChatter, message);
}
private Channel getChannel(String channelID) {
// Stores channels in a HashMap, so it should return NULL if the channel doesn't exist
Channel channel = Herochat.getChannelManager().getChannel(channelID);
if (channel == null) {
throw new IllegalArgumentException("Channel doesn't exist.");
} else {
return channel;
}
}
@Override
public String getServiceName() {
return NAME;
}
}
| true | true | public static boolean exists() {
try {
// Make sure
if (Herochat.getPlugin().isEnabled())
return true;
else
return false;
// Cannot load plugin
} catch (Exception e) {
return false;
}
}
| public static boolean exists() {
try {
// Make sure
if (Herochat.getPlugin().isEnabled())
return true;
else
return false;
// Cannot load plugin
} catch (NoClassDefFoundError e) {
return false;
}
}
|
diff --git a/collect-flex/collect-flex-server/src/main/java/org/openforis/collect/remoting/service/DataService.java b/collect-flex/collect-flex-server/src/main/java/org/openforis/collect/remoting/service/DataService.java
index c6ca2a127..749ac2c65 100644
--- a/collect-flex/collect-flex-server/src/main/java/org/openforis/collect/remoting/service/DataService.java
+++ b/collect-flex/collect-flex-server/src/main/java/org/openforis/collect/remoting/service/DataService.java
@@ -1,633 +1,636 @@
/**
*
*/
package org.openforis.collect.remoting.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.openforis.collect.manager.RecordManager;
import org.openforis.collect.manager.SessionManager;
import org.openforis.collect.metamodel.proxy.CodeListItemProxy;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.collect.model.FieldSymbol;
import org.openforis.collect.model.User;
import org.openforis.collect.model.proxy.RecordProxy;
import org.openforis.collect.persistence.AccessDeniedException;
import org.openforis.collect.persistence.InvalidIdException;
import org.openforis.collect.persistence.MultipleEditException;
import org.openforis.collect.persistence.NonexistentIdException;
import org.openforis.collect.persistence.RecordLockedException;
import org.openforis.collect.remoting.service.UpdateRequestOperation.Method;
import org.openforis.collect.session.SessionState;
import org.openforis.collect.session.SessionState.RecordState;
import org.openforis.idm.metamodel.AttributeDefinition;
import org.openforis.idm.metamodel.BooleanAttributeDefinition;
import org.openforis.idm.metamodel.CodeAttributeDefinition;
import org.openforis.idm.metamodel.CodeListItem;
import org.openforis.idm.metamodel.CoordinateAttributeDefinition;
import org.openforis.idm.metamodel.DateAttributeDefinition;
import org.openforis.idm.metamodel.EntityDefinition;
import org.openforis.idm.metamodel.ModelVersion;
import org.openforis.idm.metamodel.NodeDefinition;
import org.openforis.idm.metamodel.NumberAttributeDefinition;
import org.openforis.idm.metamodel.NumberAttributeDefinition.Type;
import org.openforis.idm.metamodel.RangeAttributeDefinition;
import org.openforis.idm.metamodel.Schema;
import org.openforis.idm.metamodel.TimeAttributeDefinition;
import org.openforis.idm.metamodel.validation.ValidationResults;
import org.openforis.idm.model.Attribute;
import org.openforis.idm.model.Code;
import org.openforis.idm.model.CodeAttribute;
import org.openforis.idm.model.Entity;
import org.openforis.idm.model.Field;
import org.openforis.idm.model.IntegerRange;
import org.openforis.idm.model.Node;
import org.openforis.idm.model.NodePointer;
import org.openforis.idm.model.NumericRange;
import org.openforis.idm.model.RealRange;
import org.openforis.idm.model.Record;
import org.openforis.idm.model.expression.ExpressionFactory;
import org.openforis.idm.model.expression.ModelPathExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* @author M. Togna
* @author S. Ricci
*
*/
public class DataService {
@Autowired
private SessionManager sessionManager;
@Autowired
private RecordManager recordManager;
@Transactional
public RecordProxy loadRecord(int id) throws RecordLockedException, MultipleEditException, NonexistentIdException, AccessDeniedException {
CollectSurvey survey = getActiveSurvey();
User user = getUserInSession();
CollectRecord record = recordManager.checkout(survey, user, id);
//record.updateNodeStates();
Entity rootEntity = record.getRootEntity();
recordManager.addEmptyNodes(rootEntity);
SessionState sessionState = sessionManager.getSessionState();
sessionState.setActiveRecord(record);
sessionState.setActiveRecordState(RecordState.SAVED);
return new RecordProxy(record);
}
/**
*
* @param rootEntityName
* @param offset
* @param toIndex
* @param orderByFieldName
* @param filter
*
* @return map with "count" and "records" items
*/
@Transactional
public Map<String, Object> getRecordSummaries(String rootEntityName, int offset, int maxNumberOfRows, String orderByFieldName, String filter) {
Map<String, Object> result = new HashMap<String, Object>();
SessionState sessionState = sessionManager.getSessionState();
CollectSurvey activeSurvey = sessionState.getActiveSurvey();
Schema schema = activeSurvey.getSchema();
EntityDefinition rootEntityDefinition = schema.getRootEntityDefinition(rootEntityName);
String rootEntityDefinitionName = rootEntityDefinition.getName();
int count = recordManager.getCountRecords(rootEntityDefinition);
List<CollectRecord> summaries = recordManager.getSummaries(activeSurvey, rootEntityDefinitionName, offset, maxNumberOfRows, orderByFieldName, filter);
List<RecordProxy> proxies = new ArrayList<RecordProxy>();
for (CollectRecord summary : summaries) {
proxies.add(new RecordProxy(summary));
}
result.put("count", count);
result.put("records", proxies);
return result;
}
@Transactional
public RecordProxy createRecord(String rootEntityName, String versionName) throws MultipleEditException, AccessDeniedException, RecordLockedException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
CollectSurvey activeSurvey = sessionState.getActiveSurvey();
ModelVersion version = activeSurvey.getVersion(versionName);
Schema schema = activeSurvey.getSchema();
EntityDefinition rootEntityDefinition = schema.getRootEntityDefinition(rootEntityName);
CollectRecord record = recordManager.create(activeSurvey, rootEntityDefinition, user, version.getName());
Entity rootEntity = record.getRootEntity();
recordManager.addEmptyNodes(rootEntity);
sessionState.setActiveRecord((CollectRecord) record);
sessionState.setActiveRecordState(RecordState.NEW);
RecordProxy recordProxy = new RecordProxy(record);
return recordProxy;
}
@Transactional
public void deleteRecord(int id) throws RecordLockedException, AccessDeniedException, MultipleEditException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
recordManager.delete(id, user);
sessionManager.clearActiveRecord();
}
@Transactional
public void saveActiveRecord() {
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
record.setModifiedDate(new java.util.Date());
record.setModifiedBy(sessionState.getUser());
recordManager.save(record);
sessionState.setActiveRecordState(RecordState.SAVED);
}
@Transactional
public void deleteActiveRecord() throws RecordLockedException, AccessDeniedException, MultipleEditException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
Record record = sessionState.getActiveRecord();
recordManager.delete(record.getId(), user);
sessionManager.clearActiveRecord();
}
public List<UpdateResponse> updateActiveRecord(UpdateRequest request) {
List<UpdateRequestOperation> operations = request.getOperations();
List<UpdateResponse> updateResponses = new ArrayList<UpdateResponse>();
for (UpdateRequestOperation operation : operations) {
Collection<UpdateResponse> responses = processUpdateRequestOperation(operation);
updateResponses.addAll(responses);
}
return updateResponses;
}
@SuppressWarnings("unchecked")
private Collection<UpdateResponse> processUpdateRequestOperation(UpdateRequestOperation operation) {
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
Integer parentEntityId = operation.getParentEntityId();
Entity parentEntity = (Entity) record.getNodeByInternalId(parentEntityId);
Integer nodeId = operation.getNodeId();
Integer fieldIndex = operation.getFieldIndex();
String nodeName = operation.getNodeName();
Node<?> node = null;
if(nodeId != null) {
node = record.getNodeByInternalId(nodeId);
}
NodeDefinition nodeDef = ((EntityDefinition) parentEntity.getDefinition()).getChildDefinition(nodeName);
String requestValue = operation.getValue();
String remarks = operation.getRemarks();
FieldSymbol symbol = operation.getSymbol();
Method method = operation.getMethod();
Map<Integer, UpdateResponse> responseMap = new HashMap<Integer, UpdateResponse>();
Set<NodePointer> relReqDependencies = null;
Set<Attribute<?,?>> checkDependensies = null;
+ List<Entity> ancestors = null;
Attribute<? extends AttributeDefinition, ?> attribute = null;
switch (method) {
case ADD :
Node<?> createdNode = addNode(parentEntity, nodeDef, requestValue, symbol, remarks);
UpdateResponse response = getUpdateResponse(responseMap, createdNode.getInternalId());
response.setCreatedNode(createdNode);
relReqDependencies = recordManager. clearRelevanceRequiredStates(createdNode);
if(createdNode instanceof Attribute){
attribute = (Attribute<? extends AttributeDefinition, ?>) createdNode;
checkDependensies = recordManager.clearValidationResults(attribute);
checkDependensies.add(attribute);
}
relReqDependencies.add(new NodePointer(createdNode.getParent(), createdNode.getName()));
+ ancestors = createdNode.getAncestors();
break;
case UPDATE:
attribute = (Attribute<AttributeDefinition, ?>) node;
+ ancestors = attribute.getAncestors();
if(fieldIndex < 0){
Object value = parseCompositeAttributeValue(parentEntity, attribute.getDefinition(), requestValue);
recordManager.setAttributeValue(attribute, value, remarks);
} else {
Object value = parseFieldValue(parentEntity, attribute.getDefinition(), requestValue, fieldIndex);
recordManager.setFieldValue(attribute, value, remarks, symbol, fieldIndex);
}
relReqDependencies = recordManager. clearRelevanceRequiredStates(attribute);
checkDependensies = recordManager.clearValidationResults(attribute);
relReqDependencies.add(new NodePointer(attribute.getParent(), attribute.getName()));
checkDependensies.add(attribute);
break;
case DELETE:
attribute = (Attribute<AttributeDefinition, ?>) node;
+ ancestors = attribute.getAncestors();
Set<NodePointer> relevantDependencies = attribute.getRelevantDependencies();
Set<NodePointer> requiredDependencies = attribute.getRequiredDependencies();
checkDependensies = attribute.getCheckDependencies();
UpdateResponse resp = getUpdateResponse(responseMap, node.getInternalId());
resp.setDeletedINodeInternalId(node.getInternalId());
recordManager.deleteNode(node);
recordManager.clearRelevantDependencies(relevantDependencies);
recordManager.clearRequiredDependencies(requiredDependencies);
recordManager.clearValidationResults(checkDependensies);
relReqDependencies = relevantDependencies;
relReqDependencies.addAll(requiredDependencies);
break;
}
- List<Entity> ancestors = attribute.getAncestors();
prepareUpdateResponse(responseMap, relReqDependencies, checkDependensies, ancestors);
return responseMap.values();
}
private void prepareUpdateResponse(Map<Integer, UpdateResponse> responseMap, Set<NodePointer> relevanceReqquiredDependencies, Set<Attribute<?, ?>> validtionResultsDependencies, List<Entity> ancestors) {
if (ancestors != null) {
for (Entity entity : ancestors) {
// entity could be root definition
Entity parent = entity.getParent();
if (parent != null) {
UpdateResponse response = getUpdateResponse(responseMap, parent.getInternalId());
String childName = entity.getName();
response.setMinCountValid(childName, parent.validateMinCount(childName));
response.setRelevant(childName, parent.isRelevant(childName));
response.setRequired(childName, parent.isRequired(childName));
}
}
}
if (relevanceReqquiredDependencies != null) {
for (NodePointer nodePointer : relevanceReqquiredDependencies) {
Entity entity = nodePointer.getEntity();
String childName = nodePointer.getChildName();
UpdateResponse response = getUpdateResponse(responseMap, entity.getInternalId());
response.setRelevant(childName, entity.isRelevant(childName));
response.setRequired(childName, entity.isRequired(childName));
response.setMinCountValid(childName, entity.validateMinCount(childName));
}
}
if (validtionResultsDependencies != null) {
for (Attribute<?, ?> checkDepAttr : validtionResultsDependencies) {
checkDepAttr.clearValidationResults();
ValidationResults results = checkDepAttr.validateValue();
UpdateResponse response = getUpdateResponse(responseMap, checkDepAttr.getInternalId());
response.setAttributeValidationResults(results);
}
}
}
private UpdateResponse getUpdateResponse(Map<Integer, UpdateResponse> responseMap, int nodeId){
UpdateResponse response = responseMap.get(nodeId);
if(response == null){
response = new UpdateResponse(nodeId);
responseMap.put(nodeId, response);
}
return response;
}
@SuppressWarnings("unchecked")
private Node<?> addNode(Entity parentEntity, NodeDefinition nodeDef, String requestValue, FieldSymbol symbol, String remarks) {
if(nodeDef instanceof AttributeDefinition) {
AttributeDefinition def = (AttributeDefinition) nodeDef;
Attribute<?, ?> attribute = (Attribute<?, ?>) def.createNode();
if(StringUtils.isNotBlank(requestValue)) {
Object value = parseCompositeAttributeValue(parentEntity, (AttributeDefinition) nodeDef, requestValue);
((Attribute<?, Object>) attribute).setValue(value);
}
if(symbol != null || remarks != null) {
Character symbolChar = null;
if(symbol != null) {
symbolChar = symbol.getCode();
}
Field<?> firstField = attribute.getField(0);
firstField.setSymbol(symbolChar);
firstField.setRemarks(remarks);
}
parentEntity.add(attribute);
return attribute;
} else {
Entity e = recordManager.addEntity(parentEntity, nodeDef.getName());
return e;
}
}
private Object parseFieldValue(Entity parentEntity, AttributeDefinition def, String value, Integer fieldIndex) {
Object fieldValue = null;
if(StringUtils.isBlank(value)) {
return null;
}
if(def instanceof BooleanAttributeDefinition) {
fieldValue = Boolean.parseBoolean(value);
} else if(def instanceof CoordinateAttributeDefinition) {
if(fieldIndex != null) {
if(fieldIndex == 2) {
fieldValue = value;
} else {
fieldValue = Double.valueOf(value);
}
}
} else if(def instanceof DateAttributeDefinition) {
Integer val = Integer.valueOf(value);
fieldValue = val;
} else if(def instanceof NumberAttributeDefinition) {
NumberAttributeDefinition numberDef = (NumberAttributeDefinition) def;
Type type = numberDef.getType();
Number number = null;
switch(type) {
case INTEGER:
number = Integer.valueOf(value);
break;
case REAL:
number = Double.valueOf(value);
break;
}
if(number != null) {
fieldValue = number;
}
} else if(def instanceof RangeAttributeDefinition) {
RangeAttributeDefinition.Type type = ((RangeAttributeDefinition) def).getType();
Number number = null;
switch(type) {
case INTEGER:
number = Integer.valueOf(value);
break;
case REAL:
number = Double.valueOf(value);
break;
}
if(number != null) {
fieldValue = number;
}
} else if(def instanceof TimeAttributeDefinition) {
fieldValue = Integer.valueOf(value);
} else {
fieldValue = value;
}
return fieldValue;
}
private Object parseCompositeAttributeValue(Entity parentEntity, AttributeDefinition defn, String value) {
Object result;
if(defn instanceof CodeAttributeDefinition) {
Record record = parentEntity.getRecord();
ModelVersion version = record .getVersion();
result = parseCode(parentEntity, (CodeAttributeDefinition) defn, value, version );
} else if(defn instanceof RangeAttributeDefinition) {
RangeAttributeDefinition rangeDef = (RangeAttributeDefinition) defn;
RangeAttributeDefinition.Type type = rangeDef.getType();
NumericRange<?> range = null;
switch(type) {
case INTEGER:
range = IntegerRange.parseIntegerRange(value);
break;
case REAL:
range = RealRange.parseRealRange(value);
break;
}
result = range;
} else {
throw new IllegalArgumentException("Invalid AttributeDefinition: expected CodeAttributeDefinition or RangeAttributeDefinition");
}
return result;
}
@Transactional
public int promoteRecord(int recordId) throws InvalidIdException, MultipleEditException, NonexistentIdException, AccessDeniedException, RecordLockedException {
SessionState sessionState = sessionManager.getSessionState();
CollectSurvey survey = sessionState.getActiveSurvey();
User user = sessionState.getUser();
int promotedId = this.recordManager.promote(survey, recordId, user);
sessionManager.clearActiveRecord();
return promotedId;
}
@Transactional
public void demoteRecord(String recordId) throws InvalidIdException, MultipleEditException, NonexistentIdException, AccessDeniedException, RecordLockedException {
this.recordManager.demote(recordId);
}
public void updateNodeHierarchy(Node<? extends NodeDefinition> node, int newPosition) {
}
public List<String> find(String context, String query) {
return null;
}
/**
* remove the active record from the current session
* @throws RecordLockedException
* @throws AccessDeniedException
* @throws MultipleEditException
*/
public void clearActiveRecord() throws RecordLockedException, AccessDeniedException, MultipleEditException {
CollectRecord activeRecord = getActiveRecord();
User user = getUserInSession();
this.recordManager.unlock(activeRecord, user);
Integer recordId = activeRecord.getId();
SessionState sessionState = this.sessionManager.getSessionState();
if(RecordState.NEW == sessionState.getActiveRecordState()) {
this.recordManager.delete(recordId, user);
}
this.sessionManager.clearActiveRecord();
}
/**
* Gets the code list items assignable to the specified attribute and matching the specified codes.
*
* @param parentEntityId
* @param attrName
* @param codes
* @return
*/
public List<CodeListItemProxy> getCodeListItems(int parentEntityId, String attrName, String[] codes){
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attrName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItem> filteredItems = new ArrayList<CodeListItem>();
if(codes != null && codes.length > 0) {
//filter by specified codes
for (CodeListItem item : items) {
for (String code : codes) {
if(item.getCode().equals(code)) {
filteredItems.add(item);
}
}
}
}
List<CodeListItemProxy> result = CodeListItemProxy.fromList(filteredItems);
return result;
}
/**
* Gets the code list items assignable to the specified attribute.
*
* @param parentEntityId
* @param attrName
* @return
*/
public List<CodeListItemProxy> findAssignableCodeListItems(int parentEntityId, String attrName){
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attrName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItemProxy> result = CodeListItemProxy.fromList(items);
List<Node<?>> selectedCodes = parent.getAll(attrName);
CodeListItemProxy.setSelectedItems(result, selectedCodes);
return result;
}
/**
* Finds a list of code list items assignable to the specified attribute and matching the passed codes
*
* @param parentEntityId
* @param attributeName
* @param codes
* @return
*/
public List<CodeListItemProxy> findAssignableCodeListItems(int parentEntityId, String attributeName, String[] codes) {
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attributeName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItemProxy> result = new ArrayList<CodeListItemProxy>();
for (String code : codes) {
CodeListItem item = findCodeListItem(items, code);
if(item != null) {
CodeListItemProxy proxy = new CodeListItemProxy(item);
result.add(proxy);
}
}
return result;
}
private User getUserInSession() {
SessionState sessionState = getSessionManager().getSessionState();
User user = sessionState.getUser();
return user;
}
private CollectSurvey getActiveSurvey() {
SessionState sessionState = getSessionManager().getSessionState();
CollectSurvey activeSurvey = sessionState.getActiveSurvey();
return activeSurvey;
}
protected CollectRecord getActiveRecord() {
SessionState sessionState = getSessionManager().getSessionState();
CollectRecord activeRecord = sessionState.getActiveRecord();
return activeRecord;
}
protected SessionManager getSessionManager() {
return sessionManager;
}
protected RecordManager getRecordManager() {
return recordManager;
}
/**
* Start of CodeList utility methods
*
* TODO move them to a better location
*/
private List<CodeListItem> getAssignableCodeListItems(Entity parent, CodeAttributeDefinition def) {
CollectRecord record = getActiveRecord();
ModelVersion version = record.getVersion();
List<CodeListItem> items = null;
if(StringUtils.isEmpty(def.getParentExpression())){
items = def.getList().getItems();
} else {
CodeAttribute parentCodeAttribute = getCodeParent(parent, def);
if(parentCodeAttribute!=null){
CodeListItem parentCodeListItem = parentCodeAttribute.getCodeListItem();
if(parentCodeListItem != null) {
//TODO exception if parent not specified
items = parentCodeListItem.getChildItems();
}
}
}
List<CodeListItem> result = new ArrayList<CodeListItem>();
if(items != null) {
for (CodeListItem item : items) {
if(version.isApplicable(item)) {
result.add(item);
}
}
}
return result;
}
private CodeAttribute getCodeParent(Entity context, CodeAttributeDefinition def) {
try {
String parentExpr = def.getParentExpression();
ExpressionFactory expressionFactory = context.getRecord().getSurveyContext().getExpressionFactory();
ModelPathExpression expression = expressionFactory.createModelPathExpression(parentExpr);
Node<?> parentNode = expression.evaluate(context, null);
if (parentNode != null && parentNode instanceof CodeAttribute) {
return (CodeAttribute) parentNode;
}
} catch (Exception e) {
// return null;
}
return null;
}
private CodeListItem findCodeListItem(List<CodeListItem> siblings, String code) {
String adaptedCode = code.trim();
adaptedCode = adaptedCode.toUpperCase();
//remove initial zeros
adaptedCode = adaptedCode.replaceFirst("^0+", "");
adaptedCode = Pattern.quote(adaptedCode);
for (CodeListItem item : siblings) {
String itemCode = item.getCode();
Pattern pattern = Pattern.compile("^[0]*" + adaptedCode + "$");
Matcher matcher = pattern.matcher(itemCode);
if(matcher.find()) {
return item;
}
}
return null;
}
private Code parseCode(Entity parent, CodeAttributeDefinition def, String value, ModelVersion version) {
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
Code code = parseCode(value, items, version);
return code;
}
private Code parseCode(String value, List<CodeListItem> codeList, ModelVersion version) {
Code code = null;
String[] strings = value.split(":");
String codeStr = null;
String qualifier = null;
switch(strings.length) {
case 2:
qualifier = strings[1].trim();
case 1:
codeStr = strings[0].trim();
break;
default:
//TODO throw error: invalid parameter
}
CodeListItem codeListItem = findCodeListItem(codeList, codeStr);
if(codeListItem != null) {
code = new Code(codeListItem.getCode(), qualifier);
}
if (code == null) {
code = new Code(codeStr, qualifier);
}
return code;
}
}
| false | true | private Collection<UpdateResponse> processUpdateRequestOperation(UpdateRequestOperation operation) {
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
Integer parentEntityId = operation.getParentEntityId();
Entity parentEntity = (Entity) record.getNodeByInternalId(parentEntityId);
Integer nodeId = operation.getNodeId();
Integer fieldIndex = operation.getFieldIndex();
String nodeName = operation.getNodeName();
Node<?> node = null;
if(nodeId != null) {
node = record.getNodeByInternalId(nodeId);
}
NodeDefinition nodeDef = ((EntityDefinition) parentEntity.getDefinition()).getChildDefinition(nodeName);
String requestValue = operation.getValue();
String remarks = operation.getRemarks();
FieldSymbol symbol = operation.getSymbol();
Method method = operation.getMethod();
Map<Integer, UpdateResponse> responseMap = new HashMap<Integer, UpdateResponse>();
Set<NodePointer> relReqDependencies = null;
Set<Attribute<?,?>> checkDependensies = null;
Attribute<? extends AttributeDefinition, ?> attribute = null;
switch (method) {
case ADD :
Node<?> createdNode = addNode(parentEntity, nodeDef, requestValue, symbol, remarks);
UpdateResponse response = getUpdateResponse(responseMap, createdNode.getInternalId());
response.setCreatedNode(createdNode);
relReqDependencies = recordManager. clearRelevanceRequiredStates(createdNode);
if(createdNode instanceof Attribute){
attribute = (Attribute<? extends AttributeDefinition, ?>) createdNode;
checkDependensies = recordManager.clearValidationResults(attribute);
checkDependensies.add(attribute);
}
relReqDependencies.add(new NodePointer(createdNode.getParent(), createdNode.getName()));
break;
case UPDATE:
attribute = (Attribute<AttributeDefinition, ?>) node;
if(fieldIndex < 0){
Object value = parseCompositeAttributeValue(parentEntity, attribute.getDefinition(), requestValue);
recordManager.setAttributeValue(attribute, value, remarks);
} else {
Object value = parseFieldValue(parentEntity, attribute.getDefinition(), requestValue, fieldIndex);
recordManager.setFieldValue(attribute, value, remarks, symbol, fieldIndex);
}
relReqDependencies = recordManager. clearRelevanceRequiredStates(attribute);
checkDependensies = recordManager.clearValidationResults(attribute);
relReqDependencies.add(new NodePointer(attribute.getParent(), attribute.getName()));
checkDependensies.add(attribute);
break;
case DELETE:
attribute = (Attribute<AttributeDefinition, ?>) node;
Set<NodePointer> relevantDependencies = attribute.getRelevantDependencies();
Set<NodePointer> requiredDependencies = attribute.getRequiredDependencies();
checkDependensies = attribute.getCheckDependencies();
UpdateResponse resp = getUpdateResponse(responseMap, node.getInternalId());
resp.setDeletedINodeInternalId(node.getInternalId());
recordManager.deleteNode(node);
recordManager.clearRelevantDependencies(relevantDependencies);
recordManager.clearRequiredDependencies(requiredDependencies);
recordManager.clearValidationResults(checkDependensies);
relReqDependencies = relevantDependencies;
relReqDependencies.addAll(requiredDependencies);
break;
}
List<Entity> ancestors = attribute.getAncestors();
prepareUpdateResponse(responseMap, relReqDependencies, checkDependensies, ancestors);
return responseMap.values();
}
| private Collection<UpdateResponse> processUpdateRequestOperation(UpdateRequestOperation operation) {
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
Integer parentEntityId = operation.getParentEntityId();
Entity parentEntity = (Entity) record.getNodeByInternalId(parentEntityId);
Integer nodeId = operation.getNodeId();
Integer fieldIndex = operation.getFieldIndex();
String nodeName = operation.getNodeName();
Node<?> node = null;
if(nodeId != null) {
node = record.getNodeByInternalId(nodeId);
}
NodeDefinition nodeDef = ((EntityDefinition) parentEntity.getDefinition()).getChildDefinition(nodeName);
String requestValue = operation.getValue();
String remarks = operation.getRemarks();
FieldSymbol symbol = operation.getSymbol();
Method method = operation.getMethod();
Map<Integer, UpdateResponse> responseMap = new HashMap<Integer, UpdateResponse>();
Set<NodePointer> relReqDependencies = null;
Set<Attribute<?,?>> checkDependensies = null;
List<Entity> ancestors = null;
Attribute<? extends AttributeDefinition, ?> attribute = null;
switch (method) {
case ADD :
Node<?> createdNode = addNode(parentEntity, nodeDef, requestValue, symbol, remarks);
UpdateResponse response = getUpdateResponse(responseMap, createdNode.getInternalId());
response.setCreatedNode(createdNode);
relReqDependencies = recordManager. clearRelevanceRequiredStates(createdNode);
if(createdNode instanceof Attribute){
attribute = (Attribute<? extends AttributeDefinition, ?>) createdNode;
checkDependensies = recordManager.clearValidationResults(attribute);
checkDependensies.add(attribute);
}
relReqDependencies.add(new NodePointer(createdNode.getParent(), createdNode.getName()));
ancestors = createdNode.getAncestors();
break;
case UPDATE:
attribute = (Attribute<AttributeDefinition, ?>) node;
ancestors = attribute.getAncestors();
if(fieldIndex < 0){
Object value = parseCompositeAttributeValue(parentEntity, attribute.getDefinition(), requestValue);
recordManager.setAttributeValue(attribute, value, remarks);
} else {
Object value = parseFieldValue(parentEntity, attribute.getDefinition(), requestValue, fieldIndex);
recordManager.setFieldValue(attribute, value, remarks, symbol, fieldIndex);
}
relReqDependencies = recordManager. clearRelevanceRequiredStates(attribute);
checkDependensies = recordManager.clearValidationResults(attribute);
relReqDependencies.add(new NodePointer(attribute.getParent(), attribute.getName()));
checkDependensies.add(attribute);
break;
case DELETE:
attribute = (Attribute<AttributeDefinition, ?>) node;
ancestors = attribute.getAncestors();
Set<NodePointer> relevantDependencies = attribute.getRelevantDependencies();
Set<NodePointer> requiredDependencies = attribute.getRequiredDependencies();
checkDependensies = attribute.getCheckDependencies();
UpdateResponse resp = getUpdateResponse(responseMap, node.getInternalId());
resp.setDeletedINodeInternalId(node.getInternalId());
recordManager.deleteNode(node);
recordManager.clearRelevantDependencies(relevantDependencies);
recordManager.clearRequiredDependencies(requiredDependencies);
recordManager.clearValidationResults(checkDependensies);
relReqDependencies = relevantDependencies;
relReqDependencies.addAll(requiredDependencies);
break;
}
prepareUpdateResponse(responseMap, relReqDependencies, checkDependensies, ancestors);
return responseMap.values();
}
|
diff --git a/src/main/java/com/flotype/bridge/Connection.java b/src/main/java/com/flotype/bridge/Connection.java
index 2e0c342..44892ab 100644
--- a/src/main/java/com/flotype/bridge/Connection.java
+++ b/src/main/java/com/flotype/bridge/Connection.java
@@ -1,216 +1,216 @@
package com.flotype.bridge;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import net.bobah.nio.TcpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Connection extends TcpClient {
private static Logger log = LoggerFactory.getLogger(Connection.class);
String clientId;
// Secret used for reconnects
private String secret;
// Queue for commands before connects happen
private Queue<String> commandQueue = new LinkedList<String>();
private boolean handshaken;
private Bridge bridge;
private String apiKey = null;
private String host = null;
private int port = -1;
private String redirector;
protected Connection(Bridge bridge) {
this.bridge = bridge;
}
protected void connect() throws IOException {
if (this.host == null || this.port == -1) {
redirector();
} else {
this.setAddress(new InetSocketAddress(host, port));
log.info("Starting TCP connection {} {}", this.host, this.port);
start();
}
}
protected void send(String string) {
if (bridge.ready) {
write(string.getBytes());
} else {
// Buffer messages until reconnection happens
commandQueue.add(string);
}
}
public void write(byte[] buffer) {
log.info("Sending {}", new String(buffer));
ByteBuffer data = ByteBuffer.allocate(buffer.length + 4);
data.put(Utils.intToByteArray(buffer.length)); // Put the length header
data.put(buffer); // Put the data
data.flip();
try {
this.send(data);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void redirector() {
String result = null;
if (redirector.startsWith("http://")) {
try {
// Send data
String urlStr = redirector;
if (urlStr.charAt(urlStr.length() - 1) != '/') {
urlStr += '/';
}
urlStr = urlStr + "redirect/" + this.apiKey;
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
result = sb.toString();
// Parse response JSON, set fields on self, and connect
Map<String, Object> jsonObj = JSONCodec.parseRedirector(result);
Map<String, String> data = (Map<String, String>) jsonObj
.get("data");
if(data.get("bridge_host") == null || data.get("bridge_port") == null) {
log.error("Could not find host and port in JSON body");
return;
}
this.host = data.get("bridge_host");
this.port = Integer.parseInt(data.get("bridge_port"));
this.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void processCommandQueue() {
for (String str : commandQueue) {
// Replace the 'null' in the JSON reference address with the
// now-known client ID
this.send(str.replace("\"ref\":[\"client\",null,",
"\"ref\":[\"client\",\"" + this.clientId + "\","));
}
commandQueue.clear();
}
@Override
protected void onRead(ByteBuffer buf) throws Exception {
while (buf.hasRemaining()) {
if(buf.remaining() < 4) {
// Full header not received yet. Wait until next time
break;
}
int length = buf.getInt();
if (buf.remaining() < length) {
// Header received but not the body. Wait until next time.
break;
}
byte[] body = new byte[length];
buf.get(body);
String bodyString = new String(body);
if (length != body.length) {
throw new Exception(
"Expected message length not equal to buffer size");
}
- log.info("Received {}", body);
+ log.info("Received {}", bodyString);
if (!bridge.ready) {
// Client not handshaken
String[] ids = (bodyString).split("\\|");
if (ids.length == 2) {
// Got a ID and secret as response
log.info("clientId receieved {}", ids[0]);
clientId = ids[0];
secret = ids[1];
this.handshaken = true;
if(clientId == null) {
bridge.onReady();
} else {
bridge.onReconnect();
}
processCommandQueue();
log.info("Handshake complete");
return;
}
}
// Parse as normal
Map<String, Object> message = Utils.deserialize(bridge, body);
if(message.get("destination") == null) {
log.warn("No destination in message {}", bodyString);
} else {
bridge.dispatcher.execute((Reference) message.get("destination"),
(List<Object>) message.get("args"));
}
}
}
@Override
protected void onDisconnected() {
log.warn("Connection closed");
bridge.onDisconnect();
}
@Override
protected void onConnected() throws Exception {
log.info("Beginning handshake");
String connectString = JSONCodec.createCONNECT(bridge, clientId,
secret, apiKey);
// Use write instead of send for unbuffered sending
this.write(connectString.getBytes());
bridge.onConnected();
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public void setRedirector(String redirectorUrl) {
this.redirector = redirectorUrl;
}
}
| true | true | protected void onRead(ByteBuffer buf) throws Exception {
while (buf.hasRemaining()) {
if(buf.remaining() < 4) {
// Full header not received yet. Wait until next time
break;
}
int length = buf.getInt();
if (buf.remaining() < length) {
// Header received but not the body. Wait until next time.
break;
}
byte[] body = new byte[length];
buf.get(body);
String bodyString = new String(body);
if (length != body.length) {
throw new Exception(
"Expected message length not equal to buffer size");
}
log.info("Received {}", body);
if (!bridge.ready) {
// Client not handshaken
String[] ids = (bodyString).split("\\|");
if (ids.length == 2) {
// Got a ID and secret as response
log.info("clientId receieved {}", ids[0]);
clientId = ids[0];
secret = ids[1];
this.handshaken = true;
if(clientId == null) {
bridge.onReady();
} else {
bridge.onReconnect();
}
processCommandQueue();
log.info("Handshake complete");
return;
}
}
// Parse as normal
Map<String, Object> message = Utils.deserialize(bridge, body);
if(message.get("destination") == null) {
log.warn("No destination in message {}", bodyString);
} else {
bridge.dispatcher.execute((Reference) message.get("destination"),
(List<Object>) message.get("args"));
}
}
}
| protected void onRead(ByteBuffer buf) throws Exception {
while (buf.hasRemaining()) {
if(buf.remaining() < 4) {
// Full header not received yet. Wait until next time
break;
}
int length = buf.getInt();
if (buf.remaining() < length) {
// Header received but not the body. Wait until next time.
break;
}
byte[] body = new byte[length];
buf.get(body);
String bodyString = new String(body);
if (length != body.length) {
throw new Exception(
"Expected message length not equal to buffer size");
}
log.info("Received {}", bodyString);
if (!bridge.ready) {
// Client not handshaken
String[] ids = (bodyString).split("\\|");
if (ids.length == 2) {
// Got a ID and secret as response
log.info("clientId receieved {}", ids[0]);
clientId = ids[0];
secret = ids[1];
this.handshaken = true;
if(clientId == null) {
bridge.onReady();
} else {
bridge.onReconnect();
}
processCommandQueue();
log.info("Handshake complete");
return;
}
}
// Parse as normal
Map<String, Object> message = Utils.deserialize(bridge, body);
if(message.get("destination") == null) {
log.warn("No destination in message {}", bodyString);
} else {
bridge.dispatcher.execute((Reference) message.get("destination"),
(List<Object>) message.get("args"));
}
}
}
|
diff --git a/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java b/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java
index 68766d12d..f231a82f4 100644
--- a/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java
+++ b/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java
@@ -1,69 +1,69 @@
package org.jboss.tools.dummy.ui.bot.test;
import static org.eclipse.swtbot.swt.finder.waits.Conditions.shellIsActive;
import static org.junit.Assert.assertEquals;
import org.apache.log4j.Logger;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Dummy bot tests - designed to test jenkins slaves
* @author jpeterka
*
*/
@RunWith(SWTBotJunit4ClassRunner.class)
public class DummyTest {
Logger log = Logger.getLogger("");
@BeforeClass
public static void before() {
}
@Test
public void dummyTest() {
String prefMenu = "Preferences";
String prefDlg = prefMenu;
String windowMenu = "Window";
if (isOSX()) {
- prefMenu = "Preferences...";
+ prefMenu = "Preferences";
windowMenu = "Eclipse";
}
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.menu(windowMenu).menu(prefMenu).click();
bot.waitUntil(shellIsActive(prefDlg), 10000);
SWTBotShell shell = bot.shell(prefDlg);
assertEquals(prefDlg,shell.getText());
bot.activeShell().close();
}
@Test
public void hundredTimes() {
final int cycles = 100;
for (int i = 0 ; i < cycles ; i++)
{
dummyTest();
log.info(i+1 + "/" + cycles + " try passed");
}
}
@AfterClass
public static void after() {
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.closeAllShells();
}
public boolean isOSX() {
String osName = System.getProperty("os.name");
boolean osX = osName.contains("OS X");
log.info("OS Name: " + osName);
return osX;
}
}
| true | true | public void dummyTest() {
String prefMenu = "Preferences";
String prefDlg = prefMenu;
String windowMenu = "Window";
if (isOSX()) {
prefMenu = "Preferences...";
windowMenu = "Eclipse";
}
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.menu(windowMenu).menu(prefMenu).click();
bot.waitUntil(shellIsActive(prefDlg), 10000);
SWTBotShell shell = bot.shell(prefDlg);
assertEquals(prefDlg,shell.getText());
bot.activeShell().close();
}
| public void dummyTest() {
String prefMenu = "Preferences";
String prefDlg = prefMenu;
String windowMenu = "Window";
if (isOSX()) {
prefMenu = "Preferences";
windowMenu = "Eclipse";
}
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.menu(windowMenu).menu(prefMenu).click();
bot.waitUntil(shellIsActive(prefDlg), 10000);
SWTBotShell shell = bot.shell(prefDlg);
assertEquals(prefDlg,shell.getText());
bot.activeShell().close();
}
|
diff --git a/tapestry-framework/src/test/org/apache/tapestry/dojo/form/TestGTimePicker.java b/tapestry-framework/src/test/org/apache/tapestry/dojo/form/TestGTimePicker.java
index 2d92972b3..9a822a162 100644
--- a/tapestry-framework/src/test/org/apache/tapestry/dojo/form/TestGTimePicker.java
+++ b/tapestry-framework/src/test/org/apache/tapestry/dojo/form/TestGTimePicker.java
@@ -1,100 +1,100 @@
package org.apache.tapestry.dojo.form;
import org.apache.tapestry.*;
import org.apache.tapestry.form.BaseFormComponentTestCase;
import org.apache.tapestry.form.MockDelegate;
import org.apache.tapestry.form.TranslatedFieldSupport;
import org.apache.tapestry.form.ValidatableFieldSupport;
import org.apache.tapestry.form.translator.DateTranslator;
import org.apache.tapestry.services.ResponseBuilder;
import static org.easymock.EasyMock.*;
import org.testng.annotations.Test;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
/**
* Tests functionality of {@link GTimePicker} component.
*/
@Test
public class TestGTimePicker extends BaseFormComponentTestCase
{
public void test_Render()
{
ValidatableFieldSupport vfs = newMock(ValidatableFieldSupport.class);
TranslatedFieldSupport tfs = newMock(TranslatedFieldSupport.class);
DateTranslator translator = new DateTranslator();
translator.setPattern("hh:mm a");
ResponseBuilder resp = newMock(ResponseBuilder.class);
IRequestCycle cycle = newMock(IRequestCycle.class);
IForm form = newMock(IForm.class);
checkOrder(form, false);
IPage page = newPage();
Locale locale = Locale.getDefault();
MockDelegate delegate = new MockDelegate();
IScript script = newMock(IScript.class);
Date dtValue = new Date();
GTimePicker component = newInstance(GTimePicker.class,
"name", "fred",
"script", script,
"validatableFieldSupport", vfs,
"translatedFieldSupport", tfs,
"translator", translator,
"value", dtValue,
"page", page);
expect(cycle.renderStackPush(component)).andReturn(component);
expect(form.getName()).andReturn("testform").anyTimes();
form.setFormFieldUpdating(true);
IMarkupWriter writer = newBufferWriter();
trainGetForm(cycle, form);
trainWasPrerendered(form, writer, component, false);
trainGetDelegate(form, delegate);
delegate.setFormComponent(component);
trainGetElementId(form, component, "fred");
trainIsRewinding(form, false);
expect(cycle.isRewinding()).andReturn(false).anyTimes();
delegate.setFormComponent(component);
expect(cycle.getResponseBuilder()).andReturn(resp).anyTimes();
expect(resp.isDynamic()).andReturn(false).anyTimes();
expect(tfs.format(component, dtValue)).andReturn(dtValue.toString());
tfs.renderContributions(component, writer, cycle);
vfs.renderContributions(component, writer, cycle);
expect(page.getLocale()).andReturn(locale).anyTimes();
PageRenderSupport prs = newPageRenderSupport();
trainGetPageRenderSupport(cycle, prs);
script.execute(eq(component), eq(cycle), eq(prs), isA(Map.class));
expect(cycle.renderStackPop()).andReturn(component);
replay();
component.render(writer, cycle);
verify();
- assertBuffer("<span class=\"prefix\"><input type=\"text\" name=\"fred\" "
+ assertBuffer("<span class=\"prefix\"><input type=\"text\" autocomplete=\"off\" name=\"fred\" "
+ "value=\"" + dtValue.toString() + "\" id=\"fred\" class=\"validation-delegate\" /></span>");
}
}
| true | true | public void test_Render()
{
ValidatableFieldSupport vfs = newMock(ValidatableFieldSupport.class);
TranslatedFieldSupport tfs = newMock(TranslatedFieldSupport.class);
DateTranslator translator = new DateTranslator();
translator.setPattern("hh:mm a");
ResponseBuilder resp = newMock(ResponseBuilder.class);
IRequestCycle cycle = newMock(IRequestCycle.class);
IForm form = newMock(IForm.class);
checkOrder(form, false);
IPage page = newPage();
Locale locale = Locale.getDefault();
MockDelegate delegate = new MockDelegate();
IScript script = newMock(IScript.class);
Date dtValue = new Date();
GTimePicker component = newInstance(GTimePicker.class,
"name", "fred",
"script", script,
"validatableFieldSupport", vfs,
"translatedFieldSupport", tfs,
"translator", translator,
"value", dtValue,
"page", page);
expect(cycle.renderStackPush(component)).andReturn(component);
expect(form.getName()).andReturn("testform").anyTimes();
form.setFormFieldUpdating(true);
IMarkupWriter writer = newBufferWriter();
trainGetForm(cycle, form);
trainWasPrerendered(form, writer, component, false);
trainGetDelegate(form, delegate);
delegate.setFormComponent(component);
trainGetElementId(form, component, "fred");
trainIsRewinding(form, false);
expect(cycle.isRewinding()).andReturn(false).anyTimes();
delegate.setFormComponent(component);
expect(cycle.getResponseBuilder()).andReturn(resp).anyTimes();
expect(resp.isDynamic()).andReturn(false).anyTimes();
expect(tfs.format(component, dtValue)).andReturn(dtValue.toString());
tfs.renderContributions(component, writer, cycle);
vfs.renderContributions(component, writer, cycle);
expect(page.getLocale()).andReturn(locale).anyTimes();
PageRenderSupport prs = newPageRenderSupport();
trainGetPageRenderSupport(cycle, prs);
script.execute(eq(component), eq(cycle), eq(prs), isA(Map.class));
expect(cycle.renderStackPop()).andReturn(component);
replay();
component.render(writer, cycle);
verify();
assertBuffer("<span class=\"prefix\"><input type=\"text\" name=\"fred\" "
+ "value=\"" + dtValue.toString() + "\" id=\"fred\" class=\"validation-delegate\" /></span>");
}
| public void test_Render()
{
ValidatableFieldSupport vfs = newMock(ValidatableFieldSupport.class);
TranslatedFieldSupport tfs = newMock(TranslatedFieldSupport.class);
DateTranslator translator = new DateTranslator();
translator.setPattern("hh:mm a");
ResponseBuilder resp = newMock(ResponseBuilder.class);
IRequestCycle cycle = newMock(IRequestCycle.class);
IForm form = newMock(IForm.class);
checkOrder(form, false);
IPage page = newPage();
Locale locale = Locale.getDefault();
MockDelegate delegate = new MockDelegate();
IScript script = newMock(IScript.class);
Date dtValue = new Date();
GTimePicker component = newInstance(GTimePicker.class,
"name", "fred",
"script", script,
"validatableFieldSupport", vfs,
"translatedFieldSupport", tfs,
"translator", translator,
"value", dtValue,
"page", page);
expect(cycle.renderStackPush(component)).andReturn(component);
expect(form.getName()).andReturn("testform").anyTimes();
form.setFormFieldUpdating(true);
IMarkupWriter writer = newBufferWriter();
trainGetForm(cycle, form);
trainWasPrerendered(form, writer, component, false);
trainGetDelegate(form, delegate);
delegate.setFormComponent(component);
trainGetElementId(form, component, "fred");
trainIsRewinding(form, false);
expect(cycle.isRewinding()).andReturn(false).anyTimes();
delegate.setFormComponent(component);
expect(cycle.getResponseBuilder()).andReturn(resp).anyTimes();
expect(resp.isDynamic()).andReturn(false).anyTimes();
expect(tfs.format(component, dtValue)).andReturn(dtValue.toString());
tfs.renderContributions(component, writer, cycle);
vfs.renderContributions(component, writer, cycle);
expect(page.getLocale()).andReturn(locale).anyTimes();
PageRenderSupport prs = newPageRenderSupport();
trainGetPageRenderSupport(cycle, prs);
script.execute(eq(component), eq(cycle), eq(prs), isA(Map.class));
expect(cycle.renderStackPop()).andReturn(component);
replay();
component.render(writer, cycle);
verify();
assertBuffer("<span class=\"prefix\"><input type=\"text\" autocomplete=\"off\" name=\"fred\" "
+ "value=\"" + dtValue.toString() + "\" id=\"fred\" class=\"validation-delegate\" /></span>");
}
|
diff --git a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java
index 51dd74906..b9c32b6af 100644
--- a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java
+++ b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java
@@ -1,242 +1,245 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 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
*
*******************************************************************************/
package org.eclipse.dltk.internal.core.mixin;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.dltk.core.DLTKLanguageManager;
import org.eclipse.dltk.core.IDLTKLanguageToolkit;
import org.eclipse.dltk.core.IModelElement;
import org.eclipse.dltk.core.IProjectFragment;
import org.eclipse.dltk.core.IScriptProject;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.core.builder.IScriptBuilder;
import org.eclipse.dltk.core.mixin.IMixinParser;
import org.eclipse.dltk.core.search.SearchEngine;
import org.eclipse.dltk.core.search.SearchParticipant;
import org.eclipse.dltk.core.search.index.Index;
import org.eclipse.dltk.core.search.indexing.IndexManager;
import org.eclipse.dltk.core.search.indexing.InternalSearchDocument;
import org.eclipse.dltk.core.search.indexing.ReadWriteMonitor;
import org.eclipse.dltk.internal.core.BuiltinProjectFragment;
import org.eclipse.dltk.internal.core.BuiltinSourceModule;
import org.eclipse.dltk.internal.core.ExternalProjectFragment;
import org.eclipse.dltk.internal.core.ExternalSourceModule;
import org.eclipse.dltk.internal.core.ModelManager;
import org.eclipse.dltk.internal.core.SourceModule;
import org.eclipse.dltk.internal.core.search.DLTKSearchDocument;
public class MixinBuilder implements IScriptBuilder {
public IStatus[] buildResources(IScriptProject project, List resources,
IProgressMonitor monitor, int status) {
return null;
}
public List getDependencies(IScriptProject project, List resources) {
return null;
}
public IStatus[] buildModelElements(IScriptProject project, List elements,
IProgressMonitor monitor, int status) {
return this.buildModelElements(project, elements, monitor, true);
}
public IStatus[] buildModelElements(IScriptProject project, List elements,
final IProgressMonitor monitor, boolean saveIndex) {
if (elements.size() == 0) {
return null;
}
IndexManager manager = ModelManager.getModelManager().getIndexManager();
final int elementsSize = elements.size();
IDLTKLanguageToolkit toolkit = null;
IMixinParser parser = null;
try {
toolkit = DLTKLanguageManager.getLanguageToolkit(project);
if (toolkit != null) {
parser = MixinManager.getMixinParser(toolkit.getNatureId());
}
} catch (CoreException e1) {
if (DLTKCore.DEBUG) {
e1.printStackTrace();
}
}
if (parser == null || toolkit == null) {
return null;
}
Map indexes = new HashMap();
// Map imons = new HashMap();
Index mixinIndex = null;
ReadWriteMonitor imon = null;
try {
// waitUntilIndexReady(toolkit);
IPath fullPath = project.getProject().getFullPath();
mixinIndex = manager.getSpecialIndex("mixin", /* project.getProject() */
fullPath.toString(), fullPath.toOSString());
imon = mixinIndex.monitor;
imon.enterWrite();
String name = "Building runtime model for "
+ project.getElementName();
if (monitor != null) {
monitor.beginTask(name, elementsSize);
}
int fileIndex = 0;
for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
ISourceModule element = (ISourceModule) iterator.next();
Index currentIndex = mixinIndex;
if (monitor != null) {
if (monitor.isCanceled()) {
return null;
}
}
String taskTitle = "Building runtime model for "
+ project.getElementName() + " ("
+ (elements.size() - fileIndex) + "):"
+ element.getElementName();
++fileIndex;
if (monitor != null) {
monitor.subTask(taskTitle);
}
// monitor.beginTask(taskTitle, 1);
IProjectFragment projectFragment = (IProjectFragment) element
.getAncestor(IModelElement.PROJECT_FRAGMENT);
IPath containerPath = project.getPath();
if (projectFragment instanceof ExternalProjectFragment
|| projectFragment instanceof BuiltinProjectFragment) {
IPath path = projectFragment.getPath();
if (indexes.containsKey(path)) {
currentIndex = (Index) indexes.get(path);
containerPath = path;
} else {
Index index = manager.getSpecialIndex("mixin", path
.toString(), path.toOSString());
if (index != null) {
currentIndex = index;
if (!indexes.values().contains(index)) {
index.monitor.enterWrite();
indexes.put(path, index);
}
containerPath = path;
}
}
}
char[] source = element.getSourceAsCharArray();
SearchParticipant participant = SearchEngine
.getDefaultSearchParticipant();
DLTKSearchDocument document;
document = new DLTKSearchDocument(element.getPath()
.toOSString(), containerPath, source, participant,
element instanceof ExternalSourceModule);
// System.out.println("mixin indexing:" + document.getPath());
((InternalSearchDocument) document).toolkit = toolkit;
String containerRelativePath = null;
if (element instanceof ExternalSourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(containerPath.segmentCount())
.setDevice(null).toString());
} else if (element instanceof SourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(1).toOSString());
} else if (element instanceof BuiltinSourceModule) {
containerRelativePath = document.getPath();
// (element.getPath()
// .removeFirstSegments().toOSString());
}
((InternalSearchDocument) document)
.setContainerRelativePath(containerRelativePath);
currentIndex.remove(containerRelativePath);
((InternalSearchDocument) document).setIndex(currentIndex);
new MixinIndexer(document, element, currentIndex)
.indexDocument();
if (monitor != null) {
monitor.worked(1);
}
}
} catch (CoreException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
} finally {
final Set saveIndexesSet = new HashSet();
if (mixinIndex != null) {
if (saveIndex) {
saveIndexesSet.add(mixinIndex);
} else {
imon.exitWrite();
}
}
Iterator iterator = indexes.values().iterator();
while (iterator.hasNext()) {
Index index = (Index) iterator.next();
if (saveIndex) {
saveIndexesSet.add(index);
} else {
index.monitor.exitWrite();
}
}
if (saveIndex) {
- if (monitor != null) {
- }
for (Iterator ind = saveIndexesSet.iterator(); ind.hasNext();) {
Index index = (Index) ind.next();
if (monitor != null) {
- monitor.subTask("Saving index for:"
- + index.containerPath);
+ String containerPath = index.containerPath;
+ if (containerPath.startsWith("#special#")) {
+ containerPath = containerPath.substring(
+ containerPath.lastIndexOf("#"),
+ containerPath.length());
+ }
+ monitor.subTask("Saving index for:" + containerPath);
}
try {
index.save();
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
} finally {
index.monitor.exitWrite();
}
}
}
if (monitor != null) {
monitor.done();
}
}
return null;
}
private static MixinBuilder builder = new MixinBuilder();
public static MixinBuilder getDefault() {
return builder;
}
public int estimateElementsToBuild(List elements) {
return elements.size();
}
}
| false | true | public IStatus[] buildModelElements(IScriptProject project, List elements,
final IProgressMonitor monitor, boolean saveIndex) {
if (elements.size() == 0) {
return null;
}
IndexManager manager = ModelManager.getModelManager().getIndexManager();
final int elementsSize = elements.size();
IDLTKLanguageToolkit toolkit = null;
IMixinParser parser = null;
try {
toolkit = DLTKLanguageManager.getLanguageToolkit(project);
if (toolkit != null) {
parser = MixinManager.getMixinParser(toolkit.getNatureId());
}
} catch (CoreException e1) {
if (DLTKCore.DEBUG) {
e1.printStackTrace();
}
}
if (parser == null || toolkit == null) {
return null;
}
Map indexes = new HashMap();
// Map imons = new HashMap();
Index mixinIndex = null;
ReadWriteMonitor imon = null;
try {
// waitUntilIndexReady(toolkit);
IPath fullPath = project.getProject().getFullPath();
mixinIndex = manager.getSpecialIndex("mixin", /* project.getProject() */
fullPath.toString(), fullPath.toOSString());
imon = mixinIndex.monitor;
imon.enterWrite();
String name = "Building runtime model for "
+ project.getElementName();
if (monitor != null) {
monitor.beginTask(name, elementsSize);
}
int fileIndex = 0;
for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
ISourceModule element = (ISourceModule) iterator.next();
Index currentIndex = mixinIndex;
if (monitor != null) {
if (monitor.isCanceled()) {
return null;
}
}
String taskTitle = "Building runtime model for "
+ project.getElementName() + " ("
+ (elements.size() - fileIndex) + "):"
+ element.getElementName();
++fileIndex;
if (monitor != null) {
monitor.subTask(taskTitle);
}
// monitor.beginTask(taskTitle, 1);
IProjectFragment projectFragment = (IProjectFragment) element
.getAncestor(IModelElement.PROJECT_FRAGMENT);
IPath containerPath = project.getPath();
if (projectFragment instanceof ExternalProjectFragment
|| projectFragment instanceof BuiltinProjectFragment) {
IPath path = projectFragment.getPath();
if (indexes.containsKey(path)) {
currentIndex = (Index) indexes.get(path);
containerPath = path;
} else {
Index index = manager.getSpecialIndex("mixin", path
.toString(), path.toOSString());
if (index != null) {
currentIndex = index;
if (!indexes.values().contains(index)) {
index.monitor.enterWrite();
indexes.put(path, index);
}
containerPath = path;
}
}
}
char[] source = element.getSourceAsCharArray();
SearchParticipant participant = SearchEngine
.getDefaultSearchParticipant();
DLTKSearchDocument document;
document = new DLTKSearchDocument(element.getPath()
.toOSString(), containerPath, source, participant,
element instanceof ExternalSourceModule);
// System.out.println("mixin indexing:" + document.getPath());
((InternalSearchDocument) document).toolkit = toolkit;
String containerRelativePath = null;
if (element instanceof ExternalSourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(containerPath.segmentCount())
.setDevice(null).toString());
} else if (element instanceof SourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(1).toOSString());
} else if (element instanceof BuiltinSourceModule) {
containerRelativePath = document.getPath();
// (element.getPath()
// .removeFirstSegments().toOSString());
}
((InternalSearchDocument) document)
.setContainerRelativePath(containerRelativePath);
currentIndex.remove(containerRelativePath);
((InternalSearchDocument) document).setIndex(currentIndex);
new MixinIndexer(document, element, currentIndex)
.indexDocument();
if (monitor != null) {
monitor.worked(1);
}
}
} catch (CoreException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
} finally {
final Set saveIndexesSet = new HashSet();
if (mixinIndex != null) {
if (saveIndex) {
saveIndexesSet.add(mixinIndex);
} else {
imon.exitWrite();
}
}
Iterator iterator = indexes.values().iterator();
while (iterator.hasNext()) {
Index index = (Index) iterator.next();
if (saveIndex) {
saveIndexesSet.add(index);
} else {
index.monitor.exitWrite();
}
}
if (saveIndex) {
if (monitor != null) {
}
for (Iterator ind = saveIndexesSet.iterator(); ind.hasNext();) {
Index index = (Index) ind.next();
if (monitor != null) {
monitor.subTask("Saving index for:"
+ index.containerPath);
}
try {
index.save();
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
} finally {
index.monitor.exitWrite();
}
}
}
if (monitor != null) {
monitor.done();
}
}
return null;
}
| public IStatus[] buildModelElements(IScriptProject project, List elements,
final IProgressMonitor monitor, boolean saveIndex) {
if (elements.size() == 0) {
return null;
}
IndexManager manager = ModelManager.getModelManager().getIndexManager();
final int elementsSize = elements.size();
IDLTKLanguageToolkit toolkit = null;
IMixinParser parser = null;
try {
toolkit = DLTKLanguageManager.getLanguageToolkit(project);
if (toolkit != null) {
parser = MixinManager.getMixinParser(toolkit.getNatureId());
}
} catch (CoreException e1) {
if (DLTKCore.DEBUG) {
e1.printStackTrace();
}
}
if (parser == null || toolkit == null) {
return null;
}
Map indexes = new HashMap();
// Map imons = new HashMap();
Index mixinIndex = null;
ReadWriteMonitor imon = null;
try {
// waitUntilIndexReady(toolkit);
IPath fullPath = project.getProject().getFullPath();
mixinIndex = manager.getSpecialIndex("mixin", /* project.getProject() */
fullPath.toString(), fullPath.toOSString());
imon = mixinIndex.monitor;
imon.enterWrite();
String name = "Building runtime model for "
+ project.getElementName();
if (monitor != null) {
monitor.beginTask(name, elementsSize);
}
int fileIndex = 0;
for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
ISourceModule element = (ISourceModule) iterator.next();
Index currentIndex = mixinIndex;
if (monitor != null) {
if (monitor.isCanceled()) {
return null;
}
}
String taskTitle = "Building runtime model for "
+ project.getElementName() + " ("
+ (elements.size() - fileIndex) + "):"
+ element.getElementName();
++fileIndex;
if (monitor != null) {
monitor.subTask(taskTitle);
}
// monitor.beginTask(taskTitle, 1);
IProjectFragment projectFragment = (IProjectFragment) element
.getAncestor(IModelElement.PROJECT_FRAGMENT);
IPath containerPath = project.getPath();
if (projectFragment instanceof ExternalProjectFragment
|| projectFragment instanceof BuiltinProjectFragment) {
IPath path = projectFragment.getPath();
if (indexes.containsKey(path)) {
currentIndex = (Index) indexes.get(path);
containerPath = path;
} else {
Index index = manager.getSpecialIndex("mixin", path
.toString(), path.toOSString());
if (index != null) {
currentIndex = index;
if (!indexes.values().contains(index)) {
index.monitor.enterWrite();
indexes.put(path, index);
}
containerPath = path;
}
}
}
char[] source = element.getSourceAsCharArray();
SearchParticipant participant = SearchEngine
.getDefaultSearchParticipant();
DLTKSearchDocument document;
document = new DLTKSearchDocument(element.getPath()
.toOSString(), containerPath, source, participant,
element instanceof ExternalSourceModule);
// System.out.println("mixin indexing:" + document.getPath());
((InternalSearchDocument) document).toolkit = toolkit;
String containerRelativePath = null;
if (element instanceof ExternalSourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(containerPath.segmentCount())
.setDevice(null).toString());
} else if (element instanceof SourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(1).toOSString());
} else if (element instanceof BuiltinSourceModule) {
containerRelativePath = document.getPath();
// (element.getPath()
// .removeFirstSegments().toOSString());
}
((InternalSearchDocument) document)
.setContainerRelativePath(containerRelativePath);
currentIndex.remove(containerRelativePath);
((InternalSearchDocument) document).setIndex(currentIndex);
new MixinIndexer(document, element, currentIndex)
.indexDocument();
if (monitor != null) {
monitor.worked(1);
}
}
} catch (CoreException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
} finally {
final Set saveIndexesSet = new HashSet();
if (mixinIndex != null) {
if (saveIndex) {
saveIndexesSet.add(mixinIndex);
} else {
imon.exitWrite();
}
}
Iterator iterator = indexes.values().iterator();
while (iterator.hasNext()) {
Index index = (Index) iterator.next();
if (saveIndex) {
saveIndexesSet.add(index);
} else {
index.monitor.exitWrite();
}
}
if (saveIndex) {
for (Iterator ind = saveIndexesSet.iterator(); ind.hasNext();) {
Index index = (Index) ind.next();
if (monitor != null) {
String containerPath = index.containerPath;
if (containerPath.startsWith("#special#")) {
containerPath = containerPath.substring(
containerPath.lastIndexOf("#"),
containerPath.length());
}
monitor.subTask("Saving index for:" + containerPath);
}
try {
index.save();
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
} finally {
index.monitor.exitWrite();
}
}
}
if (monitor != null) {
monitor.done();
}
}
return null;
}
|
diff --git a/src/ussr/physics/jme/JMEFactoryHelper.java b/src/ussr/physics/jme/JMEFactoryHelper.java
index 83545005..96000e5d 100644
--- a/src/ussr/physics/jme/JMEFactoryHelper.java
+++ b/src/ussr/physics/jme/JMEFactoryHelper.java
@@ -1,61 +1,62 @@
package ussr.physics.jme;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import ussr.model.Module;
import ussr.physics.ModuleFactory;
import ussr.physics.PhysicsLogger;
import ussr.robotbuildingblocks.GeometryDescription;
import ussr.robotbuildingblocks.Robot;
import com.jmex.physics.DynamicPhysicsNode;
/**
* Helper class for JMESimulation, responsible for creating modules in the simulation
* using the module factories.
*
* @author Modular Robots @ MMMI
*/
public class JMEFactoryHelper {
private JMESimulation simulation;
private Map<String,ModuleFactory> factories;
public JMEFactoryHelper(JMESimulation simulation, ModuleFactory[] factories_list) {
this.simulation = simulation;
factories = new HashMap<String,ModuleFactory>();
for(int i=0; i<factories_list.length; i++) {
factories.put(factories_list[i].getModulePrefix(),factories_list[i]);
factories_list[i].setSimulation(simulation);
}
}
public void createModule(int module_id, final Module module, Robot robot, String module_name) {
- if(robot.getDescription()==null) throw new Error("Internal error: robot description is null, robot type "+robot);
+ if(robot==null) throw new Error("Robot specification object is null");
+ if(robot.getDescription()==null) throw new Error("Robot description object is null, robot type "+robot);
String module_type = robot.getDescription().getType();
ModuleFactory factory = null;
// Find a matching factory
for(String prefix: factories.keySet())
if(module_type.startsWith(prefix)) {
factory = factories.get(prefix);
factory.createModule(module_id, module, robot, module_name);
return;
}
// Fallback: create generic module geometry based on description
if(robot.getDescription().getModuleGeometry().size()==1) {
PhysicsLogger.log("Warning: creating default robot for module type "+module_type);
// Create central module node
DynamicPhysicsNode moduleNode = simulation.getPhysicsSpace().createDynamicNode();
int j=0;
for(GeometryDescription geometry: robot.getDescription().getModuleGeometry()) {
JMEModuleComponent physicsModule = new JMEModuleComponent(simulation,robot,geometry,"module#"+Integer.toString(module_id)+"."+(j++),module,moduleNode);
module.addComponent(physicsModule);
simulation.getModuleComponents().add(physicsModule);
}
} else {
throw new RuntimeException("Module type can not be constructed");
}
}
}
| true | true | public void createModule(int module_id, final Module module, Robot robot, String module_name) {
if(robot.getDescription()==null) throw new Error("Internal error: robot description is null, robot type "+robot);
String module_type = robot.getDescription().getType();
ModuleFactory factory = null;
// Find a matching factory
for(String prefix: factories.keySet())
if(module_type.startsWith(prefix)) {
factory = factories.get(prefix);
factory.createModule(module_id, module, robot, module_name);
return;
}
// Fallback: create generic module geometry based on description
if(robot.getDescription().getModuleGeometry().size()==1) {
PhysicsLogger.log("Warning: creating default robot for module type "+module_type);
// Create central module node
DynamicPhysicsNode moduleNode = simulation.getPhysicsSpace().createDynamicNode();
int j=0;
for(GeometryDescription geometry: robot.getDescription().getModuleGeometry()) {
JMEModuleComponent physicsModule = new JMEModuleComponent(simulation,robot,geometry,"module#"+Integer.toString(module_id)+"."+(j++),module,moduleNode);
module.addComponent(physicsModule);
simulation.getModuleComponents().add(physicsModule);
}
} else {
throw new RuntimeException("Module type can not be constructed");
}
}
| public void createModule(int module_id, final Module module, Robot robot, String module_name) {
if(robot==null) throw new Error("Robot specification object is null");
if(robot.getDescription()==null) throw new Error("Robot description object is null, robot type "+robot);
String module_type = robot.getDescription().getType();
ModuleFactory factory = null;
// Find a matching factory
for(String prefix: factories.keySet())
if(module_type.startsWith(prefix)) {
factory = factories.get(prefix);
factory.createModule(module_id, module, robot, module_name);
return;
}
// Fallback: create generic module geometry based on description
if(robot.getDescription().getModuleGeometry().size()==1) {
PhysicsLogger.log("Warning: creating default robot for module type "+module_type);
// Create central module node
DynamicPhysicsNode moduleNode = simulation.getPhysicsSpace().createDynamicNode();
int j=0;
for(GeometryDescription geometry: robot.getDescription().getModuleGeometry()) {
JMEModuleComponent physicsModule = new JMEModuleComponent(simulation,robot,geometry,"module#"+Integer.toString(module_id)+"."+(j++),module,moduleNode);
module.addComponent(physicsModule);
simulation.getModuleComponents().add(physicsModule);
}
} else {
throw new RuntimeException("Module type can not be constructed");
}
}
|
diff --git a/src/demo/org/jdesktop/swingx/painter/AlphaPainterDemo.java b/src/demo/org/jdesktop/swingx/painter/AlphaPainterDemo.java
index b9b8f3b8..f0c72a7b 100644
--- a/src/demo/org/jdesktop/swingx/painter/AlphaPainterDemo.java
+++ b/src/demo/org/jdesktop/swingx/painter/AlphaPainterDemo.java
@@ -1,50 +1,51 @@
/*
* $Id$
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx.painter;
import org.jdesktop.swingx.JXPanel;
import javax.swing.*;
import java.awt.*;
/**
* Demo of the AlphaPainter.
*/
public class AlphaPainterDemo {
private AlphaPainterDemo() {}
public static void main(String ... args) {
JXPanel panel = new JXPanel();
AlphaPainter alpha = new AlphaPainter();
alpha.setAlpha(1f);
alpha.setPainters(new PinstripePainter(new Color(255,255,255,125),45,20,20));
panel.setBackgroundPainter(new CompoundPainter(
new MattePainter(Color.RED),
alpha
));
JFrame frame = new JFrame();
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setSize(200,200);
frame.setVisible(true);
}
}
| true | true | public static void main(String ... args) {
JXPanel panel = new JXPanel();
AlphaPainter alpha = new AlphaPainter();
alpha.setAlpha(1f);
alpha.setPainters(new PinstripePainter(new Color(255,255,255,125),45,20,20));
panel.setBackgroundPainter(new CompoundPainter(
new MattePainter(Color.RED),
alpha
));
JFrame frame = new JFrame();
frame.add(panel);
frame.pack();
frame.setSize(200,200);
frame.setVisible(true);
}
| public static void main(String ... args) {
JXPanel panel = new JXPanel();
AlphaPainter alpha = new AlphaPainter();
alpha.setAlpha(1f);
alpha.setPainters(new PinstripePainter(new Color(255,255,255,125),45,20,20));
panel.setBackgroundPainter(new CompoundPainter(
new MattePainter(Color.RED),
alpha
));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setSize(200,200);
frame.setVisible(true);
}
|
diff --git a/apps/animaldb/org/molgenis/animaldb/plugins/breeding/ManageLines.java b/apps/animaldb/org/molgenis/animaldb/plugins/breeding/ManageLines.java
index 32b2b949a..76efb1594 100644
--- a/apps/animaldb/org/molgenis/animaldb/plugins/breeding/ManageLines.java
+++ b/apps/animaldb/org/molgenis/animaldb/plugins/breeding/ManageLines.java
@@ -1,312 +1,314 @@
/* Date: April 28, 2011
* Template: PluginScreenJavaTemplateGen.java.ftl
* generator: org.molgenis.generators.ui.PluginScreenJavaTemplateGen 3.3.3
*
* THIS FILE IS A TEMPLATE. PLEASE EDIT :-)
*/
package org.molgenis.animaldb.plugins.breeding;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.molgenis.animaldb.commonservice.CommonService;
import org.molgenis.framework.db.Database;
import org.molgenis.framework.db.DatabaseException;
import org.molgenis.framework.db.Query;
import org.molgenis.framework.db.QueryRule;
import org.molgenis.framework.db.QueryRule.Operator;
import org.molgenis.framework.ui.PluginModel;
import org.molgenis.framework.ui.ScreenController;
import org.molgenis.framework.ui.ScreenMessage;
import org.molgenis.pheno.ObservationTarget;
import org.molgenis.pheno.ObservedValue;
import org.molgenis.util.Entity;
import org.molgenis.util.Tuple;
public class ManageLines extends PluginModel<Entity>
{
private static final long serialVersionUID = 3355794876439855835L;
private CommonService cs = CommonService.getInstance();
private String lineName;
private String fullName;
private String sourceName;
private String speciesName;
private String remarks;
private int lineId = -1;
private List<ObservationTarget> sourceList;
private List<ObservationTarget> lineList;
private List<ObservationTarget> speciesList;
public ManageLines(String name, ScreenController<?> parent)
{
super(name, parent);
}
public String getCustomHtmlHeaders() {
return "<script type=\"text/javascript\" src=\"res/jquery-plugins/datatables/js/jquery.dataTables.js\"></script>\n" +
"<script src=\"res/scripts/custom/addingajax.js\" language=\"javascript\"></script>\n" +
"<script src=\"res/jquery-plugins/ctnotify/lib/jquery.ctNotify.js\" language=\"javascript\"></script>\n" +
"<link rel=\"stylesheet\" style=\"text/css\" href=\"res/jquery-plugins/datatables/css/demo_table_jui.css\">\n" +
"<link rel=\"stylesheet\" style=\"text/css\" href=\"res/jquery-plugins/ctnotify/lib/jquery.ctNotify.css\">" +
"<link rel=\"stylesheet\" style=\"text/css\" href=\"res/jquery-plugins/ctnotify/lib/jquery.ctNotify.rounded.css\">" +
"<link rel=\"stylesheet\" style=\"text/css\" href=\"res/jquery-plugins/ctnotify/lib/jquery.ctNotify.roundedBr.css\">" +
"<link rel=\"stylesheet\" style=\"text/css\" href=\"res/css/animaldb.css\">";
}
@Override
public String getViewName()
{
return "org_molgenis_animaldb_plugins_breeding_ManageLines";
}
@Override
public String getViewTemplate()
{
return "org/molgenis/animaldb/plugins/breeding/ManageLines.ftl";
}
public String getFullName(String lineName) {
String fullName;
try {
fullName = cs.getMostRecentValueAsString(lineName, "LineFullName");
} catch (Exception e) {
fullName = "Error when retrieving full name";
}
return fullName;
}
public String getSourceName(String lineName) {
String sourceName;
try {
sourceName = cs.getMostRecentValueAsXrefName(lineName, "Source");
} catch (Exception e) {
sourceName = "Error when retrieving source";
}
return sourceName;
}
public String getSpeciesName(String lineName) {
String speciesName;
try {
speciesName = cs.getMostRecentValueAsXrefName(lineName, "Species");
} catch (Exception e) {
speciesName = "Error when retrieving species";
}
return speciesName;
}
public String getRemarksString(String lineName) throws DatabaseException {
//List<String> remarksList = cs.getRemarks(lineId);
String returnString = "";
// for (String remark : remarksList) {
// returnString += (remark + "<br>");
// }
// if (returnString.length() > 0) {
// returnString = returnString.substring(0, returnString.length() - 4);
// }
try {
returnString = cs.getMostRecentValueAsString(lineName, "Remark");
} catch (Exception e) {
returnString = "Error when retrieving remarks";
}
return returnString;
}
@Override
public void handleRequest(Database db, Tuple request)
{
cs.setDatabase(db);
try {
String action = request.getString("__action");
if (action.equals("Edit")) {
lineId = request.getInt("id");
lineName = this.getLine(lineId);
fullName = this.getFullName(lineName);
speciesName = this.getSpeciesName(lineName);
sourceName = this.getSourceName(lineName);
remarks = this.getRemarksString(lineName);
}
if (action.equals("Delete")) {
lineId = request.getInt("id");
List<ObservedValue> valList = db.query(ObservedValue.class).eq(ObservedValue.TARGET, lineId).
or().eq(ObservedValue.RELATION, lineId).find();
db.remove(valList);
ObservationTarget line = cs.getObservationTargetById(lineId);
db.remove(line);
this.setSuccess("Line successfully removed");
+ // Reset so form is empty again
+ lineId = -1;
}
if (action.equals("addLine")) {
Date now = new Date();
lineName = request.getString("lineName");
String invName = cs.getOwnUserInvestigationName(this.getLogin().getUserName());
String message = "";
// Make or get group
if (lineId == -1) {
lineId = cs.makePanel(invName, lineName, this.getLogin().getUserName());
message = "Line successfully added";
} else {
ObservationTarget line = cs.getObservationTargetById(lineId);
line.setName(lineName); // maybe user has changed name
db.update(line);
message = "Line successfully updated";
}
// Mark group as Line using a special event
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetTypeOfGroup", "TypeOfGroup", lineName, "Line", null));
// Set full name
if (request.getString("fullname") != null) {
fullName = request.getString("fullname");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetLineFullName", "LineFullName", lineName, fullName, null));
}
// Set species
speciesName = request.getString("species");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetSpecies", "Species", lineName, null, speciesName));
// Set source
sourceName = request.getString("source");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetSource", "Source", lineName, null, sourceName));
// Set remark
if (request.getString("remarks") != null) {
remarks = request.getString("remarks");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetRemark", "Remark", lineName, remarks, null));
}
this.setSuccess(message);
// Reset everything so form is empty again
lineId = -1;
lineName = null;
fullName = null;
speciesName = null;
sourceName = null;
remarks = null;
}
} catch (Exception e) {
this.getMessages().clear();
if (e.getMessage() != null) {
this.getMessages().add(new ScreenMessage(e.getMessage(), false));
}
e.printStackTrace();
}
}
private String getLine(int lineId) throws DatabaseException, ParseException {
return cs.getObservationTargetLabel(lineId);
}
@Override
public void reload(Database db)
{
cs.setDatabase(db);
cs.makeObservationTargetNameMap(this.getLogin().getUserName(), false);
try {
List<String> investigationNames = cs.getAllUserInvestigationNames(this.getLogin().getUserName());
// Populate source list
// All source types pertaining to "Eigen fok binnen uw organisatorische werkeenheid"
sourceList = new ArrayList<ObservationTarget>();
List<ObservationTarget> tmpSourceList = cs.getAllMarkedPanels("Source", investigationNames);
for (ObservationTarget tmpSource : tmpSourceList) {
int featid = cs.getMeasurementId("SourceType");
Query<ObservedValue> sourceTypeQuery = db.query(ObservedValue.class);
sourceTypeQuery.addRules(new QueryRule(ObservedValue.TARGET, Operator.EQUALS, tmpSource.getId()));
sourceTypeQuery.addRules(new QueryRule(ObservedValue.FEATURE, Operator.EQUALS, featid));
List<ObservedValue> sourceTypeValueList = sourceTypeQuery.find();
if (sourceTypeValueList.size() > 0)
{
String sourcetype = sourceTypeValueList.get(0).getValue();
if (sourcetype.equals("Eigen fok binnen uw organisatorische werkeenheid")) {
sourceList.add(tmpSource);
}
}
}
// Populate species list
speciesList = cs.getAllMarkedPanels("Species", investigationNames);
// Populate existing lines list
lineList = cs.getAllMarkedPanels("Line", investigationNames);
} catch (Exception e) {
this.getMessages().clear();
String message = "Something went wrong while loading lists";
if (e.getMessage() != null) {
message += (": " + e.getMessage());
}
this.getMessages().add(new ScreenMessage(message, false));
e.printStackTrace();
}
}
public void setLineName(String lineName) {
this.lineName = lineName;
}
public String getLineName() {
return lineName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getSource() {
if (sourceName == null) {
return "";
}
return sourceName;
}
public String getSpecies() {
if (speciesName == null) {
return "";
}
return speciesName;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public void setSourceList(List<ObservationTarget> sourceList) {
this.sourceList = sourceList;
}
public List<ObservationTarget> getSourceList() {
return sourceList;
}
public void setSpeciesList(List<ObservationTarget> speciesList) {
this.speciesList = speciesList;
}
public List<ObservationTarget> getSpeciesList() {
return speciesList;
}
public List<ObservationTarget> getLineList() {
return lineList;
}
public void setLineList(List<ObservationTarget> lineList) {
this.lineList = lineList;
}
}
| true | true | public void handleRequest(Database db, Tuple request)
{
cs.setDatabase(db);
try {
String action = request.getString("__action");
if (action.equals("Edit")) {
lineId = request.getInt("id");
lineName = this.getLine(lineId);
fullName = this.getFullName(lineName);
speciesName = this.getSpeciesName(lineName);
sourceName = this.getSourceName(lineName);
remarks = this.getRemarksString(lineName);
}
if (action.equals("Delete")) {
lineId = request.getInt("id");
List<ObservedValue> valList = db.query(ObservedValue.class).eq(ObservedValue.TARGET, lineId).
or().eq(ObservedValue.RELATION, lineId).find();
db.remove(valList);
ObservationTarget line = cs.getObservationTargetById(lineId);
db.remove(line);
this.setSuccess("Line successfully removed");
}
if (action.equals("addLine")) {
Date now = new Date();
lineName = request.getString("lineName");
String invName = cs.getOwnUserInvestigationName(this.getLogin().getUserName());
String message = "";
// Make or get group
if (lineId == -1) {
lineId = cs.makePanel(invName, lineName, this.getLogin().getUserName());
message = "Line successfully added";
} else {
ObservationTarget line = cs.getObservationTargetById(lineId);
line.setName(lineName); // maybe user has changed name
db.update(line);
message = "Line successfully updated";
}
// Mark group as Line using a special event
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetTypeOfGroup", "TypeOfGroup", lineName, "Line", null));
// Set full name
if (request.getString("fullname") != null) {
fullName = request.getString("fullname");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetLineFullName", "LineFullName", lineName, fullName, null));
}
// Set species
speciesName = request.getString("species");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetSpecies", "Species", lineName, null, speciesName));
// Set source
sourceName = request.getString("source");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetSource", "Source", lineName, null, sourceName));
// Set remark
if (request.getString("remarks") != null) {
remarks = request.getString("remarks");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetRemark", "Remark", lineName, remarks, null));
}
this.setSuccess(message);
// Reset everything so form is empty again
lineId = -1;
lineName = null;
fullName = null;
speciesName = null;
sourceName = null;
remarks = null;
}
} catch (Exception e) {
this.getMessages().clear();
if (e.getMessage() != null) {
this.getMessages().add(new ScreenMessage(e.getMessage(), false));
}
e.printStackTrace();
}
}
| public void handleRequest(Database db, Tuple request)
{
cs.setDatabase(db);
try {
String action = request.getString("__action");
if (action.equals("Edit")) {
lineId = request.getInt("id");
lineName = this.getLine(lineId);
fullName = this.getFullName(lineName);
speciesName = this.getSpeciesName(lineName);
sourceName = this.getSourceName(lineName);
remarks = this.getRemarksString(lineName);
}
if (action.equals("Delete")) {
lineId = request.getInt("id");
List<ObservedValue> valList = db.query(ObservedValue.class).eq(ObservedValue.TARGET, lineId).
or().eq(ObservedValue.RELATION, lineId).find();
db.remove(valList);
ObservationTarget line = cs.getObservationTargetById(lineId);
db.remove(line);
this.setSuccess("Line successfully removed");
// Reset so form is empty again
lineId = -1;
}
if (action.equals("addLine")) {
Date now = new Date();
lineName = request.getString("lineName");
String invName = cs.getOwnUserInvestigationName(this.getLogin().getUserName());
String message = "";
// Make or get group
if (lineId == -1) {
lineId = cs.makePanel(invName, lineName, this.getLogin().getUserName());
message = "Line successfully added";
} else {
ObservationTarget line = cs.getObservationTargetById(lineId);
line.setName(lineName); // maybe user has changed name
db.update(line);
message = "Line successfully updated";
}
// Mark group as Line using a special event
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetTypeOfGroup", "TypeOfGroup", lineName, "Line", null));
// Set full name
if (request.getString("fullname") != null) {
fullName = request.getString("fullname");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetLineFullName", "LineFullName", lineName, fullName, null));
}
// Set species
speciesName = request.getString("species");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetSpecies", "Species", lineName, null, speciesName));
// Set source
sourceName = request.getString("source");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetSource", "Source", lineName, null, sourceName));
// Set remark
if (request.getString("remarks") != null) {
remarks = request.getString("remarks");
db.add(cs.createObservedValueWithProtocolApplication(invName, now, null,
"SetRemark", "Remark", lineName, remarks, null));
}
this.setSuccess(message);
// Reset everything so form is empty again
lineId = -1;
lineName = null;
fullName = null;
speciesName = null;
sourceName = null;
remarks = null;
}
} catch (Exception e) {
this.getMessages().clear();
if (e.getMessage() != null) {
this.getMessages().add(new ScreenMessage(e.getMessage(), false));
}
e.printStackTrace();
}
}
|
diff --git a/src/main/java/it/joshua/crobots/impl/RunnableCrobotsManager.java b/src/main/java/it/joshua/crobots/impl/RunnableCrobotsManager.java
index c073162..fe67c6d 100644
--- a/src/main/java/it/joshua/crobots/impl/RunnableCrobotsManager.java
+++ b/src/main/java/it/joshua/crobots/impl/RunnableCrobotsManager.java
@@ -1,144 +1,144 @@
package it.joshua.crobots.impl;
import it.joshua.crobots.SharedVariables;
import it.joshua.crobots.bean.GamesBean;
import it.joshua.crobots.data.TableName;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RunnableCrobotsManager implements Runnable {
private static final Logger logger = Logger.getLogger(RunnableCrobotsManager.class.getName());
private TableName tableName;
private static SQLManager mySQLManager;
private static SharedVariables sharedVariables = SharedVariables.getInstance();
public RunnableCrobotsManager(TableName tableName) {
super();
this.tableName = tableName;
sharedVariables.setRunnable(true);
}
@Override
public void run() {
long startTime = System.currentTimeMillis();
long elapsed = 0;
boolean isCompleted = false;
int idles = 0;
int calls = 0;
int updates = 0;
List<GamesBean> i;
logger.info("Starting thread");
try {
if (sharedVariables.isLocalDb() && sharedVariables.getLocalDriver().contains("Oracle")) {
mySQLManager = SQLManagerOracle.getInstance(tableName);
} else {
mySQLManager = SQLManager.getInstance(tableName);
}
SQLManager.initialize();
GamesBean bean;
if (sharedVariables.isTimeLimit()) {
elapsed = System.currentTimeMillis();
if (((elapsed - sharedVariables.getGlobalStartTime()) / 60000) >= sharedVariables.getTimeLimitMinutes()) {
logger.warning("Time limit " + sharedVariables.getTimeLimitMinutes() + " minute(s) reached. Stopping application.");
sharedVariables.setRunnable(false);
isCompleted = true;
}
}
while (sharedVariables.isRunnable()) {
if (sharedVariables.isKill() && sharedVariables.getKillfile().exists()) {
logger.warning("Kill reached! " + sharedVariables.getKillFile() + " found!");
sharedVariables.setRunnable(false);
isCompleted = true;
}
- if (!isCompleted && sharedVariables.getBufferSize() <= sharedVariables.getBufferMinSize()) {
+ if (!isCompleted && sharedVariables.getBufferSize() < sharedVariables.getBufferSize()) {
i = mySQLManager.getGames();
if (i != null && i.size() > 0) {
logger.fine("Append " + i.size() + " match(es) to buffer...");
sharedVariables.addAllToGames(i);
} else {
isCompleted = true;
}
}
logger.fine("isGameBufferEmpty " + sharedVariables.isGameBufferEmpty() + " size " + sharedVariables.getGamesSize());
logger.fine("isInputBufferEmpty " + sharedVariables.isInputBufferEmpty() + " size " + sharedVariables.getBufferSize());
if (!sharedVariables.isGameBufferEmpty()) {
boolean ok = mySQLManager.initializeUpdates();
if (ok) {
calls++;
while (!sharedVariables.isGameBufferEmpty()) {
bean = sharedVariables.getAndRemoveBean();
if ("update".equals(bean.getAction()) && tableName.equals(bean.getTableName())) {
if (!mySQLManager.updateResults(bean)) {
logger.severe("Can't update results of " + bean.toString());
logger.warning("Retry " + tableName + " id=" + bean.getId());
sharedVariables.addToGames(bean);
} else {
updates++;
}
} else if ("recovery".equals(bean.getAction()) && tableName.equals(bean.getTableName())) {
logger.warning("Recovery " + bean.toString());
mySQLManager.recoveryTable(bean);
}
}
} else {
logger.severe("Can't initialize stored");
}
mySQLManager.releaseUpdates();
} else if (isCompleted && sharedVariables.isInputBufferEmpty()) {
sharedVariables.setRunnable(false);
logger.info("Everything is done here...");
} else if (sharedVariables.isRunnable()
&& ((!isCompleted && (sharedVariables.getBufferSize() >= sharedVariables.getBufferMinSize()))
|| (isCompleted && !sharedVariables.isInputBufferEmpty()))) {
logger.fine("Im going to sleep for " + sharedVariables.getSleepInterval(tableName) + " ms...");
try {
Thread.sleep(sharedVariables.getSleepInterval(tableName));
} catch (InterruptedException ie) {
}
idles++;
}
if (sharedVariables.isTimeLimit()) {
elapsed = System.currentTimeMillis();
if (((elapsed - sharedVariables.getGlobalStartTime()) / 60000) >= sharedVariables.getTimeLimitMinutes()) {
logger.warning("Time limit " + sharedVariables.getTimeLimitMinutes() + " minute(s) reached. Stopping application.");
sharedVariables.setRunnable(false);
isCompleted = true;
}
}
}
long endTime = System.currentTimeMillis();
float seconds = (endTime - startTime) / 1000F;
if (calls > 0 && seconds > 0) {
logger.info("Calls : "
+ calls
+ "; Updates : "
+ updates
+ " in "
+ Float.toString(seconds)
+ " seconds. Rate : "
+ Float.toString(updates / calls)
+ " update/call; "
+ Float.toString(updates / seconds)
+ " update/s. Idles : "
+ idles);
}
logger.info("Shutdown thread");
} catch (Exception exception) {
logger.log(Level.SEVERE, "RunnableCrobotsManager {0}", exception);
} finally {
SQLManager.closeAll();
}
}
}
| true | true | public void run() {
long startTime = System.currentTimeMillis();
long elapsed = 0;
boolean isCompleted = false;
int idles = 0;
int calls = 0;
int updates = 0;
List<GamesBean> i;
logger.info("Starting thread");
try {
if (sharedVariables.isLocalDb() && sharedVariables.getLocalDriver().contains("Oracle")) {
mySQLManager = SQLManagerOracle.getInstance(tableName);
} else {
mySQLManager = SQLManager.getInstance(tableName);
}
SQLManager.initialize();
GamesBean bean;
if (sharedVariables.isTimeLimit()) {
elapsed = System.currentTimeMillis();
if (((elapsed - sharedVariables.getGlobalStartTime()) / 60000) >= sharedVariables.getTimeLimitMinutes()) {
logger.warning("Time limit " + sharedVariables.getTimeLimitMinutes() + " minute(s) reached. Stopping application.");
sharedVariables.setRunnable(false);
isCompleted = true;
}
}
while (sharedVariables.isRunnable()) {
if (sharedVariables.isKill() && sharedVariables.getKillfile().exists()) {
logger.warning("Kill reached! " + sharedVariables.getKillFile() + " found!");
sharedVariables.setRunnable(false);
isCompleted = true;
}
if (!isCompleted && sharedVariables.getBufferSize() <= sharedVariables.getBufferMinSize()) {
i = mySQLManager.getGames();
if (i != null && i.size() > 0) {
logger.fine("Append " + i.size() + " match(es) to buffer...");
sharedVariables.addAllToGames(i);
} else {
isCompleted = true;
}
}
logger.fine("isGameBufferEmpty " + sharedVariables.isGameBufferEmpty() + " size " + sharedVariables.getGamesSize());
logger.fine("isInputBufferEmpty " + sharedVariables.isInputBufferEmpty() + " size " + sharedVariables.getBufferSize());
if (!sharedVariables.isGameBufferEmpty()) {
boolean ok = mySQLManager.initializeUpdates();
if (ok) {
calls++;
while (!sharedVariables.isGameBufferEmpty()) {
bean = sharedVariables.getAndRemoveBean();
if ("update".equals(bean.getAction()) && tableName.equals(bean.getTableName())) {
if (!mySQLManager.updateResults(bean)) {
logger.severe("Can't update results of " + bean.toString());
logger.warning("Retry " + tableName + " id=" + bean.getId());
sharedVariables.addToGames(bean);
} else {
updates++;
}
} else if ("recovery".equals(bean.getAction()) && tableName.equals(bean.getTableName())) {
logger.warning("Recovery " + bean.toString());
mySQLManager.recoveryTable(bean);
}
}
} else {
logger.severe("Can't initialize stored");
}
mySQLManager.releaseUpdates();
} else if (isCompleted && sharedVariables.isInputBufferEmpty()) {
sharedVariables.setRunnable(false);
logger.info("Everything is done here...");
} else if (sharedVariables.isRunnable()
&& ((!isCompleted && (sharedVariables.getBufferSize() >= sharedVariables.getBufferMinSize()))
|| (isCompleted && !sharedVariables.isInputBufferEmpty()))) {
logger.fine("Im going to sleep for " + sharedVariables.getSleepInterval(tableName) + " ms...");
try {
Thread.sleep(sharedVariables.getSleepInterval(tableName));
} catch (InterruptedException ie) {
}
idles++;
}
if (sharedVariables.isTimeLimit()) {
elapsed = System.currentTimeMillis();
if (((elapsed - sharedVariables.getGlobalStartTime()) / 60000) >= sharedVariables.getTimeLimitMinutes()) {
logger.warning("Time limit " + sharedVariables.getTimeLimitMinutes() + " minute(s) reached. Stopping application.");
sharedVariables.setRunnable(false);
isCompleted = true;
}
}
}
long endTime = System.currentTimeMillis();
float seconds = (endTime - startTime) / 1000F;
if (calls > 0 && seconds > 0) {
logger.info("Calls : "
+ calls
+ "; Updates : "
+ updates
+ " in "
+ Float.toString(seconds)
+ " seconds. Rate : "
+ Float.toString(updates / calls)
+ " update/call; "
+ Float.toString(updates / seconds)
+ " update/s. Idles : "
+ idles);
}
logger.info("Shutdown thread");
} catch (Exception exception) {
logger.log(Level.SEVERE, "RunnableCrobotsManager {0}", exception);
} finally {
SQLManager.closeAll();
}
}
| public void run() {
long startTime = System.currentTimeMillis();
long elapsed = 0;
boolean isCompleted = false;
int idles = 0;
int calls = 0;
int updates = 0;
List<GamesBean> i;
logger.info("Starting thread");
try {
if (sharedVariables.isLocalDb() && sharedVariables.getLocalDriver().contains("Oracle")) {
mySQLManager = SQLManagerOracle.getInstance(tableName);
} else {
mySQLManager = SQLManager.getInstance(tableName);
}
SQLManager.initialize();
GamesBean bean;
if (sharedVariables.isTimeLimit()) {
elapsed = System.currentTimeMillis();
if (((elapsed - sharedVariables.getGlobalStartTime()) / 60000) >= sharedVariables.getTimeLimitMinutes()) {
logger.warning("Time limit " + sharedVariables.getTimeLimitMinutes() + " minute(s) reached. Stopping application.");
sharedVariables.setRunnable(false);
isCompleted = true;
}
}
while (sharedVariables.isRunnable()) {
if (sharedVariables.isKill() && sharedVariables.getKillfile().exists()) {
logger.warning("Kill reached! " + sharedVariables.getKillFile() + " found!");
sharedVariables.setRunnable(false);
isCompleted = true;
}
if (!isCompleted && sharedVariables.getBufferSize() < sharedVariables.getBufferSize()) {
i = mySQLManager.getGames();
if (i != null && i.size() > 0) {
logger.fine("Append " + i.size() + " match(es) to buffer...");
sharedVariables.addAllToGames(i);
} else {
isCompleted = true;
}
}
logger.fine("isGameBufferEmpty " + sharedVariables.isGameBufferEmpty() + " size " + sharedVariables.getGamesSize());
logger.fine("isInputBufferEmpty " + sharedVariables.isInputBufferEmpty() + " size " + sharedVariables.getBufferSize());
if (!sharedVariables.isGameBufferEmpty()) {
boolean ok = mySQLManager.initializeUpdates();
if (ok) {
calls++;
while (!sharedVariables.isGameBufferEmpty()) {
bean = sharedVariables.getAndRemoveBean();
if ("update".equals(bean.getAction()) && tableName.equals(bean.getTableName())) {
if (!mySQLManager.updateResults(bean)) {
logger.severe("Can't update results of " + bean.toString());
logger.warning("Retry " + tableName + " id=" + bean.getId());
sharedVariables.addToGames(bean);
} else {
updates++;
}
} else if ("recovery".equals(bean.getAction()) && tableName.equals(bean.getTableName())) {
logger.warning("Recovery " + bean.toString());
mySQLManager.recoveryTable(bean);
}
}
} else {
logger.severe("Can't initialize stored");
}
mySQLManager.releaseUpdates();
} else if (isCompleted && sharedVariables.isInputBufferEmpty()) {
sharedVariables.setRunnable(false);
logger.info("Everything is done here...");
} else if (sharedVariables.isRunnable()
&& ((!isCompleted && (sharedVariables.getBufferSize() >= sharedVariables.getBufferMinSize()))
|| (isCompleted && !sharedVariables.isInputBufferEmpty()))) {
logger.fine("Im going to sleep for " + sharedVariables.getSleepInterval(tableName) + " ms...");
try {
Thread.sleep(sharedVariables.getSleepInterval(tableName));
} catch (InterruptedException ie) {
}
idles++;
}
if (sharedVariables.isTimeLimit()) {
elapsed = System.currentTimeMillis();
if (((elapsed - sharedVariables.getGlobalStartTime()) / 60000) >= sharedVariables.getTimeLimitMinutes()) {
logger.warning("Time limit " + sharedVariables.getTimeLimitMinutes() + " minute(s) reached. Stopping application.");
sharedVariables.setRunnable(false);
isCompleted = true;
}
}
}
long endTime = System.currentTimeMillis();
float seconds = (endTime - startTime) / 1000F;
if (calls > 0 && seconds > 0) {
logger.info("Calls : "
+ calls
+ "; Updates : "
+ updates
+ " in "
+ Float.toString(seconds)
+ " seconds. Rate : "
+ Float.toString(updates / calls)
+ " update/call; "
+ Float.toString(updates / seconds)
+ " update/s. Idles : "
+ idles);
}
logger.info("Shutdown thread");
} catch (Exception exception) {
logger.log(Level.SEVERE, "RunnableCrobotsManager {0}", exception);
} finally {
SQLManager.closeAll();
}
}
|
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/PasteRegisterCommand.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/PasteRegisterCommand.java
index bacfd288..08074328 100644
--- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/PasteRegisterCommand.java
+++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/PasteRegisterCommand.java
@@ -1,35 +1,41 @@
package net.sourceforge.vrapper.vim.commands;
import net.sourceforge.vrapper.platform.TextContent;
import net.sourceforge.vrapper.utils.Position;
import net.sourceforge.vrapper.vim.EditorAdaptor;
import net.sourceforge.vrapper.vim.register.Register;
import net.sourceforge.vrapper.vim.register.RegisterManager;
public class PasteRegisterCommand extends CountIgnoringNonRepeatableCommand {
public static final PasteRegisterCommand PASTE_LAST_INSERT =
new PasteRegisterCommand(RegisterManager.REGISTER_NAME_INSERT);
private String registerName;
public PasteRegisterCommand(String registerName) {
this.registerName = registerName;
}
public void execute(EditorAdaptor editorAdaptor) throws CommandExecutionException {
Register reg = editorAdaptor.getRegisterManager().getRegister(registerName);
String text = reg.getContent().getText();
if(text.length() > 0) {
TextContent content = editorAdaptor.getModelContent();
+ //Delete Eclipse selection contents, for example when completing a function's arguments.
+ Selection currentSelection = editorAdaptor.getSelection();
+ if (currentSelection.getModelLength() > 0) {
+ content.replace(currentSelection.getStart().getModelOffset(),
+ currentSelection.getModelLength(), "");
+ }
int offset = editorAdaptor.getCursorService().getPosition().getModelOffset();
//different from PasteOperation! it does length() - 1
int position = offset + text.length();
content.replace(offset, 0, text);
Position destination = editorAdaptor.getCursorService().newPositionForModelOffset(position);
editorAdaptor.setPosition(destination, true);
}
}
}
| true | true | public void execute(EditorAdaptor editorAdaptor) throws CommandExecutionException {
Register reg = editorAdaptor.getRegisterManager().getRegister(registerName);
String text = reg.getContent().getText();
if(text.length() > 0) {
TextContent content = editorAdaptor.getModelContent();
int offset = editorAdaptor.getCursorService().getPosition().getModelOffset();
//different from PasteOperation! it does length() - 1
int position = offset + text.length();
content.replace(offset, 0, text);
Position destination = editorAdaptor.getCursorService().newPositionForModelOffset(position);
editorAdaptor.setPosition(destination, true);
}
}
| public void execute(EditorAdaptor editorAdaptor) throws CommandExecutionException {
Register reg = editorAdaptor.getRegisterManager().getRegister(registerName);
String text = reg.getContent().getText();
if(text.length() > 0) {
TextContent content = editorAdaptor.getModelContent();
//Delete Eclipse selection contents, for example when completing a function's arguments.
Selection currentSelection = editorAdaptor.getSelection();
if (currentSelection.getModelLength() > 0) {
content.replace(currentSelection.getStart().getModelOffset(),
currentSelection.getModelLength(), "");
}
int offset = editorAdaptor.getCursorService().getPosition().getModelOffset();
//different from PasteOperation! it does length() - 1
int position = offset + text.length();
content.replace(offset, 0, text);
Position destination = editorAdaptor.getCursorService().newPositionForModelOffset(position);
editorAdaptor.setPosition(destination, true);
}
}
|
diff --git a/src/com/gitblit/LuceneExecutor.java b/src/com/gitblit/LuceneExecutor.java
index f7a7390..2e09930 100644
--- a/src/com/gitblit/LuceneExecutor.java
+++ b/src/com/gitblit/LuceneExecutor.java
@@ -1,1354 +1,1355 @@
/*
* Copyright 2012 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit;
import static org.eclipse.jgit.treewalk.filter.TreeFilter.ANY_DIFF;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.DateTools.Resolution;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.eclipse.jgit.diff.DiffEntry.ChangeType;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryCache.FileKey;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.treewalk.EmptyTreeIterator;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.util.FS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gitblit.Constants.SearchObjectType;
import com.gitblit.models.IssueModel;
import com.gitblit.models.IssueModel.Attachment;
import com.gitblit.models.PathModel.PathChangeModel;
import com.gitblit.models.RefModel;
import com.gitblit.models.RepositoryModel;
import com.gitblit.models.SearchResult;
import com.gitblit.utils.ArrayUtils;
import com.gitblit.utils.IssueUtils;
import com.gitblit.utils.JGitUtils;
import com.gitblit.utils.StringUtils;
/**
* The Lucene executor handles indexing and searching repositories.
*
* @author James Moger
*
*/
public class LuceneExecutor implements Runnable {
private static final int INDEX_VERSION = 4;
private static final String FIELD_OBJECT_TYPE = "type";
private static final String FIELD_ISSUE = "issue";
private static final String FIELD_PATH = "path";
private static final String FIELD_COMMIT = "commit";
private static final String FIELD_BRANCH = "branch";
private static final String FIELD_SUMMARY = "summary";
private static final String FIELD_CONTENT = "content";
private static final String FIELD_AUTHOR = "author";
private static final String FIELD_COMMITTER = "committer";
private static final String FIELD_DATE = "date";
private static final String FIELD_TAG = "tag";
private static final String FIELD_LABEL = "label";
private static final String FIELD_ATTACHMENT = "attachment";
private static final String CONF_FILE = "lucene.conf";
private static final String LUCENE_DIR = "lucene";
private static final String CONF_INDEX = "index";
private static final String CONF_VERSION = "version";
private static final String CONF_ALIAS = "aliases";
private static final String CONF_BRANCH = "branches";
private static final Version LUCENE_VERSION = Version.LUCENE_35;
private final Logger logger = LoggerFactory.getLogger(LuceneExecutor.class);
private final IStoredSettings storedSettings;
private final File repositoriesFolder;
private final Map<String, IndexSearcher> searchers = new ConcurrentHashMap<String, IndexSearcher>();
private final Map<String, IndexWriter> writers = new ConcurrentHashMap<String, IndexWriter>();
private final String luceneIgnoreExtensions = "7z arc arj bin bmp dll doc docx exe gif gz jar jpg lib lzh odg odf odt pdf ppt png so swf xcf xls xlsx zip";
private Set<String> excludedExtensions;
public LuceneExecutor(IStoredSettings settings, File repositoriesFolder) {
this.storedSettings = settings;
this.repositoriesFolder = repositoriesFolder;
String exts = luceneIgnoreExtensions;
if (settings != null) {
exts = settings.getString(Keys.web.luceneIgnoreExtensions, exts);
}
excludedExtensions = new TreeSet<String>(StringUtils.getStringsFromValue(exts));
}
/**
* Run is executed by the Gitblit executor service. Because this is called
* by an executor service, calls will queue - i.e. there can never be
* concurrent execution of repository index updates.
*/
@Override
public void run() {
if (!storedSettings.getBoolean(Keys.web.allowLuceneIndexing, true)) {
// Lucene indexing is disabled
return;
}
// reload the excluded extensions
String exts = storedSettings.getString(Keys.web.luceneIgnoreExtensions, luceneIgnoreExtensions);
excludedExtensions = new TreeSet<String>(StringUtils.getStringsFromValue(exts));
for (String repositoryName: GitBlit.self().getRepositoryList()) {
RepositoryModel model = GitBlit.self().getRepositoryModel(repositoryName);
if (model.hasCommits && !ArrayUtils.isEmpty(model.indexedBranches)) {
Repository repository = GitBlit.self().getRepository(model.name);
index(model, repository);
repository.close();
System.gc();
}
}
}
/**
* Synchronously indexes a repository. This may build a complete index of a
* repository or it may update an existing index.
*
* @param name
* the name of the repository
* @param repository
* the repository object
*/
private void index(RepositoryModel model, Repository repository) {
try {
if (shouldReindex(repository)) {
// (re)build the entire index
IndexResult result = reindex(model, repository);
if (result.success) {
if (result.commitCount > 0) {
String msg = "Built {0} Lucene index from {1} commits and {2} files across {3} branches in {4} secs";
logger.info(MessageFormat.format(msg, model.name, result.commitCount,
result.blobCount, result.branchCount, result.duration()));
}
} else {
String msg = "Could not build {0} Lucene index!";
logger.error(MessageFormat.format(msg, model.name));
}
} else {
// update the index with latest commits
IndexResult result = updateIndex(model, repository);
if (result.success) {
if (result.commitCount > 0) {
String msg = "Updated {0} Lucene index with {1} commits and {2} files across {3} branches in {4} secs";
logger.info(MessageFormat.format(msg, model.name, result.commitCount,
result.blobCount, result.branchCount, result.duration()));
}
} else {
String msg = "Could not update {0} Lucene index!";
logger.error(MessageFormat.format(msg, model.name));
}
}
} catch (Throwable t) {
logger.error(MessageFormat.format("Lucene indexing failure for {0}", model.name), t);
}
}
/**
* Close the writer/searcher objects for a repository.
*
* @param repositoryName
*/
public synchronized void close(String repositoryName) {
try {
IndexSearcher searcher = searchers.remove(repositoryName);
if (searcher != null) {
searcher.getIndexReader().close();
}
} catch (Exception e) {
logger.error("Failed to close index searcher for " + repositoryName, e);
}
try {
IndexWriter writer = writers.remove(repositoryName);
if (writer != null) {
writer.close();
}
} catch (Exception e) {
logger.error("Failed to close index writer for " + repositoryName, e);
}
}
/**
* Close all Lucene indexers.
*
*/
public synchronized void close() {
// close all writers
for (String writer : writers.keySet()) {
try {
writers.get(writer).close(true);
} catch (Throwable t) {
logger.error("Failed to close Lucene writer for " + writer, t);
}
}
writers.clear();
// close all searchers
for (String searcher : searchers.keySet()) {
try {
searchers.get(searcher).getIndexReader().close();
} catch (Throwable t) {
logger.error("Failed to close Lucene searcher for " + searcher, t);
}
}
searchers.clear();
}
/**
* Deletes the Lucene index for the specified repository.
*
* @param repositoryName
* @return true, if successful
*/
public boolean deleteIndex(String repositoryName) {
try {
// close any open writer/searcher
close(repositoryName);
// delete the index folder
File repositoryFolder = new File(repositoriesFolder, repositoryName);
File luceneIndex = new File(repositoryFolder, LUCENE_DIR);
if (luceneIndex.exists()) {
org.eclipse.jgit.util.FileUtils.delete(luceneIndex,
org.eclipse.jgit.util.FileUtils.RECURSIVE);
}
// delete the config file
File luceneConfig = new File(repositoryFolder, CONF_FILE);
if (luceneConfig.exists()) {
luceneConfig.delete();
}
return true;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Returns the author for the commit, if this information is available.
*
* @param commit
* @return an author or unknown
*/
private String getAuthor(RevCommit commit) {
String name = "unknown";
try {
name = commit.getAuthorIdent().getName();
if (StringUtils.isEmpty(name)) {
name = commit.getAuthorIdent().getEmailAddress();
}
} catch (NullPointerException n) {
}
return name;
}
/**
* Returns the committer for the commit, if this information is available.
*
* @param commit
* @return an committer or unknown
*/
private String getCommitter(RevCommit commit) {
String name = "unknown";
try {
name = commit.getCommitterIdent().getName();
if (StringUtils.isEmpty(name)) {
name = commit.getCommitterIdent().getEmailAddress();
}
} catch (NullPointerException n) {
}
return name;
}
/**
* Get the tree associated with the given commit.
*
* @param walk
* @param commit
* @return tree
* @throws IOException
*/
private RevTree getTree(final RevWalk walk, final RevCommit commit)
throws IOException {
final RevTree tree = commit.getTree();
if (tree != null) {
return tree;
}
walk.parseHeaders(commit);
return commit.getTree();
}
/**
* Construct a keyname from the branch.
*
* @param branchName
* @return a keyname appropriate for the Git config file format
*/
private String getBranchKey(String branchName) {
return StringUtils.getSHA1(branchName);
}
/**
* Returns the Lucene configuration for the specified repository.
*
* @param repository
* @return a config object
*/
private FileBasedConfig getConfig(Repository repository) {
File file = new File(repository.getDirectory(), CONF_FILE);
FileBasedConfig config = new FileBasedConfig(file, FS.detect());
return config;
}
/**
* Reads the Lucene config file for the repository to check the index
* version. If the index version is different, then rebuild the repository
* index.
*
* @param repository
* @return true of the on-disk index format is different than INDEX_VERSION
*/
private boolean shouldReindex(Repository repository) {
try {
FileBasedConfig config = getConfig(repository);
config.load();
int indexVersion = config.getInt(CONF_INDEX, CONF_VERSION, 0);
// reindex if versions do not match
return indexVersion != INDEX_VERSION;
} catch (Throwable t) {
}
return true;
}
/**
* This completely indexes the repository and will destroy any existing
* index.
*
* @param repositoryName
* @param repository
* @return IndexResult
*/
public IndexResult reindex(RepositoryModel model, Repository repository) {
IndexResult result = new IndexResult();
if (!deleteIndex(model.name)) {
return result;
}
- try {
+ try {
+ String [] encodings = storedSettings.getStrings(Keys.web.blobEncodings).toArray(new String[0]);
FileBasedConfig config = getConfig(repository);
Set<String> indexedCommits = new TreeSet<String>();
IndexWriter writer = getIndexWriter(model.name);
// build a quick lookup of tags
Map<String, List<String>> tags = new HashMap<String, List<String>>();
for (RefModel tag : JGitUtils.getTags(repository, false, -1)) {
if (!tag.isAnnotatedTag()) {
// skip non-annotated tags
continue;
}
if (!tags.containsKey(tag.getObjectId())) {
tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>());
}
tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName);
}
ObjectReader reader = repository.newObjectReader();
// get the local branches
List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1);
// sort them by most recently updated
Collections.sort(branches, new Comparator<RefModel>() {
@Override
public int compare(RefModel ref1, RefModel ref2) {
return ref2.getDate().compareTo(ref1.getDate());
}
});
// reorder default branch to first position
RefModel defaultBranch = null;
ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository);
for (RefModel branch : branches) {
if (branch.getObjectId().equals(defaultBranchId)) {
defaultBranch = branch;
break;
}
}
branches.remove(defaultBranch);
branches.add(0, defaultBranch);
// walk through each branch
for (RefModel branch : branches) {
boolean indexBranch = false;
if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH)
&& branch.equals(defaultBranch)) {
// indexing "default" branch
indexBranch = true;
} else if (IssueUtils.GB_ISSUES.equals(branch)) {
// skip the GB_ISSUES branch because it is indexed later
// note: this is different than updateIndex
indexBranch = false;
} else {
// normal explicit branch check
indexBranch = model.indexedBranches.contains(branch.getName());
}
// if this branch is not specifically indexed then skip
if (!indexBranch) {
continue;
}
String branchName = branch.getName();
RevWalk revWalk = new RevWalk(reader);
RevCommit tip = revWalk.parseCommit(branch.getObjectId());
String tipId = tip.getId().getName();
String keyName = getBranchKey(branchName);
config.setString(CONF_ALIAS, null, keyName, branchName);
config.setString(CONF_BRANCH, null, keyName, tipId);
// index the blob contents of the tree
TreeWalk treeWalk = new TreeWalk(repository);
treeWalk.addTree(tip.getTree());
treeWalk.setRecursive(true);
Map<String, ObjectId> paths = new TreeMap<String, ObjectId>();
while (treeWalk.next()) {
paths.put(treeWalk.getPathString(), treeWalk.getObjectId(0));
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] tmp = new byte[32767];
RevWalk commitWalk = new RevWalk(reader);
commitWalk.markStart(tip);
RevCommit commit;
while ((paths.size() > 0) && (commit = commitWalk.next()) != null) {
TreeWalk diffWalk = new TreeWalk(reader);
int parentCount = commit.getParentCount();
switch (parentCount) {
case 0:
diffWalk.addTree(new EmptyTreeIterator());
break;
case 1:
diffWalk.addTree(getTree(commitWalk, commit.getParent(0)));
break;
default:
// skip merge commits
continue;
}
diffWalk.addTree(getTree(commitWalk, commit));
diffWalk.setFilter(ANY_DIFF);
diffWalk.setRecursive(true);
while ((paths.size() > 0) && diffWalk.next()) {
String path = diffWalk.getPathString();
if (!paths.containsKey(path)) {
continue;
}
// remove path from set
ObjectId blobId = paths.remove(path);
result.blobCount++;
// index the blob metadata
String blobAuthor = getAuthor(commit);
String blobCommitter = getCommitter(commit);
String blobDate = DateTools.timeToString(commit.getCommitTime() * 1000L,
Resolution.MINUTE);
Document doc = new Document();
doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.blob.name(), Store.YES, Index.NOT_ANALYZED_NO_NORMS));
doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_COMMIT, commit.getName(), Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_PATH, path, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_DATE, blobDate, Store.YES, Index.NO));
doc.add(new Field(FIELD_AUTHOR, blobAuthor, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_COMMITTER, blobCommitter, Store.YES, Index.ANALYZED));
// determine extension to compare to the extension
// blacklist
String ext = null;
String name = path.toLowerCase();
if (name.indexOf('.') > -1) {
ext = name.substring(name.lastIndexOf('.') + 1);
}
// index the blob content
if (StringUtils.isEmpty(ext) || !excludedExtensions.contains(ext)) {
ObjectLoader ldr = repository.open(blobId, Constants.OBJ_BLOB);
InputStream in = ldr.openStream();
int n;
while ((n = in.read(tmp)) > 0) {
os.write(tmp, 0, n);
}
in.close();
byte[] content = os.toByteArray();
- String str = new String(content, Constants.CHARACTER_ENCODING);
+ String str = StringUtils.decodeString(content, encodings);
doc.add(new Field(FIELD_CONTENT, str, Store.YES, Index.ANALYZED));
os.reset();
}
// add the blob to the index
writer.addDocument(doc);
}
}
os.close();
// index the tip commit object
if (indexedCommits.add(tipId)) {
Document doc = createDocument(tip, tags.get(tipId));
doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
writer.addDocument(doc);
result.commitCount += 1;
result.branchCount += 1;
}
// traverse the log and index the previous commit objects
RevWalk historyWalk = new RevWalk(reader);
historyWalk.markStart(historyWalk.parseCommit(tip.getId()));
RevCommit rev;
while ((rev = historyWalk.next()) != null) {
String hash = rev.getId().getName();
if (indexedCommits.add(hash)) {
Document doc = createDocument(rev, tags.get(hash));
doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
writer.addDocument(doc);
result.commitCount += 1;
}
}
}
// finished
reader.release();
// this repository has a gb-issues branch, index all issues
if (IssueUtils.getIssuesBranch(repository) != null) {
List<IssueModel> issues = IssueUtils.getIssues(repository, null);
if (issues.size() > 0) {
result.branchCount += 1;
}
for (IssueModel issue : issues) {
result.issueCount++;
Document doc = createDocument(issue);
writer.addDocument(doc);
}
}
// commit all changes and reset the searcher
config.setInt(CONF_INDEX, null, CONF_VERSION, INDEX_VERSION);
config.save();
writer.commit();
resetIndexSearcher(model.name);
result.success();
} catch (Exception e) {
logger.error("Exception while reindexing " + model.name, e);
}
return result;
}
/**
* Incrementally update the index with the specified commit for the
* repository.
*
* @param repositoryName
* @param repository
* @param branch
* the fully qualified branch name (e.g. refs/heads/master)
* @param commit
* @return true, if successful
*/
private IndexResult index(String repositoryName, Repository repository,
String branch, RevCommit commit) {
IndexResult result = new IndexResult();
try {
String [] encodings = storedSettings.getStrings(Keys.web.blobEncodings).toArray(new String[0]);
List<PathChangeModel> changedPaths = JGitUtils.getFilesInCommit(repository, commit);
String revDate = DateTools.timeToString(commit.getCommitTime() * 1000L,
Resolution.MINUTE);
IndexWriter writer = getIndexWriter(repositoryName);
for (PathChangeModel path : changedPaths) {
// delete the indexed blob
deleteBlob(repositoryName, branch, path.name);
// re-index the blob
if (!ChangeType.DELETE.equals(path.changeType)) {
result.blobCount++;
Document doc = new Document();
doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.blob.name(), Store.YES,
Index.NOT_ANALYZED));
doc.add(new Field(FIELD_BRANCH, branch, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_COMMIT, commit.getName(), Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_PATH, path.path, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_DATE, revDate, Store.YES, Index.NO));
doc.add(new Field(FIELD_AUTHOR, getAuthor(commit), Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_COMMITTER, getCommitter(commit), Store.YES, Index.ANALYZED));
// determine extension to compare to the extension
// blacklist
String ext = null;
String name = path.name.toLowerCase();
if (name.indexOf('.') > -1) {
ext = name.substring(name.lastIndexOf('.') + 1);
}
if (StringUtils.isEmpty(ext) || !excludedExtensions.contains(ext)) {
// read the blob content
String str = JGitUtils.getStringContent(repository, commit.getTree(),
path.path, encodings);
doc.add(new Field(FIELD_CONTENT, str, Store.YES, Index.ANALYZED));
writer.addDocument(doc);
}
}
}
writer.commit();
// get any annotated commit tags
List<String> commitTags = new ArrayList<String>();
for (RefModel ref : JGitUtils.getTags(repository, false, -1)) {
if (ref.isAnnotatedTag() && ref.getReferencedObjectId().equals(commit.getId())) {
commitTags.add(ref.displayName);
}
}
// create and write the Lucene document
Document doc = createDocument(commit, commitTags);
doc.add(new Field(FIELD_BRANCH, branch, Store.YES, Index.ANALYZED));
result.commitCount++;
result.success = index(repositoryName, doc);
} catch (Exception e) {
logger.error(MessageFormat.format("Exception while indexing commit {0} in {1}", commit.getId().getName(), repositoryName), e);
}
return result;
}
/**
* Incrementally update the index with the specified issue for the
* repository.
*
* @param repositoryName
* @param issue
* @return true, if successful
*/
public boolean index(String repositoryName, IssueModel issue) {
try {
// delete the old issue from the index, if exists
deleteIssue(repositoryName, issue.id);
Document doc = createDocument(issue);
return index(repositoryName, doc);
} catch (Exception e) {
logger.error(MessageFormat.format("Error while indexing issue {0} in {1}", issue.id, repositoryName), e);
}
return false;
}
/**
* Delete an issue from the repository index.
*
* @param repositoryName
* @param issueId
* @throws Exception
* @return true, if deleted, false if no record was deleted
*/
private boolean deleteIssue(String repositoryName, String issueId) throws Exception {
BooleanQuery query = new BooleanQuery();
Term objectTerm = new Term(FIELD_OBJECT_TYPE, SearchObjectType.issue.name());
query.add(new TermQuery(objectTerm), Occur.MUST);
Term issueidTerm = new Term(FIELD_ISSUE, issueId);
query.add(new TermQuery(issueidTerm), Occur.MUST);
IndexWriter writer = getIndexWriter(repositoryName);
int numDocsBefore = writer.numDocs();
writer.deleteDocuments(query);
writer.commit();
int numDocsAfter = writer.numDocs();
if (numDocsBefore == numDocsAfter) {
logger.debug(MessageFormat.format("no records found to delete {0}", query.toString()));
return false;
} else {
logger.debug(MessageFormat.format("deleted {0} records with {1}", numDocsBefore - numDocsAfter, query.toString()));
return true;
}
}
/**
* Delete a blob from the specified branch of the repository index.
*
* @param repositoryName
* @param branch
* @param path
* @throws Exception
* @return true, if deleted, false if no record was deleted
*/
public boolean deleteBlob(String repositoryName, String branch, String path) throws Exception {
String pattern = MessageFormat.format("{0}:'{'0} AND {1}:\"'{'1'}'\" AND {2}:\"'{'2'}'\"", FIELD_OBJECT_TYPE, FIELD_BRANCH, FIELD_PATH);
String q = MessageFormat.format(pattern, SearchObjectType.blob.name(), branch, path);
BooleanQuery query = new BooleanQuery();
StandardAnalyzer analyzer = new StandardAnalyzer(LUCENE_VERSION);
QueryParser qp = new QueryParser(LUCENE_VERSION, FIELD_SUMMARY, analyzer);
query.add(qp.parse(q), Occur.MUST);
IndexWriter writer = getIndexWriter(repositoryName);
int numDocsBefore = writer.numDocs();
writer.deleteDocuments(query);
writer.commit();
int numDocsAfter = writer.numDocs();
if (numDocsBefore == numDocsAfter) {
logger.debug(MessageFormat.format("no records found to delete {0}", query.toString()));
return false;
} else {
logger.debug(MessageFormat.format("deleted {0} records with {1}", numDocsBefore - numDocsAfter, query.toString()));
return true;
}
}
/**
* Updates a repository index incrementally from the last indexed commits.
*
* @param model
* @param repository
* @return IndexResult
*/
private IndexResult updateIndex(RepositoryModel model, Repository repository) {
IndexResult result = new IndexResult();
try {
FileBasedConfig config = getConfig(repository);
config.load();
// build a quick lookup of annotated tags
Map<String, List<String>> tags = new HashMap<String, List<String>>();
for (RefModel tag : JGitUtils.getTags(repository, false, -1)) {
if (!tag.isAnnotatedTag()) {
// skip non-annotated tags
continue;
}
if (!tags.containsKey(tag.getObjectId())) {
tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>());
}
tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName);
}
// detect branch deletion
// first assume all branches are deleted and then remove each
// existing branch from deletedBranches during indexing
Set<String> deletedBranches = new TreeSet<String>();
for (String alias : config.getNames(CONF_ALIAS)) {
String branch = config.getString(CONF_ALIAS, null, alias);
deletedBranches.add(branch);
}
// get the local branches
List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1);
// sort them by most recently updated
Collections.sort(branches, new Comparator<RefModel>() {
@Override
public int compare(RefModel ref1, RefModel ref2) {
return ref2.getDate().compareTo(ref1.getDate());
}
});
// reorder default branch to first position
RefModel defaultBranch = null;
ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository);
for (RefModel branch : branches) {
if (branch.getObjectId().equals(defaultBranchId)) {
defaultBranch = branch;
break;
}
}
branches.remove(defaultBranch);
branches.add(0, defaultBranch);
// walk through each branches
for (RefModel branch : branches) {
String branchName = branch.getName();
boolean indexBranch = false;
if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH)
&& branch.equals(defaultBranch)) {
// indexing "default" branch
indexBranch = true;
} else if (IssueUtils.GB_ISSUES.equals(branch)) {
// update issues modified on the GB_ISSUES branch
// note: this is different than reindex
indexBranch = true;
} else {
// normal explicit branch check
indexBranch = model.indexedBranches.contains(branch.getName());
}
// if this branch is not specifically indexed then skip
if (!indexBranch) {
continue;
}
// remove this branch from the deletedBranches set
deletedBranches.remove(branchName);
// determine last commit
String keyName = getBranchKey(branchName);
String lastCommit = config.getString(CONF_BRANCH, null, keyName);
List<RevCommit> revs;
if (StringUtils.isEmpty(lastCommit)) {
// new branch/unindexed branch, get all commits on branch
revs = JGitUtils.getRevLog(repository, branchName, 0, -1);
} else {
// pre-existing branch, get changes since last commit
revs = JGitUtils.getRevLog(repository, lastCommit, branchName);
}
if (revs.size() > 0) {
result.branchCount += 1;
}
// track the issue ids that we have already indexed
Set<String> indexedIssues = new TreeSet<String>();
// reverse the list of commits so we start with the first commit
Collections.reverse(revs);
for (RevCommit commit : revs) {
if (IssueUtils.GB_ISSUES.equals(branch)) {
// only index an issue once during updateIndex
String issueId = commit.getShortMessage().substring(2).trim();
if (indexedIssues.contains(issueId)) {
continue;
}
indexedIssues.add(issueId);
IssueModel issue = IssueUtils.getIssue(repository, issueId);
if (issue == null) {
// issue was deleted, remove from index
if (!deleteIssue(model.name, issueId)) {
logger.error(MessageFormat.format("Failed to delete issue {0} from Lucene index!", issueId));
}
} else {
// issue was updated
index(model.name, issue);
result.issueCount++;
}
} else {
// index a commit
result.add(index(model.name, repository, branchName, commit));
}
}
// update the config
config.setInt(CONF_INDEX, null, CONF_VERSION, INDEX_VERSION);
config.setString(CONF_ALIAS, null, keyName, branchName);
config.setString(CONF_BRANCH, null, keyName, branch.getObjectId().getName());
config.save();
}
// the deletedBranches set will normally be empty by this point
// unless a branch really was deleted and no longer exists
if (deletedBranches.size() > 0) {
for (String branch : deletedBranches) {
IndexWriter writer = getIndexWriter(model.name);
writer.deleteDocuments(new Term(FIELD_BRANCH, branch));
writer.commit();
}
}
result.success = true;
} catch (Throwable t) {
logger.error(MessageFormat.format("Exception while updating {0} Lucene index", model.name), t);
}
return result;
}
/**
* Creates a Lucene document from an issue.
*
* @param issue
* @return a Lucene document
*/
private Document createDocument(IssueModel issue) {
Document doc = new Document();
doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.issue.name(), Store.YES,
Field.Index.NOT_ANALYZED));
doc.add(new Field(FIELD_ISSUE, issue.id, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_BRANCH, IssueUtils.GB_ISSUES, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_DATE, DateTools.dateToString(issue.created, Resolution.MINUTE),
Store.YES, Field.Index.NO));
doc.add(new Field(FIELD_AUTHOR, issue.reporter, Store.YES, Index.ANALYZED));
List<String> attachments = new ArrayList<String>();
for (Attachment attachment : issue.getAttachments()) {
attachments.add(attachment.name.toLowerCase());
}
doc.add(new Field(FIELD_ATTACHMENT, StringUtils.flattenStrings(attachments), Store.YES,
Index.ANALYZED));
doc.add(new Field(FIELD_SUMMARY, issue.summary, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_CONTENT, issue.toString(), Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_LABEL, StringUtils.flattenStrings(issue.getLabels()), Store.YES,
Index.ANALYZED));
return doc;
}
/**
* Creates a Lucene document for a commit
*
* @param commit
* @param tags
* @return a Lucene document
*/
private Document createDocument(RevCommit commit, List<String> tags) {
Document doc = new Document();
doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.commit.name(), Store.YES,
Index.NOT_ANALYZED));
doc.add(new Field(FIELD_COMMIT, commit.getName(), Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_DATE, DateTools.timeToString(commit.getCommitTime() * 1000L,
Resolution.MINUTE), Store.YES, Index.NO));
doc.add(new Field(FIELD_AUTHOR, getAuthor(commit), Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_COMMITTER, getCommitter(commit), Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_SUMMARY, commit.getShortMessage(), Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_CONTENT, commit.getFullMessage(), Store.YES, Index.ANALYZED));
if (!ArrayUtils.isEmpty(tags)) {
doc.add(new Field(FIELD_TAG, StringUtils.flattenStrings(tags), Store.YES, Index.ANALYZED));
}
return doc;
}
/**
* Incrementally index an object for the repository.
*
* @param repositoryName
* @param doc
* @return true, if successful
*/
private boolean index(String repositoryName, Document doc) {
try {
IndexWriter writer = getIndexWriter(repositoryName);
writer.addDocument(doc);
writer.commit();
resetIndexSearcher(repositoryName);
return true;
} catch (Exception e) {
logger.error(MessageFormat.format("Exception while incrementally updating {0} Lucene index", repositoryName), e);
}
return false;
}
private SearchResult createSearchResult(Document doc, float score, int hitId, int totalHits) throws ParseException {
SearchResult result = new SearchResult();
result.hitId = hitId;
result.totalHits = totalHits;
result.score = score;
result.date = DateTools.stringToDate(doc.get(FIELD_DATE));
result.summary = doc.get(FIELD_SUMMARY);
result.author = doc.get(FIELD_AUTHOR);
result.committer = doc.get(FIELD_COMMITTER);
result.type = SearchObjectType.fromName(doc.get(FIELD_OBJECT_TYPE));
result.branch = doc.get(FIELD_BRANCH);
result.commitId = doc.get(FIELD_COMMIT);
result.issueId = doc.get(FIELD_ISSUE);
result.path = doc.get(FIELD_PATH);
if (doc.get(FIELD_TAG) != null) {
result.tags = StringUtils.getStringsFromValue(doc.get(FIELD_TAG));
}
if (doc.get(FIELD_LABEL) != null) {
result.labels = StringUtils.getStringsFromValue(doc.get(FIELD_LABEL));
}
return result;
}
private synchronized void resetIndexSearcher(String repository) throws IOException {
IndexSearcher searcher = searchers.remove(repository);
if (searcher != null) {
searcher.getIndexReader().close();
}
}
/**
* Gets an index searcher for the repository.
*
* @param repository
* @return
* @throws IOException
*/
private IndexSearcher getIndexSearcher(String repository) throws IOException {
IndexSearcher searcher = searchers.get(repository);
if (searcher == null) {
IndexWriter writer = getIndexWriter(repository);
searcher = new IndexSearcher(IndexReader.open(writer, true));
searchers.put(repository, searcher);
}
return searcher;
}
/**
* Gets an index writer for the repository. The index will be created if it
* does not already exist or if forceCreate is specified.
*
* @param repository
* @return an IndexWriter
* @throws IOException
*/
private IndexWriter getIndexWriter(String repository) throws IOException {
IndexWriter indexWriter = writers.get(repository);
File repositoryFolder = FileKey.resolve(new File(repositoriesFolder, repository), FS.DETECTED);
File indexFolder = new File(repositoryFolder, LUCENE_DIR);
Directory directory = FSDirectory.open(indexFolder);
if (indexWriter == null) {
if (!indexFolder.exists()) {
indexFolder.mkdirs();
}
StandardAnalyzer analyzer = new StandardAnalyzer(LUCENE_VERSION);
IndexWriterConfig config = new IndexWriterConfig(LUCENE_VERSION, analyzer);
config.setOpenMode(OpenMode.CREATE_OR_APPEND);
indexWriter = new IndexWriter(directory, config);
writers.put(repository, indexWriter);
}
return indexWriter;
}
/**
* Searches the specified repositories for the given text or query
*
* @param text
* if the text is null or empty, null is returned
* @param page
* the page number to retrieve. page is 1-indexed.
* @param pageSize
* the number of elements to return for this page
* @param repositories
* a list of repositories to search. if no repositories are
* specified null is returned.
* @return a list of SearchResults in order from highest to the lowest score
*
*/
public List<SearchResult> search(String text, int page, int pageSize, List<String> repositories) {
if (ArrayUtils.isEmpty(repositories)) {
return null;
}
return search(text, page, pageSize, repositories.toArray(new String[0]));
}
/**
* Searches the specified repositories for the given text or query
*
* @param text
* if the text is null or empty, null is returned
* @param page
* the page number to retrieve. page is 1-indexed.
* @param pageSize
* the number of elements to return for this page
* @param repositories
* a list of repositories to search. if no repositories are
* specified null is returned.
* @return a list of SearchResults in order from highest to the lowest score
*
*/
public List<SearchResult> search(String text, int page, int pageSize, String... repositories) {
if (StringUtils.isEmpty(text)) {
return null;
}
if (ArrayUtils.isEmpty(repositories)) {
return null;
}
Set<SearchResult> results = new LinkedHashSet<SearchResult>();
StandardAnalyzer analyzer = new StandardAnalyzer(LUCENE_VERSION);
try {
// default search checks summary and content
BooleanQuery query = new BooleanQuery();
QueryParser qp;
qp = new QueryParser(LUCENE_VERSION, FIELD_SUMMARY, analyzer);
qp.setAllowLeadingWildcard(true);
query.add(qp.parse(text), Occur.SHOULD);
qp = new QueryParser(LUCENE_VERSION, FIELD_CONTENT, analyzer);
qp.setAllowLeadingWildcard(true);
query.add(qp.parse(text), Occur.SHOULD);
IndexSearcher searcher;
if (repositories.length == 1) {
// single repository search
searcher = getIndexSearcher(repositories[0]);
} else {
// multiple repository search
List<IndexReader> readers = new ArrayList<IndexReader>();
for (String repository : repositories) {
IndexSearcher repositoryIndex = getIndexSearcher(repository);
readers.add(repositoryIndex.getIndexReader());
}
IndexReader[] rdrs = readers.toArray(new IndexReader[readers.size()]);
MultiSourceReader reader = new MultiSourceReader(rdrs);
searcher = new IndexSearcher(reader);
}
Query rewrittenQuery = searcher.rewrite(query);
logger.debug(rewrittenQuery.toString());
TopScoreDocCollector collector = TopScoreDocCollector.create(5000, true);
searcher.search(rewrittenQuery, collector);
int offset = Math.max(0, (page - 1) * pageSize);
ScoreDoc[] hits = collector.topDocs(offset, pageSize).scoreDocs;
int totalHits = collector.getTotalHits();
for (int i = 0; i < hits.length; i++) {
int docId = hits[i].doc;
Document doc = searcher.doc(docId);
SearchResult result = createSearchResult(doc, hits[i].score, offset + i + 1, totalHits);
if (repositories.length == 1) {
// single repository search
result.repository = repositories[0];
} else {
// multi-repository search
MultiSourceReader reader = (MultiSourceReader) searcher.getIndexReader();
int index = reader.getSourceIndex(docId);
result.repository = repositories[index];
}
String content = doc.get(FIELD_CONTENT);
result.fragment = getHighlightedFragment(analyzer, query, content, result);
results.add(result);
}
} catch (Exception e) {
logger.error(MessageFormat.format("Exception while searching for {0}", text), e);
}
return new ArrayList<SearchResult>(results);
}
/**
*
* @param analyzer
* @param query
* @param content
* @param result
* @return
* @throws IOException
* @throws InvalidTokenOffsetsException
*/
private String getHighlightedFragment(Analyzer analyzer, Query query,
String content, SearchResult result) throws IOException, InvalidTokenOffsetsException {
if (content == null) {
content = "";
}
int fragmentLength = SearchObjectType.commit == result.type ? 512 : 150;
QueryScorer scorer = new QueryScorer(query, "content");
Fragmenter fragmenter = new SimpleSpanFragmenter(scorer, fragmentLength);
// use an artificial delimiter for the token
String termTag = "!!--[";
String termTagEnd = "]--!!";
SimpleHTMLFormatter formatter = new SimpleHTMLFormatter(termTag, termTagEnd);
Highlighter highlighter = new Highlighter(formatter, scorer);
highlighter.setTextFragmenter(fragmenter);
String [] fragments = highlighter.getBestFragments(analyzer, "content", content, 3);
if (ArrayUtils.isEmpty(fragments)) {
if (SearchObjectType.blob == result.type) {
return "";
}
// clip commit message
String fragment = content;
if (fragment.length() > fragmentLength) {
fragment = fragment.substring(0, fragmentLength) + "...";
}
return "<pre class=\"text\">" + StringUtils.escapeForHtml(fragment, true) + "</pre>";
}
// make sure we have unique fragments
Set<String> uniqueFragments = new LinkedHashSet<String>();
for (String fragment : fragments) {
uniqueFragments.add(fragment);
}
fragments = uniqueFragments.toArray(new String[uniqueFragments.size()]);
StringBuilder sb = new StringBuilder();
for (int i = 0, len = fragments.length; i < len; i++) {
String fragment = fragments[i];
String tag = "<pre class=\"text\">";
// resurrect the raw fragment from removing the artificial delimiters
String raw = fragment.replace(termTag, "").replace(termTagEnd, "");
// determine position of the raw fragment in the content
int pos = content.indexOf(raw);
// restore complete first line of fragment
int c = pos;
while (c > 0) {
c--;
if (content.charAt(c) == '\n') {
break;
}
}
if (c > 0) {
// inject leading chunk of first fragment line
fragment = content.substring(c + 1, pos) + fragment;
}
if (SearchObjectType.blob == result.type) {
// count lines as offset into the content for this fragment
int line = Math.max(1, StringUtils.countLines(content.substring(0, pos)));
// create fragment tag with line number and language
String lang = "";
String ext = StringUtils.getFileExtension(result.path).toLowerCase();
if (!StringUtils.isEmpty(ext)) {
// maintain leading space!
lang = " lang-" + ext;
}
tag = MessageFormat.format("<pre class=\"prettyprint linenums:{0,number,0}{1}\">", line, lang);
}
sb.append(tag);
// replace the artificial delimiter with html tags
String html = StringUtils.escapeForHtml(fragment, false);
html = html.replace(termTag, "<span class=\"highlight\">").replace(termTagEnd, "</span>");
sb.append(html);
sb.append("</pre>");
if (i < len - 1) {
sb.append("<span class=\"ellipses\">...</span><br/>");
}
}
return sb.toString();
}
/**
* Simple class to track the results of an index update.
*/
private class IndexResult {
long startTime = System.currentTimeMillis();
long endTime = startTime;
boolean success;
int branchCount;
int commitCount;
int blobCount;
int issueCount;
void add(IndexResult result) {
this.branchCount += result.branchCount;
this.commitCount += result.commitCount;
this.blobCount += result.blobCount;
this.issueCount += result.issueCount;
}
void success() {
success = true;
endTime = System.currentTimeMillis();
}
float duration() {
return (endTime - startTime)/1000f;
}
}
/**
* Custom subclass of MultiReader to identify the source index for a given
* doc id. This would not be necessary of there was a public method to
* obtain this information.
*
*/
private class MultiSourceReader extends MultiReader {
final Method method;
MultiSourceReader(IndexReader[] subReaders) {
super(subReaders);
Method m = null;
try {
m = MultiReader.class.getDeclaredMethod("readerIndex", int.class);
m.setAccessible(true);
} catch (Exception e) {
logger.error("Error getting readerIndex method", e);
}
method = m;
}
int getSourceIndex(int docId) {
int index = -1;
try {
Object o = method.invoke(this, docId);
index = (Integer) o;
} catch (Exception e) {
logger.error("Error getting source index", e);
}
return index;
}
}
}
| false | true | public IndexResult reindex(RepositoryModel model, Repository repository) {
IndexResult result = new IndexResult();
if (!deleteIndex(model.name)) {
return result;
}
try {
FileBasedConfig config = getConfig(repository);
Set<String> indexedCommits = new TreeSet<String>();
IndexWriter writer = getIndexWriter(model.name);
// build a quick lookup of tags
Map<String, List<String>> tags = new HashMap<String, List<String>>();
for (RefModel tag : JGitUtils.getTags(repository, false, -1)) {
if (!tag.isAnnotatedTag()) {
// skip non-annotated tags
continue;
}
if (!tags.containsKey(tag.getObjectId())) {
tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>());
}
tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName);
}
ObjectReader reader = repository.newObjectReader();
// get the local branches
List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1);
// sort them by most recently updated
Collections.sort(branches, new Comparator<RefModel>() {
@Override
public int compare(RefModel ref1, RefModel ref2) {
return ref2.getDate().compareTo(ref1.getDate());
}
});
// reorder default branch to first position
RefModel defaultBranch = null;
ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository);
for (RefModel branch : branches) {
if (branch.getObjectId().equals(defaultBranchId)) {
defaultBranch = branch;
break;
}
}
branches.remove(defaultBranch);
branches.add(0, defaultBranch);
// walk through each branch
for (RefModel branch : branches) {
boolean indexBranch = false;
if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH)
&& branch.equals(defaultBranch)) {
// indexing "default" branch
indexBranch = true;
} else if (IssueUtils.GB_ISSUES.equals(branch)) {
// skip the GB_ISSUES branch because it is indexed later
// note: this is different than updateIndex
indexBranch = false;
} else {
// normal explicit branch check
indexBranch = model.indexedBranches.contains(branch.getName());
}
// if this branch is not specifically indexed then skip
if (!indexBranch) {
continue;
}
String branchName = branch.getName();
RevWalk revWalk = new RevWalk(reader);
RevCommit tip = revWalk.parseCommit(branch.getObjectId());
String tipId = tip.getId().getName();
String keyName = getBranchKey(branchName);
config.setString(CONF_ALIAS, null, keyName, branchName);
config.setString(CONF_BRANCH, null, keyName, tipId);
// index the blob contents of the tree
TreeWalk treeWalk = new TreeWalk(repository);
treeWalk.addTree(tip.getTree());
treeWalk.setRecursive(true);
Map<String, ObjectId> paths = new TreeMap<String, ObjectId>();
while (treeWalk.next()) {
paths.put(treeWalk.getPathString(), treeWalk.getObjectId(0));
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] tmp = new byte[32767];
RevWalk commitWalk = new RevWalk(reader);
commitWalk.markStart(tip);
RevCommit commit;
while ((paths.size() > 0) && (commit = commitWalk.next()) != null) {
TreeWalk diffWalk = new TreeWalk(reader);
int parentCount = commit.getParentCount();
switch (parentCount) {
case 0:
diffWalk.addTree(new EmptyTreeIterator());
break;
case 1:
diffWalk.addTree(getTree(commitWalk, commit.getParent(0)));
break;
default:
// skip merge commits
continue;
}
diffWalk.addTree(getTree(commitWalk, commit));
diffWalk.setFilter(ANY_DIFF);
diffWalk.setRecursive(true);
while ((paths.size() > 0) && diffWalk.next()) {
String path = diffWalk.getPathString();
if (!paths.containsKey(path)) {
continue;
}
// remove path from set
ObjectId blobId = paths.remove(path);
result.blobCount++;
// index the blob metadata
String blobAuthor = getAuthor(commit);
String blobCommitter = getCommitter(commit);
String blobDate = DateTools.timeToString(commit.getCommitTime() * 1000L,
Resolution.MINUTE);
Document doc = new Document();
doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.blob.name(), Store.YES, Index.NOT_ANALYZED_NO_NORMS));
doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_COMMIT, commit.getName(), Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_PATH, path, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_DATE, blobDate, Store.YES, Index.NO));
doc.add(new Field(FIELD_AUTHOR, blobAuthor, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_COMMITTER, blobCommitter, Store.YES, Index.ANALYZED));
// determine extension to compare to the extension
// blacklist
String ext = null;
String name = path.toLowerCase();
if (name.indexOf('.') > -1) {
ext = name.substring(name.lastIndexOf('.') + 1);
}
// index the blob content
if (StringUtils.isEmpty(ext) || !excludedExtensions.contains(ext)) {
ObjectLoader ldr = repository.open(blobId, Constants.OBJ_BLOB);
InputStream in = ldr.openStream();
int n;
while ((n = in.read(tmp)) > 0) {
os.write(tmp, 0, n);
}
in.close();
byte[] content = os.toByteArray();
String str = new String(content, Constants.CHARACTER_ENCODING);
doc.add(new Field(FIELD_CONTENT, str, Store.YES, Index.ANALYZED));
os.reset();
}
// add the blob to the index
writer.addDocument(doc);
}
}
os.close();
// index the tip commit object
if (indexedCommits.add(tipId)) {
Document doc = createDocument(tip, tags.get(tipId));
doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
writer.addDocument(doc);
result.commitCount += 1;
result.branchCount += 1;
}
// traverse the log and index the previous commit objects
RevWalk historyWalk = new RevWalk(reader);
historyWalk.markStart(historyWalk.parseCommit(tip.getId()));
RevCommit rev;
while ((rev = historyWalk.next()) != null) {
String hash = rev.getId().getName();
if (indexedCommits.add(hash)) {
Document doc = createDocument(rev, tags.get(hash));
doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
writer.addDocument(doc);
result.commitCount += 1;
}
}
}
// finished
reader.release();
// this repository has a gb-issues branch, index all issues
if (IssueUtils.getIssuesBranch(repository) != null) {
List<IssueModel> issues = IssueUtils.getIssues(repository, null);
if (issues.size() > 0) {
result.branchCount += 1;
}
for (IssueModel issue : issues) {
result.issueCount++;
Document doc = createDocument(issue);
writer.addDocument(doc);
}
}
// commit all changes and reset the searcher
config.setInt(CONF_INDEX, null, CONF_VERSION, INDEX_VERSION);
config.save();
writer.commit();
resetIndexSearcher(model.name);
result.success();
} catch (Exception e) {
logger.error("Exception while reindexing " + model.name, e);
}
return result;
}
| public IndexResult reindex(RepositoryModel model, Repository repository) {
IndexResult result = new IndexResult();
if (!deleteIndex(model.name)) {
return result;
}
try {
String [] encodings = storedSettings.getStrings(Keys.web.blobEncodings).toArray(new String[0]);
FileBasedConfig config = getConfig(repository);
Set<String> indexedCommits = new TreeSet<String>();
IndexWriter writer = getIndexWriter(model.name);
// build a quick lookup of tags
Map<String, List<String>> tags = new HashMap<String, List<String>>();
for (RefModel tag : JGitUtils.getTags(repository, false, -1)) {
if (!tag.isAnnotatedTag()) {
// skip non-annotated tags
continue;
}
if (!tags.containsKey(tag.getObjectId())) {
tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>());
}
tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName);
}
ObjectReader reader = repository.newObjectReader();
// get the local branches
List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1);
// sort them by most recently updated
Collections.sort(branches, new Comparator<RefModel>() {
@Override
public int compare(RefModel ref1, RefModel ref2) {
return ref2.getDate().compareTo(ref1.getDate());
}
});
// reorder default branch to first position
RefModel defaultBranch = null;
ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository);
for (RefModel branch : branches) {
if (branch.getObjectId().equals(defaultBranchId)) {
defaultBranch = branch;
break;
}
}
branches.remove(defaultBranch);
branches.add(0, defaultBranch);
// walk through each branch
for (RefModel branch : branches) {
boolean indexBranch = false;
if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH)
&& branch.equals(defaultBranch)) {
// indexing "default" branch
indexBranch = true;
} else if (IssueUtils.GB_ISSUES.equals(branch)) {
// skip the GB_ISSUES branch because it is indexed later
// note: this is different than updateIndex
indexBranch = false;
} else {
// normal explicit branch check
indexBranch = model.indexedBranches.contains(branch.getName());
}
// if this branch is not specifically indexed then skip
if (!indexBranch) {
continue;
}
String branchName = branch.getName();
RevWalk revWalk = new RevWalk(reader);
RevCommit tip = revWalk.parseCommit(branch.getObjectId());
String tipId = tip.getId().getName();
String keyName = getBranchKey(branchName);
config.setString(CONF_ALIAS, null, keyName, branchName);
config.setString(CONF_BRANCH, null, keyName, tipId);
// index the blob contents of the tree
TreeWalk treeWalk = new TreeWalk(repository);
treeWalk.addTree(tip.getTree());
treeWalk.setRecursive(true);
Map<String, ObjectId> paths = new TreeMap<String, ObjectId>();
while (treeWalk.next()) {
paths.put(treeWalk.getPathString(), treeWalk.getObjectId(0));
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] tmp = new byte[32767];
RevWalk commitWalk = new RevWalk(reader);
commitWalk.markStart(tip);
RevCommit commit;
while ((paths.size() > 0) && (commit = commitWalk.next()) != null) {
TreeWalk diffWalk = new TreeWalk(reader);
int parentCount = commit.getParentCount();
switch (parentCount) {
case 0:
diffWalk.addTree(new EmptyTreeIterator());
break;
case 1:
diffWalk.addTree(getTree(commitWalk, commit.getParent(0)));
break;
default:
// skip merge commits
continue;
}
diffWalk.addTree(getTree(commitWalk, commit));
diffWalk.setFilter(ANY_DIFF);
diffWalk.setRecursive(true);
while ((paths.size() > 0) && diffWalk.next()) {
String path = diffWalk.getPathString();
if (!paths.containsKey(path)) {
continue;
}
// remove path from set
ObjectId blobId = paths.remove(path);
result.blobCount++;
// index the blob metadata
String blobAuthor = getAuthor(commit);
String blobCommitter = getCommitter(commit);
String blobDate = DateTools.timeToString(commit.getCommitTime() * 1000L,
Resolution.MINUTE);
Document doc = new Document();
doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.blob.name(), Store.YES, Index.NOT_ANALYZED_NO_NORMS));
doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_COMMIT, commit.getName(), Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_PATH, path, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_DATE, blobDate, Store.YES, Index.NO));
doc.add(new Field(FIELD_AUTHOR, blobAuthor, Store.YES, Index.ANALYZED));
doc.add(new Field(FIELD_COMMITTER, blobCommitter, Store.YES, Index.ANALYZED));
// determine extension to compare to the extension
// blacklist
String ext = null;
String name = path.toLowerCase();
if (name.indexOf('.') > -1) {
ext = name.substring(name.lastIndexOf('.') + 1);
}
// index the blob content
if (StringUtils.isEmpty(ext) || !excludedExtensions.contains(ext)) {
ObjectLoader ldr = repository.open(blobId, Constants.OBJ_BLOB);
InputStream in = ldr.openStream();
int n;
while ((n = in.read(tmp)) > 0) {
os.write(tmp, 0, n);
}
in.close();
byte[] content = os.toByteArray();
String str = StringUtils.decodeString(content, encodings);
doc.add(new Field(FIELD_CONTENT, str, Store.YES, Index.ANALYZED));
os.reset();
}
// add the blob to the index
writer.addDocument(doc);
}
}
os.close();
// index the tip commit object
if (indexedCommits.add(tipId)) {
Document doc = createDocument(tip, tags.get(tipId));
doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
writer.addDocument(doc);
result.commitCount += 1;
result.branchCount += 1;
}
// traverse the log and index the previous commit objects
RevWalk historyWalk = new RevWalk(reader);
historyWalk.markStart(historyWalk.parseCommit(tip.getId()));
RevCommit rev;
while ((rev = historyWalk.next()) != null) {
String hash = rev.getId().getName();
if (indexedCommits.add(hash)) {
Document doc = createDocument(rev, tags.get(hash));
doc.add(new Field(FIELD_BRANCH, branchName, Store.YES, Index.ANALYZED));
writer.addDocument(doc);
result.commitCount += 1;
}
}
}
// finished
reader.release();
// this repository has a gb-issues branch, index all issues
if (IssueUtils.getIssuesBranch(repository) != null) {
List<IssueModel> issues = IssueUtils.getIssues(repository, null);
if (issues.size() > 0) {
result.branchCount += 1;
}
for (IssueModel issue : issues) {
result.issueCount++;
Document doc = createDocument(issue);
writer.addDocument(doc);
}
}
// commit all changes and reset the searcher
config.setInt(CONF_INDEX, null, CONF_VERSION, INDEX_VERSION);
config.save();
writer.commit();
resetIndexSearcher(model.name);
result.success();
} catch (Exception e) {
logger.error("Exception while reindexing " + model.name, e);
}
return result;
}
|
diff --git a/src/test/webui/dashboard/services/PuStatusBeforeDeploymentEndsTest.java b/src/test/webui/dashboard/services/PuStatusBeforeDeploymentEndsTest.java
index fb85dad5..0ac522dc 100644
--- a/src/test/webui/dashboard/services/PuStatusBeforeDeploymentEndsTest.java
+++ b/src/test/webui/dashboard/services/PuStatusBeforeDeploymentEndsTest.java
@@ -1,95 +1,96 @@
package test.webui.dashboard.services;
import static framework.utils.AdminUtils.loadGSCs;
import static framework.utils.AdminUtils.loadGSM;
import static framework.utils.LogUtils.log;
import org.openspaces.admin.gsa.GridServiceAgent;
import org.openspaces.admin.gsm.GridServiceManager;
import org.openspaces.admin.machine.Machine;
import org.openspaces.admin.pu.DeploymentStatus;
import org.openspaces.admin.pu.ProcessingUnit;
import org.openspaces.admin.space.SpaceDeployment;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import framework.utils.AssertUtils;
import framework.utils.AssertUtils.RepetitiveConditionProvider;
import test.webui.AbstractSeleniumTest;
import test.webui.objects.LoginPage;
import test.webui.objects.dashboard.DashboardTab;
import test.webui.objects.dashboard.ServicesGrid;
import test.webui.objects.dashboard.ServicesGrid.ApplicationServicesGrid;
import test.webui.objects.dashboard.ServicesGrid.ApplicationServicesGrid.StatefullModule;
import test.webui.objects.dashboard.ServicesGrid.Icon;
public class PuStatusBeforeDeploymentEndsTest extends AbstractSeleniumTest {
Machine machineA;
ProcessingUnit pu;
GridServiceManager gsmA;
@BeforeMethod(alwaysRun = true)
public void startSetup() {
log("waiting for 1 machine");
admin.getMachines().waitFor(1);
log("waiting for 1 GSA");
admin.getGridServiceAgents().waitFor(1);
GridServiceAgent[] agents = admin.getGridServiceAgents().getAgents();
GridServiceAgent gsaA = agents[0];
machineA = gsaA.getMachine();
log("starting: 1 GSM and 2 GSC's on 1 machine");
gsmA = loadGSM(machineA);
loadGSCs(machineA, 2);
}
@Test(timeOut = DEFAULT_TEST_TIMEOUT)
public void puStatusTest() throws InterruptedException {
LoginPage loginPage = getLoginPage();
DashboardTab dashboardTab = loginPage.login().switchToDashboard();
ServicesGrid appGrid = dashboardTab.getServicesGrid();
final ApplicationServicesGrid applicationServices = appGrid.getApplicationServicesGrid();
// deploy a pu
SpaceDeployment deployment = new SpaceDeployment("Test").partitioned(2, 0).maxInstancesPerVM(1);
pu = gsmA.deploy(deployment);
RepetitiveConditionProvider condition = new RepetitiveConditionProvider() {
@Override
public boolean getCondition() {
if (applicationServices.getStatefullModule() != null) return true;
return false;
}
};
AssertUtils.repetitiveAssertTrue(null, condition, waitingTime);
+ StatefullModule module = applicationServices.getStatefullModule();
DeploymentStatus testStatus = admin.getProcessingUnits().getProcessingUnit("Test").getStatus();
- StatefullModule module = applicationServices.getStatefullModule();
while (!testStatus.equals(DeploymentStatus.INTACT)) {
- assertTrue(!module.getIcon().equals(Icon.OK));
+ Icon icon = module.getIcon();
+ assertTrue((icon != null) && !icon.equals(Icon.OK));
testStatus = admin.getProcessingUnits().getProcessingUnit("Test").getStatus();
}
condition = new RepetitiveConditionProvider() {
@Override
public boolean getCondition() {
StatefullModule module = applicationServices.getStatefullModule();
return module.getIcon().equals(Icon.OK);
}
};
AssertUtils.repetitiveAssertTrue(null, condition, waitingTime);
}
}
| false | true | public void puStatusTest() throws InterruptedException {
LoginPage loginPage = getLoginPage();
DashboardTab dashboardTab = loginPage.login().switchToDashboard();
ServicesGrid appGrid = dashboardTab.getServicesGrid();
final ApplicationServicesGrid applicationServices = appGrid.getApplicationServicesGrid();
// deploy a pu
SpaceDeployment deployment = new SpaceDeployment("Test").partitioned(2, 0).maxInstancesPerVM(1);
pu = gsmA.deploy(deployment);
RepetitiveConditionProvider condition = new RepetitiveConditionProvider() {
@Override
public boolean getCondition() {
if (applicationServices.getStatefullModule() != null) return true;
return false;
}
};
AssertUtils.repetitiveAssertTrue(null, condition, waitingTime);
DeploymentStatus testStatus = admin.getProcessingUnits().getProcessingUnit("Test").getStatus();
StatefullModule module = applicationServices.getStatefullModule();
while (!testStatus.equals(DeploymentStatus.INTACT)) {
assertTrue(!module.getIcon().equals(Icon.OK));
testStatus = admin.getProcessingUnits().getProcessingUnit("Test").getStatus();
}
condition = new RepetitiveConditionProvider() {
@Override
public boolean getCondition() {
StatefullModule module = applicationServices.getStatefullModule();
return module.getIcon().equals(Icon.OK);
}
};
AssertUtils.repetitiveAssertTrue(null, condition, waitingTime);
}
| public void puStatusTest() throws InterruptedException {
LoginPage loginPage = getLoginPage();
DashboardTab dashboardTab = loginPage.login().switchToDashboard();
ServicesGrid appGrid = dashboardTab.getServicesGrid();
final ApplicationServicesGrid applicationServices = appGrid.getApplicationServicesGrid();
// deploy a pu
SpaceDeployment deployment = new SpaceDeployment("Test").partitioned(2, 0).maxInstancesPerVM(1);
pu = gsmA.deploy(deployment);
RepetitiveConditionProvider condition = new RepetitiveConditionProvider() {
@Override
public boolean getCondition() {
if (applicationServices.getStatefullModule() != null) return true;
return false;
}
};
AssertUtils.repetitiveAssertTrue(null, condition, waitingTime);
StatefullModule module = applicationServices.getStatefullModule();
DeploymentStatus testStatus = admin.getProcessingUnits().getProcessingUnit("Test").getStatus();
while (!testStatus.equals(DeploymentStatus.INTACT)) {
Icon icon = module.getIcon();
assertTrue((icon != null) && !icon.equals(Icon.OK));
testStatus = admin.getProcessingUnits().getProcessingUnit("Test").getStatus();
}
condition = new RepetitiveConditionProvider() {
@Override
public boolean getCondition() {
StatefullModule module = applicationServices.getStatefullModule();
return module.getIcon().equals(Icon.OK);
}
};
AssertUtils.repetitiveAssertTrue(null, condition, waitingTime);
}
|
diff --git a/src/org/bukkit/craftbukkit/CraftPlayerCache.java b/src/org/bukkit/craftbukkit/CraftPlayerCache.java
index 8144f5b..ab747c7 100644
--- a/src/org/bukkit/craftbukkit/CraftPlayerCache.java
+++ b/src/org/bukkit/craftbukkit/CraftPlayerCache.java
@@ -1,46 +1,46 @@
package org.bukkit.craftbukkit;
import java.util.HashMap;
import net.minecraft.entity.player.EntityPlayerMP;
import org.bukkit.craftbukkit.entity.CraftPlayer;
public class CraftPlayerCache {
private static final HashMap<String, CraftPlayer> playerCache = new HashMap<String, CraftPlayer>();
public static CraftPlayer getCraftPlayer(EntityPlayerMP player) {
- if (playerCache.containsKey(player.username))
+ if (playerCache.containsKey(player.username.toLowerCase()))
{
- CraftPlayer ply = playerCache.get(player.username);
- if (ply.getHandle().entityId != player.entityId || ply.getHandle().isDead) {
+ CraftPlayer ply = playerCache.get(player.username.toLowerCase());
+ if (ply.getHandle().isDead) {
// new player needed
//removePlayer(player.username);
ply.setHandle(player);
return ply;
}
else {
return ply;
}
}
- playerCache.put(player.username, new CraftPlayer(player));
- return playerCache.get(player.username);
+ playerCache.put(player.username.toLowerCase(), new CraftPlayer(player));
+ return playerCache.get(player.username.toLowerCase());
}
public static CraftPlayer getCraftPlayer( CraftServer server, EntityPlayerMP player) {
/*if (playerCache.containsKey(player.username))
return playerCache.get(player.username);
playerCache.put(player.username, new CraftPlayer(server, player));
return playerCache.get(player.username);*/
return getCraftPlayer(player);
}
public static void removePlayer(String name) {
if (playerCache.containsKey(name))
playerCache.remove(name);
}
}
| false | true | public static CraftPlayer getCraftPlayer(EntityPlayerMP player) {
if (playerCache.containsKey(player.username))
{
CraftPlayer ply = playerCache.get(player.username);
if (ply.getHandle().entityId != player.entityId || ply.getHandle().isDead) {
// new player needed
//removePlayer(player.username);
ply.setHandle(player);
return ply;
}
else {
return ply;
}
}
playerCache.put(player.username, new CraftPlayer(player));
return playerCache.get(player.username);
}
| public static CraftPlayer getCraftPlayer(EntityPlayerMP player) {
if (playerCache.containsKey(player.username.toLowerCase()))
{
CraftPlayer ply = playerCache.get(player.username.toLowerCase());
if (ply.getHandle().isDead) {
// new player needed
//removePlayer(player.username);
ply.setHandle(player);
return ply;
}
else {
return ply;
}
}
playerCache.put(player.username.toLowerCase(), new CraftPlayer(player));
return playerCache.get(player.username.toLowerCase());
}
|
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java
index 0353cd8..eeba116 100644
--- a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java
+++ b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java
@@ -1,60 +1,60 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.ItemDb;
import com.earth2me.essentials.User;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class Commandgive extends EssentialsCommand
{
public Commandgive()
{
super("give");
}
@Override
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
- ItemStack stack = ItemDb.get(args[0]);
+ ItemStack stack = ItemDb.get(args[1]);
String itemname = stack.getType().toString().toLowerCase().replace("_", "");
if (sender instanceof Player
&& (ess.getSettings().permissionBasedItemSpawn()
? (!ess.getUser(sender).isAuthorized("essentials.give.item-all")
&& !ess.getUser(sender).isAuthorized("essentials.give.item-" + itemname)
&& !ess.getUser(sender).isAuthorized("essentials.give.item-" + stack.getTypeId()))
: (!ess.getUser(sender).isAuthorized("essentials.itemspawn.exempt")
&& !ess.getUser(sender).canSpawnItem(stack.getTypeId()))))
{
sender.sendMessage(ChatColor.RED + "You are not allowed to spawn the item " + itemname);
return;
}
if (args.length > 2 && Integer.parseInt(args[2]) > 0)
{
stack.setAmount(Integer.parseInt(args[2]));
}
if (stack.getType() == Material.AIR)
{
sender.sendMessage(ChatColor.RED + "You can't give air.");
return;
}
User giveTo = getPlayer(server, args, 0);
String itemName = stack.getType().name().toLowerCase().replace('_', ' ');
charge(sender);
sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + ".");
giveTo.getInventory().addItem(stack);
giveTo.updateInventory();
}
}
| true | true | public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
ItemStack stack = ItemDb.get(args[0]);
String itemname = stack.getType().toString().toLowerCase().replace("_", "");
if (sender instanceof Player
&& (ess.getSettings().permissionBasedItemSpawn()
? (!ess.getUser(sender).isAuthorized("essentials.give.item-all")
&& !ess.getUser(sender).isAuthorized("essentials.give.item-" + itemname)
&& !ess.getUser(sender).isAuthorized("essentials.give.item-" + stack.getTypeId()))
: (!ess.getUser(sender).isAuthorized("essentials.itemspawn.exempt")
&& !ess.getUser(sender).canSpawnItem(stack.getTypeId()))))
{
sender.sendMessage(ChatColor.RED + "You are not allowed to spawn the item " + itemname);
return;
}
if (args.length > 2 && Integer.parseInt(args[2]) > 0)
{
stack.setAmount(Integer.parseInt(args[2]));
}
if (stack.getType() == Material.AIR)
{
sender.sendMessage(ChatColor.RED + "You can't give air.");
return;
}
User giveTo = getPlayer(server, args, 0);
String itemName = stack.getType().name().toLowerCase().replace('_', ' ');
charge(sender);
sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + ".");
giveTo.getInventory().addItem(stack);
giveTo.updateInventory();
}
| public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
ItemStack stack = ItemDb.get(args[1]);
String itemname = stack.getType().toString().toLowerCase().replace("_", "");
if (sender instanceof Player
&& (ess.getSettings().permissionBasedItemSpawn()
? (!ess.getUser(sender).isAuthorized("essentials.give.item-all")
&& !ess.getUser(sender).isAuthorized("essentials.give.item-" + itemname)
&& !ess.getUser(sender).isAuthorized("essentials.give.item-" + stack.getTypeId()))
: (!ess.getUser(sender).isAuthorized("essentials.itemspawn.exempt")
&& !ess.getUser(sender).canSpawnItem(stack.getTypeId()))))
{
sender.sendMessage(ChatColor.RED + "You are not allowed to spawn the item " + itemname);
return;
}
if (args.length > 2 && Integer.parseInt(args[2]) > 0)
{
stack.setAmount(Integer.parseInt(args[2]));
}
if (stack.getType() == Material.AIR)
{
sender.sendMessage(ChatColor.RED + "You can't give air.");
return;
}
User giveTo = getPlayer(server, args, 0);
String itemName = stack.getType().name().toLowerCase().replace('_', ' ');
charge(sender);
sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + ".");
giveTo.getInventory().addItem(stack);
giveTo.updateInventory();
}
|
diff --git a/bundles/IndexLucene/src/main/java/org/paxle/se/index/lucene/impl/SnippetFetcher.java b/bundles/IndexLucene/src/main/java/org/paxle/se/index/lucene/impl/SnippetFetcher.java
index d942ba48..56af292e 100644
--- a/bundles/IndexLucene/src/main/java/org/paxle/se/index/lucene/impl/SnippetFetcher.java
+++ b/bundles/IndexLucene/src/main/java/org/paxle/se/index/lucene/impl/SnippetFetcher.java
@@ -1,245 +1,245 @@
/**
* This file is part of the Paxle project.
* Visit http://www.paxle.net for more information.
* Copyright 2007-2009 the original author or authors.
*
* Licensed under the terms of the Common Public License 1.0 ("CPL 1.0").
* Any use, reproduction or distribution of this program constitutes the recipient's acceptance of this agreement.
* The full license text is available under http://www.opensource.org/licenses/cpl1.0.txt
* or in the file LICENSE.txt in the root directory of the Paxle distribution.
*
* Unless required by applicable law or agreed to in writing, this software is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.paxle.se.index.lucene.impl;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URI;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.util.tracker.ServiceTracker;
import org.paxle.core.IMWComponent;
import org.paxle.core.doc.IIndexerDocument;
import org.paxle.core.doc.IParserDocument;
import org.paxle.core.doc.IParserDocument.Status;
import org.paxle.core.io.IOTools;
import org.paxle.core.queue.Command;
import org.paxle.core.queue.ICommand;
import org.paxle.core.queue.ICommand.Result;
public class SnippetFetcher {
/**
* Thread pool service
*/
private ExecutorService execService;
/**
* For logging
*/
protected Log logger = LogFactory.getLog(this.getClass());
/**
* @scr.reference target="(component.ID=org.paxle.crawler)"
*/
protected ServiceTracker crawler;
/**
* @scr.reference target="(component.ID=org.paxle.parser)"
*/
protected ServiceTracker parser;
protected PaxleAnalyzer analyzer;
public SnippetFetcher(BundleContext ctx, PaxleAnalyzer analyzer) throws InvalidSyntaxException {
this.crawler = new ServiceTracker(ctx, ctx.createFilter("(&(objectClass=org.paxle.core.IMWComponent)(component.ID=org.paxle.crawler))"),null);
this.crawler.open();
this.parser = new ServiceTracker(ctx, ctx.createFilter("(&(objectClass=org.paxle.core.IMWComponent)(component.ID=org.paxle.parser))"),null);
this.parser.open();
this.analyzer = analyzer;
this.execService = Executors.newCachedThreadPool();
}
public void close() {
this.crawler.close();
this.parser.close();
}
public String getSnippet(Query query, String locationStr) {
try {
// creating a dummy command
URI locationURI = URI.create(locationStr);
ICommand cmd = Command.createCommand(locationURI);
// getting the crawler
@SuppressWarnings("unchecked")
IMWComponent<ICommand> crawlerComp = (IMWComponent<ICommand>) crawler.getService();
if (crawlerComp == null) return null;
// getting the parser
@SuppressWarnings("unchecked")
IMWComponent<ICommand> parserComp = (IMWComponent<ICommand>) parser.getService();
if (parserComp == null) return null;
// crawling the resource
crawlerComp.process(cmd);
if (cmd.getResult() != Result.Passed) return null;
// parsing the resource
parserComp.process(cmd);
if (cmd.getResult() != Result.Passed) return null;
// trying to get the parsed content
IParserDocument pdoc = cmd.getParserDocument();
if (pdoc == null) return null;
else if (pdoc.getStatus() != Status.OK) return null;
// getting the document content
Reader content = pdoc.getTextAsReader();
if (content == null) return null;
// reading some text
StringBuilder text = new StringBuilder();
IOTools.copy(content, text, 10240);
final Highlighter highlighter = new Highlighter(new QueryScorer(query));
final TokenStream tokenStream = this.analyzer.tokenStream("content", new StringReader(text.toString()));
final String result = highlighter.getBestFragments(tokenStream, text.toString(), 3, "...");
return result;
} catch (Throwable e) {
- this.logger.equals(e);
+ this.logger.error(e.getMessage(), e);
}
return null;
}
/**
* Method to generate a dynamic proxy around an {@link IIndexerDocument}
* @param idoc the {@link IIndexerDocument} to wrap
* @param query the query as entered by the user
* @param deadline a point in time when the snippet generation should have finished
* @return a wrapped {@link IIndexerDocument}
*/
public IIndexerDocument createProxy(IIndexerDocument idoc, Query query,long deadline) {
IIndexerDocument idocProxy = (IIndexerDocument) Proxy.newProxyInstance(
IIndexerDocument.class.getClassLoader(),
new Class[] { IIndexerDocument.class },
new SnippetFetchingWrapper(idoc, query, deadline)
);
return idocProxy;
}
/**
* This class is a dynamic wrapper around an {@link IIndexerDocument}, intercepts
* method calls to {@link IIndexerDocument#get(org.paxle.core.doc.Field)} and
* injects snippets fetched asynchronous by the {@link ExecutorService}
*/
private class SnippetFetchingWrapper implements InvocationHandler, Callable<String> {
/**
* The {@link IIndexerDocument indexer-document} we need to generate a snippet for
*/
private IIndexerDocument idoc;
/**
* The query as entered by the user
*/
private Query query;
/**
* An object to determine the snippet-generation status
*/
private Future<String> pendingTask;
/**
* The time when snippet-generation should have been finished
*/
private long deadline;
/**
* A flag specifying if the caller has already tried to get the snippet via a function
* call to {@link IIndexerDocument#get(org.paxle.core.doc.Field)}.
*/
private boolean fetched;
public SnippetFetchingWrapper(IIndexerDocument idoc, Query query, long deadline) {
this.idoc = idoc;
this.query = query;
this.deadline = deadline;
// starting an async task for snippet fetching
this.pendingTask = execService.submit(this);
}
/**
* This method is used to intercept function calls to {@link IIndexerDocument#get(org.paxle.core.doc.Field)} if
* {@link IIndexerDocument#SNIPPET} is used as argument, and to take a look if the asnychronous snippet-fetching-task
* has finished and returned a result.
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("get") && args != null && args.length > 0 && IIndexerDocument.SNIPPET.equals(args[0])) {
this.fetched = true;
if (this.idoc.get(IIndexerDocument.SNIPPET) == null) {
/*
* if the task has not finished yet we'll wait some time to receive the result
*/
if (!this.pendingTask.isDone()) {
try {
long timeToWait = this.deadline - System.currentTimeMillis();
if (timeToWait > 100) {
String result = this.pendingTask.get(timeToWait, TimeUnit.MILLISECONDS);
if (result != null) return result;
}
} catch (Exception e) {
// ignore this
}
}
}
}
return method.invoke(this.idoc, args);
}
/**
* This method is called asynchronous by an {@link ExecutorService} to generate
* a snippet for a found {@link IIndexerDocument}
*/
public String call() throws Exception {
// getting the URI of the document
String locationStr = this.idoc.get(IIndexerDocument.LOCATION);
// generating the snippet
String snippet = getSnippet(query, locationStr);
// if a snippet was generated successfully we store it into the
// IIndexerDocument now
if (snippet != null) {
this.idoc.set(IIndexerDocument.SNIPPET, snippet);
if (this.fetched) {
/* The caller already has tried to fetch the snippet.
*
* TODO: we could insert the generated snippet into a cache here
* so that it can be fetched asynchronous, e.g. by an ajax task
*/
}
}
return snippet;
}
}
}
| true | true | public String getSnippet(Query query, String locationStr) {
try {
// creating a dummy command
URI locationURI = URI.create(locationStr);
ICommand cmd = Command.createCommand(locationURI);
// getting the crawler
@SuppressWarnings("unchecked")
IMWComponent<ICommand> crawlerComp = (IMWComponent<ICommand>) crawler.getService();
if (crawlerComp == null) return null;
// getting the parser
@SuppressWarnings("unchecked")
IMWComponent<ICommand> parserComp = (IMWComponent<ICommand>) parser.getService();
if (parserComp == null) return null;
// crawling the resource
crawlerComp.process(cmd);
if (cmd.getResult() != Result.Passed) return null;
// parsing the resource
parserComp.process(cmd);
if (cmd.getResult() != Result.Passed) return null;
// trying to get the parsed content
IParserDocument pdoc = cmd.getParserDocument();
if (pdoc == null) return null;
else if (pdoc.getStatus() != Status.OK) return null;
// getting the document content
Reader content = pdoc.getTextAsReader();
if (content == null) return null;
// reading some text
StringBuilder text = new StringBuilder();
IOTools.copy(content, text, 10240);
final Highlighter highlighter = new Highlighter(new QueryScorer(query));
final TokenStream tokenStream = this.analyzer.tokenStream("content", new StringReader(text.toString()));
final String result = highlighter.getBestFragments(tokenStream, text.toString(), 3, "...");
return result;
} catch (Throwable e) {
this.logger.equals(e);
}
return null;
}
| public String getSnippet(Query query, String locationStr) {
try {
// creating a dummy command
URI locationURI = URI.create(locationStr);
ICommand cmd = Command.createCommand(locationURI);
// getting the crawler
@SuppressWarnings("unchecked")
IMWComponent<ICommand> crawlerComp = (IMWComponent<ICommand>) crawler.getService();
if (crawlerComp == null) return null;
// getting the parser
@SuppressWarnings("unchecked")
IMWComponent<ICommand> parserComp = (IMWComponent<ICommand>) parser.getService();
if (parserComp == null) return null;
// crawling the resource
crawlerComp.process(cmd);
if (cmd.getResult() != Result.Passed) return null;
// parsing the resource
parserComp.process(cmd);
if (cmd.getResult() != Result.Passed) return null;
// trying to get the parsed content
IParserDocument pdoc = cmd.getParserDocument();
if (pdoc == null) return null;
else if (pdoc.getStatus() != Status.OK) return null;
// getting the document content
Reader content = pdoc.getTextAsReader();
if (content == null) return null;
// reading some text
StringBuilder text = new StringBuilder();
IOTools.copy(content, text, 10240);
final Highlighter highlighter = new Highlighter(new QueryScorer(query));
final TokenStream tokenStream = this.analyzer.tokenStream("content", new StringReader(text.toString()));
final String result = highlighter.getBestFragments(tokenStream, text.toString(), 3, "...");
return result;
} catch (Throwable e) {
this.logger.error(e.getMessage(), e);
}
return null;
}
|
diff --git a/src/de/danoeh/antennapod/opml/OpmlReader.java b/src/de/danoeh/antennapod/opml/OpmlReader.java
index 55ab74b2..6f16a8f3 100644
--- a/src/de/danoeh/antennapod/opml/OpmlReader.java
+++ b/src/de/danoeh/antennapod/opml/OpmlReader.java
@@ -1,82 +1,86 @@
package de.danoeh.antennapod.opml;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.util.Log;
import de.danoeh.antennapod.AppConfig;
/** Reads OPML documents. */
public class OpmlReader {
private static final String TAG = "OpmlReader";
// ATTRIBUTES
private boolean isInOpml = false;
private boolean isInBody = false;
private ArrayList<OpmlElement> elementList;
/**
* Reads an Opml document and returns a list of all OPML elements it can
* find
*
* @throws IOException
* @throws XmlPullParserException
*/
public ArrayList<OpmlElement> readDocument(Reader reader)
throws XmlPullParserException, IOException {
elementList = new ArrayList<OpmlElement>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(reader);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
if (AppConfig.DEBUG)
Log.d(TAG, "Reached beginning of document");
break;
case XmlPullParser.START_TAG:
if (xpp.getName().equals(OpmlSymbols.OPML)) {
isInOpml = true;
if (AppConfig.DEBUG)
Log.d(TAG, "Reached beginning of OPML tree.");
} else if (isInOpml && xpp.getName().equals(OpmlSymbols.BODY)) {
isInBody = true;
if (AppConfig.DEBUG)
Log.d(TAG, "Reached beginning of body tree.");
} else if (isInBody && xpp.getName().equals(OpmlSymbols.OUTLINE)) {
if (AppConfig.DEBUG)
Log.d(TAG, "Found new Opml element");
OpmlElement element = new OpmlElement();
element.setText(xpp.getAttributeValue(null, OpmlSymbols.TEXT));
element.setXmlUrl(xpp.getAttributeValue(null, OpmlSymbols.XMLURL));
element.setHtmlUrl(xpp.getAttributeValue(null, OpmlSymbols.HTMLURL));
element.setType(xpp.getAttributeValue(null, OpmlSymbols.TYPE));
if (element.getXmlUrl() != null) {
+ if (element.getText() == null) {
+ Log.i(TAG, "Opml element has no text attribute.");
+ element.setText(element.getXmlUrl());
+ }
elementList.add(element);
} else {
if (AppConfig.DEBUG)
Log.d(TAG,
"Skipping element because of missing xml url");
}
}
break;
}
eventType = xpp.next();
}
if (AppConfig.DEBUG)
Log.d(TAG, "Parsing finished.");
return elementList;
}
}
| true | true | public ArrayList<OpmlElement> readDocument(Reader reader)
throws XmlPullParserException, IOException {
elementList = new ArrayList<OpmlElement>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(reader);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
if (AppConfig.DEBUG)
Log.d(TAG, "Reached beginning of document");
break;
case XmlPullParser.START_TAG:
if (xpp.getName().equals(OpmlSymbols.OPML)) {
isInOpml = true;
if (AppConfig.DEBUG)
Log.d(TAG, "Reached beginning of OPML tree.");
} else if (isInOpml && xpp.getName().equals(OpmlSymbols.BODY)) {
isInBody = true;
if (AppConfig.DEBUG)
Log.d(TAG, "Reached beginning of body tree.");
} else if (isInBody && xpp.getName().equals(OpmlSymbols.OUTLINE)) {
if (AppConfig.DEBUG)
Log.d(TAG, "Found new Opml element");
OpmlElement element = new OpmlElement();
element.setText(xpp.getAttributeValue(null, OpmlSymbols.TEXT));
element.setXmlUrl(xpp.getAttributeValue(null, OpmlSymbols.XMLURL));
element.setHtmlUrl(xpp.getAttributeValue(null, OpmlSymbols.HTMLURL));
element.setType(xpp.getAttributeValue(null, OpmlSymbols.TYPE));
if (element.getXmlUrl() != null) {
elementList.add(element);
} else {
if (AppConfig.DEBUG)
Log.d(TAG,
"Skipping element because of missing xml url");
}
}
break;
}
eventType = xpp.next();
}
if (AppConfig.DEBUG)
Log.d(TAG, "Parsing finished.");
return elementList;
}
| public ArrayList<OpmlElement> readDocument(Reader reader)
throws XmlPullParserException, IOException {
elementList = new ArrayList<OpmlElement>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(reader);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
if (AppConfig.DEBUG)
Log.d(TAG, "Reached beginning of document");
break;
case XmlPullParser.START_TAG:
if (xpp.getName().equals(OpmlSymbols.OPML)) {
isInOpml = true;
if (AppConfig.DEBUG)
Log.d(TAG, "Reached beginning of OPML tree.");
} else if (isInOpml && xpp.getName().equals(OpmlSymbols.BODY)) {
isInBody = true;
if (AppConfig.DEBUG)
Log.d(TAG, "Reached beginning of body tree.");
} else if (isInBody && xpp.getName().equals(OpmlSymbols.OUTLINE)) {
if (AppConfig.DEBUG)
Log.d(TAG, "Found new Opml element");
OpmlElement element = new OpmlElement();
element.setText(xpp.getAttributeValue(null, OpmlSymbols.TEXT));
element.setXmlUrl(xpp.getAttributeValue(null, OpmlSymbols.XMLURL));
element.setHtmlUrl(xpp.getAttributeValue(null, OpmlSymbols.HTMLURL));
element.setType(xpp.getAttributeValue(null, OpmlSymbols.TYPE));
if (element.getXmlUrl() != null) {
if (element.getText() == null) {
Log.i(TAG, "Opml element has no text attribute.");
element.setText(element.getXmlUrl());
}
elementList.add(element);
} else {
if (AppConfig.DEBUG)
Log.d(TAG,
"Skipping element because of missing xml url");
}
}
break;
}
eventType = xpp.next();
}
if (AppConfig.DEBUG)
Log.d(TAG, "Parsing finished.");
return elementList;
}
|
diff --git a/src/main/java/in/mDev/MiracleM4n/mChatSuite/commands/MECommandSender.java b/src/main/java/in/mDev/MiracleM4n/mChatSuite/commands/MECommandSender.java
index 829537e..a4846ba 100644
--- a/src/main/java/in/mDev/MiracleM4n/mChatSuite/commands/MECommandSender.java
+++ b/src/main/java/in/mDev/MiracleM4n/mChatSuite/commands/MECommandSender.java
@@ -1,278 +1,278 @@
package in.mDev.MiracleM4n.mChatSuite.commands;
import in.mDev.MiracleM4n.mChatSuite.mChatSuite;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.getspout.spoutapi.player.SpoutPlayer;
public class MECommandSender implements CommandExecutor {
mChatSuite plugin;
public MECommandSender(mChatSuite plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
String commandName = command.getName();
if (!plugin.mChatEB) {
sender.sendMessage(formatMessage(plugin.getAPI().addColour("mChatEssentials' functions are currently disabled.")));
return true;
}
if (commandName.equalsIgnoreCase("mchatme")) {
if (args.length > 0) {
String message = "";
for (String arg : args)
message += " " + arg;
message = message.trim();
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.getAPI().checkPermissions(player, "mchat.me"))
plugin.getServer().broadcastMessage(plugin.getAPI().ParseMe(player, message));
else
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
} else {
String senderName = "Console";
plugin.getServer().broadcastMessage("* " + senderName + " " + message);
plugin.getAPI().log("* " + senderName + " " + message);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatwho")) {
if (args.length > 0) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.who")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
} else {
Player receiver = plugin.getServer().getPlayer(args[0]);
formatWho(sender, receiver);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatafk")) {
String message = " Away From Keyboard";
if (args.length > 0) {
message = "";
for (String arg : args)
message += " " + arg;
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.isAFK.get(player.getName()) != null)
if (plugin.isAFK.get(player.getName()))
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + player.getName());
if (!plugin.getAPI().checkPermissions(player, "mchat.afk")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + sender.getName() + message);
return true;
} else {
plugin.getAPI().log(formatMessage("Console's can't be AFK."));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatafkother")) {
String message = " Away From Keyboard";
if (args.length > 1) {
message = "";
for (int i = 1; i < args.length; ++i)
message += " " + args[i];
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.afkother")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
}
Player afkTarget = plugin.getServer().getPlayer(args[0]);
if (plugin.isAFK.get(afkTarget.getName()) != null &&
plugin.isAFK.get(afkTarget.getName())) {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("noLongerAFK"), Material.PAPER);
else
players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("notAFK"));
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget));
} else
plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("notAFK"));
afkTarget.setSleepingIgnored(false);
plugin.isAFK.put(afkTarget.getName(), false);
if (plugin.useAFKList)
if (plugin.getAPI().ParseTabbedList(afkTarget).length() > 15) {
String pLName = plugin.getAPI().ParseTabbedList(afkTarget);
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
afkTarget.setPlayerListName(plugin.getAPI().ParseTabbedList(afkTarget));
return true;
} else {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("isAFK"), Material.PAPER);
else
players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget));
} else
plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
afkTarget.setSleepingIgnored(true);
plugin.isAFK.put(afkTarget.getName(), true);
plugin.AFKLoc.put(afkTarget.getName(), afkTarget.getLocation());
if (plugin.useAFKList)
- if (("[" + plugin.getLocale().getOption("AFK") + "] " + plugin.getAPI().ParseTabbedList(afkTarget)).length() > 15) {
+ if ((plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget)).length() > 15) {
String pLName = plugin.getAPI().addColour("[<gold>" + plugin.getLocale().getOption("AFK") + "] " + afkTarget);
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
afkTarget.setPlayerListName(plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatlist")) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.list")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
// My Way
// sender.sendMessage(plugin.getAPI().addColour("&4" + plugin.getLocale().pOffline + ": &8" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers()));
// Waxdt's Way
sender.sendMessage(plugin.getAPI().addColour("&6-- There are &8" + plugin.getServer().getOnlinePlayers().length + "&6 out of the maximum of &8" + plugin.getServer().getMaxPlayers() + "&6 Players online. --"));
formatList(sender);
return true;
}
return false;
}
void formatList(CommandSender sender) {
String msg = "";
String[] msgS;
for (Player players : plugin.getServer().getOnlinePlayers()) {
String iVar = plugin.getInfoReader().getInfo(players, plugin.listVar);
String mName = plugin.getAPI().ParseListCmd(players.getName());
if (iVar.isEmpty())
continue;
if (plugin.isAFK.get(players.getName())) {
if (msg.contains(iVar + ": &f")) {
msg = msg.replace(iVar + ": &f", iVar + ": &f&4[" + plugin.getLocale().getOption("AFK") + "]" + mName + "&f, &f");
} else {
msg += (iVar + ": &f&4[" + plugin.getLocale().getOption("AFK") + "]" + mName + "&f, &f" + '\n');
}
} else {
if (msg.contains(iVar + ": &f")) {
msg = msg.replace(iVar + ": &f", iVar + ": &f" + mName + "&f, &f");
} else {
msg += (iVar + ": &f" + mName + "&f, &f" + '\n');
}
}
if (!msg.contains("" + '\n'))
msg += '\n';
}
if (msg.contains("" + '\n')) {
msgS = msg.split("" + '\n');
for (String arg : msgS) {
sender.sendMessage(plugin.getAPI().addColour(arg));
}
sender.sendMessage(plugin.getAPI().addColour("&6-------------------------"));
return;
}
sender.sendMessage(plugin.getAPI().addColour(msg));
}
void formatWho(CommandSender sender, Player recipient) {
String recipientName = plugin.getAPI().ParsePlayerName(recipient);
Integer locX = (int) recipient.getLocation().getX();
Integer locY = (int) recipient.getLocation().getY();
Integer locZ = (int) recipient.getLocation().getZ();
String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
String world = recipient.getWorld().getName();
sender.sendMessage(plugin.getAPI().addColour(plugin.getLocale().getOption("player") + " Name: " + recipient.getName()));
sender.sendMessage(plugin.getAPI().addColour("Display Name: " + recipient.getDisplayName()));
sender.sendMessage(plugin.getAPI().addColour("Formatted Name: " + recipientName));
sender.sendMessage(plugin.getAPI().addColour(plugin.getLocale().getOption("player") + "'s Location: [ " + loc + " ]"));
sender.sendMessage(plugin.getAPI().addColour(plugin.getLocale().getOption("player") + "'s World: " + world));
sender.sendMessage(plugin.getAPI().addColour(plugin.getLocale().getOption("player") + "'s Health: " + plugin.getAPI().healthBar(recipient) + " " + recipient.getHealth() + "/20"));
sender.sendMessage(plugin.getAPI().addColour(plugin.getLocale().getOption("player") + "'s IP: " + recipient.getAddress().toString().replace("/", "")));
sender.sendMessage(plugin.getAPI().addColour("Current Item: " + recipient.getItemInHand().getType().name()));
sender.sendMessage(plugin.getAPI().addColour("Entity ID: #" + recipient.getEntityId()));
}
String formatMessage(String message) {
return (plugin.getAPI().addColour("&4[" + (plugin.pdfFile.getName()) + "] " + message));
}
String formatPNF(String playerNotFound) {
return (plugin.getAPI().addColour(formatMessage("") + " " + plugin.getLocale().getOption("player") + " &e" + playerNotFound + " &4" + plugin.getLocale().getOption("notFound")));
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
String commandName = command.getName();
if (!plugin.mChatEB) {
sender.sendMessage(formatMessage(plugin.getAPI().addColour("mChatEssentials' functions are currently disabled.")));
return true;
}
if (commandName.equalsIgnoreCase("mchatme")) {
if (args.length > 0) {
String message = "";
for (String arg : args)
message += " " + arg;
message = message.trim();
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.getAPI().checkPermissions(player, "mchat.me"))
plugin.getServer().broadcastMessage(plugin.getAPI().ParseMe(player, message));
else
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
} else {
String senderName = "Console";
plugin.getServer().broadcastMessage("* " + senderName + " " + message);
plugin.getAPI().log("* " + senderName + " " + message);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatwho")) {
if (args.length > 0) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.who")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
} else {
Player receiver = plugin.getServer().getPlayer(args[0]);
formatWho(sender, receiver);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatafk")) {
String message = " Away From Keyboard";
if (args.length > 0) {
message = "";
for (String arg : args)
message += " " + arg;
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.isAFK.get(player.getName()) != null)
if (plugin.isAFK.get(player.getName()))
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + player.getName());
if (!plugin.getAPI().checkPermissions(player, "mchat.afk")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + sender.getName() + message);
return true;
} else {
plugin.getAPI().log(formatMessage("Console's can't be AFK."));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatafkother")) {
String message = " Away From Keyboard";
if (args.length > 1) {
message = "";
for (int i = 1; i < args.length; ++i)
message += " " + args[i];
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.afkother")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
}
Player afkTarget = plugin.getServer().getPlayer(args[0]);
if (plugin.isAFK.get(afkTarget.getName()) != null &&
plugin.isAFK.get(afkTarget.getName())) {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("noLongerAFK"), Material.PAPER);
else
players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("notAFK"));
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget));
} else
plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("notAFK"));
afkTarget.setSleepingIgnored(false);
plugin.isAFK.put(afkTarget.getName(), false);
if (plugin.useAFKList)
if (plugin.getAPI().ParseTabbedList(afkTarget).length() > 15) {
String pLName = plugin.getAPI().ParseTabbedList(afkTarget);
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
afkTarget.setPlayerListName(plugin.getAPI().ParseTabbedList(afkTarget));
return true;
} else {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("isAFK"), Material.PAPER);
else
players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget));
} else
plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
afkTarget.setSleepingIgnored(true);
plugin.isAFK.put(afkTarget.getName(), true);
plugin.AFKLoc.put(afkTarget.getName(), afkTarget.getLocation());
if (plugin.useAFKList)
if (("[" + plugin.getLocale().getOption("AFK") + "] " + plugin.getAPI().ParseTabbedList(afkTarget)).length() > 15) {
String pLName = plugin.getAPI().addColour("[<gold>" + plugin.getLocale().getOption("AFK") + "] " + afkTarget);
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
afkTarget.setPlayerListName(plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatlist")) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.list")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
// My Way
// sender.sendMessage(plugin.getAPI().addColour("&4" + plugin.getLocale().pOffline + ": &8" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers()));
// Waxdt's Way
sender.sendMessage(plugin.getAPI().addColour("&6-- There are &8" + plugin.getServer().getOnlinePlayers().length + "&6 out of the maximum of &8" + plugin.getServer().getMaxPlayers() + "&6 Players online. --"));
formatList(sender);
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
String commandName = command.getName();
if (!plugin.mChatEB) {
sender.sendMessage(formatMessage(plugin.getAPI().addColour("mChatEssentials' functions are currently disabled.")));
return true;
}
if (commandName.equalsIgnoreCase("mchatme")) {
if (args.length > 0) {
String message = "";
for (String arg : args)
message += " " + arg;
message = message.trim();
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.getAPI().checkPermissions(player, "mchat.me"))
plugin.getServer().broadcastMessage(plugin.getAPI().ParseMe(player, message));
else
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
} else {
String senderName = "Console";
plugin.getServer().broadcastMessage("* " + senderName + " " + message);
plugin.getAPI().log("* " + senderName + " " + message);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatwho")) {
if (args.length > 0) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.who")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
} else {
Player receiver = plugin.getServer().getPlayer(args[0]);
formatWho(sender, receiver);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatafk")) {
String message = " Away From Keyboard";
if (args.length > 0) {
message = "";
for (String arg : args)
message += " " + arg;
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.isAFK.get(player.getName()) != null)
if (plugin.isAFK.get(player.getName()))
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + player.getName());
if (!plugin.getAPI().checkPermissions(player, "mchat.afk")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + sender.getName() + message);
return true;
} else {
plugin.getAPI().log(formatMessage("Console's can't be AFK."));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatafkother")) {
String message = " Away From Keyboard";
if (args.length > 1) {
message = "";
for (int i = 1; i < args.length; ++i)
message += " " + args[i];
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.afkother")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
}
Player afkTarget = plugin.getServer().getPlayer(args[0]);
if (plugin.isAFK.get(afkTarget.getName()) != null &&
plugin.isAFK.get(afkTarget.getName())) {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("noLongerAFK"), Material.PAPER);
else
players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("notAFK"));
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget));
} else
plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("notAFK"));
afkTarget.setSleepingIgnored(false);
plugin.isAFK.put(afkTarget.getName(), false);
if (plugin.useAFKList)
if (plugin.getAPI().ParseTabbedList(afkTarget).length() > 15) {
String pLName = plugin.getAPI().ParseTabbedList(afkTarget);
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
afkTarget.setPlayerListName(plugin.getAPI().ParseTabbedList(afkTarget));
return true;
} else {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("isAFK"), Material.PAPER);
else
players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget));
} else
plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
afkTarget.setSleepingIgnored(true);
plugin.isAFK.put(afkTarget.getName(), true);
plugin.AFKLoc.put(afkTarget.getName(), afkTarget.getLocation());
if (plugin.useAFKList)
if ((plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget)).length() > 15) {
String pLName = plugin.getAPI().addColour("[<gold>" + plugin.getLocale().getOption("AFK") + "] " + afkTarget);
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
afkTarget.setPlayerListName(plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatlist")) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.list")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
// My Way
// sender.sendMessage(plugin.getAPI().addColour("&4" + plugin.getLocale().pOffline + ": &8" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers()));
// Waxdt's Way
sender.sendMessage(plugin.getAPI().addColour("&6-- There are &8" + plugin.getServer().getOnlinePlayers().length + "&6 out of the maximum of &8" + plugin.getServer().getMaxPlayers() + "&6 Players online. --"));
formatList(sender);
return true;
}
return false;
}
|
diff --git a/src/kfs/kfsDbi/kfsString.java b/src/kfs/kfsDbi/kfsString.java
index d692205..ddc58dd 100644
--- a/src/kfs/kfsDbi/kfsString.java
+++ b/src/kfs/kfsDbi/kfsString.java
@@ -1,123 +1,123 @@
package kfs.kfsDbi;
import java.io.UnsupportedEncodingException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author pavedrim
*/
public class kfsString extends kfsColObject implements kfsDbiColumnComparator {
protected static final String defaultCharSet = "UTF-8";
private static final Logger l = Logger.getLogger(kfsString.class.getName());
private final int maxLength;
private final String charset;
public kfsString(final String name, final String label, final int maxLength, final int position) {
this(name, label, maxLength, position, defaultCharSet);
}
public kfsString(final String name, final String label, final int maxLength, final int position, final String charset) {
super(name, label, position, true);
this.maxLength = maxLength;
this.charset = charset;
}
public void setData(String data, kfsRowData row) {
setString(data, row);
}
public String getData(kfsRowData row) {
return getString(row);
}
public String getString(kfsRowData row) {
Object o = super.getObject(row);
return (o == null) ? "" : (String) o;
}
public void setString(String data, kfsRowData row) {
if (data == null) {
super.setObject("", row);
} else {
data = data.trim();
if (data.length() > this.maxLength) {
l.log(Level.WARNING, "kfsString.{0}({1}) try to set longer text ({2}): {3}", //
new Object[]{getColumnName(), maxLength, data.length(), data});
- super.setObject(data.substring(1, maxLength), row);
+ super.setObject(data.substring(0, maxLength), row);
} else {
super.setObject(data, row);
}
}
}
public String getStringHead(kfsRowData rd, int shortTxtLen) {
String s = getString(rd);
if (s.length() < shortTxtLen) {
return s.replaceAll("\\p{Cntrl}", ".");
}
return s.substring(0, shortTxtLen - 3).replaceAll("\\p{Cntrl}", ".") + "...";
}
/*
* public String getString() { return data; }
*
* public String getStringStriped() { return data.replaceAll("\\s+", " "); }
*/
@Override
public String getColumnCreateTable(kfsDbServerType serverType) {
switch (serverType) {
case kfsDbiOracle:
return getColumnName() + " VARCHAR(" + maxLength + ") ";
case kfsDbiMysql:
return getColumnName() + " VARCHAR(" + maxLength + ") CHARACTER SET utf8 ";
case kfsDbiPostgre:
case kfsDbiSqlite:
return getColumnName() + " VARCHAR(" + maxLength + ") ";
}
return null;
}
public int getColumnMaxLength() {
return maxLength;
}
@Override
public void setParam(int inx, PreparedStatement ps, kfsRowData data) throws SQLException {
ps.setString(inx, getString(data));
}
@Override
public void getParam(int inx, ResultSet ps, kfsRowData row) throws SQLException {
try {
byte[] strb = ps.getBytes(inx);
if (strb == null) {
setString("", row);
} else {
setString(new String(strb, charset), row);
}
} catch (UnsupportedEncodingException ex) {
l.log(Level.SEVERE, "Error in getParam + " + inx, ex);
}
}
@Override
public Class<?> getColumnJavaClass() {
return String.class;
}
@Override
public Object getObject(kfsRowData row) {
return ((String) super.getObject(row)).replaceAll("\\p{Cntrl}", ".");
}
@Override
public int compare(kfsRowData t, kfsRowData t1) {
return getSortDirection() * getData(t).compareTo(getData(t1));
}
}
| true | true | public void setString(String data, kfsRowData row) {
if (data == null) {
super.setObject("", row);
} else {
data = data.trim();
if (data.length() > this.maxLength) {
l.log(Level.WARNING, "kfsString.{0}({1}) try to set longer text ({2}): {3}", //
new Object[]{getColumnName(), maxLength, data.length(), data});
super.setObject(data.substring(1, maxLength), row);
} else {
super.setObject(data, row);
}
}
}
| public void setString(String data, kfsRowData row) {
if (data == null) {
super.setObject("", row);
} else {
data = data.trim();
if (data.length() > this.maxLength) {
l.log(Level.WARNING, "kfsString.{0}({1}) try to set longer text ({2}): {3}", //
new Object[]{getColumnName(), maxLength, data.length(), data});
super.setObject(data.substring(0, maxLength), row);
} else {
super.setObject(data, row);
}
}
}
|
diff --git a/org.caleydo.core/src/org/caleydo/core/data/collection/Histogram.java b/org.caleydo.core/src/org/caleydo/core/data/collection/Histogram.java
index ceb0db07e..d7f8223ee 100644
--- a/org.caleydo.core/src/org/caleydo/core/data/collection/Histogram.java
+++ b/org.caleydo.core/src/org/caleydo/core/data/collection/Histogram.java
@@ -1,169 +1,169 @@
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.core.data.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import com.google.common.collect.ImmutableSortedSet;
/**
* Histogram holds the data structure of a histogram. It is based on an ArrayList<Integer> and maps the relevant
* functions directly. It adds the functionality of keeping score of the biggest element.
* <p>
* The buckets have a unique ID across all instances of Histogram. This id is a running increment starting with
* {@link #firstBucketID}.
* </p>
*
* @author Alexander Lex
*/
public class Histogram {
/** Static counter for buckets to guarantee unique bucket IDs */
private static int bucketCounter = 0;
/**
* One entry per bucket in the list, the value of a cell corresponds to the number of buckets + one for the nans
*/
private final int[] histogram;
/**
* Contains the IDs of the elements in the buckets in the ArrayList and an Identifier as the first member of the
* pair. Same order as {@link #histogram}.
*/
private final List<SortedSet<Integer>> ids;
private int sizeOfBiggestBucket = -1;
/** The id of the first bucket in this histogram instance. */
private final int firstBucketID;
private final int nanIndex;
/**
* Constructor initializing the Histogram with the specified number of buckets
*
* @param numberOfBuckets
* the number of buckets in the histogram
*/
public Histogram(int numberOfBuckets) {
synchronized (this) {
firstBucketID = bucketCounter;
bucketCounter += numberOfBuckets;
}
histogram = new int[numberOfBuckets + 1];
ids = new ArrayList<>(numberOfBuckets + 1);
nanIndex = numberOfBuckets;
- for (int i = 0; i < ids.size(); i++) {
+ for (int i = 0; i < histogram.length; i++) {
ids.add(new TreeSet<Integer>());
}
}
/**
* optimize the data structure to be immutable
*
* @return
*/
public Histogram optimize() {
// optimize the data structures to immutables for faster access
for (int i = 0; i < ids.size(); ++i) {
ids.set(i, ImmutableSortedSet.copyOf(ids.get(i)));
}
return this;
}
/**
* Adds one to the bucket at the specified bucketNumber. Adds the id to the ids associated with this bucket.
*
* @param bucketNumber
* the bucket in which to increase the number of elements
* @param value
* the value to set at the index
* @return the value previously at this position
*/
public void add(int bucketNumber, Integer objectID) {
int act = histogram[bucketNumber];
histogram[bucketNumber] = ++act;
if (act > sizeOfBiggestBucket)
sizeOfBiggestBucket = act;
ids.get(bucketNumber).add(objectID);
// histogram.set(index, value);
}
/** Adds an object to the dedicated NaN bucket. */
public void addNAN(Integer objectID) {
add(nanIndex, objectID);
}
/**
* Returns the value of the histogram at the specified index.
*
* @param bucketNumber
* @return
*/
public int get(int bucketNumber) {
return histogram[bucketNumber];
}
/**
* @return the nanCount, see {@link #nanCount}
*/
public int getNanCount() {
return get(nanIndex);
}
/**
* @return the nanIDs, see {@link #nanIDs}
*/
public SortedSet<Integer> getNanIDs() {
return getIDsForBucket(nanIndex);
}
public Integer getBucketID(int bucketNumber) {
return Integer.valueOf(bucketNumber + firstBucketID);
}
public SortedSet<Integer> getIDsForBucketFromBucketID(Integer bucketID) {
return getIDsForBucket(bucketID - firstBucketID);
}
public SortedSet<Integer> getIDsForBucket(int bucketNumber) {
return ids.get(bucketNumber);
}
/**
* The size of the histogram
*
* @return the size
*/
public int size() {
return histogram.length - 1; // for nan
}
/**
* The largest value in the histogram
*
* @return the largest value
*/
public int getLargestValue() {
return sizeOfBiggestBucket;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Histogram [histogram=");
builder.append(Arrays.toString(histogram));
builder.append("]");
return builder.toString();
}
}
| true | true | public Histogram(int numberOfBuckets) {
synchronized (this) {
firstBucketID = bucketCounter;
bucketCounter += numberOfBuckets;
}
histogram = new int[numberOfBuckets + 1];
ids = new ArrayList<>(numberOfBuckets + 1);
nanIndex = numberOfBuckets;
for (int i = 0; i < ids.size(); i++) {
ids.add(new TreeSet<Integer>());
}
}
| public Histogram(int numberOfBuckets) {
synchronized (this) {
firstBucketID = bucketCounter;
bucketCounter += numberOfBuckets;
}
histogram = new int[numberOfBuckets + 1];
ids = new ArrayList<>(numberOfBuckets + 1);
nanIndex = numberOfBuckets;
for (int i = 0; i < histogram.length; i++) {
ids.add(new TreeSet<Integer>());
}
}
|
diff --git a/org.epic.debug/src/org/epic/debug/db/RE.java b/org.epic.debug/src/org/epic/debug/db/RE.java
index cdb799c3..9222f305 100644
--- a/org.epic.debug/src/org/epic/debug/db/RE.java
+++ b/org.epic.debug/src/org/epic/debug/db/RE.java
@@ -1,57 +1,57 @@
package org.epic.debug.db;
import gnu.regexp.REException;
import gnu.regexp.RESyntax;
/**
* Regular expressions used for parsing "perl -d" output
*/
class RE
{
final gnu.regexp.RE CMD_FINISHED1;
final gnu.regexp.RE CMD_FINISHED2;
final gnu.regexp.RE SESSION_FINISHED1;
final gnu.regexp.RE SESSION_FINISHED2;
final gnu.regexp.RE IP_POS;
final gnu.regexp.RE IP_POS_EVAL;
final gnu.regexp.RE IP_POS_CODE;
final gnu.regexp.RE SWITCH_FILE_FAIL;
final gnu.regexp.RE SET_LINE_BREAKPOINT;
final gnu.regexp.RE STACK_TRACE;
final gnu.regexp.RE ENTER_FRAME;
final gnu.regexp.RE EXIT_FRAME;
public RE()
{
CMD_FINISHED1 = newRE("\n\\s+DB<+\\d+>+", false);
CMD_FINISHED2 = newRE("^\\s+DB<\\d+>", false);
SESSION_FINISHED1 = newRE("Use `q' to quit or `R' to restart", false);
SESSION_FINISHED2 = newRE("Debugged program terminated.", false);
IP_POS = newRE("^[^\\(]*\\((.*):(\\d+)\\):[\\n\\t]", false);
IP_POS_EVAL = newRE("^[^\\(]*\\(eval\\s+\\d+\\)\\[(.*):(\\d+)\\]$", false);
- IP_POS_CODE = newRE("^.*CODE\\(0x[0-9a-fA-F]+\\)\\(([^:]*):(\\d+)\\):[\\n\\t]", false);
+ IP_POS_CODE = newRE("^.*CODE\\(0x[0-9a-fA-F]+\\)\\((.*):(\\d+)\\):[\\n\\t]", false);
SWITCH_FILE_FAIL = newRE("^No file", false);
SET_LINE_BREAKPOINT = newRE("^Line \\d+ not breakable", false);
ENTER_FRAME = newRE("^\\s*entering", false);
EXIT_FRAME = newRE("^\\s*exited", false);
STACK_TRACE = newRE(
"(.)\\s+=\\s+(.*)called from .* \\`([^\\']+)\\'\\s*line (\\d+)\\s*",
false);
}
private gnu.regexp.RE newRE(String re, boolean multiline)
{
try
{
return new gnu.regexp.RE(
re,
multiline ? gnu.regexp.RE.REG_MULTILINE : 0,
RESyntax.RE_SYNTAX_PERL5);
}
catch (REException e)
{
// we have a bug in the constructor
throw new RuntimeException(e);
}
}
}
| true | true | public RE()
{
CMD_FINISHED1 = newRE("\n\\s+DB<+\\d+>+", false);
CMD_FINISHED2 = newRE("^\\s+DB<\\d+>", false);
SESSION_FINISHED1 = newRE("Use `q' to quit or `R' to restart", false);
SESSION_FINISHED2 = newRE("Debugged program terminated.", false);
IP_POS = newRE("^[^\\(]*\\((.*):(\\d+)\\):[\\n\\t]", false);
IP_POS_EVAL = newRE("^[^\\(]*\\(eval\\s+\\d+\\)\\[(.*):(\\d+)\\]$", false);
IP_POS_CODE = newRE("^.*CODE\\(0x[0-9a-fA-F]+\\)\\(([^:]*):(\\d+)\\):[\\n\\t]", false);
SWITCH_FILE_FAIL = newRE("^No file", false);
SET_LINE_BREAKPOINT = newRE("^Line \\d+ not breakable", false);
ENTER_FRAME = newRE("^\\s*entering", false);
EXIT_FRAME = newRE("^\\s*exited", false);
STACK_TRACE = newRE(
"(.)\\s+=\\s+(.*)called from .* \\`([^\\']+)\\'\\s*line (\\d+)\\s*",
false);
}
| public RE()
{
CMD_FINISHED1 = newRE("\n\\s+DB<+\\d+>+", false);
CMD_FINISHED2 = newRE("^\\s+DB<\\d+>", false);
SESSION_FINISHED1 = newRE("Use `q' to quit or `R' to restart", false);
SESSION_FINISHED2 = newRE("Debugged program terminated.", false);
IP_POS = newRE("^[^\\(]*\\((.*):(\\d+)\\):[\\n\\t]", false);
IP_POS_EVAL = newRE("^[^\\(]*\\(eval\\s+\\d+\\)\\[(.*):(\\d+)\\]$", false);
IP_POS_CODE = newRE("^.*CODE\\(0x[0-9a-fA-F]+\\)\\((.*):(\\d+)\\):[\\n\\t]", false);
SWITCH_FILE_FAIL = newRE("^No file", false);
SET_LINE_BREAKPOINT = newRE("^Line \\d+ not breakable", false);
ENTER_FRAME = newRE("^\\s*entering", false);
EXIT_FRAME = newRE("^\\s*exited", false);
STACK_TRACE = newRE(
"(.)\\s+=\\s+(.*)called from .* \\`([^\\']+)\\'\\s*line (\\d+)\\s*",
false);
}
|
diff --git a/src/main/java/com/censoredsoftware/demigods/ability/passive/RainbowHorse.java b/src/main/java/com/censoredsoftware/demigods/ability/passive/RainbowHorse.java
index c5f301fb..aa055345 100644
--- a/src/main/java/com/censoredsoftware/demigods/ability/passive/RainbowHorse.java
+++ b/src/main/java/com/censoredsoftware/demigods/ability/passive/RainbowHorse.java
@@ -1,126 +1,123 @@
package com.censoredsoftware.demigods.ability.passive;
import com.censoredsoftware.demigods.Demigods;
import com.censoredsoftware.demigods.ability.Ability;
import com.censoredsoftware.demigods.player.Pet;
import com.censoredsoftware.demigods.util.Randoms;
import com.google.common.collect.Lists;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Horse;
import org.bukkit.event.Listener;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List;
public class RainbowHorse implements Ability
{
private final static String name = "Horse of a Different Color", command = null;
private final static int cost = 0, delay = 0, repeat = 100;
private final static Devotion.Type type = Devotion.Type.PASSIVE;
private final static List<String> details = Lists.newArrayList("All of you horse are belong to us.");
private String deity, permission;
public RainbowHorse(String deity, String permission)
{
this.deity = deity;
this.permission = permission;
}
@Override
public String getDeity()
{
return deity;
}
@Override
public String getName()
{
return name;
}
@Override
public String getCommand()
{
return command;
}
@Override
public String getPermission()
{
return permission;
}
@Override
public int getCost()
{
return cost;
}
@Override
public int getDelay()
{
return delay;
}
@Override
public int getRepeat()
{
return repeat;
}
@Override
public List<String> getDetails()
{
return details;
}
@Override
public Devotion.Type getType()
{
return type;
}
@Override
public Material getWeapon()
{
return null;
}
@Override
public boolean hasWeapon()
{
return getWeapon() != null;
}
@Override
public Listener getListener()
{
return null;
}
@Override
public BukkitRunnable getRunnable()
{
return new BukkitRunnable()
{
@Override
public void run()
{
for(Pet horse : Pet.Util.findByType(EntityType.HORSE))
{
- if(Demigods.isDisabledWorld(horse.getCurrentLocation().getWorld())) return;
- if(horse.getDeity().getName().equals("DrD1sco") && horse.getEntity() != null && !horse.getEntity().isDead())
- {
- ((Horse) horse.getEntity()).setColor(getRandomHorseColor());
- }
+ if(horse.getCurrentLocation() == null || Demigods.isDisabledWorld(horse.getCurrentLocation().getWorld())) return;
+ if(horse.getDeity().getName().equals("DrD1sco") && horse.getEntity() != null && !horse.getEntity().isDead()) ((Horse) horse.getEntity()).setColor(getRandomHorseColor());
}
}
private Horse.Color getRandomHorseColor()
{
return Lists.newArrayList(Horse.Color.values()).get(Randoms.generateIntRange(0, 5));
}
};
}
}
| true | true | public BukkitRunnable getRunnable()
{
return new BukkitRunnable()
{
@Override
public void run()
{
for(Pet horse : Pet.Util.findByType(EntityType.HORSE))
{
if(Demigods.isDisabledWorld(horse.getCurrentLocation().getWorld())) return;
if(horse.getDeity().getName().equals("DrD1sco") && horse.getEntity() != null && !horse.getEntity().isDead())
{
((Horse) horse.getEntity()).setColor(getRandomHorseColor());
}
}
}
private Horse.Color getRandomHorseColor()
{
return Lists.newArrayList(Horse.Color.values()).get(Randoms.generateIntRange(0, 5));
}
};
}
| public BukkitRunnable getRunnable()
{
return new BukkitRunnable()
{
@Override
public void run()
{
for(Pet horse : Pet.Util.findByType(EntityType.HORSE))
{
if(horse.getCurrentLocation() == null || Demigods.isDisabledWorld(horse.getCurrentLocation().getWorld())) return;
if(horse.getDeity().getName().equals("DrD1sco") && horse.getEntity() != null && !horse.getEntity().isDead()) ((Horse) horse.getEntity()).setColor(getRandomHorseColor());
}
}
private Horse.Color getRandomHorseColor()
{
return Lists.newArrayList(Horse.Color.values()).get(Randoms.generateIntRange(0, 5));
}
};
}
|
diff --git a/org.maven.ide.eclipse/src/org/maven/ide/eclipse/internal/repository/RepositoryRegistry.java b/org.maven.ide.eclipse/src/org/maven/ide/eclipse/internal/repository/RepositoryRegistry.java
index 1f1b8c88..cc5e744d 100644
--- a/org.maven.ide.eclipse/src/org/maven/ide/eclipse/internal/repository/RepositoryRegistry.java
+++ b/org.maven.ide.eclipse/src/org/maven/ide/eclipse/internal/repository/RepositoryRegistry.java
@@ -1,320 +1,320 @@
/*******************************************************************************
* Copyright (c) 2008 Sonatype, 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
*******************************************************************************/
package org.maven.ide.eclipse.internal.repository;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.settings.Mirror;
import org.apache.maven.settings.Server;
import org.apache.maven.settings.Settings;
import org.apache.maven.wagon.authentication.AuthenticationInfo;
import org.maven.ide.eclipse.core.MavenLogger;
import org.maven.ide.eclipse.embedder.ArtifactRepositoryRef;
import org.maven.ide.eclipse.embedder.IMaven;
import org.maven.ide.eclipse.embedder.ISettingsChangeListener;
import org.maven.ide.eclipse.project.IMavenProjectChangedListener;
import org.maven.ide.eclipse.project.IMavenProjectFacade;
import org.maven.ide.eclipse.project.MavenProjectChangedEvent;
import org.maven.ide.eclipse.project.MavenProjectManager;
import org.maven.ide.eclipse.repository.IRepository;
import org.maven.ide.eclipse.repository.IRepositoryRegistry;
/**
* RepositoryRegistry
*
* @author igor
*/
public class RepositoryRegistry implements IRepositoryRegistry, IMavenProjectChangedListener, ISettingsChangeListener {
private final IMaven maven;
private final MavenProjectManager projectManager;
/**
* Maps repositoryUrl to IndexInfo of repository index
*/
private final Map<String, RepositoryInfo> repositories = new ConcurrentHashMap<String, RepositoryInfo>();
/**
* Lazy instantiated local repository instance.
*/
private RepositoryInfo localRepository;
/**
* Lock guarding lazy instantiation of localRepository instance
*/
private final Object localRepositoryLock = new Object();
private final RepositoryInfo workspaceRepository;
private ArrayList<IRepositoryIndexer> indexers = new ArrayList<IRepositoryIndexer>();
private ArrayList<IRepositoryDiscoverer> discoverers = new ArrayList<IRepositoryDiscoverer>();
private final RepositoryRegistryUpdateJob job = new RepositoryRegistryUpdateJob(this);
public RepositoryRegistry(IMaven maven, MavenProjectManager projectManager) {
this.maven = maven;
this.projectManager = projectManager;
this.workspaceRepository = new RepositoryInfo(null/*id*/, "workspace://"/*url*/, null/*basedir*/, SCOPE_WORKSPACE, null/*auth*/);
}
private RepositoryInfo newLocalRepositoryInfo() {
File localBasedir = new File(maven.getLocalRepositoryPath());
try {
localBasedir = localBasedir.getCanonicalFile();
} catch (IOException e) {
// will never happen
localBasedir = localBasedir.getAbsoluteFile();
}
String localUrl;
try {
localUrl = localBasedir.toURL().toExternalForm();
} catch(MalformedURLException ex) {
MavenLogger.log("Could not parse local repository path", ex);
localUrl = "file://" + localBasedir.getAbsolutePath();
}
// initialize local and workspace repositories
RepositoryInfo localRepository = new RepositoryInfo(null/*id*/, localUrl, localBasedir, SCOPE_LOCAL, null/*auth*/);
return localRepository;
}
public void mavenProjectChanged(MavenProjectChangedEvent[] events, IProgressMonitor monitor) {
/*
* This method is called while holding workspace lock. Avoid long-running operations if possible.
*/
Settings settings = null;
try {
settings = maven.getSettings();
} catch(CoreException ex) {
MavenLogger.log(ex);
}
for(MavenProjectChangedEvent event : events) {
IMavenProjectFacade oldFacade = event.getOldMavenProject();
if (oldFacade != null) {
removeProjectRepositories(oldFacade, monitor);
}
IMavenProjectFacade facade = event.getMavenProject();
if(facade != null) {
try {
addProjectRepositories(settings, facade, null /*asyncUpdate*/);
} catch(CoreException ex) {
MavenLogger.log(ex);
}
}
}
}
private void addProjectRepositories(Settings settings, IMavenProjectFacade facade, IProgressMonitor monitor) throws CoreException {
ArrayList<ArtifactRepositoryRef> repositories = getProjectRepositories(facade);
for (ArtifactRepositoryRef repo : repositories) {
RepositoryInfo repository = getRepository(repo);
if (repository != null) {
repository.addProject(facade.getPom().getFullPath());
continue;
}
AuthenticationInfo auth = getAuthenticationInfo(settings, repo.getId());
repository = new RepositoryInfo(repo.getId(), repo.getUrl(), SCOPE_PROJECT, auth);
repository.addProject(facade.getPom().getFullPath());
addRepository(repository, monitor);
}
}
public void addRepository(RepositoryInfo repository, IProgressMonitor monitor) {
if (!repositories.containsKey(repository.getUid())) {
repositories.put(repository.getUid(), repository);
for (IRepositoryIndexer indexer : indexers) {
try {
indexer.repositoryAdded(repository, monitor);
} catch (CoreException e) {
MavenLogger.log(e);
}
}
}
}
private void removeProjectRepositories(IMavenProjectFacade facade, IProgressMonitor monitor) {
ArrayList<ArtifactRepositoryRef> repositories = getProjectRepositories(facade);
for (ArtifactRepositoryRef repo : repositories) {
RepositoryInfo repository = getRepository(repo);
if (repository != null && repository.isScope(SCOPE_PROJECT)) {
repository.removeProject(facade.getPom().getFullPath());
if (repository.getProjects().isEmpty()) {
removeRepository(repository, monitor);
}
}
}
}
private void removeRepository(RepositoryInfo repository, IProgressMonitor monitor) {
repositories.remove(repository.getUid());
for (IRepositoryIndexer indexer : indexers) {
try {
indexer.repositoryRemoved(repository, monitor);
} catch (CoreException e) {
MavenLogger.log(e);
}
}
}
private ArrayList<ArtifactRepositoryRef> getProjectRepositories(IMavenProjectFacade facade) {
ArrayList<ArtifactRepositoryRef> repositories = new ArrayList<ArtifactRepositoryRef>();
repositories.addAll(facade.getArtifactRepositoryRefs());
repositories.addAll(facade.getPluginArtifactRepositoryRefs());
return repositories;
}
public AuthenticationInfo getAuthenticationInfo(Settings settings, String id) throws CoreException {
if (settings == null) {
return null;
}
Server server = settings.getServer(id);
if (server == null || server.getUsername() == null) {
return null;
}
server = maven.decryptPassword(server);
AuthenticationInfo info = new AuthenticationInfo();
info.setUserName(server.getUsername());
info.setPassword(server.getPassword());
return info;
}
public void updateRegistry(IProgressMonitor monitor) throws CoreException {
Settings settings = maven.getSettings();
List<Mirror> mirrors = maven.getMirrors();
// initialize indexers
for (IRepositoryIndexer indexer : indexers) {
indexer.initialize(monitor);
}
// process configured repositories
Map<String, RepositoryInfo> oldRepositories = new HashMap<String, RepositoryInfo>(repositories);
repositories.clear();
addRepository(this.workspaceRepository, monitor);
- synchronized(localRepository) {
+ synchronized(localRepositoryLock) {
this.localRepository = newLocalRepositoryInfo();
}
addRepository(this.localRepository, monitor);
// mirrors
for(Mirror mirror : mirrors) {
AuthenticationInfo auth = getAuthenticationInfo(settings, mirror.getId());
RepositoryInfo repository = new RepositoryInfo(mirror.getId(), mirror.getUrl(), SCOPE_SETTINGS, auth);
repository.setMirrorOf(mirror.getMirrorOf());
addRepository(repository, monitor);
}
// repositories from settings.xml
ArrayList<ArtifactRepository> repos = new ArrayList<ArtifactRepository>();
repos.addAll(maven.getArtifactRepositories(false));
repos.addAll(maven.getPluginArtifactRepositories(false));
for(ArtifactRepository repo : repos) {
Mirror mirror = maven.getMirror(repo);
AuthenticationInfo auth = getAuthenticationInfo(settings, repo.getId());
RepositoryInfo repository = new RepositoryInfo(repo.getId(), repo.getUrl(), SCOPE_SETTINGS, auth);
if (mirror != null) {
repository.setMirrorId(mirror.getId());
}
addRepository(repository, monitor);
}
// project-specific repositories
for (IMavenProjectFacade facade : projectManager.getProjects()) {
addProjectRepositories(settings, facade, monitor);
}
// custom repositories
for (IRepositoryDiscoverer discoverer : discoverers) {
discoverer.addRepositories(this, monitor);
}
oldRepositories.keySet().removeAll(repositories.keySet());
for (RepositoryInfo repository : oldRepositories.values()) {
removeRepository(repository, monitor);
}
}
public List<IRepository> getRepositories(int scope) {
ArrayList<IRepository> result = new ArrayList<IRepository>();
for (RepositoryInfo repository : repositories.values()) {
if (repository.isScope(scope)) {
result.add(repository);
}
}
return result;
}
public void updateRegistry() {
job.updateRegistry();
}
public void addRepositoryIndexer(IRepositoryIndexer indexer) {
this.indexers.add(indexer);
}
public void addRepositoryDiscoverer(IRepositoryDiscoverer discoverer) {
this.discoverers.add(discoverer);
}
public RepositoryInfo getRepository(ArtifactRepositoryRef ref) {
String uid = RepositoryInfo.getUid(ref.getId(), ref.getUrl(), ref.getUsername());
return repositories.get(uid);
}
public IRepository getWorkspaceRepository() {
return workspaceRepository;
}
public IRepository getLocalRepository() {
synchronized(localRepositoryLock) {
if(localRepository == null) {
localRepository = newLocalRepositoryInfo();
}
}
return localRepository;
}
public void settingsChanged(Settings settings) {
updateRegistry();
}
}
| true | true | public void updateRegistry(IProgressMonitor monitor) throws CoreException {
Settings settings = maven.getSettings();
List<Mirror> mirrors = maven.getMirrors();
// initialize indexers
for (IRepositoryIndexer indexer : indexers) {
indexer.initialize(monitor);
}
// process configured repositories
Map<String, RepositoryInfo> oldRepositories = new HashMap<String, RepositoryInfo>(repositories);
repositories.clear();
addRepository(this.workspaceRepository, monitor);
synchronized(localRepository) {
this.localRepository = newLocalRepositoryInfo();
}
addRepository(this.localRepository, monitor);
// mirrors
for(Mirror mirror : mirrors) {
AuthenticationInfo auth = getAuthenticationInfo(settings, mirror.getId());
RepositoryInfo repository = new RepositoryInfo(mirror.getId(), mirror.getUrl(), SCOPE_SETTINGS, auth);
repository.setMirrorOf(mirror.getMirrorOf());
addRepository(repository, monitor);
}
// repositories from settings.xml
ArrayList<ArtifactRepository> repos = new ArrayList<ArtifactRepository>();
repos.addAll(maven.getArtifactRepositories(false));
repos.addAll(maven.getPluginArtifactRepositories(false));
for(ArtifactRepository repo : repos) {
Mirror mirror = maven.getMirror(repo);
AuthenticationInfo auth = getAuthenticationInfo(settings, repo.getId());
RepositoryInfo repository = new RepositoryInfo(repo.getId(), repo.getUrl(), SCOPE_SETTINGS, auth);
if (mirror != null) {
repository.setMirrorId(mirror.getId());
}
addRepository(repository, monitor);
}
// project-specific repositories
for (IMavenProjectFacade facade : projectManager.getProjects()) {
addProjectRepositories(settings, facade, monitor);
}
// custom repositories
for (IRepositoryDiscoverer discoverer : discoverers) {
discoverer.addRepositories(this, monitor);
}
oldRepositories.keySet().removeAll(repositories.keySet());
for (RepositoryInfo repository : oldRepositories.values()) {
removeRepository(repository, monitor);
}
}
| public void updateRegistry(IProgressMonitor monitor) throws CoreException {
Settings settings = maven.getSettings();
List<Mirror> mirrors = maven.getMirrors();
// initialize indexers
for (IRepositoryIndexer indexer : indexers) {
indexer.initialize(monitor);
}
// process configured repositories
Map<String, RepositoryInfo> oldRepositories = new HashMap<String, RepositoryInfo>(repositories);
repositories.clear();
addRepository(this.workspaceRepository, monitor);
synchronized(localRepositoryLock) {
this.localRepository = newLocalRepositoryInfo();
}
addRepository(this.localRepository, monitor);
// mirrors
for(Mirror mirror : mirrors) {
AuthenticationInfo auth = getAuthenticationInfo(settings, mirror.getId());
RepositoryInfo repository = new RepositoryInfo(mirror.getId(), mirror.getUrl(), SCOPE_SETTINGS, auth);
repository.setMirrorOf(mirror.getMirrorOf());
addRepository(repository, monitor);
}
// repositories from settings.xml
ArrayList<ArtifactRepository> repos = new ArrayList<ArtifactRepository>();
repos.addAll(maven.getArtifactRepositories(false));
repos.addAll(maven.getPluginArtifactRepositories(false));
for(ArtifactRepository repo : repos) {
Mirror mirror = maven.getMirror(repo);
AuthenticationInfo auth = getAuthenticationInfo(settings, repo.getId());
RepositoryInfo repository = new RepositoryInfo(repo.getId(), repo.getUrl(), SCOPE_SETTINGS, auth);
if (mirror != null) {
repository.setMirrorId(mirror.getId());
}
addRepository(repository, monitor);
}
// project-specific repositories
for (IMavenProjectFacade facade : projectManager.getProjects()) {
addProjectRepositories(settings, facade, monitor);
}
// custom repositories
for (IRepositoryDiscoverer discoverer : discoverers) {
discoverer.addRepositories(this, monitor);
}
oldRepositories.keySet().removeAll(repositories.keySet());
for (RepositoryInfo repository : oldRepositories.values()) {
removeRepository(repository, monitor);
}
}
|
diff --git a/hadoop-src/edu/berkeley/gamesman/hadoop/TieredHadoopTool.java b/hadoop-src/edu/berkeley/gamesman/hadoop/TieredHadoopTool.java
index 929b0bf4..626a03b5 100644
--- a/hadoop-src/edu/berkeley/gamesman/hadoop/TieredHadoopTool.java
+++ b/hadoop-src/edu/berkeley/gamesman/hadoop/TieredHadoopTool.java
@@ -1,131 +1,131 @@
package edu.berkeley.gamesman.hadoop;
import java.io.IOException;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.Tool;
import edu.berkeley.gamesman.core.*;
import edu.berkeley.gamesman.database.util.SplitDatabaseWritable;
import edu.berkeley.gamesman.database.util.SplitDatabaseWritableList;
import edu.berkeley.gamesman.hadoop.util.*;
import edu.berkeley.gamesman.util.DebugFacility;
import edu.berkeley.gamesman.util.Util;
/**
* The TieredHadoopTool is the code that runs on the master node. It loops over
* all tiers, and for each tier, it sets "tier" in the JobConf. Then, it uses
* SequenceInputFormat to subdivide the hash space into a set of inputs for each
* mapper.
*
* @author Patrick Horn
*/
@SuppressWarnings("deprecation")
public class TieredHadoopTool extends Configured implements Tool {
edu.berkeley.gamesman.core.Configuration myConf;
public int run(String[] args) throws Exception {
Configuration conf = getConf();
assert Util.debug(DebugFacility.HADOOP,
"Hadoop launching with configuration " + args[0]);
myConf = edu.berkeley.gamesman.core.Configuration.load(Util
.decodeBase64(args[0]));
conf.set("configuration_data", args[0]);
conf.setStrings("args", args);
// Determine last index
TieredGame<?> g = Util.checkedCast(myConf.getGame());
int primitiveTier = g.numberOfTiers() - 1;
int tier = primitiveTier;
Util.debug(DebugFacility.HADOOP, "Processing first tier " + tier);
processRun(conf, tier, -1);
for (tier--; tier >= 0; tier--) {
processRun(conf, tier, tier+1);
}
FileSystem fs = FileSystem.get(conf);
SplitDatabaseWritableList allDatabases = new SplitDatabaseWritableList();
myConf.setProperty("gamesman.database", "SplitSolidDatabase");
allDatabases.setConf(myConf);
for (tier = 0; tier <= primitiveTier; tier++) {
SplitDatabaseWritableList thisTier = new SplitDatabaseWritableList();
FSDataInputStream di = fs.open(HadoopUtil.getTierIndexPath(conf, myConf, tier));
thisTier.readFields(di);
di.close();
for (SplitDatabaseWritable w : thisTier) {
w.setFilename(HadoopUtil.getTierDirectoryName(tier)+
"/"+w.getFilename());
allDatabases.add(w);
}
}
FSDataOutputStream dout = fs.create(new Path(HadoopUtil.getParentPath(conf, myConf), "index.db"));
allDatabases.write(dout);
dout.close();
return 0;
}
private void processRun(Configuration conf, int tier, int lastTier) throws IOException {
TieredHasher<?> h = Util.checkedCast(myConf.getHasher());
long firstHash = h.hashOffsetForTier(tier);
long endHash = h.hashOffsetForTier(tier+1);
JobConf job = new JobConf(conf, TierMap.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(HadoopSplitDatabaseWritable.class);
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(HadoopSplitDatabaseWritableList.class);
Util.debug(DebugFacility.HADOOP, "Processing tier " + tier+" from "+firstHash+" to "+endHash);
int numMappers = myConf.getInteger("gamesman.hadoop.numMappers", 60);
int minSplit = myConf.getInteger("gamesman.hadoop.minSplit",
myConf.getInteger("gamesman.minSplit", myConf.recordsPerGroup));
if (numMappers < 1) {
numMappers = 1;
}
if (minSplit > 0) {
- if (((int)(endHash - firstHash))/numMappers < minSplit) {
- numMappers = ((int)(endHash - firstHash))/minSplit;
+ if (((endHash - firstHash)/numMappers) < minSplit) {
+ numMappers = (int)((endHash - firstHash)/minSplit);
if (numMappers < 1) {
numMappers = 1;
}
}
}
job.set("first", Long.toString(firstHash));
job.set("end", Long.toString(endHash));
job.set("numMappersHack", Integer.toString(numMappers));
job.set("tier", Integer.toString(tier));
job.set("recordsPerGroup", Integer.toString(myConf.recordsPerGroup));
if (lastTier >= 0) {
job.set("previousTierDb", HadoopUtil.getTierIndexPath(conf, myConf, lastTier).toString());
}
Path outputPath = HadoopUtil.getTierPath(conf, myConf, tier);
FileOutputFormat.setOutputPath(job, outputPath);
FileSystem.get(job).mkdirs(outputPath);
job.setJobName("Tier Map-Reduce");
FileInputFormat.setInputPaths(job, new Path("in"));
job.setInputFormat(SequenceInputFormat.class);
job.setOutputFormat(SplitDatabaseOutputFormat.class);
job.setMapperClass(TierMap.class);
job.setNumMapTasks(numMappers);
job.setNumReduceTasks(1);
job.setReducerClass(SplitDatabaseReduce.class);
JobClient.runJob(job);
return;
}
}
| true | true | private void processRun(Configuration conf, int tier, int lastTier) throws IOException {
TieredHasher<?> h = Util.checkedCast(myConf.getHasher());
long firstHash = h.hashOffsetForTier(tier);
long endHash = h.hashOffsetForTier(tier+1);
JobConf job = new JobConf(conf, TierMap.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(HadoopSplitDatabaseWritable.class);
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(HadoopSplitDatabaseWritableList.class);
Util.debug(DebugFacility.HADOOP, "Processing tier " + tier+" from "+firstHash+" to "+endHash);
int numMappers = myConf.getInteger("gamesman.hadoop.numMappers", 60);
int minSplit = myConf.getInteger("gamesman.hadoop.minSplit",
myConf.getInteger("gamesman.minSplit", myConf.recordsPerGroup));
if (numMappers < 1) {
numMappers = 1;
}
if (minSplit > 0) {
if (((int)(endHash - firstHash))/numMappers < minSplit) {
numMappers = ((int)(endHash - firstHash))/minSplit;
if (numMappers < 1) {
numMappers = 1;
}
}
}
job.set("first", Long.toString(firstHash));
job.set("end", Long.toString(endHash));
job.set("numMappersHack", Integer.toString(numMappers));
job.set("tier", Integer.toString(tier));
job.set("recordsPerGroup", Integer.toString(myConf.recordsPerGroup));
if (lastTier >= 0) {
job.set("previousTierDb", HadoopUtil.getTierIndexPath(conf, myConf, lastTier).toString());
}
Path outputPath = HadoopUtil.getTierPath(conf, myConf, tier);
FileOutputFormat.setOutputPath(job, outputPath);
FileSystem.get(job).mkdirs(outputPath);
job.setJobName("Tier Map-Reduce");
FileInputFormat.setInputPaths(job, new Path("in"));
job.setInputFormat(SequenceInputFormat.class);
job.setOutputFormat(SplitDatabaseOutputFormat.class);
job.setMapperClass(TierMap.class);
job.setNumMapTasks(numMappers);
job.setNumReduceTasks(1);
job.setReducerClass(SplitDatabaseReduce.class);
JobClient.runJob(job);
return;
}
| private void processRun(Configuration conf, int tier, int lastTier) throws IOException {
TieredHasher<?> h = Util.checkedCast(myConf.getHasher());
long firstHash = h.hashOffsetForTier(tier);
long endHash = h.hashOffsetForTier(tier+1);
JobConf job = new JobConf(conf, TierMap.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(HadoopSplitDatabaseWritable.class);
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(HadoopSplitDatabaseWritableList.class);
Util.debug(DebugFacility.HADOOP, "Processing tier " + tier+" from "+firstHash+" to "+endHash);
int numMappers = myConf.getInteger("gamesman.hadoop.numMappers", 60);
int minSplit = myConf.getInteger("gamesman.hadoop.minSplit",
myConf.getInteger("gamesman.minSplit", myConf.recordsPerGroup));
if (numMappers < 1) {
numMappers = 1;
}
if (minSplit > 0) {
if (((endHash - firstHash)/numMappers) < minSplit) {
numMappers = (int)((endHash - firstHash)/minSplit);
if (numMappers < 1) {
numMappers = 1;
}
}
}
job.set("first", Long.toString(firstHash));
job.set("end", Long.toString(endHash));
job.set("numMappersHack", Integer.toString(numMappers));
job.set("tier", Integer.toString(tier));
job.set("recordsPerGroup", Integer.toString(myConf.recordsPerGroup));
if (lastTier >= 0) {
job.set("previousTierDb", HadoopUtil.getTierIndexPath(conf, myConf, lastTier).toString());
}
Path outputPath = HadoopUtil.getTierPath(conf, myConf, tier);
FileOutputFormat.setOutputPath(job, outputPath);
FileSystem.get(job).mkdirs(outputPath);
job.setJobName("Tier Map-Reduce");
FileInputFormat.setInputPaths(job, new Path("in"));
job.setInputFormat(SequenceInputFormat.class);
job.setOutputFormat(SplitDatabaseOutputFormat.class);
job.setMapperClass(TierMap.class);
job.setNumMapTasks(numMappers);
job.setNumReduceTasks(1);
job.setReducerClass(SplitDatabaseReduce.class);
JobClient.runJob(job);
return;
}
|
diff --git a/OWFGScannerOS5/src/main/java/WebServiceExtension/com/owfg/webservice/Client.java b/OWFGScannerOS5/src/main/java/WebServiceExtension/com/owfg/webservice/Client.java
index a19fac3..cf2a3b6 100644
--- a/OWFGScannerOS5/src/main/java/WebServiceExtension/com/owfg/webservice/Client.java
+++ b/OWFGScannerOS5/src/main/java/WebServiceExtension/com/owfg/webservice/Client.java
@@ -1,60 +1,64 @@
package com.owfg.webservice;
import java.io.IOException;
import net.rim.device.api.script.ScriptableFunction;
import net.rim.device.api.system.EventInjector;
import net.rim.device.api.system.EventLogger;
public final class Client extends ScriptableFunction {
public static final String GET_INFO = "getInfo";
public static final String GET_BANNERS = "getBanners";
public static final String GET_STORES = "getStores";
public static final String SET_STORE = "setStore";
public static final long GUID = 0x2051fd67b72d11L;
public static final String APP_NAME = "WebService Plugin";
public static WebService ws = null;
public Object invoke(Object obj, Object[] args) throws Exception {
EventLogger.register(GUID, APP_NAME, EventLogger.VIEWER_STRING);
Logger.logErrorEvent("Client.invoke(): invoke");
String fnName = (String) args[5];
ScriptableFunction success = (ScriptableFunction) args[0];
ScriptableFunction error = (ScriptableFunction) args[1];
if (ws == null) {
Logger.logErrorEvent("Client.invoke(): create WS");
ws = new WebService((String) args[2], (String) args[3], (String) args[4]);
}
if (ws.getAddress().equals((String) args[2]) == false) {
ws.setAddress((String) args[2]);
}
if (ws.getUser().equals((String) args[3]) == false) {
ws.setUser((String) args[3]);
}
if (ws.getPass().equals((String) args[4]) == false) {
ws.setPass((String) args[4]);
}
try {
+ Logger.logErrorEvent("Client() function called: " + fnName);
if (fnName.equals(GET_INFO)) {
Logger.logErrorEvent("Client.invoke(): get Info");
ws.getInfo(success, error, (String) args[6]);
}
if (fnName.equals(GET_BANNERS)) {
Logger.logErrorEvent("Client.invoke(): get banners");
ws.getBanners(success, error);
}
if (fnName.equals(GET_STORES)) {
Logger.logErrorEvent("Client.invoke(): get stores");
ws.getStores(success, error);
}
if (fnName.equals(SET_STORE)) {
- Logger.logErrorEvent("Client.invoke(): get stores");
- ws.setStore(success, error, (Long) args[6]);
+ Logger.logErrorEvent("Called setStore, about to cast this object: " + args[6]);
+ String storeIDstr = (String) args[6];
+ Long storeID = new Long(Long.parseLong(storeIDstr));
+ Logger.logErrorEvent("Client.invoke(): get stores. (StoreID: " + storeID + ")");
+ ws.setStore(success, error, storeID);
}
} catch (Exception e) {
Logger.logErrorEvent("Exception: Client.Invoke(); (" + e + ") " + e.getMessage());
}
return UNDEFINED;
}
}
| false | true | public Object invoke(Object obj, Object[] args) throws Exception {
EventLogger.register(GUID, APP_NAME, EventLogger.VIEWER_STRING);
Logger.logErrorEvent("Client.invoke(): invoke");
String fnName = (String) args[5];
ScriptableFunction success = (ScriptableFunction) args[0];
ScriptableFunction error = (ScriptableFunction) args[1];
if (ws == null) {
Logger.logErrorEvent("Client.invoke(): create WS");
ws = new WebService((String) args[2], (String) args[3], (String) args[4]);
}
if (ws.getAddress().equals((String) args[2]) == false) {
ws.setAddress((String) args[2]);
}
if (ws.getUser().equals((String) args[3]) == false) {
ws.setUser((String) args[3]);
}
if (ws.getPass().equals((String) args[4]) == false) {
ws.setPass((String) args[4]);
}
try {
if (fnName.equals(GET_INFO)) {
Logger.logErrorEvent("Client.invoke(): get Info");
ws.getInfo(success, error, (String) args[6]);
}
if (fnName.equals(GET_BANNERS)) {
Logger.logErrorEvent("Client.invoke(): get banners");
ws.getBanners(success, error);
}
if (fnName.equals(GET_STORES)) {
Logger.logErrorEvent("Client.invoke(): get stores");
ws.getStores(success, error);
}
if (fnName.equals(SET_STORE)) {
Logger.logErrorEvent("Client.invoke(): get stores");
ws.setStore(success, error, (Long) args[6]);
}
} catch (Exception e) {
Logger.logErrorEvent("Exception: Client.Invoke(); (" + e + ") " + e.getMessage());
}
return UNDEFINED;
}
| public Object invoke(Object obj, Object[] args) throws Exception {
EventLogger.register(GUID, APP_NAME, EventLogger.VIEWER_STRING);
Logger.logErrorEvent("Client.invoke(): invoke");
String fnName = (String) args[5];
ScriptableFunction success = (ScriptableFunction) args[0];
ScriptableFunction error = (ScriptableFunction) args[1];
if (ws == null) {
Logger.logErrorEvent("Client.invoke(): create WS");
ws = new WebService((String) args[2], (String) args[3], (String) args[4]);
}
if (ws.getAddress().equals((String) args[2]) == false) {
ws.setAddress((String) args[2]);
}
if (ws.getUser().equals((String) args[3]) == false) {
ws.setUser((String) args[3]);
}
if (ws.getPass().equals((String) args[4]) == false) {
ws.setPass((String) args[4]);
}
try {
Logger.logErrorEvent("Client() function called: " + fnName);
if (fnName.equals(GET_INFO)) {
Logger.logErrorEvent("Client.invoke(): get Info");
ws.getInfo(success, error, (String) args[6]);
}
if (fnName.equals(GET_BANNERS)) {
Logger.logErrorEvent("Client.invoke(): get banners");
ws.getBanners(success, error);
}
if (fnName.equals(GET_STORES)) {
Logger.logErrorEvent("Client.invoke(): get stores");
ws.getStores(success, error);
}
if (fnName.equals(SET_STORE)) {
Logger.logErrorEvent("Called setStore, about to cast this object: " + args[6]);
String storeIDstr = (String) args[6];
Long storeID = new Long(Long.parseLong(storeIDstr));
Logger.logErrorEvent("Client.invoke(): get stores. (StoreID: " + storeID + ")");
ws.setStore(success, error, storeID);
}
} catch (Exception e) {
Logger.logErrorEvent("Exception: Client.Invoke(); (" + e + ") " + e.getMessage());
}
return UNDEFINED;
}
|
diff --git a/cdi/plugins/org.jboss.tools.cdi.ui/src/org/jboss/tools/cdi/ui/search/CDIBeanQueryParticipant.java b/cdi/plugins/org.jboss.tools.cdi.ui/src/org/jboss/tools/cdi/ui/search/CDIBeanQueryParticipant.java
index 139012ea2..a031f229e 100644
--- a/cdi/plugins/org.jboss.tools.cdi.ui/src/org/jboss/tools/cdi/ui/search/CDIBeanQueryParticipant.java
+++ b/cdi/plugins/org.jboss.tools.cdi.ui/src/org/jboss/tools/cdi/ui/search/CDIBeanQueryParticipant.java
@@ -1,201 +1,201 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.cdi.ui.search;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.search.ElementQuerySpecification;
import org.eclipse.jdt.ui.search.IMatchPresentation;
import org.eclipse.jdt.ui.search.IQueryParticipant;
import org.eclipse.jdt.ui.search.ISearchRequestor;
import org.eclipse.jdt.ui.search.QuerySpecification;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.search.ui.text.Match;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.PartInitException;
import org.jboss.tools.cdi.core.CDICoreNature;
import org.jboss.tools.cdi.core.CDICorePlugin;
import org.jboss.tools.cdi.core.CDIImages;
import org.jboss.tools.cdi.core.IBean;
import org.jboss.tools.cdi.core.ICDIElement;
import org.jboss.tools.cdi.core.ICDIProject;
import org.jboss.tools.cdi.core.IInjectionPoint;
import org.jboss.tools.cdi.core.util.BeanPresentationUtil;
import org.jboss.tools.cdi.ui.CDIUIMessages;
import org.jboss.tools.cdi.ui.CDIUIPlugin;
import org.jboss.tools.common.java.IParametedType;
public class CDIBeanQueryParticipant implements IQueryParticipant{
static CDIBeanLabelProvider labelProvider = new CDIBeanLabelProvider();
@Override
public void search(ISearchRequestor requestor,
QuerySpecification querySpecification, IProgressMonitor monitor)
throws CoreException {
if(querySpecification instanceof ElementQuerySpecification){
if (!isSearchForReferences(querySpecification.getLimitTo())) {
return;
}
ElementQuerySpecification qs = (ElementQuerySpecification)querySpecification;
IJavaElement element = qs.getElement();
IProject project = element.getJavaProject().getProject();
ICDIProject cdiProject = CDICorePlugin.getCDIProject(project, true);
if(cdiProject == null) {
return;
}
searchInProject(requestor, querySpecification, cdiProject, monitor, element);
- CDICoreNature[] natures = cdiProject.getNature().getAllDependentProjects();
+ CDICoreNature[] natures = cdiProject.getNature().getAllDependentProjects(true);
for(CDICoreNature nature : natures){
ICDIProject p = nature.getDelegate();
if(p != null){
searchInProject(requestor, querySpecification, p, monitor, element);
}
}
}
}
private void searchInProject(ISearchRequestor requestor, QuerySpecification querySpecification, ICDIProject cdiProject, IProgressMonitor monitor, IJavaElement element){
Set<IBean> sourceBeans = cdiProject.getBeans(element);
Set<IInjectionPoint> injectionPoints = new HashSet<IInjectionPoint>();
for (IBean b: sourceBeans) {
Set<IParametedType> ts = b.getLegalTypes();
for (IParametedType t: ts) {
injectionPoints.addAll(cdiProject.getInjections(t.getType().getFullyQualifiedName()));
}
}
monitor.beginTask(CDIUIMessages.CDI_BEAN_QUERY_PARTICIPANT_TASK, injectionPoints.size());
for(IInjectionPoint injectionPoint : injectionPoints){
if(monitor.isCanceled())
break;
Set<IBean> resultBeans = cdiProject.getBeans(false, injectionPoint);
monitor.worked(1);
for(IBean cBean : resultBeans){
if(sourceBeans.contains(cBean) && InjectionPointQueryParticipant.containsInSearchScope(querySpecification, cBean)){
Match match = new CDIMatch(injectionPoint);
requestor.reportMatch(match);
break;
}
}
}
monitor.done();
}
public boolean isSearchForReferences(int limitTo) {
int maskedLimitTo = limitTo & ~(IJavaSearchConstants.IGNORE_DECLARING_TYPE+IJavaSearchConstants.IGNORE_RETURN_TYPE);
if (maskedLimitTo == IJavaSearchConstants.REFERENCES || maskedLimitTo == IJavaSearchConstants.ALL_OCCURRENCES) {
return true;
}
return false;
}
@Override
public int estimateTicks(QuerySpecification specification) {
return 10;
}
@Override
public IMatchPresentation getUIParticipant() {
return new CDIBeanMatchPresentation();
}
class CDIBeanMatchPresentation implements IMatchPresentation{
@Override
public ILabelProvider createLabelProvider() {
return labelProvider;
}
@Override
public void showMatch(Match match, int currentOffset,
int currentLength, boolean activate) throws PartInitException {
if(match instanceof CDIMatch){
IJavaElement element = ((CDIMatch)match).getJavaElement();
if(element != null){
try{
JavaUI.openInEditor(element);
}catch(JavaModelException ex){
CDIUIPlugin.getDefault().logError(ex);
}catch(PartInitException ex){
CDIUIPlugin.getDefault().logError(ex);
}
}
}
}
}
static class CDIBeanLabelProvider implements ILabelProvider{
@Override
public void addListener(ILabelProviderListener listener) {
}
@Override
public void dispose() {
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public void removeListener(ILabelProviderListener listener) {
}
@Override
public Image getImage(Object element) {
if(element instanceof CDIElementWrapper){
return CDIImages.getImageByElement(((CDIElementWrapper)element).getCDIElement());
}
return CDIImages.WELD_IMAGE;
}
@Override
public String getText(Object element) {
if(element instanceof CDIElementWrapper){
ICDIElement cdiElement = ((CDIElementWrapper)element).getCDIElement();
String kind = BeanPresentationUtil.getCDIElementKind(cdiElement);
String text = "";
if(kind != null){
text = kind+" ";
}
return text+cdiElement.getElementName()+BeanPresentationUtil.getCDIElementLocation(cdiElement, false);
}
return ""; //$NON-NLS-1$
}
}
}
| true | true | public void search(ISearchRequestor requestor,
QuerySpecification querySpecification, IProgressMonitor monitor)
throws CoreException {
if(querySpecification instanceof ElementQuerySpecification){
if (!isSearchForReferences(querySpecification.getLimitTo())) {
return;
}
ElementQuerySpecification qs = (ElementQuerySpecification)querySpecification;
IJavaElement element = qs.getElement();
IProject project = element.getJavaProject().getProject();
ICDIProject cdiProject = CDICorePlugin.getCDIProject(project, true);
if(cdiProject == null) {
return;
}
searchInProject(requestor, querySpecification, cdiProject, monitor, element);
CDICoreNature[] natures = cdiProject.getNature().getAllDependentProjects();
for(CDICoreNature nature : natures){
ICDIProject p = nature.getDelegate();
if(p != null){
searchInProject(requestor, querySpecification, p, monitor, element);
}
}
}
}
| public void search(ISearchRequestor requestor,
QuerySpecification querySpecification, IProgressMonitor monitor)
throws CoreException {
if(querySpecification instanceof ElementQuerySpecification){
if (!isSearchForReferences(querySpecification.getLimitTo())) {
return;
}
ElementQuerySpecification qs = (ElementQuerySpecification)querySpecification;
IJavaElement element = qs.getElement();
IProject project = element.getJavaProject().getProject();
ICDIProject cdiProject = CDICorePlugin.getCDIProject(project, true);
if(cdiProject == null) {
return;
}
searchInProject(requestor, querySpecification, cdiProject, monitor, element);
CDICoreNature[] natures = cdiProject.getNature().getAllDependentProjects(true);
for(CDICoreNature nature : natures){
ICDIProject p = nature.getDelegate();
if(p != null){
searchInProject(requestor, querySpecification, p, monitor, element);
}
}
}
}
|
diff --git a/modular-pircbot-modules/src/main/java/org/pircbotx/listeners/urlhandlers/YouTubeVideoURLHandler.java b/modular-pircbot-modules/src/main/java/org/pircbotx/listeners/urlhandlers/YouTubeVideoURLHandler.java
index f439322..e4ac7f8 100644
--- a/modular-pircbot-modules/src/main/java/org/pircbotx/listeners/urlhandlers/YouTubeVideoURLHandler.java
+++ b/modular-pircbot-modules/src/main/java/org/pircbotx/listeners/urlhandlers/YouTubeVideoURLHandler.java
@@ -1,153 +1,155 @@
package org.pircbotx.listeners.urlhandlers;
import static com.google.common.base.Preconditions.checkArgument;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.joda.time.Duration;
import org.pircbotx.util.URLUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
import com.google.common.net.InternetDomainName;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.Category;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.util.ServiceException;
/**
* A {@link VideoURLHandler} specifically made to retrieve video information from YouTube.
*
* @author Emmanuel Cron
*/
public class YouTubeVideoURLHandler extends VideoURLHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(YouTubeVideoURLHandler.class);
private static final String GDATA_URL = "http://gdata.youtube.com/feeds/api/videos/%s?hl=%s";
private static final String YOUTUBE_SHORT_URL = "http://youtu.be/%s";
private static final String YOUTUBE_COM = "youtube.com";
private static final String YOUTU_BE = "youtu.be";
private String applicationName;
private String hl;
private int connectTimeoutMillis;
private int readTimeoutMillis;
/**
* Creates a new handler.
*
* @param applicationName the name under which this handler will identify itself on YouTube
* @param hl the language in which retrieve categories in {@code ISO-639-1} format
* @param connectTimeoutMillis millis after which the connection attempt is abandoned
* @param readTimeoutMillis millis after which the read attempt is abandoned
*/
public YouTubeVideoURLHandler(String applicationName, String hl, int connectTimeoutMillis,
int readTimeoutMillis, VideoInfoFormat format) {
super(format);
checkArgument(!Strings.isNullOrEmpty(applicationName),
"Application name cannot be null or empty");
checkArgument(!Strings.isNullOrEmpty(hl), "Language must be provided");
checkArgument(connectTimeoutMillis > 0, "Connect timeout must be > 0");
checkArgument(readTimeoutMillis > 0, "Read timeout must be > 0");
this.applicationName = applicationName;
this.hl = hl;
this.connectTimeoutMillis = connectTimeoutMillis;
this.readTimeoutMillis = readTimeoutMillis;
}
@Override
public int getUrlRequiredMinLength() {
// youtu.be/<id>
return 10;
}
@Override
public boolean matches(URL url) {
if (YOUTU_BE.equalsIgnoreCase(url.getHost())) {
return true;
}
String host = InternetDomainName.from(url.getHost()).topPrivateDomain().toString();
if (host.equalsIgnoreCase(YOUTUBE_COM)) {
return true;
}
return false;
}
@Override
public VideoInfo retrieveVideoInfo(URL url) {
String videoId = parseVideoId(url);
if (Strings.isNullOrEmpty(videoId)) {
return null;
}
YouTubeService service = new YouTubeService(applicationName);
service.setConnectTimeout(connectTimeoutMillis);
service.setReadTimeout(readTimeoutMillis);
VideoEntry videoEntry;
try {
URL gDataUrl = new URL(String.format(GDATA_URL, videoId, hl));
videoEntry = service.getEntry(gDataUrl, VideoEntry.class);
} catch (ServiceException | IOException e) {
LOGGER.warn(String.format("Could not retrieve video information, ignoring: %s", videoId), e);
return null;
}
URL videoUrl;
try {
videoUrl = new URL(String.format(YOUTUBE_SHORT_URL, videoId));
} catch (MalformedURLException murle) {
LOGGER.error("Could not format short YouTube URL with video id, ignoring", murle);
return null;
}
VideoInfo videoInfo = new VideoInfo(videoUrl, videoEntry.getTitle().getPlainText());
if (videoEntry.getAuthors().size() > 0) {
videoInfo.setUser(videoEntry.getAuthors().get(0).getName());
}
if (videoEntry.getCategories().size() > 0) {
for (Category category : videoEntry.getCategories()) {
if (!Strings.isNullOrEmpty(category.getLabel())) {
videoInfo.setCategory(category.getLabel());
break;
}
}
}
if (videoEntry.getMediaGroup() != null) {
videoInfo.setDuration(new Duration(videoEntry.getMediaGroup().getDuration() * 1000));
}
- videoInfo.setLikes(videoEntry.getYtRating().getNumLikes());
- videoInfo.setDislikes(videoEntry.getYtRating().getNumDislikes());
+ if (videoEntry.getYtRating() != null) {
+ videoInfo.setLikes(videoEntry.getYtRating().getNumLikes());
+ videoInfo.setDislikes(videoEntry.getYtRating().getNumDislikes());
+ }
videoInfo.setViews(videoEntry.getStatistics().getViewCount());
return videoInfo;
}
// internal helpers
private String parseVideoId(URL url) {
String host = InternetDomainName.from(url.getHost()).topPrivateDomain().toString();
if (host.equalsIgnoreCase(YOUTU_BE)) {
if (url.getPath().length() < 1) {
// No video id provided
return null;
}
return url.getPath().substring(1);
}
if (host.equalsIgnoreCase(YOUTUBE_COM)) {
if (url.getPath().length() > 3 && url.getPath().toLowerCase().startsWith("/v/")) {
return url.getPath().substring(3);
}
if (url.getPath().toLowerCase().equals("/watch")) {
return URLUtils.getQueryParamFirstValue(url, "v");
}
// Not recognized
}
return null;
}
}
| true | true | public VideoInfo retrieveVideoInfo(URL url) {
String videoId = parseVideoId(url);
if (Strings.isNullOrEmpty(videoId)) {
return null;
}
YouTubeService service = new YouTubeService(applicationName);
service.setConnectTimeout(connectTimeoutMillis);
service.setReadTimeout(readTimeoutMillis);
VideoEntry videoEntry;
try {
URL gDataUrl = new URL(String.format(GDATA_URL, videoId, hl));
videoEntry = service.getEntry(gDataUrl, VideoEntry.class);
} catch (ServiceException | IOException e) {
LOGGER.warn(String.format("Could not retrieve video information, ignoring: %s", videoId), e);
return null;
}
URL videoUrl;
try {
videoUrl = new URL(String.format(YOUTUBE_SHORT_URL, videoId));
} catch (MalformedURLException murle) {
LOGGER.error("Could not format short YouTube URL with video id, ignoring", murle);
return null;
}
VideoInfo videoInfo = new VideoInfo(videoUrl, videoEntry.getTitle().getPlainText());
if (videoEntry.getAuthors().size() > 0) {
videoInfo.setUser(videoEntry.getAuthors().get(0).getName());
}
if (videoEntry.getCategories().size() > 0) {
for (Category category : videoEntry.getCategories()) {
if (!Strings.isNullOrEmpty(category.getLabel())) {
videoInfo.setCategory(category.getLabel());
break;
}
}
}
if (videoEntry.getMediaGroup() != null) {
videoInfo.setDuration(new Duration(videoEntry.getMediaGroup().getDuration() * 1000));
}
videoInfo.setLikes(videoEntry.getYtRating().getNumLikes());
videoInfo.setDislikes(videoEntry.getYtRating().getNumDislikes());
videoInfo.setViews(videoEntry.getStatistics().getViewCount());
return videoInfo;
}
| public VideoInfo retrieveVideoInfo(URL url) {
String videoId = parseVideoId(url);
if (Strings.isNullOrEmpty(videoId)) {
return null;
}
YouTubeService service = new YouTubeService(applicationName);
service.setConnectTimeout(connectTimeoutMillis);
service.setReadTimeout(readTimeoutMillis);
VideoEntry videoEntry;
try {
URL gDataUrl = new URL(String.format(GDATA_URL, videoId, hl));
videoEntry = service.getEntry(gDataUrl, VideoEntry.class);
} catch (ServiceException | IOException e) {
LOGGER.warn(String.format("Could not retrieve video information, ignoring: %s", videoId), e);
return null;
}
URL videoUrl;
try {
videoUrl = new URL(String.format(YOUTUBE_SHORT_URL, videoId));
} catch (MalformedURLException murle) {
LOGGER.error("Could not format short YouTube URL with video id, ignoring", murle);
return null;
}
VideoInfo videoInfo = new VideoInfo(videoUrl, videoEntry.getTitle().getPlainText());
if (videoEntry.getAuthors().size() > 0) {
videoInfo.setUser(videoEntry.getAuthors().get(0).getName());
}
if (videoEntry.getCategories().size() > 0) {
for (Category category : videoEntry.getCategories()) {
if (!Strings.isNullOrEmpty(category.getLabel())) {
videoInfo.setCategory(category.getLabel());
break;
}
}
}
if (videoEntry.getMediaGroup() != null) {
videoInfo.setDuration(new Duration(videoEntry.getMediaGroup().getDuration() * 1000));
}
if (videoEntry.getYtRating() != null) {
videoInfo.setLikes(videoEntry.getYtRating().getNumLikes());
videoInfo.setDislikes(videoEntry.getYtRating().getNumDislikes());
}
videoInfo.setViews(videoEntry.getStatistics().getViewCount());
return videoInfo;
}
|
diff --git a/Courseworks/201011/One/BadShuffleTest.java b/Courseworks/201011/One/BadShuffleTest.java
index 8f24738..10b2d5a 100644
--- a/Courseworks/201011/One/BadShuffleTest.java
+++ b/Courseworks/201011/One/BadShuffleTest.java
@@ -1,61 +1,61 @@
// Oliver Kullmann, 29.11.2010 (Swansea)
/* Usage:
BadShuffleTest M N
where M, N are integers with M >= 0 will create N random permutation of
the sequence 0, ..., M-1, and prints to standard output in line i
for i = 0, ..., M-1 how often i ended up in position j for j = 0,...,M-1
(in this order).
*/
class BadShuffleTest {
public static final int
error_missing_arguments = 1,
error_not_an_int = 2,
error_negative_number = 3;
static final String error_header = "ERROR[BadShuffleTest]: ";
public static void main(final String[] args) {
if (args.length <= 1) {
System.err.println(error_header + "Two arguments are needed (the number M of integers to be shuffled, and the number N of trials).");
System.exit(error_missing_arguments);
}
try {
final int M = Integer.parseInt(args[0]);
if (M < 0) {
System.err.println(error_header + "The number M of items must not be negative.");
System.exit(error_negative_number);
}
final int N = Integer.parseInt(args[1]);
// running the experiment:
final int[][] count = new int[M][M];
{final int[] a = new int[M];
for (int exp = 0; exp < N; ++exp) { // experiment-counter
for (int i = 0; i < M; ++i) a[i] = i;
// shuffling:
for (int i = 0; i < M; ++i) {
final int rand = (int) (Math.random() * M); // CHANGE!
final int t = a[rand];
a[rand] = a[i];
a[i] = t;
}
- for (int i = 0; i < M; ++i) ++count[i][a[i]];
+ for (int i = 0; i < M; ++i) ++count[a[i]][i];
}
}
// output of counts:
for (int i = 0; i < M; ++i) {
for (int j = 0; j < M; ++j) System.out.print(count[i][j] + " ");
System.out.println();
}
}
catch (final RuntimeException e) {
System.err.println(error_header + "The command-line argument \"" + args[0] + "\" or \"" + args[1] + "\" is not an integer.");
System.exit(error_not_an_int);
}
}
}
| true | true | public static void main(final String[] args) {
if (args.length <= 1) {
System.err.println(error_header + "Two arguments are needed (the number M of integers to be shuffled, and the number N of trials).");
System.exit(error_missing_arguments);
}
try {
final int M = Integer.parseInt(args[0]);
if (M < 0) {
System.err.println(error_header + "The number M of items must not be negative.");
System.exit(error_negative_number);
}
final int N = Integer.parseInt(args[1]);
// running the experiment:
final int[][] count = new int[M][M];
{final int[] a = new int[M];
for (int exp = 0; exp < N; ++exp) { // experiment-counter
for (int i = 0; i < M; ++i) a[i] = i;
// shuffling:
for (int i = 0; i < M; ++i) {
final int rand = (int) (Math.random() * M); // CHANGE!
final int t = a[rand];
a[rand] = a[i];
a[i] = t;
}
for (int i = 0; i < M; ++i) ++count[i][a[i]];
}
}
// output of counts:
for (int i = 0; i < M; ++i) {
for (int j = 0; j < M; ++j) System.out.print(count[i][j] + " ");
System.out.println();
}
}
catch (final RuntimeException e) {
System.err.println(error_header + "The command-line argument \"" + args[0] + "\" or \"" + args[1] + "\" is not an integer.");
System.exit(error_not_an_int);
}
}
| public static void main(final String[] args) {
if (args.length <= 1) {
System.err.println(error_header + "Two arguments are needed (the number M of integers to be shuffled, and the number N of trials).");
System.exit(error_missing_arguments);
}
try {
final int M = Integer.parseInt(args[0]);
if (M < 0) {
System.err.println(error_header + "The number M of items must not be negative.");
System.exit(error_negative_number);
}
final int N = Integer.parseInt(args[1]);
// running the experiment:
final int[][] count = new int[M][M];
{final int[] a = new int[M];
for (int exp = 0; exp < N; ++exp) { // experiment-counter
for (int i = 0; i < M; ++i) a[i] = i;
// shuffling:
for (int i = 0; i < M; ++i) {
final int rand = (int) (Math.random() * M); // CHANGE!
final int t = a[rand];
a[rand] = a[i];
a[i] = t;
}
for (int i = 0; i < M; ++i) ++count[a[i]][i];
}
}
// output of counts:
for (int i = 0; i < M; ++i) {
for (int j = 0; j < M; ++j) System.out.print(count[i][j] + " ");
System.out.println();
}
}
catch (final RuntimeException e) {
System.err.println(error_header + "The command-line argument \"" + args[0] + "\" or \"" + args[1] + "\" is not an integer.");
System.exit(error_not_an_int);
}
}
|
diff --git a/src/com/massivecraft/factions/listeners/FactionsEntityListener.java b/src/com/massivecraft/factions/listeners/FactionsEntityListener.java
index 2d81371e..db3e3e60 100644
--- a/src/com/massivecraft/factions/listeners/FactionsEntityListener.java
+++ b/src/com/massivecraft/factions/listeners/FactionsEntityListener.java
@@ -1,414 +1,414 @@
package com.massivecraft.factions.listeners;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.text.MessageFormat;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCombustByEntityEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.FFlag;
import com.massivecraft.factions.struct.Rel;
import com.massivecraft.factions.util.MiscUtil;
public class FactionsEntityListener implements Listener
{
public P p;
public FactionsEntityListener(P p)
{
this.p = p;
}
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityDeath(EntityDeathEvent event)
{
Entity entity = event.getEntity();
if ( ! (entity instanceof Player)) return;
Player player = (Player) entity;
FPlayer fplayer = FPlayers.i.get(player);
Faction faction = Board.getFactionAt(new FLocation(player.getLocation()));
if ( ! faction.getFlag(FFlag.POWERLOSS))
{
fplayer.msg("<i>You didn't lose any power since the territory you died in works that way.");
return;
}
if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName()))
{
fplayer.msg("<i>You didn't lose any power due to the world you died in.");
return;
}
fplayer.onDeath();
fplayer.msg("<i>Your power is now <h>"+fplayer.getPowerRounded()+" / "+fplayer.getPowerMaxRounded());
}
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityDamage(EntityDamageEvent event)
{
if (event.isCancelled()) return;
if (event instanceof EntityDamageByEntityEvent)
{
EntityDamageByEntityEvent sub = (EntityDamageByEntityEvent)event;
if ( ! this.canDamagerHurtDamagee(sub, true))
{
event.setCancelled(true);
}
}
// TODO: Add a no damage at all flag??
/*else if (Conf.safeZonePreventAllDamageToPlayers && isPlayerInSafeZone(event.getEntity()))
{
// Players can not take any damage in a Safe Zone
event.setCancelled(true);
}*/
}
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityExplode(EntityExplodeEvent event)
{
if (event.isCancelled()) return;
Set<FLocation> explosionLocs = new HashSet<FLocation>();
for (Block block : event.blockList())
{
explosionLocs.add(new FLocation(block));
}
for (FLocation loc : explosionLocs)
{
Faction faction = Board.getFactionAt(loc);
if (faction.getFlag(FFlag.EXPLOSIONS) == false)
{
// faction has explosions disabled
event.setCancelled(true);
return;
}
}
// TNT in water/lava doesn't normally destroy any surrounding blocks, which is usually desired behavior, but...
// this optional change below provides workaround for waterwalling providing perfect protection,
// and makes cheap (non-obsidian) TNT cannons require minor maintenance between shots
Block center = event.getLocation().getBlock();
if (event.getEntity() instanceof TNTPrimed && Conf.handleExploitTNTWaterlog && center.isLiquid())
{
// a single surrounding block in all 6 directions is broken if the material is weak enough
List<Block> targets = new ArrayList<Block>();
targets.add(center.getRelative(0, 0, 1));
targets.add(center.getRelative(0, 0, -1));
targets.add(center.getRelative(0, 1, 0));
targets.add(center.getRelative(0, -1, 0));
targets.add(center.getRelative(1, 0, 0));
targets.add(center.getRelative(-1, 0, 0));
for (Block target : targets)
{
int id = target.getTypeId();
// ignore air, bedrock, water, lava, obsidian, enchanting table... too bad we can't get a working material durability # yet
if (id != 0 && (id < 7 || id > 11) && id != 49 && id != 116)
target.breakNaturally();
}
}
}
// mainly for flaming arrows; don't want allies or people in safe zones to be ignited even after damage event is cancelled
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityCombustByEntity(EntityCombustByEntityEvent event)
{
if (event.isCancelled()) return;
EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), EntityDamageEvent.DamageCause.FIRE, 0);
if ( ! this.canDamagerHurtDamagee(sub, false))
event.setCancelled(true);
sub = null;
}
private static final Set<PotionEffectType> badPotionEffects = new LinkedHashSet<PotionEffectType>(Arrays.asList(
PotionEffectType.BLINDNESS, PotionEffectType.CONFUSION, PotionEffectType.HARM, PotionEffectType.HUNGER,
PotionEffectType.POISON, PotionEffectType.SLOW, PotionEffectType.SLOW_DIGGING, PotionEffectType.WEAKNESS
));
@EventHandler(priority = EventPriority.NORMAL)
public void onPotionSplashEvent(PotionSplashEvent event)
{
if (event.isCancelled()) return;
// see if the potion has a harmful effect
boolean badjuju = false;
for (PotionEffect effect : event.getPotion().getEffects())
{
if (badPotionEffects.contains(effect.getType()))
{
badjuju = true;
break;
}
}
if ( ! badjuju) return;
Entity thrower = event.getPotion().getShooter();
// scan through affected entities to make sure they're all valid targets
Iterator<LivingEntity> iter = event.getAffectedEntities().iterator();
while (iter.hasNext())
{
LivingEntity target = iter.next();
EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(thrower, target, EntityDamageEvent.DamageCause.CUSTOM, 0);
if ( ! this.canDamagerHurtDamagee(sub, true))
event.setIntensity(target, 0.0); // affected entity list doesn't accept modification (iter.remove() is a no-go), but this works
sub = null;
}
}
public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub)
{
return canDamagerHurtDamagee(sub, true);
}
public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify)
{
Entity damager = sub.getDamager();
Entity damagee = sub.getEntity();
int damage = sub.getDamage();
if ( ! (damagee instanceof Player)) return true;
FPlayer defender = FPlayers.i.get((Player)damagee);
if (defender == null || defender.getPlayer() == null)
return true;
Location defenderLoc = defender.getPlayer().getLocation();
Faction defLocFaction = Board.getFactionAt(new FLocation(defenderLoc));
// for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source
if (damager instanceof Projectile)
damager = ((Projectile)damager).getShooter();
if (damager == damagee) // ender pearl usage and other self-inflicted damage
return true;
// Players can not take attack damage in a SafeZone, or possibly peaceful territory
if (defLocFaction.getFlag(FFlag.PVP) == false)
{
if (damager instanceof Player)
{
if (notify)
{
FPlayer attacker = FPlayers.i.get((Player)damager);
attacker.msg("<i>PVP is disabled in %s.", defLocFaction.describeTo(attacker));
}
return false;
}
return defLocFaction.getFlag(FFlag.MONSTERS);
}
if ( ! (damager instanceof Player))
return true;
FPlayer attacker = FPlayers.i.get((Player)damager);
if (attacker == null || attacker.getPlayer() == null)
return true;
if (Conf.playersWhoBypassAllProtection.contains(attacker.getName())) return true;
if (attacker.hasLoginPvpDisabled())
{
if (notify) attacker.msg("<i>You can't hurt other players for " + Conf.noPVPDamageToOthersForXSecondsAfterLogin + " seconds after logging in.");
return false;
}
Faction locFaction = Board.getFactionAt(new FLocation(attacker));
// so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be?
if (locFaction.getFlag(FFlag.PVP) == false)
{
if (notify) attacker.msg("<i>PVP is disabled in %s.", locFaction.describeTo(attacker));
return false;
}
if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName()))
return true;
Faction defendFaction = defender.getFaction();
Faction attackFaction = attacker.getFaction();
if (attackFaction.isNone() && Conf.disablePVPForFactionlessPlayers)
{
if (notify) attacker.msg("<i>You can't hurt other players until you join a faction.");
return false;
}
else if (defendFaction.isNone())
{
if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand)
{
// Allow PVP vs. Factionless in attacker's faction territory
return true;
}
else if (Conf.disablePVPForFactionlessPlayers)
{
if (notify) attacker.msg("<i>You can't hurt players who are not currently in a faction.");
return false;
}
}
Rel relation = defendFaction.getRelationTo(attackFaction);
// Check the relation
- if (relation.isAtLeast(Conf.friendlyFireFromRel) && defLocFaction.getFlag(FFlag.FRIENDLYFIRE) == false)
+ if (defender.hasFaction() && relation.isAtLeast(Conf.friendlyFireFromRel) && defLocFaction.getFlag(FFlag.FRIENDLYFIRE) == false)
{
if (notify) attacker.msg("<i>You can't hurt %s<i>.", relation.getDescPlayerMany());
return false;
}
// You can not hurt neutrals in their own territory.
boolean ownTerritory = defender.isInOwnTerritory();
if (defender.hasFaction() && ownTerritory && relation == Rel.NEUTRAL)
{
if (notify)
{
attacker.msg("<i>You can't hurt %s<i> in their own territory unless you declare them as an enemy.", defender.describeTo(attacker));
defender.msg("%s<i> tried to hurt you.", attacker.describeTo(defender, true));
}
return false;
}
// Damage will be dealt. However check if the damage should be reduced.
- if (damage > 0.0 && ownTerritory && Conf.territoryShieldFactor > 0)
+ if (damage > 0.0 && defender.hasFaction() && ownTerritory && Conf.territoryShieldFactor > 0)
{
int newDamage = (int)Math.ceil(damage * (1D - Conf.territoryShieldFactor));
sub.setDamage(newDamage);
// Send message
if (notify)
{
String perc = MessageFormat.format("{0,number,#%}", (Conf.territoryShieldFactor)); // TODO does this display correctly??
defender.msg("<i>Enemy damage reduced by <rose>%s<i>.", perc);
}
}
return true;
}
@EventHandler(priority = EventPriority.NORMAL)
public void onCreatureSpawn(CreatureSpawnEvent event)
{
if (event.isCancelled()) return;
if (event.getLocation() == null) return;
FLocation floc = new FLocation(event.getLocation());
Faction faction = Board.getFactionAt(floc);
if (faction.getFlag(FFlag.MONSTERS)) return;
if ( ! Conf.monsters.contains(event.getEntityType())) return;
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityTarget(EntityTargetEvent event)
{
if (event.isCancelled()) return;
// if there is a target
Entity target = event.getTarget();
if (target == null) return;
// We are interested in blocking targeting for certain mobs:
if ( ! Conf.monsters.contains(MiscUtil.creatureTypeFromEntity(event.getEntity()))) return;
FLocation floc = new FLocation(target.getLocation());
Faction faction = Board.getFactionAt(floc);
if (faction.getFlag(FFlag.MONSTERS)) return;
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPaintingBreak(PaintingBreakEvent event)
{
if (event.isCancelled()) return;
if (! (event instanceof PaintingBreakByEntityEvent))
{
return;
}
Entity breaker = ((PaintingBreakByEntityEvent)event).getRemover();
if (! (breaker instanceof Player))
{
return;
}
if ( ! FactionsBlockListener.playerCanBuildDestroyBlock((Player)breaker, event.getPainting().getLocation().getBlock(), "remove paintings", false))
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPaintingPlace(PaintingPlaceEvent event)
{
if (event.isCancelled()) return;
if ( ! FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation().getBlock(), "place paintings", false) )
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityChangeBlock(EntityChangeBlockEvent event)
{
if (event.isCancelled()) return;
// for now, only interested in Enderman tomfoolery
if (!(event.getEntity() instanceof Enderman)) return;
FLocation floc = new FLocation(event.getBlock());
Faction faction = Board.getFactionAt(floc);
if (faction.getFlag(FFlag.ENDERGRIEF)) return;
event.setCancelled(true);
}
}
| false | true | public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify)
{
Entity damager = sub.getDamager();
Entity damagee = sub.getEntity();
int damage = sub.getDamage();
if ( ! (damagee instanceof Player)) return true;
FPlayer defender = FPlayers.i.get((Player)damagee);
if (defender == null || defender.getPlayer() == null)
return true;
Location defenderLoc = defender.getPlayer().getLocation();
Faction defLocFaction = Board.getFactionAt(new FLocation(defenderLoc));
// for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source
if (damager instanceof Projectile)
damager = ((Projectile)damager).getShooter();
if (damager == damagee) // ender pearl usage and other self-inflicted damage
return true;
// Players can not take attack damage in a SafeZone, or possibly peaceful territory
if (defLocFaction.getFlag(FFlag.PVP) == false)
{
if (damager instanceof Player)
{
if (notify)
{
FPlayer attacker = FPlayers.i.get((Player)damager);
attacker.msg("<i>PVP is disabled in %s.", defLocFaction.describeTo(attacker));
}
return false;
}
return defLocFaction.getFlag(FFlag.MONSTERS);
}
if ( ! (damager instanceof Player))
return true;
FPlayer attacker = FPlayers.i.get((Player)damager);
if (attacker == null || attacker.getPlayer() == null)
return true;
if (Conf.playersWhoBypassAllProtection.contains(attacker.getName())) return true;
if (attacker.hasLoginPvpDisabled())
{
if (notify) attacker.msg("<i>You can't hurt other players for " + Conf.noPVPDamageToOthersForXSecondsAfterLogin + " seconds after logging in.");
return false;
}
Faction locFaction = Board.getFactionAt(new FLocation(attacker));
// so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be?
if (locFaction.getFlag(FFlag.PVP) == false)
{
if (notify) attacker.msg("<i>PVP is disabled in %s.", locFaction.describeTo(attacker));
return false;
}
if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName()))
return true;
Faction defendFaction = defender.getFaction();
Faction attackFaction = attacker.getFaction();
if (attackFaction.isNone() && Conf.disablePVPForFactionlessPlayers)
{
if (notify) attacker.msg("<i>You can't hurt other players until you join a faction.");
return false;
}
else if (defendFaction.isNone())
{
if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand)
{
// Allow PVP vs. Factionless in attacker's faction territory
return true;
}
else if (Conf.disablePVPForFactionlessPlayers)
{
if (notify) attacker.msg("<i>You can't hurt players who are not currently in a faction.");
return false;
}
}
Rel relation = defendFaction.getRelationTo(attackFaction);
// Check the relation
if (relation.isAtLeast(Conf.friendlyFireFromRel) && defLocFaction.getFlag(FFlag.FRIENDLYFIRE) == false)
{
if (notify) attacker.msg("<i>You can't hurt %s<i>.", relation.getDescPlayerMany());
return false;
}
// You can not hurt neutrals in their own territory.
boolean ownTerritory = defender.isInOwnTerritory();
if (defender.hasFaction() && ownTerritory && relation == Rel.NEUTRAL)
{
if (notify)
{
attacker.msg("<i>You can't hurt %s<i> in their own territory unless you declare them as an enemy.", defender.describeTo(attacker));
defender.msg("%s<i> tried to hurt you.", attacker.describeTo(defender, true));
}
return false;
}
// Damage will be dealt. However check if the damage should be reduced.
if (damage > 0.0 && ownTerritory && Conf.territoryShieldFactor > 0)
{
int newDamage = (int)Math.ceil(damage * (1D - Conf.territoryShieldFactor));
sub.setDamage(newDamage);
// Send message
if (notify)
{
String perc = MessageFormat.format("{0,number,#%}", (Conf.territoryShieldFactor)); // TODO does this display correctly??
defender.msg("<i>Enemy damage reduced by <rose>%s<i>.", perc);
}
}
return true;
}
| public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify)
{
Entity damager = sub.getDamager();
Entity damagee = sub.getEntity();
int damage = sub.getDamage();
if ( ! (damagee instanceof Player)) return true;
FPlayer defender = FPlayers.i.get((Player)damagee);
if (defender == null || defender.getPlayer() == null)
return true;
Location defenderLoc = defender.getPlayer().getLocation();
Faction defLocFaction = Board.getFactionAt(new FLocation(defenderLoc));
// for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source
if (damager instanceof Projectile)
damager = ((Projectile)damager).getShooter();
if (damager == damagee) // ender pearl usage and other self-inflicted damage
return true;
// Players can not take attack damage in a SafeZone, or possibly peaceful territory
if (defLocFaction.getFlag(FFlag.PVP) == false)
{
if (damager instanceof Player)
{
if (notify)
{
FPlayer attacker = FPlayers.i.get((Player)damager);
attacker.msg("<i>PVP is disabled in %s.", defLocFaction.describeTo(attacker));
}
return false;
}
return defLocFaction.getFlag(FFlag.MONSTERS);
}
if ( ! (damager instanceof Player))
return true;
FPlayer attacker = FPlayers.i.get((Player)damager);
if (attacker == null || attacker.getPlayer() == null)
return true;
if (Conf.playersWhoBypassAllProtection.contains(attacker.getName())) return true;
if (attacker.hasLoginPvpDisabled())
{
if (notify) attacker.msg("<i>You can't hurt other players for " + Conf.noPVPDamageToOthersForXSecondsAfterLogin + " seconds after logging in.");
return false;
}
Faction locFaction = Board.getFactionAt(new FLocation(attacker));
// so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be?
if (locFaction.getFlag(FFlag.PVP) == false)
{
if (notify) attacker.msg("<i>PVP is disabled in %s.", locFaction.describeTo(attacker));
return false;
}
if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName()))
return true;
Faction defendFaction = defender.getFaction();
Faction attackFaction = attacker.getFaction();
if (attackFaction.isNone() && Conf.disablePVPForFactionlessPlayers)
{
if (notify) attacker.msg("<i>You can't hurt other players until you join a faction.");
return false;
}
else if (defendFaction.isNone())
{
if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand)
{
// Allow PVP vs. Factionless in attacker's faction territory
return true;
}
else if (Conf.disablePVPForFactionlessPlayers)
{
if (notify) attacker.msg("<i>You can't hurt players who are not currently in a faction.");
return false;
}
}
Rel relation = defendFaction.getRelationTo(attackFaction);
// Check the relation
if (defender.hasFaction() && relation.isAtLeast(Conf.friendlyFireFromRel) && defLocFaction.getFlag(FFlag.FRIENDLYFIRE) == false)
{
if (notify) attacker.msg("<i>You can't hurt %s<i>.", relation.getDescPlayerMany());
return false;
}
// You can not hurt neutrals in their own territory.
boolean ownTerritory = defender.isInOwnTerritory();
if (defender.hasFaction() && ownTerritory && relation == Rel.NEUTRAL)
{
if (notify)
{
attacker.msg("<i>You can't hurt %s<i> in their own territory unless you declare them as an enemy.", defender.describeTo(attacker));
defender.msg("%s<i> tried to hurt you.", attacker.describeTo(defender, true));
}
return false;
}
// Damage will be dealt. However check if the damage should be reduced.
if (damage > 0.0 && defender.hasFaction() && ownTerritory && Conf.territoryShieldFactor > 0)
{
int newDamage = (int)Math.ceil(damage * (1D - Conf.territoryShieldFactor));
sub.setDamage(newDamage);
// Send message
if (notify)
{
String perc = MessageFormat.format("{0,number,#%}", (Conf.territoryShieldFactor)); // TODO does this display correctly??
defender.msg("<i>Enemy damage reduced by <rose>%s<i>.", perc);
}
}
return true;
}
|
diff --git a/frost-wot/source/frost/fileTransfer/FileListManager.java b/frost-wot/source/frost/fileTransfer/FileListManager.java
index aeefe997..0787b566 100644
--- a/frost-wot/source/frost/fileTransfer/FileListManager.java
+++ b/frost-wot/source/frost/fileTransfer/FileListManager.java
@@ -1,277 +1,279 @@
/*
FileListManager.java / Frost
Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.fileTransfer;
import java.util.*;
import java.util.logging.*;
import frost.*;
import frost.fileTransfer.download.*;
import frost.fileTransfer.sharing.*;
import frost.identities.*;
import frost.storage.perst.filelist.*;
public class FileListManager {
private static final Logger logger = Logger.getLogger(FileListManager.class.getName());
public static final int MAX_FILES_PER_FILE = 250; // TODO: count utf-8 size of sharedxmlfiles, not more than 512kb!
/**
* Used to sort FrostSharedFileItems by refLastSent ascending.
*/
private static final Comparator<FrostSharedFileItem> refLastSentComparator = new Comparator<FrostSharedFileItem>() {
public int compare(FrostSharedFileItem value1, FrostSharedFileItem value2) {
if (value1.getRefLastSent() > value2.getRefLastSent()) {
return 1;
} else if (value1.getRefLastSent() < value2.getRefLastSent()) {
return -1;
} else {
return 0;
}
}
};
/**
* @return an info class that is guaranteed to contain an owner and files
*/
public static FileListManagerFileInfo getFilesToSend() {
// get files to share from UPLOADFILES
// - max. 250 keys per fileindex
// - get keys of only 1 owner/anonymous, next time get keys from different owner
// this wrap-arounding ensures that each file will be send over the time
// compute minDate, items last shared before this date must be reshared
final int maxAge = Core.frostSettings.getIntValue(SettingsClass.MIN_DAYS_BEFORE_FILE_RESHARE);
final long maxDiff = maxAge * 24L * 60L * 60L * 1000L;
final long now = System.currentTimeMillis();
final long minDate = now - maxDiff;
final List<LocalIdentity> localIdentities = Core.getIdentities().getLocalIdentities();
int identityCount = localIdentities.size();
while(identityCount > 0) {
LocalIdentity idToUpdate = null;
long minUpdateMillis = Long.MAX_VALUE;
// find next identity to update
for(final LocalIdentity id : localIdentities ) {
final long lastShared = id.getLastFilesSharedMillis();
if( lastShared < minUpdateMillis ) {
minUpdateMillis = lastShared;
idToUpdate = id;
}
}
// mark that we tried this owner
idToUpdate.updateLastFilesSharedMillis();
final LinkedList<SharedFileXmlFile> filesToShare = getUploadItemsToShare(idToUpdate.getUniqueName(), MAX_FILES_PER_FILE, minDate);
if( filesToShare != null && filesToShare.size() > 0 ) {
final FileListManagerFileInfo fif = new FileListManagerFileInfo(filesToShare, idToUpdate);
return fif;
}
// else try next owner
identityCount--;
}
// nothing to share now
return null;
}
private static LinkedList<SharedFileXmlFile> getUploadItemsToShare(final String owner, final int maxItems, final long minDate) {
final LinkedList<SharedFileXmlFile> result = new LinkedList<SharedFileXmlFile>();
final ArrayList<FrostSharedFileItem> sorted = new ArrayList<FrostSharedFileItem>();
{
final List<FrostSharedFileItem> sharedFileItems = FileTransferManager.inst().getSharedFilesManager().getSharedFileItemList();
// first collect all items for this owner and sort them
for( final FrostSharedFileItem sfo : sharedFileItems ) {
if( !sfo.isValid() ) {
continue;
}
if( !sfo.getOwner().equals(owner) ) {
continue;
}
sorted.add(sfo);
}
}
if( sorted.isEmpty() ) {
// no shared files for this owner
return result;
}
// sort ascending, oldest items at the beginning
Collections.sort(sorted, refLastSentComparator);
{
// check if oldest item must be shared (maybe its new or updated)
final FrostSharedFileItem sfo = sorted.get(0);
if( sfo.getRefLastSent() > minDate ) {
// oldest item is'nt too old, don't share
return result;
}
}
// finally add up to MAX_FILES items from the sorted list
for( final FrostSharedFileItem sfo : sorted ) {
result.add( sfo.getSharedFileXmlFileInstance() );
if( result.size() >= maxItems ) {
return result;
}
}
return result;
}
/**
* Update sent files.
* @param files List of SharedFileXmlFile objects that were successfully sent inside a CHK file
*/
public static boolean updateFileListWasSuccessfullySent(final List<SharedFileXmlFile> files) {
final long now = System.currentTimeMillis();
final List<FrostSharedFileItem> sharedFileItems = FileTransferManager.inst().getSharedFilesManager().getSharedFileItemList();
for( final SharedFileXmlFile sfx : files ) {
// update FrostSharedUploadFileObject
for( final FrostSharedFileItem sfo : sharedFileItems ) {
if( sfo.getSha().equals(sfx.getSha()) ) {
sfo.setRefLastSent(now);
}
}
}
return true;
}
/**
* Add or update received files from owner
*/
public static boolean processReceivedFileList(final FileListFileContent content) {
if( content == null
|| content.getReceivedOwner() == null
|| content.getFileList() == null
|| content.getFileList().size() == 0 )
{
return false;
}
Identity localOwner = Core.getIdentities().getIdentity(content.getReceivedOwner().getUniqueName());
if( localOwner == null ) {
// new identity, maybe add
if( !Core.getIdentities().isNewIdentityValid(content.getReceivedOwner()) ) {
// hash of public key does not match the unique name
return false;
}
Core.getIdentities().addIdentity(content.getReceivedOwner());
localOwner = content.getReceivedOwner();
}
localOwner.updateLastSeenTimestamp(content.getTimestamp());
if (localOwner.isBAD() && Core.frostSettings.getBoolValue(SettingsClass.SEARCH_HIDE_BAD)) {
logger.info("Skipped index file from BAD user " + localOwner.getUniqueName());
return true;
}
final List<FrostDownloadItem> downloadItems = FileTransferManager.inst().getDownloadManager().getDownloadItemList();
// update all filelist files, maybe restart failed downloads
final List<FrostDownloadItem> downloadsToRestart = new ArrayList<FrostDownloadItem>();
boolean errorOccured = false;
try {
for( final SharedFileXmlFile sfx : content.getFileList() ) {
final FrostFileListFileObject sfo = new FrostFileListFileObject(sfx, localOwner, content.getTimestamp());
// before updating the file list object (this overwrites the current lastUploaded time),
// check if there is a failed download item for this shared file. If yes, and the lastUpload
// time is later than the current one, restart the download automatically.
for( final FrostDownloadItem dlItem : downloadItems ) {
if( !dlItem.isSharedFile() || dlItem.getState() != FrostDownloadItem.STATE_FAILED ) {
continue;
}
final FrostFileListFileObject dlSfo = dlItem.getFileListFileObject();
if( dlSfo.getSha().equals( sfx.getSha() ) ) {
if( dlSfo.getLastUploaded() < sfo.getLastUploaded() ) {
// restart failed download, file was uploaded again
downloadsToRestart.add(dlItem); // restart later if no error occured
}
}
}
// update filelist storage
- final boolean wasOk = FileListStorage.inst().insertOrUpdateFileListFileObject(sfo);
+ final boolean wasOk = FileListStorage.inst().insertOrUpdateFileListFileObject(sfo, false);
if( wasOk == false ) {
errorOccured = true;
break;
}
}
} catch(final Throwable t) {
logger.log(Level.SEVERE, "Exception during insertOrUpdateFrostSharedFileObject", t);
+ } finally {
+ FileListStorage.inst().commit();
}
if( errorOccured ) {
return false;
}
// after updating the db, check if we have to update download items with the new informations
for( final SharedFileXmlFile sfx : content.getFileList() ) {
// if a FrostDownloadItem references this file (by sha), retrieve the updated file from db and set it
for( final FrostDownloadItem dlItem : downloadItems ) {
if( !dlItem.isSharedFile() ) {
continue;
}
final FrostFileListFileObject dlSfo = dlItem.getFileListFileObject();
if( dlSfo.getSha().equals( sfx.getSha() ) ) {
// this download item references the updated file
// update the shared file object from database (owner, sources, ... may have changed)
// NOTE: if no key was set before, this sets the chkKey and the ticker will start to download this file!
FrostFileListFileObject updatedSfo = null;
updatedSfo = FileListStorage.inst().getFileBySha(sfx.getSha());
if( updatedSfo != null ) {
dlItem.setFileListFileObject(updatedSfo);
} else {
System.out.println("no file for sha!");
}
break; // there is only one file in download table with same SHA
}
}
}
// restart failed downloads, as collected above
for( final FrostDownloadItem dlItem : downloadsToRestart ) {
dlItem.setState(FrostDownloadItem.STATE_WAITING);
dlItem.setRetries(0);
dlItem.setLastDownloadStopTime(0);
dlItem.setEnabled(Boolean.valueOf(true)); // enable download on restart
}
return true;
}
}
| false | true | public static boolean processReceivedFileList(final FileListFileContent content) {
if( content == null
|| content.getReceivedOwner() == null
|| content.getFileList() == null
|| content.getFileList().size() == 0 )
{
return false;
}
Identity localOwner = Core.getIdentities().getIdentity(content.getReceivedOwner().getUniqueName());
if( localOwner == null ) {
// new identity, maybe add
if( !Core.getIdentities().isNewIdentityValid(content.getReceivedOwner()) ) {
// hash of public key does not match the unique name
return false;
}
Core.getIdentities().addIdentity(content.getReceivedOwner());
localOwner = content.getReceivedOwner();
}
localOwner.updateLastSeenTimestamp(content.getTimestamp());
if (localOwner.isBAD() && Core.frostSettings.getBoolValue(SettingsClass.SEARCH_HIDE_BAD)) {
logger.info("Skipped index file from BAD user " + localOwner.getUniqueName());
return true;
}
final List<FrostDownloadItem> downloadItems = FileTransferManager.inst().getDownloadManager().getDownloadItemList();
// update all filelist files, maybe restart failed downloads
final List<FrostDownloadItem> downloadsToRestart = new ArrayList<FrostDownloadItem>();
boolean errorOccured = false;
try {
for( final SharedFileXmlFile sfx : content.getFileList() ) {
final FrostFileListFileObject sfo = new FrostFileListFileObject(sfx, localOwner, content.getTimestamp());
// before updating the file list object (this overwrites the current lastUploaded time),
// check if there is a failed download item for this shared file. If yes, and the lastUpload
// time is later than the current one, restart the download automatically.
for( final FrostDownloadItem dlItem : downloadItems ) {
if( !dlItem.isSharedFile() || dlItem.getState() != FrostDownloadItem.STATE_FAILED ) {
continue;
}
final FrostFileListFileObject dlSfo = dlItem.getFileListFileObject();
if( dlSfo.getSha().equals( sfx.getSha() ) ) {
if( dlSfo.getLastUploaded() < sfo.getLastUploaded() ) {
// restart failed download, file was uploaded again
downloadsToRestart.add(dlItem); // restart later if no error occured
}
}
}
// update filelist storage
final boolean wasOk = FileListStorage.inst().insertOrUpdateFileListFileObject(sfo);
if( wasOk == false ) {
errorOccured = true;
break;
}
}
} catch(final Throwable t) {
logger.log(Level.SEVERE, "Exception during insertOrUpdateFrostSharedFileObject", t);
}
if( errorOccured ) {
return false;
}
// after updating the db, check if we have to update download items with the new informations
for( final SharedFileXmlFile sfx : content.getFileList() ) {
// if a FrostDownloadItem references this file (by sha), retrieve the updated file from db and set it
for( final FrostDownloadItem dlItem : downloadItems ) {
if( !dlItem.isSharedFile() ) {
continue;
}
final FrostFileListFileObject dlSfo = dlItem.getFileListFileObject();
if( dlSfo.getSha().equals( sfx.getSha() ) ) {
// this download item references the updated file
// update the shared file object from database (owner, sources, ... may have changed)
// NOTE: if no key was set before, this sets the chkKey and the ticker will start to download this file!
FrostFileListFileObject updatedSfo = null;
updatedSfo = FileListStorage.inst().getFileBySha(sfx.getSha());
if( updatedSfo != null ) {
dlItem.setFileListFileObject(updatedSfo);
} else {
System.out.println("no file for sha!");
}
break; // there is only one file in download table with same SHA
}
}
}
// restart failed downloads, as collected above
for( final FrostDownloadItem dlItem : downloadsToRestart ) {
dlItem.setState(FrostDownloadItem.STATE_WAITING);
dlItem.setRetries(0);
dlItem.setLastDownloadStopTime(0);
dlItem.setEnabled(Boolean.valueOf(true)); // enable download on restart
}
return true;
}
| public static boolean processReceivedFileList(final FileListFileContent content) {
if( content == null
|| content.getReceivedOwner() == null
|| content.getFileList() == null
|| content.getFileList().size() == 0 )
{
return false;
}
Identity localOwner = Core.getIdentities().getIdentity(content.getReceivedOwner().getUniqueName());
if( localOwner == null ) {
// new identity, maybe add
if( !Core.getIdentities().isNewIdentityValid(content.getReceivedOwner()) ) {
// hash of public key does not match the unique name
return false;
}
Core.getIdentities().addIdentity(content.getReceivedOwner());
localOwner = content.getReceivedOwner();
}
localOwner.updateLastSeenTimestamp(content.getTimestamp());
if (localOwner.isBAD() && Core.frostSettings.getBoolValue(SettingsClass.SEARCH_HIDE_BAD)) {
logger.info("Skipped index file from BAD user " + localOwner.getUniqueName());
return true;
}
final List<FrostDownloadItem> downloadItems = FileTransferManager.inst().getDownloadManager().getDownloadItemList();
// update all filelist files, maybe restart failed downloads
final List<FrostDownloadItem> downloadsToRestart = new ArrayList<FrostDownloadItem>();
boolean errorOccured = false;
try {
for( final SharedFileXmlFile sfx : content.getFileList() ) {
final FrostFileListFileObject sfo = new FrostFileListFileObject(sfx, localOwner, content.getTimestamp());
// before updating the file list object (this overwrites the current lastUploaded time),
// check if there is a failed download item for this shared file. If yes, and the lastUpload
// time is later than the current one, restart the download automatically.
for( final FrostDownloadItem dlItem : downloadItems ) {
if( !dlItem.isSharedFile() || dlItem.getState() != FrostDownloadItem.STATE_FAILED ) {
continue;
}
final FrostFileListFileObject dlSfo = dlItem.getFileListFileObject();
if( dlSfo.getSha().equals( sfx.getSha() ) ) {
if( dlSfo.getLastUploaded() < sfo.getLastUploaded() ) {
// restart failed download, file was uploaded again
downloadsToRestart.add(dlItem); // restart later if no error occured
}
}
}
// update filelist storage
final boolean wasOk = FileListStorage.inst().insertOrUpdateFileListFileObject(sfo, false);
if( wasOk == false ) {
errorOccured = true;
break;
}
}
} catch(final Throwable t) {
logger.log(Level.SEVERE, "Exception during insertOrUpdateFrostSharedFileObject", t);
} finally {
FileListStorage.inst().commit();
}
if( errorOccured ) {
return false;
}
// after updating the db, check if we have to update download items with the new informations
for( final SharedFileXmlFile sfx : content.getFileList() ) {
// if a FrostDownloadItem references this file (by sha), retrieve the updated file from db and set it
for( final FrostDownloadItem dlItem : downloadItems ) {
if( !dlItem.isSharedFile() ) {
continue;
}
final FrostFileListFileObject dlSfo = dlItem.getFileListFileObject();
if( dlSfo.getSha().equals( sfx.getSha() ) ) {
// this download item references the updated file
// update the shared file object from database (owner, sources, ... may have changed)
// NOTE: if no key was set before, this sets the chkKey and the ticker will start to download this file!
FrostFileListFileObject updatedSfo = null;
updatedSfo = FileListStorage.inst().getFileBySha(sfx.getSha());
if( updatedSfo != null ) {
dlItem.setFileListFileObject(updatedSfo);
} else {
System.out.println("no file for sha!");
}
break; // there is only one file in download table with same SHA
}
}
}
// restart failed downloads, as collected above
for( final FrostDownloadItem dlItem : downloadsToRestart ) {
dlItem.setState(FrostDownloadItem.STATE_WAITING);
dlItem.setRetries(0);
dlItem.setLastDownloadStopTime(0);
dlItem.setEnabled(Boolean.valueOf(true)); // enable download on restart
}
return true;
}
|
diff --git a/NTalk/src/main/java/fr/ribesg/bukkit/ntalk/TalkListener.java b/NTalk/src/main/java/fr/ribesg/bukkit/ntalk/TalkListener.java
index c5523a00..b36b4bd6 100644
--- a/NTalk/src/main/java/fr/ribesg/bukkit/ntalk/TalkListener.java
+++ b/NTalk/src/main/java/fr/ribesg/bukkit/ntalk/TalkListener.java
@@ -1,153 +1,153 @@
/***************************************************************************
* Project file: NPlugins - NTalk - TalkListener.java *
* Full Class name: fr.ribesg.bukkit.ntalk.TalkListener *
* *
* Copyright (c) 2012-2014 Ribesg - www.ribesg.fr *
* This file is under GPLv3 -> http://www.gnu.org/licenses/gpl-3.0.txt *
* Please contact me at ribesg[at]yahoo.fr if you improve this file! *
***************************************************************************/
package fr.ribesg.bukkit.ntalk;
import fr.ribesg.bukkit.ncore.lang.MessageId;
import fr.ribesg.bukkit.ncore.utils.ColorUtils;
import fr.ribesg.bukkit.ntalk.filter.ChatFilter;
import fr.ribesg.bukkit.ntalk.filter.bean.BanFilter;
import fr.ribesg.bukkit.ntalk.filter.bean.Filter;
import fr.ribesg.bukkit.ntalk.filter.bean.JailFilter;
import fr.ribesg.bukkit.ntalk.filter.bean.MuteFilter;
import fr.ribesg.bukkit.ntalk.filter.bean.ReplaceFilter;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import java.util.concurrent.Callable;
import java.util.logging.Logger;
public class TalkListener implements Listener {
private static final Logger LOGGER = Logger.getLogger(TalkListener.class.getName());
private final NTalk plugin;
private final ChatFilter filter;
public TalkListener(final NTalk instance) {
plugin = instance;
filter = plugin.getChatFilter();
}
/** Handles "@playerName message" PMs */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerChatFirst(final AsyncPlayerChatEvent event) {
if (event.getMessage().startsWith("@") && !event.getMessage().startsWith("@ ")) {
final String[] split = event.getMessage().substring(1).split(" ");
if (split.length >= 2) {
event.setCancelled(true);
final String targetName = split[0];
final String message = event.getMessage().substring(targetName.length() + 1);
final StringBuilder command = new StringBuilder("pm ");
command.append(targetName);
command.append(message);
plugin.getServer().dispatchCommand(event.getPlayer(), command.toString());
}
}
}
/** Handles chat filter */
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerChatThen(final AsyncPlayerChatEvent event) {
if (filter != null) {
final String message = event.getMessage();
final String uncoloredMessage = ColorUtils.stripColorCodes(message);
- final Filter result = filter.check(uncoloredMessage);
+ final Filter result = filter.check(' ' + uncoloredMessage + ' ');
if (result != null) {
switch (result.getResponseType()) {
case DENY:
event.setCancelled(true);
break;
case REPLACE:
final ReplaceFilter replaceFilter = (ReplaceFilter) result;
String newMessage;
if (replaceFilter.isRegex()) {
newMessage = message.replaceAll(replaceFilter.getFilteredString(), replaceFilter.getReplacement());
} else {
newMessage = message;
while (newMessage.contains(replaceFilter.getFilteredString())) {
newMessage = newMessage.replace(replaceFilter.getFilteredString(), replaceFilter.getReplacement());
}
}
event.setMessage(newMessage);
break;
case TEMPORARY_MUTE:
final MuteFilter muteFilter = (MuteFilter) result;
final String mutePlayerName = event.getPlayer().getName();
final long muteDuration = muteFilter.getDuration();
final String muteReason = plugin.getMessages()
.get(MessageId.talk_filterMutedReason, muteFilter.getOutputString())[0];
final String muteCommand = plugin.getPluginConfig().getTempMuteCommand(mutePlayerName, muteDuration, muteReason);
Bukkit.getScheduler().callSyncMethod(plugin, new Callable<Object>() {
@Override
public Object call() throws Exception {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), muteCommand);
return null;
}
});
break;
case TEMPORARY_BAN:
final BanFilter banFilter = (BanFilter) result;
final String banPlayerName = event.getPlayer().getName();
final long banDuration = banFilter.getDuration();
final String banReason = plugin.getMessages()
.get(MessageId.talk_filterBannedReason, banFilter.getOutputString())[0];
final String banCommand = plugin.getPluginConfig().getTempBanCommand(banPlayerName, banDuration, banReason);
Bukkit.getScheduler().callSyncMethod(plugin, new Callable<Object>() {
@Override
public Object call() throws Exception {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), banCommand);
return null;
}
});
break;
case TEMPORARY_JAIL:
final JailFilter jailFilter = (JailFilter) result;
final String jailPlayerName = event.getPlayer().getName();
final long jailDuration = jailFilter.getDuration();
final String jailName = jailFilter.getJailName();
final String jailReason = plugin.getMessages()
.get(MessageId.talk_filterJailedReason, jailFilter.getOutputString())[0];
final String jailCommand = plugin.getPluginConfig()
.getTempJailCommand(jailPlayerName, jailDuration, jailName, jailReason);
Bukkit.getScheduler().callSyncMethod(plugin, new Callable<Object>() {
@Override
public Object call() throws Exception {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), jailCommand);
return null;
}
});
break;
case DIVINE_PUNISHMENT:
// TODO
LOGGER.severe("Divine Punishment has not yet been implemented! Please don't use it!");
break;
default:
break;
}
}
}
}
/** Handles colors in chat */
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerChatLast(final AsyncPlayerChatEvent event) {
event.setFormat(plugin.getFormater().getFormat(event.getPlayer(), true));
if (Perms.hasColor(event.getPlayer(), true)) {
event.setMessage(ChatColor.translateAlternateColorCodes('&', event.getMessage())); // Reformat the message
}
}
}
| true | true | public void onPlayerChatThen(final AsyncPlayerChatEvent event) {
if (filter != null) {
final String message = event.getMessage();
final String uncoloredMessage = ColorUtils.stripColorCodes(message);
final Filter result = filter.check(uncoloredMessage);
if (result != null) {
switch (result.getResponseType()) {
case DENY:
event.setCancelled(true);
break;
case REPLACE:
final ReplaceFilter replaceFilter = (ReplaceFilter) result;
String newMessage;
if (replaceFilter.isRegex()) {
newMessage = message.replaceAll(replaceFilter.getFilteredString(), replaceFilter.getReplacement());
} else {
newMessage = message;
while (newMessage.contains(replaceFilter.getFilteredString())) {
newMessage = newMessage.replace(replaceFilter.getFilteredString(), replaceFilter.getReplacement());
}
}
event.setMessage(newMessage);
break;
case TEMPORARY_MUTE:
final MuteFilter muteFilter = (MuteFilter) result;
final String mutePlayerName = event.getPlayer().getName();
final long muteDuration = muteFilter.getDuration();
final String muteReason = plugin.getMessages()
.get(MessageId.talk_filterMutedReason, muteFilter.getOutputString())[0];
final String muteCommand = plugin.getPluginConfig().getTempMuteCommand(mutePlayerName, muteDuration, muteReason);
Bukkit.getScheduler().callSyncMethod(plugin, new Callable<Object>() {
@Override
public Object call() throws Exception {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), muteCommand);
return null;
}
});
break;
case TEMPORARY_BAN:
final BanFilter banFilter = (BanFilter) result;
final String banPlayerName = event.getPlayer().getName();
final long banDuration = banFilter.getDuration();
final String banReason = plugin.getMessages()
.get(MessageId.talk_filterBannedReason, banFilter.getOutputString())[0];
final String banCommand = plugin.getPluginConfig().getTempBanCommand(banPlayerName, banDuration, banReason);
Bukkit.getScheduler().callSyncMethod(plugin, new Callable<Object>() {
@Override
public Object call() throws Exception {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), banCommand);
return null;
}
});
break;
case TEMPORARY_JAIL:
final JailFilter jailFilter = (JailFilter) result;
final String jailPlayerName = event.getPlayer().getName();
final long jailDuration = jailFilter.getDuration();
final String jailName = jailFilter.getJailName();
final String jailReason = plugin.getMessages()
.get(MessageId.talk_filterJailedReason, jailFilter.getOutputString())[0];
final String jailCommand = plugin.getPluginConfig()
.getTempJailCommand(jailPlayerName, jailDuration, jailName, jailReason);
Bukkit.getScheduler().callSyncMethod(plugin, new Callable<Object>() {
@Override
public Object call() throws Exception {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), jailCommand);
return null;
}
});
break;
case DIVINE_PUNISHMENT:
// TODO
LOGGER.severe("Divine Punishment has not yet been implemented! Please don't use it!");
break;
default:
break;
}
}
}
}
| public void onPlayerChatThen(final AsyncPlayerChatEvent event) {
if (filter != null) {
final String message = event.getMessage();
final String uncoloredMessage = ColorUtils.stripColorCodes(message);
final Filter result = filter.check(' ' + uncoloredMessage + ' ');
if (result != null) {
switch (result.getResponseType()) {
case DENY:
event.setCancelled(true);
break;
case REPLACE:
final ReplaceFilter replaceFilter = (ReplaceFilter) result;
String newMessage;
if (replaceFilter.isRegex()) {
newMessage = message.replaceAll(replaceFilter.getFilteredString(), replaceFilter.getReplacement());
} else {
newMessage = message;
while (newMessage.contains(replaceFilter.getFilteredString())) {
newMessage = newMessage.replace(replaceFilter.getFilteredString(), replaceFilter.getReplacement());
}
}
event.setMessage(newMessage);
break;
case TEMPORARY_MUTE:
final MuteFilter muteFilter = (MuteFilter) result;
final String mutePlayerName = event.getPlayer().getName();
final long muteDuration = muteFilter.getDuration();
final String muteReason = plugin.getMessages()
.get(MessageId.talk_filterMutedReason, muteFilter.getOutputString())[0];
final String muteCommand = plugin.getPluginConfig().getTempMuteCommand(mutePlayerName, muteDuration, muteReason);
Bukkit.getScheduler().callSyncMethod(plugin, new Callable<Object>() {
@Override
public Object call() throws Exception {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), muteCommand);
return null;
}
});
break;
case TEMPORARY_BAN:
final BanFilter banFilter = (BanFilter) result;
final String banPlayerName = event.getPlayer().getName();
final long banDuration = banFilter.getDuration();
final String banReason = plugin.getMessages()
.get(MessageId.talk_filterBannedReason, banFilter.getOutputString())[0];
final String banCommand = plugin.getPluginConfig().getTempBanCommand(banPlayerName, banDuration, banReason);
Bukkit.getScheduler().callSyncMethod(plugin, new Callable<Object>() {
@Override
public Object call() throws Exception {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), banCommand);
return null;
}
});
break;
case TEMPORARY_JAIL:
final JailFilter jailFilter = (JailFilter) result;
final String jailPlayerName = event.getPlayer().getName();
final long jailDuration = jailFilter.getDuration();
final String jailName = jailFilter.getJailName();
final String jailReason = plugin.getMessages()
.get(MessageId.talk_filterJailedReason, jailFilter.getOutputString())[0];
final String jailCommand = plugin.getPluginConfig()
.getTempJailCommand(jailPlayerName, jailDuration, jailName, jailReason);
Bukkit.getScheduler().callSyncMethod(plugin, new Callable<Object>() {
@Override
public Object call() throws Exception {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), jailCommand);
return null;
}
});
break;
case DIVINE_PUNISHMENT:
// TODO
LOGGER.severe("Divine Punishment has not yet been implemented! Please don't use it!");
break;
default:
break;
}
}
}
}
|
diff --git a/src/org/accesointeligente/server/robots/RequestCreator.java b/src/org/accesointeligente/server/robots/RequestCreator.java
index d41bf63..65a9838 100644
--- a/src/org/accesointeligente/server/robots/RequestCreator.java
+++ b/src/org/accesointeligente/server/robots/RequestCreator.java
@@ -1,79 +1,79 @@
/**
* Acceso Inteligente
*
* Copyright (C) 2010-2011 Fundación Ciudadano Inteligente
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.accesointeligente.server.robots;
import org.accesointeligente.model.Request;
import org.accesointeligente.server.HibernateUtil;
import org.accesointeligente.server.RobotContext;
import org.accesointeligente.shared.RequestStatus;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import java.util.List;
public class RequestCreator {
private static final Logger logger = Logger.getLogger(RequestCreator.class);
public void createRequests() {
Session hibernate = null;
try {
hibernate = HibernateUtil.getSession();
hibernate.beginTransaction();
Criteria criteria = hibernate.createCriteria(Request.class);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.setFetchMode("institution", FetchMode.JOIN);
criteria.add(Restrictions.eq("status", RequestStatus.NEW));
- criteria.createAlias("institution", "ins").add(Restrictions.eq("ins.masterEnabled", "true"));
+ criteria.createAlias("institution", "ins").add(Restrictions.eq("ins.masterEnabled", true));
List<Request> newRequests = criteria.list();
hibernate.getTransaction().commit();
for (Request request : newRequests) {
if (!request.getInstitution().getEnabled()) {
continue;
}
logger.info("requestId = " + request.getId());
try {
Robot robot = RobotContext.getRobot(request.getInstitution().getInstitutionClass());
if (robot != null) {
request = robot.makeRequest(request);
hibernate = HibernateUtil.getSession();
hibernate.beginTransaction();
hibernate.update(request);
hibernate.getTransaction().commit();
}
} catch (Exception ex) {
logger.error("requestId = " + request.getId(), ex);
}
}
} catch (Exception ex) {
if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
hibernate.getTransaction().rollback();
logger.error("Failure", ex);
}
}
}
}
| true | true | public void createRequests() {
Session hibernate = null;
try {
hibernate = HibernateUtil.getSession();
hibernate.beginTransaction();
Criteria criteria = hibernate.createCriteria(Request.class);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.setFetchMode("institution", FetchMode.JOIN);
criteria.add(Restrictions.eq("status", RequestStatus.NEW));
criteria.createAlias("institution", "ins").add(Restrictions.eq("ins.masterEnabled", "true"));
List<Request> newRequests = criteria.list();
hibernate.getTransaction().commit();
for (Request request : newRequests) {
if (!request.getInstitution().getEnabled()) {
continue;
}
logger.info("requestId = " + request.getId());
try {
Robot robot = RobotContext.getRobot(request.getInstitution().getInstitutionClass());
if (robot != null) {
request = robot.makeRequest(request);
hibernate = HibernateUtil.getSession();
hibernate.beginTransaction();
hibernate.update(request);
hibernate.getTransaction().commit();
}
} catch (Exception ex) {
logger.error("requestId = " + request.getId(), ex);
}
}
} catch (Exception ex) {
if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
hibernate.getTransaction().rollback();
logger.error("Failure", ex);
}
}
}
| public void createRequests() {
Session hibernate = null;
try {
hibernate = HibernateUtil.getSession();
hibernate.beginTransaction();
Criteria criteria = hibernate.createCriteria(Request.class);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.setFetchMode("institution", FetchMode.JOIN);
criteria.add(Restrictions.eq("status", RequestStatus.NEW));
criteria.createAlias("institution", "ins").add(Restrictions.eq("ins.masterEnabled", true));
List<Request> newRequests = criteria.list();
hibernate.getTransaction().commit();
for (Request request : newRequests) {
if (!request.getInstitution().getEnabled()) {
continue;
}
logger.info("requestId = " + request.getId());
try {
Robot robot = RobotContext.getRobot(request.getInstitution().getInstitutionClass());
if (robot != null) {
request = robot.makeRequest(request);
hibernate = HibernateUtil.getSession();
hibernate.beginTransaction();
hibernate.update(request);
hibernate.getTransaction().commit();
}
} catch (Exception ex) {
logger.error("requestId = " + request.getId(), ex);
}
}
} catch (Exception ex) {
if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
hibernate.getTransaction().rollback();
logger.error("Failure", ex);
}
}
}
|
diff --git a/src/org/ops4j/peaberry/Peaberry.java b/src/org/ops4j/peaberry/Peaberry.java
index 03bd4cbb..21d46098 100644
--- a/src/org/ops4j/peaberry/Peaberry.java
+++ b/src/org/ops4j/peaberry/Peaberry.java
@@ -1,164 +1,164 @@
/**
* Copyright (C) 2008 Stuart McCulloch
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ops4j.peaberry;
import static com.google.inject.matcher.Matchers.member;
import static org.ops4j.peaberry.internal.ServiceMatcher.annotatedWithService;
import static org.ops4j.peaberry.internal.ServiceProviderFactory.getServiceProvider;
import java.lang.annotation.Annotation;
import org.ops4j.peaberry.internal.NonDelegatingClassLoaderHook;
import org.ops4j.peaberry.internal.OSGiServiceRegistry;
import org.ops4j.peaberry.internal.ServiceBindingFactory;
import org.osgi.framework.BundleContext;
import com.google.inject.Binder;
import com.google.inject.ClassLoaderHook;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.internal.GuiceCodeGen;
/**
* Guice extension that supports injection of dynamic services.
*
* @author [email protected] (Stuart McCulloch)
*/
public final class Peaberry {
// instances not allowed
private Peaberry() {}
/**
* Create a {@link Service} specification on-the-fly.
*
* @param filter RFC-1960 (LDAP) filter
* @param interfaces custom service API
* @return {@link Service} specification
*/
public static Service service(final String filter,
final Class<?>... interfaces) {
return new Service() {
public Class<?>[] interfaces() {
return interfaces;
}
public String value() {
- return filter;
+ return null == filter ? "" : filter;
}
public Class<? extends Annotation> annotationType() {
return Service.class;
}
};
}
/**
* Create a {@link Leased} setting on-the-fly.
*
* @param seconds lease time in seconds
* @return {@link Leased} setting
*/
public static Leased leased(final int seconds) {
return new Leased() {
public int seconds() {
return seconds;
}
public Class<? extends Annotation> annotationType() {
return Leased.class;
}
};
}
/**
* Creates a dynamic service provider for the given {@link ServiceRegistry}.
* The provider is configured with the {@link Service} specification and is
* optionally {@link Leased}.
*
* @param registry dynamic service registry
* @param target literal type of the target
* @return dynamic service provider
*/
public static <T> Provider<T> serviceProvider(ServiceRegistry registry,
TypeLiteral<T> target) {
return getServiceProvider(registry, target, null, null);
}
/**
* Creates a dynamic service provider for the given {@link ServiceRegistry}.
* The provider is configured with the {@link Service} specification and is
* optionally {@link Leased}.
*
* @param registry dynamic service registry
* @param target literal type of the target
* @param spec custom service specification
* @param leased optionally leased
* @return dynamic service provider
*/
public static <T> Provider<T> serviceProvider(ServiceRegistry registry,
TypeLiteral<T> target, Service spec, Leased leased) {
return getServiceProvider(registry, target, spec, leased);
}
/**
* Create a new OSGi {@link ServiceRegistry} adaptor for the given bundle.
*
* @param bundleContext current bundle context
* @return OSGi specific {@link ServiceRegistry}
*/
public static ServiceRegistry getOSGiServiceRegistry(
BundleContext bundleContext) {
return new OSGiServiceRegistry(bundleContext);
}
private static final ClassLoaderHook OSGI_CLASSLOADER_HOOK =
new NonDelegatingClassLoaderHook();
/**
* Enable support for non-delegating containers, such as OSGi
*/
public static void nonDelegatingContainer() {
GuiceCodeGen.setThreadClassLoaderHook(OSGI_CLASSLOADER_HOOK);
}
/**
* @param bundleContext current bundle context
* @return OSGi service injection rules
*/
public static Module getBundleModule(final BundleContext bundleContext) {
return new Module() {
public void configure(Binder binder) {
binder.bind(BundleContext.class).toInstance(bundleContext);
// auto-bind service dependencies and implementations
binder.addBindingFactory(member(annotatedWithService()),
new ServiceBindingFactory(getOSGiServiceRegistry(bundleContext)));
nonDelegatingContainer();
}
};
}
}
| true | true | public static Service service(final String filter,
final Class<?>... interfaces) {
return new Service() {
public Class<?>[] interfaces() {
return interfaces;
}
public String value() {
return filter;
}
public Class<? extends Annotation> annotationType() {
return Service.class;
}
};
}
| public static Service service(final String filter,
final Class<?>... interfaces) {
return new Service() {
public Class<?>[] interfaces() {
return interfaces;
}
public String value() {
return null == filter ? "" : filter;
}
public Class<? extends Annotation> annotationType() {
return Service.class;
}
};
}
|
diff --git a/AE-go_GameServer/data/scripts/system/handlers/admincommands/Set.java b/AE-go_GameServer/data/scripts/system/handlers/admincommands/Set.java
index 4cc8a086..1799f99e 100644
--- a/AE-go_GameServer/data/scripts/system/handlers/admincommands/Set.java
+++ b/AE-go_GameServer/data/scripts/system/handlers/admincommands/Set.java
@@ -1,205 +1,205 @@
package admincommands;
import java.util.Arrays;
import com.aionemu.gameserver.configs.AdminConfig;
import com.aionemu.gameserver.model.PlayerClass;
import com.aionemu.gameserver.model.gameobjects.VisibleObject;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_TITLE_SET;
import com.aionemu.gameserver.network.aion.serverpackets.SM_TITLE_UPDATE;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.chathandlers.AdminCommand;
/**
* @author Nemiroff, ATracer, IceReaper
* Date: 11.12.2009
*/
public class Set extends AdminCommand {
public Set() {
super("set");
}
@Override
public void executeCommand(Player admin, String[] params)
{
- if (params == null || params.length < 1)
+ if (params == null || params.length < 2)
{
PacketSendUtility.sendMessage(admin, "syntax //set <class|exp|level|title>");
return;
}
Player target = null;
VisibleObject creature = admin.getTarget();
if (admin.getTarget() instanceof Player)
{
target = (Player) creature;
}
if (target == null)
{
PacketSendUtility.sendMessage(admin, "You should select a target first!");
return;
}
if (params[1] == null)
{
PacketSendUtility.sendMessage(admin, "You should enter second params!");
return;
}
String paramValue = params[1];
if (params[0].equals("class"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETCLASS)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
byte newClass;
try
{
newClass = Byte.parseByte(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
PlayerClass oldClass = admin.getPlayerClass();
setClass(admin, oldClass, newClass);
}
else if (params[0].equals("exp"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETEXP)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
long exp;
try
{
exp = Long.parseLong(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
if (target instanceof Player)
{
Player player = (Player) target;
player.getCommonData().setExp(exp);
PacketSendUtility.sendMessage(admin, "Set your exp to " + paramValue);
}
}
else if (params[0].equals("level"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETLEVEL)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
int level;
try
{
level = Integer.parseInt(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
if (target instanceof Player)
{
Player player = (Player) target;
if (level <= 51)
player.getCommonData().setLevel(level);
PacketSendUtility.sendMessage(admin, "Set target level to " + level);
}
}
else if (params[0].equals("title"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETTITLE)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
int titleId;
try
{
titleId = Integer.parseInt(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
if (target instanceof Player)
{
Player player = (Player) target;
if (titleId <= 106)
setTitle(player, titleId);
PacketSendUtility.sendMessage(admin, "Set title to " + titleId);
}
}
}
private void setTitle(Player player, int value)
{
PacketSendUtility.sendPacket(player, new SM_TITLE_SET(value));
PacketSendUtility.broadcastPacket(player, (new SM_TITLE_UPDATE(player, value)));
player.getCommonData().setTitleId(value);
}
private void setClass(Player player, PlayerClass oldClass, byte value)
{
PlayerClass playerClass = PlayerClass.getPlayerClassById(value);
int level = player.getLevel();
if (level < 9)
{
PacketSendUtility.sendMessage(player, "You can switch class after your level reach 9");
return;
}
if (Arrays.asList(new int[]{1, 2, 4, 5, 7, 8, 10, 11}).contains(oldClass.ordinal()))
{
PacketSendUtility.sendMessage(player, "You already switched class");
return;
}
int newClassId = playerClass.ordinal();
switch (oldClass.ordinal())
{
case 0:
if (newClassId == 1 || newClassId == 2)
break;
case 3:
if (newClassId == 4 || newClassId == 5)
break;
case 6:
if (newClassId == 7 || newClassId == 8)
break;
case 9:
if (newClassId == 10 || newClassId == 11)
break;
default:
PacketSendUtility.sendMessage(player, "Invalid class switch chosen");
return;
}
player.getCommonData().setPlayerClass(playerClass);
player.getCommonData().upgradePlayer();
PacketSendUtility.sendMessage(player, "You have success switch class");
}
}
| true | true | public void executeCommand(Player admin, String[] params)
{
if (params == null || params.length < 1)
{
PacketSendUtility.sendMessage(admin, "syntax //set <class|exp|level|title>");
return;
}
Player target = null;
VisibleObject creature = admin.getTarget();
if (admin.getTarget() instanceof Player)
{
target = (Player) creature;
}
if (target == null)
{
PacketSendUtility.sendMessage(admin, "You should select a target first!");
return;
}
if (params[1] == null)
{
PacketSendUtility.sendMessage(admin, "You should enter second params!");
return;
}
String paramValue = params[1];
if (params[0].equals("class"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETCLASS)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
byte newClass;
try
{
newClass = Byte.parseByte(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
PlayerClass oldClass = admin.getPlayerClass();
setClass(admin, oldClass, newClass);
}
else if (params[0].equals("exp"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETEXP)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
long exp;
try
{
exp = Long.parseLong(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
if (target instanceof Player)
{
Player player = (Player) target;
player.getCommonData().setExp(exp);
PacketSendUtility.sendMessage(admin, "Set your exp to " + paramValue);
}
}
else if (params[0].equals("level"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETLEVEL)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
int level;
try
{
level = Integer.parseInt(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
if (target instanceof Player)
{
Player player = (Player) target;
if (level <= 51)
player.getCommonData().setLevel(level);
PacketSendUtility.sendMessage(admin, "Set target level to " + level);
}
}
else if (params[0].equals("title"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETTITLE)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
int titleId;
try
{
titleId = Integer.parseInt(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
if (target instanceof Player)
{
Player player = (Player) target;
if (titleId <= 106)
setTitle(player, titleId);
PacketSendUtility.sendMessage(admin, "Set title to " + titleId);
}
}
}
| public void executeCommand(Player admin, String[] params)
{
if (params == null || params.length < 2)
{
PacketSendUtility.sendMessage(admin, "syntax //set <class|exp|level|title>");
return;
}
Player target = null;
VisibleObject creature = admin.getTarget();
if (admin.getTarget() instanceof Player)
{
target = (Player) creature;
}
if (target == null)
{
PacketSendUtility.sendMessage(admin, "You should select a target first!");
return;
}
if (params[1] == null)
{
PacketSendUtility.sendMessage(admin, "You should enter second params!");
return;
}
String paramValue = params[1];
if (params[0].equals("class"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETCLASS)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
byte newClass;
try
{
newClass = Byte.parseByte(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
PlayerClass oldClass = admin.getPlayerClass();
setClass(admin, oldClass, newClass);
}
else if (params[0].equals("exp"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETEXP)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
long exp;
try
{
exp = Long.parseLong(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
if (target instanceof Player)
{
Player player = (Player) target;
player.getCommonData().setExp(exp);
PacketSendUtility.sendMessage(admin, "Set your exp to " + paramValue);
}
}
else if (params[0].equals("level"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETLEVEL)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
int level;
try
{
level = Integer.parseInt(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
if (target instanceof Player)
{
Player player = (Player) target;
if (level <= 51)
player.getCommonData().setLevel(level);
PacketSendUtility.sendMessage(admin, "Set target level to " + level);
}
}
else if (params[0].equals("title"))
{
if(admin.getCommonData().getAdminRole() < AdminConfig.COMMAND_SETTITLE)
{
PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
return;
}
int titleId;
try
{
titleId = Integer.parseInt(paramValue);
}
catch (NumberFormatException e)
{
PacketSendUtility.sendMessage(admin, "You should enter valid second params!");
return;
}
if (target instanceof Player)
{
Player player = (Player) target;
if (titleId <= 106)
setTitle(player, titleId);
PacketSendUtility.sendMessage(admin, "Set title to " + titleId);
}
}
}
|
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/CallInfo.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/CallInfo.java
index 697ff4c1..32574789 100644
--- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/CallInfo.java
+++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/CallInfo.java
@@ -1,146 +1,148 @@
package jp.ac.osaka_u.ist.sel.metricstool.main.data.target;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import jp.ac.osaka_u.ist.sel.metricstool.main.security.MetricsToolSecurityManager;
/**
* ���\�b�h�Ăяo���C�R���X�g���N�^�Ăяo���̋��ʂ̐e�N���X
*
* @author higo
*
*/
public abstract class CallInfo<T extends CallableUnitInfo> extends ExpressionInfo {
/**
* @param callee �Ă�Ă���I�u�W�F�N�g�C���̌Ăяo�����C�z��̃R���X�g���N�^�̏ꍇ��null�������Ă���D
* @param ownerMethod �I�[�i�[���\�b�h
* @param fromLine �J�n�s
* @param fromColumn �J�n��
* @param toLine �I���s
* @param toColumn �I����
*/
CallInfo(final T callee, final CallableUnitInfo ownerMethod, final int fromLine,
final int fromColumn, final int toLine, final int toColumn) {
super(ownerMethod, fromLine, fromColumn, toLine, toColumn);
this.arguments = new LinkedList<ExpressionInfo>();
this.typeArguments = new LinkedList<ReferenceTypeInfo>();
this.callee = callee;
// ���\�b�h�Ăяo���W���\�z
- this.callee.addCaller(ownerMethod);
+ if (null != callee) {
+ this.callee.addCaller(ownerMethod);
+ }
}
/**
* ���̃��\�b�h�Ăяo���̎�������lj��D�v���O�C������͌Ăяo���Ȃ��D
*
* @param argument �lj����������
*/
public final void addArgument(final ExpressionInfo argument) {
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == argument) {
throw new NullPointerException();
}
this.arguments.add(argument);
argument.setOwnerExecutableElement(this);
}
/**
* ���̌Ăяo���̎�������lj��D�v���O�C������͌Ăяo���Ȃ��D
*
* @param arguments �lj����������
*/
public final void addArguments(final List<ExpressionInfo> arguments) {
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == arguments) {
throw new NullPointerException();
}
this.arguments.addAll(arguments);
for (final ExpressionInfo argument : arguments) {
argument.setOwnerExecutableElement(this);
}
}
/**
* ���̃��\�b�h�Ăяo���̌^������lj��D�v���O�C������͌Ăяo���Ȃ�
*
* @param typeArgument �lj�����^����
*/
public final void addTypeArgument(final ReferenceTypeInfo typeArgument) {
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == typeArgument) {
throw new NullPointerException();
}
this.typeArguments.add(typeArgument);
}
/**
* ���̌Ăяo���̌^������lj��D�v���O�C������͌Ăяo���Ȃ��D
*
* @param typeArguments �lj�����^����
*/
public final void addTypeArguments(final List<ReferenceTypeInfo> typeArguments) {
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == typeArguments) {
throw new NullPointerException();
}
this.typeArguments.addAll(typeArguments);
}
/**
* ���̌Ăяo���̎�������List��Ԃ��D
*
* @return�@���̌Ăяo���̎�������List
*/
public List<ExpressionInfo> getArguments() {
return Collections.unmodifiableList(this.arguments);
}
/**
* ���̌Ăяo���ɂ�����ϐ��g�p�Q��Ԃ�
*
* @return ���̌Ăяo���ɂ�����ϐ��g�p�Q
*/
@Override
public Set<VariableUsageInfo<?>> getVariableUsages() {
final SortedSet<VariableUsageInfo<?>> variableUsages = new TreeSet<VariableUsageInfo<?>>();
for (final ExpressionInfo parameter : this.getArguments()) {
variableUsages.addAll(parameter.getVariableUsages());
}
return Collections.unmodifiableSortedSet(variableUsages);
}
/**
* ���̌Ăяo���ŌĂяo����Ă�����̂�Ԃ�
*
* @return ���̌Ăяo���ŌĂяo����Ă������
*/
public final T getCallee() {
return this.callee;
}
private final T callee;
private final List<ExpressionInfo> arguments;
private final List<ReferenceTypeInfo> typeArguments;
}
| true | true | CallInfo(final T callee, final CallableUnitInfo ownerMethod, final int fromLine,
final int fromColumn, final int toLine, final int toColumn) {
super(ownerMethod, fromLine, fromColumn, toLine, toColumn);
this.arguments = new LinkedList<ExpressionInfo>();
this.typeArguments = new LinkedList<ReferenceTypeInfo>();
this.callee = callee;
// ���\�b�h�Ăяo���W���\�z
this.callee.addCaller(ownerMethod);
}
| CallInfo(final T callee, final CallableUnitInfo ownerMethod, final int fromLine,
final int fromColumn, final int toLine, final int toColumn) {
super(ownerMethod, fromLine, fromColumn, toLine, toColumn);
this.arguments = new LinkedList<ExpressionInfo>();
this.typeArguments = new LinkedList<ReferenceTypeInfo>();
this.callee = callee;
// ���\�b�h�Ăяo���W���\�z
if (null != callee) {
this.callee.addCaller(ownerMethod);
}
}
|
diff --git a/core/src/net/sf/openrocket/startup/jij/JarInJarStarter.java b/core/src/net/sf/openrocket/startup/jij/JarInJarStarter.java
index 8865cd19..1f52be39 100644
--- a/core/src/net/sf/openrocket/startup/jij/JarInJarStarter.java
+++ b/core/src/net/sf/openrocket/startup/jij/JarInJarStarter.java
@@ -1,42 +1,43 @@
package net.sf.openrocket.startup.jij;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
public class JarInJarStarter {
/**
* Runs a main class with an alternative classpath.
*
* @param mainClass the class containing the main method to call.
* @param args the arguments to the main method.
* @param providers the classpath sources.
*/
public static void runMain(String mainClass, String[] args, ClasspathProvider... providers) {
List<URL> urls = new ArrayList<URL>();
for (ClasspathProvider p : providers) {
urls.addAll(p.getUrls());
}
System.out.println("New classpath:");
for (URL u : urls) {
System.out.println(" " + u);
}
URL[] urlArray = urls.toArray(new URL[0]);
ClassLoader loader = new URLClassLoader(urlArray, null);
try {
- Class<?> c = loader.loadClass(mainClass);
+ Thread.currentThread().setContextClassLoader(loader);
+ Class<?> c = Class.forName(mainClass, true, loader);
Method m = c.getMethod("main", args.getClass());
m.invoke(null, (Object) args);
} catch (Exception e) {
throw new RuntimeException("Error starting OpenRocket", e);
}
}
}
| true | true | public static void runMain(String mainClass, String[] args, ClasspathProvider... providers) {
List<URL> urls = new ArrayList<URL>();
for (ClasspathProvider p : providers) {
urls.addAll(p.getUrls());
}
System.out.println("New classpath:");
for (URL u : urls) {
System.out.println(" " + u);
}
URL[] urlArray = urls.toArray(new URL[0]);
ClassLoader loader = new URLClassLoader(urlArray, null);
try {
Class<?> c = loader.loadClass(mainClass);
Method m = c.getMethod("main", args.getClass());
m.invoke(null, (Object) args);
} catch (Exception e) {
throw new RuntimeException("Error starting OpenRocket", e);
}
}
| public static void runMain(String mainClass, String[] args, ClasspathProvider... providers) {
List<URL> urls = new ArrayList<URL>();
for (ClasspathProvider p : providers) {
urls.addAll(p.getUrls());
}
System.out.println("New classpath:");
for (URL u : urls) {
System.out.println(" " + u);
}
URL[] urlArray = urls.toArray(new URL[0]);
ClassLoader loader = new URLClassLoader(urlArray, null);
try {
Thread.currentThread().setContextClassLoader(loader);
Class<?> c = Class.forName(mainClass, true, loader);
Method m = c.getMethod("main", args.getClass());
m.invoke(null, (Object) args);
} catch (Exception e) {
throw new RuntimeException("Error starting OpenRocket", e);
}
}
|
diff --git a/user-tool-prefs/tool/src/java/org/sakaiproject/user/tool/PreferenceServlet.java b/user-tool-prefs/tool/src/java/org/sakaiproject/user/tool/PreferenceServlet.java
index 49e19cf..fcf365e 100644
--- a/user-tool-prefs/tool/src/java/org/sakaiproject/user/tool/PreferenceServlet.java
+++ b/user-tool-prefs/tool/src/java/org/sakaiproject/user/tool/PreferenceServlet.java
@@ -1,41 +1,46 @@
package org.sakaiproject.user.tool;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.jsf.util.JsfTool;
public class PreferenceServlet extends JsfTool {
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
//UserPrefsTool tool = (UserPrefsTool) config.getServletContext().getAttribute("UserPrefsTool");
m_default= defaultValue();
}
protected String defaultValue()
{
String defaultPreference="prefs_tab_title, prefs_noti_title, prefs_timezone_title, prefs_lang_title";
String Notification="prefs_noti_title", CustomTab="prefs_tab_title", Timezone="prefs_timezone_title", Language="prefs_lang_title";
String tabOrder=ServerConfigurationService.getString("preference.pages",defaultPreference);
String[] tablist=tabOrder.split(",");
String defaultPage=null;
if(tablist[0].equals(Notification)) defaultPage="noti";
- else if(tablist[0].equals(CustomTab)) defaultPage="tab";
+ else if(tablist[0].equals(CustomTab)){
+ if (ServerConfigurationService.getBoolean ("portal.use.dhtml.more", false))
+ defaultPage = "tab-dhtml-moresites";
+ else
+ defaultPage="tab";
+ }
else if(tablist[0].equals(Timezone)) defaultPage="timezone";
else if (tablist[0].equals(Language)) defaultPage="locale";
return defaultPage;
}
}
| true | true | protected String defaultValue()
{
String defaultPreference="prefs_tab_title, prefs_noti_title, prefs_timezone_title, prefs_lang_title";
String Notification="prefs_noti_title", CustomTab="prefs_tab_title", Timezone="prefs_timezone_title", Language="prefs_lang_title";
String tabOrder=ServerConfigurationService.getString("preference.pages",defaultPreference);
String[] tablist=tabOrder.split(",");
String defaultPage=null;
if(tablist[0].equals(Notification)) defaultPage="noti";
else if(tablist[0].equals(CustomTab)) defaultPage="tab";
else if(tablist[0].equals(Timezone)) defaultPage="timezone";
else if (tablist[0].equals(Language)) defaultPage="locale";
return defaultPage;
}
| protected String defaultValue()
{
String defaultPreference="prefs_tab_title, prefs_noti_title, prefs_timezone_title, prefs_lang_title";
String Notification="prefs_noti_title", CustomTab="prefs_tab_title", Timezone="prefs_timezone_title", Language="prefs_lang_title";
String tabOrder=ServerConfigurationService.getString("preference.pages",defaultPreference);
String[] tablist=tabOrder.split(",");
String defaultPage=null;
if(tablist[0].equals(Notification)) defaultPage="noti";
else if(tablist[0].equals(CustomTab)){
if (ServerConfigurationService.getBoolean ("portal.use.dhtml.more", false))
defaultPage = "tab-dhtml-moresites";
else
defaultPage="tab";
}
else if(tablist[0].equals(Timezone)) defaultPage="timezone";
else if (tablist[0].equals(Language)) defaultPage="locale";
return defaultPage;
}
|
diff --git a/DeCluster.java b/DeCluster.java
index a5afcbb..518e08d 100644
--- a/DeCluster.java
+++ b/DeCluster.java
@@ -1,105 +1,105 @@
//? name=DeCluster v1.0, help=This Java file is a JEB plugin
import jeb.api.IScript;
import jeb.api.JebInstance;
import jeb.api.dex.Dex;
import java.util.ArrayList;
public class DeCluster implements IScript {
@SuppressWarnings("unchecked")
public void run(JebInstance jeb) {
jeb.print("DeCluster Plugin v1.0");
jeb.print("By [email protected]");
String classPre = "_JEBClass";
- String fieldPre = "_JEBfield";
+ String fieldPre = "_JEBField";
String methodPre = "_JEBMethod";
int count = 0;
if (!jeb.isFileLoaded()) {
jeb.print("Please load a dex/apk/jar file");
} else {
jeb.print("Renaming fields");
ArrayList<String> myArr = jeb.getDex().getFieldSignatures(true);
for (int i = myArr.size()-1; i >= 0; i--) {
String fieldName = myArr.get(i);
if (!isValid(fieldName.substring(fieldName.indexOf(">")+1, fieldName.indexOf(":")))) {
++count;
if(!jeb.setFieldComment(fieldName, "Renamed from " +fieldName)) {
jeb.print("Error commenting field " + fieldName);
}
if(!jeb.renameField(fieldName,fieldPre + Integer.toString(count))) {
jeb.print("Error renaming field " + fieldName);
}
}
}
count = 0;
myArr.clear();
jeb.print("Renaming methods");
myArr = jeb.getDex().getMethodSignatures(true);
for (int i = myArr.size()-1; i >= 0; i--) {
String methodName = myArr.get(i);
if (!isValid(methodName.substring(methodName.indexOf(">")+1, methodName.indexOf("(")))) {
++count;
- /* For some reason commenting on some methods throws null pointers for me
+ /* For some reason un-commenting on some methods throws null pointers for me
if(!jeb.setMethodComment(methodName, "Renamed from " +methodName)) {
jeb.print("Error commenting method " + methodName);
}*/
if(!jeb.renameMethod(methodName,methodPre + Integer.toString(count))) {
jeb.print("Error renaming method " + methodName);
}
}
}
count = 0;
myArr.clear();
jeb.print("Renaming classes");
myArr = jeb.getDex().getClassSignatures(true);
for (int i = myArr.size()-1; i >= 0; i--) {
String className = myArr.get(i);
if (!isValid(className.substring(className.lastIndexOf("/")+1, className.length()-1))) {
++count;
if(!jeb.setClassComment(className, "Renamed from " +className)) {
jeb.print("Error commenting class " + className);
}
if(!jeb.renameClass(className,classPre + Integer.toString(count))) {
jeb.print("Error renaming class " + className);
}
}
}
}
}
public boolean isValid (String className){
// This needs
if (className == null || className.length() == 0 || className.contains("<init>") || className.contains("<clinit>") )
return true;
return className.matches("\\w+");
}
}
| false | true | public void run(JebInstance jeb) {
jeb.print("DeCluster Plugin v1.0");
jeb.print("By [email protected]");
String classPre = "_JEBClass";
String fieldPre = "_JEBfield";
String methodPre = "_JEBMethod";
int count = 0;
if (!jeb.isFileLoaded()) {
jeb.print("Please load a dex/apk/jar file");
} else {
jeb.print("Renaming fields");
ArrayList<String> myArr = jeb.getDex().getFieldSignatures(true);
for (int i = myArr.size()-1; i >= 0; i--) {
String fieldName = myArr.get(i);
if (!isValid(fieldName.substring(fieldName.indexOf(">")+1, fieldName.indexOf(":")))) {
++count;
if(!jeb.setFieldComment(fieldName, "Renamed from " +fieldName)) {
jeb.print("Error commenting field " + fieldName);
}
if(!jeb.renameField(fieldName,fieldPre + Integer.toString(count))) {
jeb.print("Error renaming field " + fieldName);
}
}
}
count = 0;
myArr.clear();
jeb.print("Renaming methods");
myArr = jeb.getDex().getMethodSignatures(true);
for (int i = myArr.size()-1; i >= 0; i--) {
String methodName = myArr.get(i);
if (!isValid(methodName.substring(methodName.indexOf(">")+1, methodName.indexOf("(")))) {
++count;
/* For some reason commenting on some methods throws null pointers for me
if(!jeb.setMethodComment(methodName, "Renamed from " +methodName)) {
jeb.print("Error commenting method " + methodName);
}*/
if(!jeb.renameMethod(methodName,methodPre + Integer.toString(count))) {
jeb.print("Error renaming method " + methodName);
}
}
}
count = 0;
myArr.clear();
jeb.print("Renaming classes");
myArr = jeb.getDex().getClassSignatures(true);
for (int i = myArr.size()-1; i >= 0; i--) {
String className = myArr.get(i);
if (!isValid(className.substring(className.lastIndexOf("/")+1, className.length()-1))) {
++count;
if(!jeb.setClassComment(className, "Renamed from " +className)) {
jeb.print("Error commenting class " + className);
}
if(!jeb.renameClass(className,classPre + Integer.toString(count))) {
jeb.print("Error renaming class " + className);
}
}
}
}
}
| public void run(JebInstance jeb) {
jeb.print("DeCluster Plugin v1.0");
jeb.print("By [email protected]");
String classPre = "_JEBClass";
String fieldPre = "_JEBField";
String methodPre = "_JEBMethod";
int count = 0;
if (!jeb.isFileLoaded()) {
jeb.print("Please load a dex/apk/jar file");
} else {
jeb.print("Renaming fields");
ArrayList<String> myArr = jeb.getDex().getFieldSignatures(true);
for (int i = myArr.size()-1; i >= 0; i--) {
String fieldName = myArr.get(i);
if (!isValid(fieldName.substring(fieldName.indexOf(">")+1, fieldName.indexOf(":")))) {
++count;
if(!jeb.setFieldComment(fieldName, "Renamed from " +fieldName)) {
jeb.print("Error commenting field " + fieldName);
}
if(!jeb.renameField(fieldName,fieldPre + Integer.toString(count))) {
jeb.print("Error renaming field " + fieldName);
}
}
}
count = 0;
myArr.clear();
jeb.print("Renaming methods");
myArr = jeb.getDex().getMethodSignatures(true);
for (int i = myArr.size()-1; i >= 0; i--) {
String methodName = myArr.get(i);
if (!isValid(methodName.substring(methodName.indexOf(">")+1, methodName.indexOf("(")))) {
++count;
/* For some reason un-commenting on some methods throws null pointers for me
if(!jeb.setMethodComment(methodName, "Renamed from " +methodName)) {
jeb.print("Error commenting method " + methodName);
}*/
if(!jeb.renameMethod(methodName,methodPre + Integer.toString(count))) {
jeb.print("Error renaming method " + methodName);
}
}
}
count = 0;
myArr.clear();
jeb.print("Renaming classes");
myArr = jeb.getDex().getClassSignatures(true);
for (int i = myArr.size()-1; i >= 0; i--) {
String className = myArr.get(i);
if (!isValid(className.substring(className.lastIndexOf("/")+1, className.length()-1))) {
++count;
if(!jeb.setClassComment(className, "Renamed from " +className)) {
jeb.print("Error commenting class " + className);
}
if(!jeb.renameClass(className,classPre + Integer.toString(count))) {
jeb.print("Error renaming class " + className);
}
}
}
}
}
|
diff --git a/core/org.eclipse.ptp.remote.remotetools.core/src/org/eclipse/ptp/remote/remotetools/environment/core/PTPTargetControl.java b/core/org.eclipse.ptp.remote.remotetools.core/src/org/eclipse/ptp/remote/remotetools/environment/core/PTPTargetControl.java
index 083b2d204..3bcc08513 100755
--- a/core/org.eclipse.ptp.remote.remotetools.core/src/org/eclipse/ptp/remote/remotetools/environment/core/PTPTargetControl.java
+++ b/core/org.eclipse.ptp.remote.remotetools.core/src/org/eclipse/ptp/remote/remotetools/environment/core/PTPTargetControl.java
@@ -1,229 +1,231 @@
/**
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - Initial Implementation
*
*/
package org.eclipse.ptp.remote.remotetools.environment.core;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ptp.remote.remotetools.Activator;
import org.eclipse.ptp.remotetools.RemotetoolsPlugin;
import org.eclipse.ptp.remotetools.core.IRemoteExecutionManager;
import org.eclipse.ptp.remotetools.environment.control.ITargetControl;
import org.eclipse.ptp.remotetools.environment.control.ITargetStatus;
import org.eclipse.ptp.remotetools.environment.control.SSHTargetControl;
import org.eclipse.ptp.remotetools.environment.core.ITargetElement;
import org.eclipse.ptp.remotetools.environment.extension.ITargetVariables;
import org.eclipse.ptp.remotetools.exception.RemoteConnectionException;
/**
* Controls an instance of a target created from the Environment.
* @author Daniel Felix Ferber
* @since 1.2
*/
public class PTPTargetControl extends SSHTargetControl implements ITargetControl, ITargetVariables {
private static final int NOT_OPERATIONAL = 1;
private static final int CONNECTING = 2;
private static final int CONNECTED = 3;
private static final int DISCONNECTING = 4;
/**
* Default cipher id
*/
public static final String DEFAULT_CIPHER = RemotetoolsPlugin.CIPHER_DEFAULT;
/**
* Configuration provided to the target control.
*/
private ConfigFactory configFactory;
private TargetConfig currentTargetConfig;
/**
* BackReference to the target element
*/
private ITargetElement targetElement;
private IRemoteExecutionManager executionManager;
/**
* Current connection state.
*/
private int state;
/**
* Creates a target control. If some attribute related to the environment has an invalid
* format, an exception is thrown. Simulator attributes are not checked yet, but will be checked when the target is
* created (launched).
*
* @param attributes
* Configuration attributes
* @param element
* Name for the target (displayed in GUI)
* @throws CoreException
* Some attribute is not valid
*/
public PTPTargetControl(ITargetElement element) throws CoreException {
super();
state = NOT_OPERATIONAL;
targetElement = element;
configFactory = new ConfigFactory(targetElement.getAttributes());
currentTargetConfig = configFactory.createTargetConfig();
}
/**
* Connect to the remote host. On every error or possible failure, an exception
* (CoreException) is thrown, whose (multi)status describe the error(s) that prevented creating the target control.
*
* @param monitor
* Progress indicator or <code>null</code>
* @return Always true.
* @throws CoreException
* Some attribute is not valid, the simulator cannot be launched, the ssh failed to connect.
*/
public boolean create(IProgressMonitor monitor) throws CoreException {
monitor.beginTask(Messages.TargetControl_create_MonitorConnecting, 1);
/*
* Connect to the remote host
*/
if(currentTargetConfig.isPasswordAuth()) {
setConnectionParameters(
new SSHParameters(
currentTargetConfig.getConnectionAddress(),
currentTargetConfig.getConnectionPort(),
currentTargetConfig.getLoginUserName(),
currentTargetConfig.getLoginPassword(),
currentTargetConfig.getCipherType(),
currentTargetConfig.getConnectionTimeout()*1000
)
);
} else {
setConnectionParameters(
new SSHParameters(
currentTargetConfig.getConnectionAddress(),
currentTargetConfig.getConnectionPort(),
currentTargetConfig.getLoginUserName(),
currentTargetConfig.getKeyPath(),
currentTargetConfig.getKeyPassphrase(),
currentTargetConfig.getCipherType(),
currentTargetConfig.getConnectionTimeout()*1000
)
);
}
try {
setState(CONNECTING);
super.create(monitor);
setState(CONNECTED);
monitor.worked(1);
} catch (CoreException e) {
disconnect();
setState(NOT_OPERATIONAL);
+ monitor.done();
+ return true;
}
try {
executionManager = super.createRemoteExecutionManager();
} catch (RemoteConnectionException e) {
disconnect();
setState(NOT_OPERATIONAL);
}
monitor.done();
return true;
}
public TargetSocket createTargetSocket(int port) {
Assert.isTrue(isConnected());
TargetSocket socket = new TargetSocket();
socket.host = currentTargetConfig.getConnectionAddress();
socket.port = port;
return socket;
}
public void destroy() throws CoreException {
// End all jobs, if possible, then disconnect
try {
terminateJobs(null);
} finally {
disconnect();
}
}
/**
* Get the main execution manager for this control.
*
* @return execution manager
*/
public IRemoteExecutionManager getExecutionManager() {
return executionManager;
}
public String getName() {
return targetElement.getName();
}
protected String getPluginId() {
return Activator.PLUGIN_ID;
}
public String getSystemWorkspace() {
return currentTargetConfig.getSystemWorkspace();
}
public boolean kill(IProgressMonitor monitor) throws CoreException {
try {
setState(DISCONNECTING);
super.kill(monitor);
} finally {
setState(NOT_OPERATIONAL);
}
return true;
}
public synchronized int query() {
switch (state) {
case NOT_OPERATIONAL:
return ITargetStatus.STOPPED;
case CONNECTING:
case DISCONNECTING:
return ITargetStatus.STARTED;
case CONNECTED:
if (isConnected()) {
return ITargetStatus.RESUMED;
} else {
return ITargetStatus.STARTED;
}
default:
return ITargetStatus.STOPPED;
}
}
public boolean resume(IProgressMonitor monitor) throws CoreException {
throw new CoreException(new Status(IStatus.ERROR, getPluginId(), 0,
Messages.TargetControl_resume_CannotResume, null));
}
private synchronized void setState(int state) {
this.state = state;
}
public boolean stop(IProgressMonitor monitor) throws CoreException {
throw new CoreException(new Status(IStatus.ERROR, getPluginId(), 0,
Messages.TargetControl_stop_CannotPause, null));
}
/**
* Sets new attributes.
*/
public void updateConfiguration() throws CoreException {
//targetElement.setName(name);
configFactory = new ConfigFactory(targetElement.getAttributes());
currentTargetConfig = configFactory.createTargetConfig();
}
}
| true | true | public boolean create(IProgressMonitor monitor) throws CoreException {
monitor.beginTask(Messages.TargetControl_create_MonitorConnecting, 1);
/*
* Connect to the remote host
*/
if(currentTargetConfig.isPasswordAuth()) {
setConnectionParameters(
new SSHParameters(
currentTargetConfig.getConnectionAddress(),
currentTargetConfig.getConnectionPort(),
currentTargetConfig.getLoginUserName(),
currentTargetConfig.getLoginPassword(),
currentTargetConfig.getCipherType(),
currentTargetConfig.getConnectionTimeout()*1000
)
);
} else {
setConnectionParameters(
new SSHParameters(
currentTargetConfig.getConnectionAddress(),
currentTargetConfig.getConnectionPort(),
currentTargetConfig.getLoginUserName(),
currentTargetConfig.getKeyPath(),
currentTargetConfig.getKeyPassphrase(),
currentTargetConfig.getCipherType(),
currentTargetConfig.getConnectionTimeout()*1000
)
);
}
try {
setState(CONNECTING);
super.create(monitor);
setState(CONNECTED);
monitor.worked(1);
} catch (CoreException e) {
disconnect();
setState(NOT_OPERATIONAL);
}
try {
executionManager = super.createRemoteExecutionManager();
} catch (RemoteConnectionException e) {
disconnect();
setState(NOT_OPERATIONAL);
}
monitor.done();
return true;
}
| public boolean create(IProgressMonitor monitor) throws CoreException {
monitor.beginTask(Messages.TargetControl_create_MonitorConnecting, 1);
/*
* Connect to the remote host
*/
if(currentTargetConfig.isPasswordAuth()) {
setConnectionParameters(
new SSHParameters(
currentTargetConfig.getConnectionAddress(),
currentTargetConfig.getConnectionPort(),
currentTargetConfig.getLoginUserName(),
currentTargetConfig.getLoginPassword(),
currentTargetConfig.getCipherType(),
currentTargetConfig.getConnectionTimeout()*1000
)
);
} else {
setConnectionParameters(
new SSHParameters(
currentTargetConfig.getConnectionAddress(),
currentTargetConfig.getConnectionPort(),
currentTargetConfig.getLoginUserName(),
currentTargetConfig.getKeyPath(),
currentTargetConfig.getKeyPassphrase(),
currentTargetConfig.getCipherType(),
currentTargetConfig.getConnectionTimeout()*1000
)
);
}
try {
setState(CONNECTING);
super.create(monitor);
setState(CONNECTED);
monitor.worked(1);
} catch (CoreException e) {
disconnect();
setState(NOT_OPERATIONAL);
monitor.done();
return true;
}
try {
executionManager = super.createRemoteExecutionManager();
} catch (RemoteConnectionException e) {
disconnect();
setState(NOT_OPERATIONAL);
}
monitor.done();
return true;
}
|
diff --git a/android/src/org/coolreader/crengine/FileBrowser.java b/android/src/org/coolreader/crengine/FileBrowser.java
index 46bdbeba..fe3ed4c6 100644
--- a/android/src/org/coolreader/crengine/FileBrowser.java
+++ b/android/src/org/coolreader/crengine/FileBrowser.java
@@ -1,740 +1,740 @@
package org.coolreader.crengine;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import org.coolreader.CoolReader;
import org.coolreader.R;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class FileBrowser extends ListView {
Engine mEngine;
Scanner mScanner;
CoolReader mActivity;
LayoutInflater mInflater;
History mHistory;
public FileBrowser(CoolReader activity, Engine engine, Scanner scanner, History history) {
super(activity);
this.mActivity = activity;
this.mEngine = engine;
this.mScanner = scanner;
this.mInflater = LayoutInflater.from(activity);// activity.getLayoutInflater();
this.mHistory = history;
setFocusable(true);
setFocusableInTouchMode(true);
setLongClickable(true);
//registerForContextMenu(this);
//final FileBrowser _this = this;
setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.d("cr3", "onItemLongClick("+position+")");
//return super.performItemClick(view, position, id);
if ( position==0 && currDirectory.parent!=null ) {
showParentDirectory();
return true;
}
FileInfo item = (FileInfo) getAdapter().getItem(position);
if ( item==null )
return false;
if ( item.isDirectory ) {
showDirectory(item, null);
return true;
}
//openContextMenu(_this);
//mActivity.loadDocument(item);
selectedItem = item;
showContextMenu();
return true;
}
});
setChoiceMode(CHOICE_MODE_SINGLE);
showDirectory( null, null );
}
FileInfo selectedItem = null;
public boolean onContextItemSelected(MenuItem item) {
if ( selectedItem==null || selectedItem.isDirectory )
return false;
switch (item.getItemId()) {
case R.id.book_open:
Log.d("cr3", "book_open menu item selected");
mActivity.loadDocument(selectedItem);
return true;
case R.id.book_sort_order:
mActivity.showToast("Sorry, sort order selection is not yet implemented");
return true;
case R.id.book_recent_books:
showRecentBooks();
return true;
case R.id.book_root:
showRootDirectory();
return true;
case R.id.book_back_to_reading:
if ( mActivity.isBookOpened() )
mActivity.showReader();
else
mActivity.showToast("No book opened");
return true;
case R.id.book_delete:
Log.d("cr3", "book_delete menu item selected");
mActivity.getReaderView().closeIfOpened(selectedItem);
if ( selectedItem.deleteFile() ) {
mHistory.removeBookInfo(selectedItem, true, true);
}
showDirectory(currDirectory, null);
return true;
case R.id.book_recent_goto:
Log.d("cr3", "book_recent_goto menu item selected");
showDirectory(selectedItem, selectedItem);
return true;
case R.id.book_recent_remove:
Log.d("cr3", "book_recent_remove menu item selected");
mActivity.getHistory().removeBookInfo(selectedItem, true, false);
showRecentBooks();
return true;
}
return false;
}
@Override
public void createContextMenu(ContextMenu menu) {
Log.d("cr3", "createContextMenu()");
menu.clear();
MenuInflater inflater = mActivity.getMenuInflater();
if ( isRecentDir() ) {
inflater.inflate(R.menu.cr3_file_browser_recent_context_menu, menu);
menu.setHeaderTitle(mActivity.getString(R.string.context_menu_title_recent_book));
} else if (selectedItem!=null && selectedItem.isDirectory) {
inflater.inflate(R.menu.cr3_file_browser_folder_context_menu, menu);
menu.setHeaderTitle(mActivity.getString(R.string.context_menu_title_book));
} else {
inflater.inflate(R.menu.cr3_file_browser_context_menu, menu);
menu.setHeaderTitle(mActivity.getString(R.string.context_menu_title_book));
}
for ( int i=0; i<menu.size(); i++ ) {
menu.getItem(i).setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
onContextItemSelected(item);
return true;
}
});
}
return;
}
@Override
public boolean performItemClick(View view, int position, long id) {
Log.d("cr3", "performItemClick("+position+")");
//return super.performItemClick(view, position, id);
if ( position==0 && currDirectory.parent!=null ) {
showParentDirectory();
return true;
}
FileInfo item = (FileInfo) getAdapter().getItem(position);
if ( item==null )
return false;
if ( item.isDirectory ) {
showDirectory(item, null);
return true;
}
mActivity.loadDocument(item);
return true;
}
protected void showParentDirectory()
{
if ( currDirectory.parent!=null ) {
showDirectory(currDirectory.parent, currDirectory);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ( keyCode==KeyEvent.KEYCODE_BACK && mActivity.isBookOpened() ) {
if ( isRootDir() ) {
if ( mActivity.isBookOpened() ) {
mActivity.showReader();
return true;
} else
return super.onKeyDown(keyCode, event);
}
showParentDirectory();
return true;
}
return super.onKeyDown(keyCode, event);
}
boolean mInitStarted = false;
boolean mInitialized = false;
public void init()
{
if ( mInitStarted )
return;
Log.e("cr3", "FileBrowser.init() called");
mInitStarted = true;
//mEngine.showProgress(1000, R.string.progress_scanning);
execute( new Task() {
public void work() {
mHistory.loadFromDB(mScanner, 100);
}
public void done() {
Log.e("cr3", "Directory scan is finished. " + mScanner.mFileList.size() + " files found" + ", root item count is " + mScanner.mRoot.itemCount());
mInitialized = true;
//mEngine.hideProgress();
//mEngine.hideProgress();
showDirectory( mScanner.mRoot, null );
setSelection(0);
}
public void fail(Exception e )
{
//mEngine.showProgress(9000, "Scan is failed");
//mEngine.hideProgress();
mActivity.showToast("Scan is failed");
Log.e("cr3", "Exception while scanning directories", e);
}
});
}
@Override
public void setSelection(int position) {
super.setSelection(position);
}
public static String formatAuthors( String authors ) {
if ( authors==null || authors.length()==0 )
return null;
String[] list = authors.split("\\|");
StringBuilder buf = new StringBuilder(authors.length());
for ( String a : list ) {
if ( buf.length()>0 )
buf.append(", ");
String[] items = a.split(" ");
if ( items.length==3 && items[1]!=null && items[1].length()>=1 )
buf.append(items[0] + " " + items[1].charAt(0) + ". " + items[2]);
else
buf.append(a);
}
return buf.toString();
}
public static String formatSize( int size )
{
if ( size<10000 )
return String.valueOf(size);
else if ( size<1000000 )
return String.valueOf(size/1000) + "K";
else if ( size<10000000 )
return String.valueOf(size/1000000) + "." + String.valueOf(size%1000000/100000) + "M";
else
return String.valueOf(size/1000000) + "M";
}
public static String formatSeries( String name, int number )
{
if ( name==null || name.length()==0 )
return null;
if ( number>0 )
return "#" + number + " " + name;
else
return name;
}
static private SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yy", Locale.getDefault());
static private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
public static String formatDate( long timeStamp )
{
if ( timeStamp<5000*60*60*24*1000 )
return "";
TimeZone tz = java.util.TimeZone.getDefault();
Calendar now = Calendar.getInstance(tz);
Calendar c = Calendar.getInstance(tz);
c.setTimeInMillis(timeStamp);
if ( c.get(Calendar.YEAR)<1980 )
return "";
if ( c.get(Calendar.YEAR)==now.get(Calendar.YEAR)
&& c.get(Calendar.MONTH)==now.get(Calendar.MONTH)
&& c.get(Calendar.DAY_OF_MONTH)==now.get(Calendar.DAY_OF_MONTH)) {
timeFormat.setTimeZone(tz);
return timeFormat.format(c.getTime());
} else {
dateFormat.setTimeZone(tz);
return dateFormat.format(c.getTime());
}
}
public static String formatPercent( int percent )
{
if ( percent<=0 )
return null;
return String.valueOf(percent/100) + "." + String.valueOf(percent/10%10) + "%";
}
private FileInfo currDirectory;
public boolean isRootDir()
{
return currDirectory == mScanner.getRoot();
}
public boolean isRecentDir()
{
return currDirectory!=null && currDirectory.isRecentDir();
}
public void showRecentBooks()
{
showDirectory(null, null);
}
public void showLastDirectory()
{
if ( currDirectory==null || currDirectory==mScanner.getRoot() )
showRecentBooks();
else
showDirectory(currDirectory, null);
}
public void showSearchResult( FileInfo[] books ) {
FileInfo dir = mScanner.setSearchResults( books );
showDirectory(dir, null);
}
public void showFindBookDialog()
{
BookSearchDialog dlg = new BookSearchDialog( mActivity, new BookSearchDialog.SearchCallback() {
@Override
public void done(FileInfo[] results) {
if ( results!=null ) {
if ( results.length==0 ) {
mActivity.showToast(R.string.dlg_book_search_not_found);
} else {
showSearchResult( results );
}
}
}
});
dlg.show();
}
public void showRootDirectory()
{
showDirectory(mScanner.getRoot(), null);
}
private FileInfo.SortOrder mSortOrder = FileInfo.DEF_SORT_ORDER;
public void setSortOrder(FileInfo.SortOrder order) {
if ( mSortOrder == order )
return;
mSortOrder = order!=null ? order : FileInfo.DEF_SORT_ORDER;
if ( currDirectory!=null && !currDirectory.isRootDir() && !currDirectory.isRecentDir() ) {
currDirectory.sort(mSortOrder);
showDirectory(currDirectory, null);
mActivity.saveSetting(ReaderView.PROP_APP_BOOK_SORT_ORDER, mSortOrder.name());
}
}
public void setSortOrder(String orderName) {
setSortOrder(FileInfo.SortOrder.fromName(orderName));
}
public void showSortOrderMenu() {
final Properties properties = new Properties();
properties.setProperty(ReaderView.PROP_APP_BOOK_SORT_ORDER, mActivity.getSetting(ReaderView.PROP_APP_BOOK_SORT_ORDER));
final String oldValue = properties.getProperty(ReaderView.PROP_APP_BOOK_SORT_ORDER);
int[] optionLabels = {
FileInfo.SortOrder.FILENAME.resourceId,
FileInfo.SortOrder.FILENAME_DESC.resourceId,
FileInfo.SortOrder.AUTHOR_TITLE.resourceId,
FileInfo.SortOrder.AUTHOR_TITLE_DESC.resourceId,
FileInfo.SortOrder.TITLE_AUTHOR.resourceId,
FileInfo.SortOrder.TITLE_AUTHOR_DESC.resourceId,
FileInfo.SortOrder.TIMESTAMP.resourceId,
FileInfo.SortOrder.TIMESTAMP_DESC.resourceId,
};
String[] optionValues = {
FileInfo.SortOrder.FILENAME.name(),
FileInfo.SortOrder.FILENAME_DESC.name(),
FileInfo.SortOrder.AUTHOR_TITLE.name(),
FileInfo.SortOrder.AUTHOR_TITLE_DESC.name(),
FileInfo.SortOrder.TITLE_AUTHOR.name(),
FileInfo.SortOrder.TITLE_AUTHOR_DESC.name(),
FileInfo.SortOrder.TIMESTAMP.name(),
FileInfo.SortOrder.TIMESTAMP_DESC.name(),
};
OptionsDialog.ListOption dlg = new OptionsDialog.ListOption(
new OptionOwner() {
public CoolReader getActivity() { return mActivity; }
public Properties getProperties() { return properties; }
public LayoutInflater getInflater() { return mInflater; }
},
mActivity.getString(R.string.mi_book_sort_order),
ReaderView.PROP_APP_BOOK_SORT_ORDER).add(optionValues, optionLabels);
dlg.setOnChangeHandler(new Runnable() {
public void run() {
final String newValue = properties.getProperty(ReaderView.PROP_APP_BOOK_SORT_ORDER);
if ( newValue!=null && oldValue!=null && !newValue.equals(oldValue) ) {
Log.d("cr3", "New sort order: " + newValue);
setSortOrder(newValue);
}
}
});
dlg.onSelect();
}
public void showDirectory( FileInfo fileOrDir, FileInfo itemToSelect )
{
if ( fileOrDir==null && mScanner.getRoot()!=null && mScanner.getRoot().dirCount()>0 ) {
if ( mScanner.getRoot().getDir(0).fileCount()>0 ) {
fileOrDir = mScanner.getRoot().getDir(0);
itemToSelect = mScanner.getRoot().getDir(0).getFile(0);
} else {
fileOrDir = mScanner.getRoot();
itemToSelect = mScanner.getRoot().dirCount()>1 ? mScanner.getRoot().getDir(1) : null;
}
}
final FileInfo file = fileOrDir==null || fileOrDir.isDirectory ? itemToSelect : fileOrDir;
final FileInfo dir = fileOrDir!=null && !fileOrDir.isDirectory ? mScanner.findParent(file, mScanner.getRoot()) : fileOrDir;
if ( dir!=null ) {
mScanner.scanDirectory(dir, new Runnable() {
public void run() {
if ( !dir.isRootDir() && !dir.isRecentDir() )
dir.sort(mSortOrder);
showDirectoryInternal(dir, file);
}
}, false, new Scanner.ScanControl() );
} else
showDirectoryInternal(dir, file);
}
public void scanCurrentDirectoryRecursive() {
if ( currDirectory==null )
return;
Log.i("cr3", "scanCurrentDirectoryRecursive started");
final Scanner.ScanControl control = new Scanner.ScanControl();
final ProgressDialog dlg = ProgressDialog.show(getContext(),
mActivity.getString(R.string.dlg_scan_title),
mActivity.getString(R.string.dlg_scan_message),
true, true, new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Log.i("cr3", "scanCurrentDirectoryRecursive : stop handler");
control.stop();
}
});
mScanner.scanDirectory(currDirectory, new Runnable() {
@Override
public void run() {
Log.i("cr3", "scanCurrentDirectoryRecursive : finish handler");
if ( dlg.isShowing() )
dlg.dismiss();
}
}, true, control);
}
public boolean isSimpleViewMode() {
return isSimpleViewMode;
}
public void setSimpleViewMode( boolean isSimple ) {
if ( isSimpleViewMode!=isSimple ) {
isSimpleViewMode = isSimple;
mSortOrder = FileInfo.SortOrder.FILENAME;
mActivity.saveSetting(ReaderView.PROP_APP_BOOK_SORT_ORDER, mSortOrder.name());
if ( isShown() && currDirectory!=null ) {
showDirectory(currDirectory, null);
}
}
}
private boolean isSimpleViewMode = true;
private void showDirectoryInternal( final FileInfo dir, final FileInfo file )
{
currDirectory = dir;
if ( dir!=null )
Log.i("cr3", "Showing directory " + dir);
this.setAdapter(new ListAdapter() {
public boolean areAllItemsEnabled() {
return true;
}
public boolean isEnabled(int arg0) {
return true;
}
public int getCount() {
if ( dir==null )
return 0;
return dir.fileCount() + dir.dirCount() + (dir.parent!=null ? 1 : 0);
}
public Object getItem(int position) {
if ( dir==null )
return null;
if ( position<0 )
return null;
int start = (dir.parent!=null ? 1 : 0);
if ( position<start )
return dir.parent;
return dir.getItem(position-start);
}
public long getItemId(int position) {
if ( dir==null )
return 0;
return position;
}
public final int VIEW_TYPE_LEVEL_UP = 0;
public final int VIEW_TYPE_DIRECTORY = 1;
public final int VIEW_TYPE_FILE = 2;
public final int VIEW_TYPE_FILE_SIMPLE = 3;
public final int VIEW_TYPE_COUNT = 4;
public int getItemViewType(int position) {
if ( dir==null )
return 0;
if ( position<0 )
return Adapter.IGNORE_ITEM_VIEW_TYPE;
int start = (dir.parent!=null ? 1 : 0);
if ( position<start )
return VIEW_TYPE_LEVEL_UP;
if ( position<start + dir.dirCount() )
return VIEW_TYPE_DIRECTORY;
start += dir.dirCount();
position -= start;
if ( position<dir.fileCount() )
return isSimpleViewMode ? VIEW_TYPE_FILE_SIMPLE : VIEW_TYPE_FILE;
return Adapter.IGNORE_ITEM_VIEW_TYPE;
}
class ViewHolder {
int viewType;
ImageView image;
TextView name;
TextView author;
TextView series;
TextView filename;
TextView field1;
TextView field2;
//TextView field3;
void setText( TextView view, String text )
{
if ( view==null )
return;
if ( text!=null && text.length()>0 ) {
view.setText(text);
view.setVisibility(VISIBLE);
} else {
view.setText(null);
view.setVisibility(INVISIBLE);
}
}
void setItem(FileInfo item, FileInfo parentItem)
{
if ( item==null ) {
image.setImageResource(R.drawable.cr3_browser_back);
String thisDir = "";
if ( parentItem!=null ) {
if ( parentItem.pathname.startsWith("@") )
thisDir = "/" + parentItem.filename;
// else if ( parentItem.isArchive )
// thisDir = parentItem.arcname;
else
thisDir = parentItem.pathname;
//parentDir = parentItem.path;
}
name.setText(thisDir);
return;
}
if ( item.isDirectory ) {
if ( item.isRecentDir() )
image.setImageResource(R.drawable.cr3_browser_folder_recent);
else if ( item.isArchive )
image.setImageResource(R.drawable.cr3_browser_folder_zip);
else
image.setImageResource(R.drawable.cr3_browser_folder);
setText(name, item.filename);
setText(field1, "books: " + String.valueOf(item.fileCount()));
setText(field2, "folders: " + String.valueOf(item.dirCount()));
} else {
boolean isSimple = (viewType == VIEW_TYPE_FILE_SIMPLE);
if ( image!=null ) {
if ( isSimple ) {
image.setImageResource(item.format.getIconResourceId());
} else {
Drawable drawable = null;
if ( item.id!=null )
drawable = mHistory.getBookCoverpageImage(null, item.id);
if ( drawable!=null ) {
image.setImageDrawable(drawable);
} else {
int resId = item.format!=null ? item.format.getIconResourceId() : 0;
if ( resId!=0 )
image.setImageResource(item.format.getIconResourceId());
}
}
}
if ( isSimple ) {
String fn = item.getFileNameToDisplay();
setText( filename, fn );
} else {
setText( author, formatAuthors(item.authors) );
String seriesName = formatSeries(item.series, item.seriesNumber);
String title = item.title;
String filename1 = item.filename;
String filename2 = item.isArchive /*&& !item.isDirectory */
? new File(item.arcname).getName() : null;
if ( title==null || title.length()==0 ) {
title = filename1;
if (seriesName==null)
seriesName = filename2;
} else if (seriesName==null)
seriesName = filename1;
setText( name, title );
setText( series, seriesName );
// field1.setVisibility(VISIBLE);
// field2.setVisibility(VISIBLE);
// field3.setVisibility(VISIBLE);
- field1.setText(formatSize(item.size) + " " + item.format.name() + " " + formatDate(item.createTime));
+ field1.setText(formatSize(item.size) + " " + item.format.name().toLowerCase() + " " + formatDate(item.createTime) + " ");
//field2.setText(formatDate(pos!=null ? pos.getTimeStamp() : item.createTime));
Bookmark pos = mHistory.getLastPos(item);
if ( pos!=null ) {
- field2.setText(formatDate(pos.getTimeStamp()) + " " + formatPercent(pos.getPercent())) ;
+ field2.setText(formatPercent(pos.getPercent()) + " " + formatDate(pos.getTimeStamp())) ;
} else {
field2.setText("");
}
//field3.setText(pos!=null ? formatPercent(pos.getPercent()) : null);
}
}
}
}
public View getView(int position, View convertView, ViewGroup parent) {
if ( dir==null )
return null;
View view;
ViewHolder holder;
int vt = getItemViewType(position);
if ( convertView==null ) {
if ( vt==VIEW_TYPE_LEVEL_UP )
view = mInflater.inflate(R.layout.browser_item_parent_dir, null);
else if ( vt==VIEW_TYPE_DIRECTORY )
view = mInflater.inflate(R.layout.browser_item_folder, null);
else if ( vt==VIEW_TYPE_FILE_SIMPLE )
view = mInflater.inflate(R.layout.browser_item_book_simple, null);
else
view = mInflater.inflate(R.layout.browser_item_book, null);
holder = new ViewHolder();
holder.image = (ImageView)view.findViewById(R.id.book_icon);
holder.name = (TextView)view.findViewById(R.id.book_name);
holder.author = (TextView)view.findViewById(R.id.book_author);
holder.series = (TextView)view.findViewById(R.id.book_series);
holder.filename = (TextView)view.findViewById(R.id.book_filename);
holder.field1 = (TextView)view.findViewById(R.id.browser_item_field1);
holder.field2 = (TextView)view.findViewById(R.id.browser_item_field2);
//holder.field3 = (TextView)view.findViewById(R.id.browser_item_field3);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
holder.viewType = vt;
FileInfo item = (FileInfo)getItem(position);
FileInfo parentItem = null;//item!=null ? item.parent : null;
if ( vt == VIEW_TYPE_LEVEL_UP ) {
item = null;
parentItem = currDirectory;
}
holder.setItem(item, parentItem);
return view;
}
public int getViewTypeCount() {
if ( dir==null )
return 1;
return VIEW_TYPE_COUNT;
}
public boolean hasStableIds() {
return true;
}
public boolean isEmpty() {
if ( dir==null )
return true;
return mScanner.mFileList.size()==0;
}
private ArrayList<DataSetObserver> observers = new ArrayList<DataSetObserver>();
public void registerDataSetObserver(DataSetObserver observer) {
observers.add(observer);
}
public void unregisterDataSetObserver(DataSetObserver observer) {
observers.remove(observer);
}
});
int index = dir!=null ? dir.getItemIndex(file) : -1;
if ( dir!=null && !dir.isRootDir() )
index++;
setSelection(index);
setChoiceMode(CHOICE_MODE_SINGLE);
invalidate();
}
private void execute( Engine.EngineTask task )
{
mEngine.execute(task);
}
private abstract class Task implements Engine.EngineTask {
public void done() {
// override to do something useful
}
public void fail(Exception e) {
// do nothing, just log exception
// override to do custom action
Log.e("cr3", "Task " + this.getClass().getSimpleName() + " is failed with exception " + e.getMessage(), e);
}
}
}
| false | true | private void showDirectoryInternal( final FileInfo dir, final FileInfo file )
{
currDirectory = dir;
if ( dir!=null )
Log.i("cr3", "Showing directory " + dir);
this.setAdapter(new ListAdapter() {
public boolean areAllItemsEnabled() {
return true;
}
public boolean isEnabled(int arg0) {
return true;
}
public int getCount() {
if ( dir==null )
return 0;
return dir.fileCount() + dir.dirCount() + (dir.parent!=null ? 1 : 0);
}
public Object getItem(int position) {
if ( dir==null )
return null;
if ( position<0 )
return null;
int start = (dir.parent!=null ? 1 : 0);
if ( position<start )
return dir.parent;
return dir.getItem(position-start);
}
public long getItemId(int position) {
if ( dir==null )
return 0;
return position;
}
public final int VIEW_TYPE_LEVEL_UP = 0;
public final int VIEW_TYPE_DIRECTORY = 1;
public final int VIEW_TYPE_FILE = 2;
public final int VIEW_TYPE_FILE_SIMPLE = 3;
public final int VIEW_TYPE_COUNT = 4;
public int getItemViewType(int position) {
if ( dir==null )
return 0;
if ( position<0 )
return Adapter.IGNORE_ITEM_VIEW_TYPE;
int start = (dir.parent!=null ? 1 : 0);
if ( position<start )
return VIEW_TYPE_LEVEL_UP;
if ( position<start + dir.dirCount() )
return VIEW_TYPE_DIRECTORY;
start += dir.dirCount();
position -= start;
if ( position<dir.fileCount() )
return isSimpleViewMode ? VIEW_TYPE_FILE_SIMPLE : VIEW_TYPE_FILE;
return Adapter.IGNORE_ITEM_VIEW_TYPE;
}
class ViewHolder {
int viewType;
ImageView image;
TextView name;
TextView author;
TextView series;
TextView filename;
TextView field1;
TextView field2;
//TextView field3;
void setText( TextView view, String text )
{
if ( view==null )
return;
if ( text!=null && text.length()>0 ) {
view.setText(text);
view.setVisibility(VISIBLE);
} else {
view.setText(null);
view.setVisibility(INVISIBLE);
}
}
void setItem(FileInfo item, FileInfo parentItem)
{
if ( item==null ) {
image.setImageResource(R.drawable.cr3_browser_back);
String thisDir = "";
if ( parentItem!=null ) {
if ( parentItem.pathname.startsWith("@") )
thisDir = "/" + parentItem.filename;
// else if ( parentItem.isArchive )
// thisDir = parentItem.arcname;
else
thisDir = parentItem.pathname;
//parentDir = parentItem.path;
}
name.setText(thisDir);
return;
}
if ( item.isDirectory ) {
if ( item.isRecentDir() )
image.setImageResource(R.drawable.cr3_browser_folder_recent);
else if ( item.isArchive )
image.setImageResource(R.drawable.cr3_browser_folder_zip);
else
image.setImageResource(R.drawable.cr3_browser_folder);
setText(name, item.filename);
setText(field1, "books: " + String.valueOf(item.fileCount()));
setText(field2, "folders: " + String.valueOf(item.dirCount()));
} else {
boolean isSimple = (viewType == VIEW_TYPE_FILE_SIMPLE);
if ( image!=null ) {
if ( isSimple ) {
image.setImageResource(item.format.getIconResourceId());
} else {
Drawable drawable = null;
if ( item.id!=null )
drawable = mHistory.getBookCoverpageImage(null, item.id);
if ( drawable!=null ) {
image.setImageDrawable(drawable);
} else {
int resId = item.format!=null ? item.format.getIconResourceId() : 0;
if ( resId!=0 )
image.setImageResource(item.format.getIconResourceId());
}
}
}
if ( isSimple ) {
String fn = item.getFileNameToDisplay();
setText( filename, fn );
} else {
setText( author, formatAuthors(item.authors) );
String seriesName = formatSeries(item.series, item.seriesNumber);
String title = item.title;
String filename1 = item.filename;
String filename2 = item.isArchive /*&& !item.isDirectory */
? new File(item.arcname).getName() : null;
if ( title==null || title.length()==0 ) {
title = filename1;
if (seriesName==null)
seriesName = filename2;
} else if (seriesName==null)
seriesName = filename1;
setText( name, title );
setText( series, seriesName );
// field1.setVisibility(VISIBLE);
// field2.setVisibility(VISIBLE);
// field3.setVisibility(VISIBLE);
field1.setText(formatSize(item.size) + " " + item.format.name() + " " + formatDate(item.createTime));
//field2.setText(formatDate(pos!=null ? pos.getTimeStamp() : item.createTime));
Bookmark pos = mHistory.getLastPos(item);
if ( pos!=null ) {
field2.setText(formatDate(pos.getTimeStamp()) + " " + formatPercent(pos.getPercent())) ;
} else {
field2.setText("");
}
//field3.setText(pos!=null ? formatPercent(pos.getPercent()) : null);
}
}
}
}
public View getView(int position, View convertView, ViewGroup parent) {
if ( dir==null )
return null;
View view;
ViewHolder holder;
int vt = getItemViewType(position);
if ( convertView==null ) {
if ( vt==VIEW_TYPE_LEVEL_UP )
view = mInflater.inflate(R.layout.browser_item_parent_dir, null);
else if ( vt==VIEW_TYPE_DIRECTORY )
view = mInflater.inflate(R.layout.browser_item_folder, null);
else if ( vt==VIEW_TYPE_FILE_SIMPLE )
view = mInflater.inflate(R.layout.browser_item_book_simple, null);
else
view = mInflater.inflate(R.layout.browser_item_book, null);
holder = new ViewHolder();
holder.image = (ImageView)view.findViewById(R.id.book_icon);
holder.name = (TextView)view.findViewById(R.id.book_name);
holder.author = (TextView)view.findViewById(R.id.book_author);
holder.series = (TextView)view.findViewById(R.id.book_series);
holder.filename = (TextView)view.findViewById(R.id.book_filename);
holder.field1 = (TextView)view.findViewById(R.id.browser_item_field1);
holder.field2 = (TextView)view.findViewById(R.id.browser_item_field2);
//holder.field3 = (TextView)view.findViewById(R.id.browser_item_field3);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
holder.viewType = vt;
FileInfo item = (FileInfo)getItem(position);
FileInfo parentItem = null;//item!=null ? item.parent : null;
if ( vt == VIEW_TYPE_LEVEL_UP ) {
item = null;
parentItem = currDirectory;
}
holder.setItem(item, parentItem);
return view;
}
public int getViewTypeCount() {
if ( dir==null )
return 1;
return VIEW_TYPE_COUNT;
}
public boolean hasStableIds() {
return true;
}
public boolean isEmpty() {
if ( dir==null )
return true;
return mScanner.mFileList.size()==0;
}
private ArrayList<DataSetObserver> observers = new ArrayList<DataSetObserver>();
public void registerDataSetObserver(DataSetObserver observer) {
observers.add(observer);
}
public void unregisterDataSetObserver(DataSetObserver observer) {
observers.remove(observer);
}
});
int index = dir!=null ? dir.getItemIndex(file) : -1;
if ( dir!=null && !dir.isRootDir() )
index++;
setSelection(index);
setChoiceMode(CHOICE_MODE_SINGLE);
invalidate();
}
| private void showDirectoryInternal( final FileInfo dir, final FileInfo file )
{
currDirectory = dir;
if ( dir!=null )
Log.i("cr3", "Showing directory " + dir);
this.setAdapter(new ListAdapter() {
public boolean areAllItemsEnabled() {
return true;
}
public boolean isEnabled(int arg0) {
return true;
}
public int getCount() {
if ( dir==null )
return 0;
return dir.fileCount() + dir.dirCount() + (dir.parent!=null ? 1 : 0);
}
public Object getItem(int position) {
if ( dir==null )
return null;
if ( position<0 )
return null;
int start = (dir.parent!=null ? 1 : 0);
if ( position<start )
return dir.parent;
return dir.getItem(position-start);
}
public long getItemId(int position) {
if ( dir==null )
return 0;
return position;
}
public final int VIEW_TYPE_LEVEL_UP = 0;
public final int VIEW_TYPE_DIRECTORY = 1;
public final int VIEW_TYPE_FILE = 2;
public final int VIEW_TYPE_FILE_SIMPLE = 3;
public final int VIEW_TYPE_COUNT = 4;
public int getItemViewType(int position) {
if ( dir==null )
return 0;
if ( position<0 )
return Adapter.IGNORE_ITEM_VIEW_TYPE;
int start = (dir.parent!=null ? 1 : 0);
if ( position<start )
return VIEW_TYPE_LEVEL_UP;
if ( position<start + dir.dirCount() )
return VIEW_TYPE_DIRECTORY;
start += dir.dirCount();
position -= start;
if ( position<dir.fileCount() )
return isSimpleViewMode ? VIEW_TYPE_FILE_SIMPLE : VIEW_TYPE_FILE;
return Adapter.IGNORE_ITEM_VIEW_TYPE;
}
class ViewHolder {
int viewType;
ImageView image;
TextView name;
TextView author;
TextView series;
TextView filename;
TextView field1;
TextView field2;
//TextView field3;
void setText( TextView view, String text )
{
if ( view==null )
return;
if ( text!=null && text.length()>0 ) {
view.setText(text);
view.setVisibility(VISIBLE);
} else {
view.setText(null);
view.setVisibility(INVISIBLE);
}
}
void setItem(FileInfo item, FileInfo parentItem)
{
if ( item==null ) {
image.setImageResource(R.drawable.cr3_browser_back);
String thisDir = "";
if ( parentItem!=null ) {
if ( parentItem.pathname.startsWith("@") )
thisDir = "/" + parentItem.filename;
// else if ( parentItem.isArchive )
// thisDir = parentItem.arcname;
else
thisDir = parentItem.pathname;
//parentDir = parentItem.path;
}
name.setText(thisDir);
return;
}
if ( item.isDirectory ) {
if ( item.isRecentDir() )
image.setImageResource(R.drawable.cr3_browser_folder_recent);
else if ( item.isArchive )
image.setImageResource(R.drawable.cr3_browser_folder_zip);
else
image.setImageResource(R.drawable.cr3_browser_folder);
setText(name, item.filename);
setText(field1, "books: " + String.valueOf(item.fileCount()));
setText(field2, "folders: " + String.valueOf(item.dirCount()));
} else {
boolean isSimple = (viewType == VIEW_TYPE_FILE_SIMPLE);
if ( image!=null ) {
if ( isSimple ) {
image.setImageResource(item.format.getIconResourceId());
} else {
Drawable drawable = null;
if ( item.id!=null )
drawable = mHistory.getBookCoverpageImage(null, item.id);
if ( drawable!=null ) {
image.setImageDrawable(drawable);
} else {
int resId = item.format!=null ? item.format.getIconResourceId() : 0;
if ( resId!=0 )
image.setImageResource(item.format.getIconResourceId());
}
}
}
if ( isSimple ) {
String fn = item.getFileNameToDisplay();
setText( filename, fn );
} else {
setText( author, formatAuthors(item.authors) );
String seriesName = formatSeries(item.series, item.seriesNumber);
String title = item.title;
String filename1 = item.filename;
String filename2 = item.isArchive /*&& !item.isDirectory */
? new File(item.arcname).getName() : null;
if ( title==null || title.length()==0 ) {
title = filename1;
if (seriesName==null)
seriesName = filename2;
} else if (seriesName==null)
seriesName = filename1;
setText( name, title );
setText( series, seriesName );
// field1.setVisibility(VISIBLE);
// field2.setVisibility(VISIBLE);
// field3.setVisibility(VISIBLE);
field1.setText(formatSize(item.size) + " " + item.format.name().toLowerCase() + " " + formatDate(item.createTime) + " ");
//field2.setText(formatDate(pos!=null ? pos.getTimeStamp() : item.createTime));
Bookmark pos = mHistory.getLastPos(item);
if ( pos!=null ) {
field2.setText(formatPercent(pos.getPercent()) + " " + formatDate(pos.getTimeStamp())) ;
} else {
field2.setText("");
}
//field3.setText(pos!=null ? formatPercent(pos.getPercent()) : null);
}
}
}
}
public View getView(int position, View convertView, ViewGroup parent) {
if ( dir==null )
return null;
View view;
ViewHolder holder;
int vt = getItemViewType(position);
if ( convertView==null ) {
if ( vt==VIEW_TYPE_LEVEL_UP )
view = mInflater.inflate(R.layout.browser_item_parent_dir, null);
else if ( vt==VIEW_TYPE_DIRECTORY )
view = mInflater.inflate(R.layout.browser_item_folder, null);
else if ( vt==VIEW_TYPE_FILE_SIMPLE )
view = mInflater.inflate(R.layout.browser_item_book_simple, null);
else
view = mInflater.inflate(R.layout.browser_item_book, null);
holder = new ViewHolder();
holder.image = (ImageView)view.findViewById(R.id.book_icon);
holder.name = (TextView)view.findViewById(R.id.book_name);
holder.author = (TextView)view.findViewById(R.id.book_author);
holder.series = (TextView)view.findViewById(R.id.book_series);
holder.filename = (TextView)view.findViewById(R.id.book_filename);
holder.field1 = (TextView)view.findViewById(R.id.browser_item_field1);
holder.field2 = (TextView)view.findViewById(R.id.browser_item_field2);
//holder.field3 = (TextView)view.findViewById(R.id.browser_item_field3);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
holder.viewType = vt;
FileInfo item = (FileInfo)getItem(position);
FileInfo parentItem = null;//item!=null ? item.parent : null;
if ( vt == VIEW_TYPE_LEVEL_UP ) {
item = null;
parentItem = currDirectory;
}
holder.setItem(item, parentItem);
return view;
}
public int getViewTypeCount() {
if ( dir==null )
return 1;
return VIEW_TYPE_COUNT;
}
public boolean hasStableIds() {
return true;
}
public boolean isEmpty() {
if ( dir==null )
return true;
return mScanner.mFileList.size()==0;
}
private ArrayList<DataSetObserver> observers = new ArrayList<DataSetObserver>();
public void registerDataSetObserver(DataSetObserver observer) {
observers.add(observer);
}
public void unregisterDataSetObserver(DataSetObserver observer) {
observers.remove(observer);
}
});
int index = dir!=null ? dir.getItemIndex(file) : -1;
if ( dir!=null && !dir.isRootDir() )
index++;
setSelection(index);
setChoiceMode(CHOICE_MODE_SINGLE);
invalidate();
}
|
diff --git a/tool/src/java/org/sakaiproject/evaluation/tool/producers/ReportsViewingProducer.java b/tool/src/java/org/sakaiproject/evaluation/tool/producers/ReportsViewingProducer.java
index d350bc88..9803c8d4 100644
--- a/tool/src/java/org/sakaiproject/evaluation/tool/producers/ReportsViewingProducer.java
+++ b/tool/src/java/org/sakaiproject/evaluation/tool/producers/ReportsViewingProducer.java
@@ -1,279 +1,279 @@
/******************************************************************************
* ViewReportProducer.java - created by on Oct 05, 2006
*
* Copyright (c) 2007 Virginia Polytechnic Institute and State University
* 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
*
* Contributors:
* Will Humphries ([email protected])
*****************************************************************************/
package org.sakaiproject.evaluation.tool.producers;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.evaluation.logic.EvalEvaluationsLogic;
import org.sakaiproject.evaluation.logic.EvalExternalLogic;
import org.sakaiproject.evaluation.logic.EvalItemsLogic;
import org.sakaiproject.evaluation.logic.EvalResponsesLogic;
import org.sakaiproject.evaluation.logic.model.EvalGroup;
import org.sakaiproject.evaluation.logic.utils.TemplateItemUtils;
import org.sakaiproject.evaluation.model.EvalAnswer;
import org.sakaiproject.evaluation.model.EvalEvaluation;
import org.sakaiproject.evaluation.model.EvalItem;
import org.sakaiproject.evaluation.model.EvalScale;
import org.sakaiproject.evaluation.model.EvalTemplate;
import org.sakaiproject.evaluation.model.EvalTemplateItem;
import org.sakaiproject.evaluation.model.constant.EvalConstants;
import org.sakaiproject.evaluation.tool.EvaluationBean;
import org.sakaiproject.evaluation.tool.EvaluationConstant;
import org.sakaiproject.evaluation.tool.ReportsBean;
import org.sakaiproject.evaluation.tool.viewparams.CSVReportViewParams;
import org.sakaiproject.evaluation.tool.viewparams.EssayResponseParams;
import org.sakaiproject.evaluation.tool.viewparams.ReportParameters;
import org.sakaiproject.evaluation.tool.viewparams.TemplateViewParameters;
import uk.org.ponder.rsf.components.UIBoundBoolean;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UIContainer;
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.decorators.DecoratorList;
import uk.org.ponder.rsf.components.decorators.UIColourDecorator;
import uk.org.ponder.rsf.components.decorators.UIStyleDecorator;
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;
/**
* rendering the report results from an evaluation
*
* @author:Will Humphries ([email protected])
* @author Aaron Zeckoski ([email protected])
*/
public class ReportsViewingProducer implements ViewComponentProducer, NavigationCaseReporter, ViewParamsReporter {
private static Log log = LogFactory.getLog(EvaluationBean.class);
public static final String VIEW_ID = "report_view";
public String getViewID() {
return VIEW_ID;
}
private EvalExternalLogic externalLogic;
public void setExternalLogic(EvalExternalLogic externalLogic) {
this.externalLogic = externalLogic;
}
private EvalEvaluationsLogic evalsLogic;
public void setEvalsLogic(EvalEvaluationsLogic evalsLogic) {
this.evalsLogic = evalsLogic;
}
private EvalResponsesLogic responsesLogic;
public void setResponsesLogic(EvalResponsesLogic responsesLogic) {
this.responsesLogic = responsesLogic;
}
private EvalItemsLogic itemsLogic;
public void setItemsLogic(EvalItemsLogic itemsLogic) {
this.itemsLogic = itemsLogic;
}
public ReportsBean reportsBean;
public void setReportsBean(ReportsBean reportsBean) {
this.reportsBean = reportsBean;
}
int displayNumber = 1;
String[] groupIds;
/* (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) {
String currentUserId = externalLogic.getCurrentUserId();
UIMessage.make(tofill, "view-report-title", "viewreport.page.title");
ReportParameters reportViewParams = (ReportParameters) viewparams;
Long evaluationId = reportViewParams.evaluationId;
if (evaluationId != null) {
// bread crumbs
UIInternalLink.make(tofill, "summary-toplink", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID));
UIInternalLink.make(tofill, "report-groups-title", UIMessage.make("reportgroups.page.title"),
new TemplateViewParameters(ReportChooseGroupsProducer.VIEW_ID, reportViewParams.evaluationId));
EvalEvaluation evaluation = evalsLogic.getEvaluationById(reportViewParams.evaluationId);
// do a permission check
if (!currentUserId.equals(evaluation.getOwner()) &&
!externalLogic.isUserAdmin(currentUserId)) { // TODO - this check is no good, we need a real one -AZ
throw new SecurityException("Invalid user attempting to access reports page: " + currentUserId);
}
// get template from DAO
EvalTemplate template = evaluation.getTemplate();
// TODO - this should respect the user
//List allTemplateItems = itemsLogic.getTemplateItemsForEvaluation(evaluationId, null, null);
List allTemplateItems = new ArrayList(template.getTemplateItems());
if (!allTemplateItems.isEmpty()) {
if (reportViewParams.groupIds == null || reportViewParams.groupIds.length == 0) {
// TODO - this is a security hole -AZ
// no passed in groups so just list all of them
Map evalGroups = evalsLogic.getEvaluationGroups(new Long[] { evaluationId }, false);
List groups = (List) evalGroups.get(evaluationId);
groupIds = new String[groups.size()];
for (int i = 0; i < groups.size(); i++) {
EvalGroup currGroup = (EvalGroup) groups.get(i);
groupIds[i] = currGroup.evalGroupId;
}
} else {
// use passed in group ids
groupIds = reportViewParams.groupIds;
}
UIInternalLink.make(tofill, "fullEssayResponse", UIMessage.make("viewreport.view.essays"), new EssayResponseParams(
ReportsViewEssaysProducer.VIEW_ID, reportViewParams.evaluationId, groupIds));
UIInternalLink.make(tofill, "csvResultsReport", UIMessage.make("viewreport.view.csv"), new CSVReportViewParams(
"csvResultsReport", template.getId(), reportViewParams.evaluationId, groupIds)); //$NON-NLS-3$
// filter out items that cannot be answered (header, etc.)
List answerableItemsList = TemplateItemUtils.getAnswerableTemplateItems(allTemplateItems);
UIBranchContainer courseSection = null;
UIBranchContainer instructorSection = null;
// handle showing all course type items
if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_COURSE, answerableItemsList)) {
courseSection = UIBranchContainer.make(tofill, "courseSection:");
UIMessage.make(courseSection, "report-course-questions", "viewreport.itemlist.coursequestions");
for (int i = 0; i < answerableItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) answerableItemsList.get(i);
if (EvalConstants.ITEM_CATEGORY_COURSE.equals(templateItem.getItemCategory())) {
UIBranchContainer branch = UIBranchContainer.make(courseSection, "itemrow:first", i + "");
if (i % 2 == 1)
- branch.decorators = new DecoratorList( new UIStyleDecorator("itemsListOddLine") ); // must match the existing CSS class
+ branch.decorators = new DecoratorList( new UIStyleDecorator("") ); // must match the existing CSS class
renderTemplateItemResults(templateItem, evaluation.getId(), displayNumber, branch);
displayNumber++;
}
}
}
// handle showing all instructor type items
if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_INSTRUCTOR, answerableItemsList)) {
instructorSection = UIBranchContainer.make(tofill, "instructorSection:");
UIMessage.make(instructorSection, "report-instructor-questions", "viewreport.itemlist.instructorquestions");
for (int i = 0; i < answerableItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) answerableItemsList.get(i);
if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(templateItem.getItemCategory())) {
UIBranchContainer branch = UIBranchContainer.make(instructorSection, "itemrow:first", i + "");
if (i % 2 == 1)
- branch.decorators = new DecoratorList( new UIStyleDecorator("itemsListOddLine") ); // must match the existing CSS class
+ branch.decorators = new DecoratorList( new UIStyleDecorator("") ); // must match the existing CSS class
renderTemplateItemResults(templateItem, evaluation.getId(), i, branch);
displayNumber++;
}
} // end of for loop
//}
}
}
} else {
// invalid view params
throw new IllegalArgumentException("Evaluation id is required to view report");
}
}
/**
* @param templateItem
* @param evalId
* @param displayNum
* @param branch
*/
private void renderTemplateItemResults(EvalTemplateItem templateItem, Long evalId, int displayNum, UIBranchContainer branch) {
EvalItem item = templateItem.getItem();
String templateItemType = item.getClassification();
if (templateItemType.equals(EvalConstants.ITEM_TYPE_SCALED)) {
//normal scaled type
EvalScale scale = item.getScale();
String[] scaleOptions = scale.getOptions();
int optionCount = scaleOptions.length;
String scaleLabels[] = new String[optionCount];
Boolean useNA = templateItem.getUsesNA();
UIBranchContainer scaled = UIBranchContainer.make(branch, "scaledSurvey:");
UIOutput.make(scaled, "itemNum", displayNum+"");
UIOutput.make(scaled, "itemText", item.getItemText());
if (useNA.booleanValue() == true) {
UIBranchContainer radiobranch3 = UIBranchContainer.make(scaled, "showNA:");
UIBoundBoolean.make(radiobranch3, "itemNA", useNA);
}
List itemAnswers = responsesLogic.getEvalAnswers(item.getId(), evalId, groupIds);
for (int x = 0; x < scaleLabels.length; x++) {
UIBranchContainer answerbranch = UIBranchContainer.make(scaled, "answers:", x + "");
UIOutput.make(answerbranch, "responseText", scaleOptions[x]);
int answers = 0;
//count the number of answers that match this one
for (int y = 0; y < itemAnswers.size(); y++) {
EvalAnswer curr = (EvalAnswer) itemAnswers.get(y);
if (curr.getNumeric().intValue() == x) {
answers++;
}
}
UIOutput.make(answerbranch, "responseTotal", answers + "", x + "");
}
} else if (templateItemType.equals(EvalConstants.ITEM_TYPE_TEXT)) { //"Short Answer/Essay"
UIBranchContainer essay = UIBranchContainer.make(branch, "essayType:");
UIOutput.make(essay, "itemNum", displayNum + "");
UIOutput.make(essay, "itemText", item.getItemText());
UIInternalLink.make(essay, "essayResponse",
new EssayResponseParams(ReportsViewEssaysProducer.VIEW_ID, evalId, templateItem.getId(), groupIds));
} else {
log.warn("Skipped invalid item type ("+templateItemType+"): TI: " + templateItem.getId() + ", Item: " + item.getId() );
}
}
/* (non-Javadoc)
* @see uk.org.ponder.rsf.viewstate.ViewParamsReporter#getViewParameters()
*/
public ViewParameters getViewParameters() {
return new ReportParameters();
}
/* (non-Javadoc)
* @see uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter#reportNavigationCases()
*/
public List reportNavigationCases() {
List i = new ArrayList();
return i;
}
}
| false | true | public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
String currentUserId = externalLogic.getCurrentUserId();
UIMessage.make(tofill, "view-report-title", "viewreport.page.title");
ReportParameters reportViewParams = (ReportParameters) viewparams;
Long evaluationId = reportViewParams.evaluationId;
if (evaluationId != null) {
// bread crumbs
UIInternalLink.make(tofill, "summary-toplink", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID));
UIInternalLink.make(tofill, "report-groups-title", UIMessage.make("reportgroups.page.title"),
new TemplateViewParameters(ReportChooseGroupsProducer.VIEW_ID, reportViewParams.evaluationId));
EvalEvaluation evaluation = evalsLogic.getEvaluationById(reportViewParams.evaluationId);
// do a permission check
if (!currentUserId.equals(evaluation.getOwner()) &&
!externalLogic.isUserAdmin(currentUserId)) { // TODO - this check is no good, we need a real one -AZ
throw new SecurityException("Invalid user attempting to access reports page: " + currentUserId);
}
// get template from DAO
EvalTemplate template = evaluation.getTemplate();
// TODO - this should respect the user
//List allTemplateItems = itemsLogic.getTemplateItemsForEvaluation(evaluationId, null, null);
List allTemplateItems = new ArrayList(template.getTemplateItems());
if (!allTemplateItems.isEmpty()) {
if (reportViewParams.groupIds == null || reportViewParams.groupIds.length == 0) {
// TODO - this is a security hole -AZ
// no passed in groups so just list all of them
Map evalGroups = evalsLogic.getEvaluationGroups(new Long[] { evaluationId }, false);
List groups = (List) evalGroups.get(evaluationId);
groupIds = new String[groups.size()];
for (int i = 0; i < groups.size(); i++) {
EvalGroup currGroup = (EvalGroup) groups.get(i);
groupIds[i] = currGroup.evalGroupId;
}
} else {
// use passed in group ids
groupIds = reportViewParams.groupIds;
}
UIInternalLink.make(tofill, "fullEssayResponse", UIMessage.make("viewreport.view.essays"), new EssayResponseParams(
ReportsViewEssaysProducer.VIEW_ID, reportViewParams.evaluationId, groupIds));
UIInternalLink.make(tofill, "csvResultsReport", UIMessage.make("viewreport.view.csv"), new CSVReportViewParams(
"csvResultsReport", template.getId(), reportViewParams.evaluationId, groupIds)); //$NON-NLS-3$
// filter out items that cannot be answered (header, etc.)
List answerableItemsList = TemplateItemUtils.getAnswerableTemplateItems(allTemplateItems);
UIBranchContainer courseSection = null;
UIBranchContainer instructorSection = null;
// handle showing all course type items
if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_COURSE, answerableItemsList)) {
courseSection = UIBranchContainer.make(tofill, "courseSection:");
UIMessage.make(courseSection, "report-course-questions", "viewreport.itemlist.coursequestions");
for (int i = 0; i < answerableItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) answerableItemsList.get(i);
if (EvalConstants.ITEM_CATEGORY_COURSE.equals(templateItem.getItemCategory())) {
UIBranchContainer branch = UIBranchContainer.make(courseSection, "itemrow:first", i + "");
if (i % 2 == 1)
branch.decorators = new DecoratorList( new UIStyleDecorator("itemsListOddLine") ); // must match the existing CSS class
renderTemplateItemResults(templateItem, evaluation.getId(), displayNumber, branch);
displayNumber++;
}
}
}
// handle showing all instructor type items
if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_INSTRUCTOR, answerableItemsList)) {
instructorSection = UIBranchContainer.make(tofill, "instructorSection:");
UIMessage.make(instructorSection, "report-instructor-questions", "viewreport.itemlist.instructorquestions");
for (int i = 0; i < answerableItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) answerableItemsList.get(i);
if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(templateItem.getItemCategory())) {
UIBranchContainer branch = UIBranchContainer.make(instructorSection, "itemrow:first", i + "");
if (i % 2 == 1)
branch.decorators = new DecoratorList( new UIStyleDecorator("itemsListOddLine") ); // must match the existing CSS class
renderTemplateItemResults(templateItem, evaluation.getId(), i, branch);
displayNumber++;
}
} // end of for loop
//}
}
}
} else {
// invalid view params
throw new IllegalArgumentException("Evaluation id is required to view report");
}
}
| public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
String currentUserId = externalLogic.getCurrentUserId();
UIMessage.make(tofill, "view-report-title", "viewreport.page.title");
ReportParameters reportViewParams = (ReportParameters) viewparams;
Long evaluationId = reportViewParams.evaluationId;
if (evaluationId != null) {
// bread crumbs
UIInternalLink.make(tofill, "summary-toplink", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID));
UIInternalLink.make(tofill, "report-groups-title", UIMessage.make("reportgroups.page.title"),
new TemplateViewParameters(ReportChooseGroupsProducer.VIEW_ID, reportViewParams.evaluationId));
EvalEvaluation evaluation = evalsLogic.getEvaluationById(reportViewParams.evaluationId);
// do a permission check
if (!currentUserId.equals(evaluation.getOwner()) &&
!externalLogic.isUserAdmin(currentUserId)) { // TODO - this check is no good, we need a real one -AZ
throw new SecurityException("Invalid user attempting to access reports page: " + currentUserId);
}
// get template from DAO
EvalTemplate template = evaluation.getTemplate();
// TODO - this should respect the user
//List allTemplateItems = itemsLogic.getTemplateItemsForEvaluation(evaluationId, null, null);
List allTemplateItems = new ArrayList(template.getTemplateItems());
if (!allTemplateItems.isEmpty()) {
if (reportViewParams.groupIds == null || reportViewParams.groupIds.length == 0) {
// TODO - this is a security hole -AZ
// no passed in groups so just list all of them
Map evalGroups = evalsLogic.getEvaluationGroups(new Long[] { evaluationId }, false);
List groups = (List) evalGroups.get(evaluationId);
groupIds = new String[groups.size()];
for (int i = 0; i < groups.size(); i++) {
EvalGroup currGroup = (EvalGroup) groups.get(i);
groupIds[i] = currGroup.evalGroupId;
}
} else {
// use passed in group ids
groupIds = reportViewParams.groupIds;
}
UIInternalLink.make(tofill, "fullEssayResponse", UIMessage.make("viewreport.view.essays"), new EssayResponseParams(
ReportsViewEssaysProducer.VIEW_ID, reportViewParams.evaluationId, groupIds));
UIInternalLink.make(tofill, "csvResultsReport", UIMessage.make("viewreport.view.csv"), new CSVReportViewParams(
"csvResultsReport", template.getId(), reportViewParams.evaluationId, groupIds)); //$NON-NLS-3$
// filter out items that cannot be answered (header, etc.)
List answerableItemsList = TemplateItemUtils.getAnswerableTemplateItems(allTemplateItems);
UIBranchContainer courseSection = null;
UIBranchContainer instructorSection = null;
// handle showing all course type items
if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_COURSE, answerableItemsList)) {
courseSection = UIBranchContainer.make(tofill, "courseSection:");
UIMessage.make(courseSection, "report-course-questions", "viewreport.itemlist.coursequestions");
for (int i = 0; i < answerableItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) answerableItemsList.get(i);
if (EvalConstants.ITEM_CATEGORY_COURSE.equals(templateItem.getItemCategory())) {
UIBranchContainer branch = UIBranchContainer.make(courseSection, "itemrow:first", i + "");
if (i % 2 == 1)
branch.decorators = new DecoratorList( new UIStyleDecorator("") ); // must match the existing CSS class
renderTemplateItemResults(templateItem, evaluation.getId(), displayNumber, branch);
displayNumber++;
}
}
}
// handle showing all instructor type items
if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_INSTRUCTOR, answerableItemsList)) {
instructorSection = UIBranchContainer.make(tofill, "instructorSection:");
UIMessage.make(instructorSection, "report-instructor-questions", "viewreport.itemlist.instructorquestions");
for (int i = 0; i < answerableItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) answerableItemsList.get(i);
if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(templateItem.getItemCategory())) {
UIBranchContainer branch = UIBranchContainer.make(instructorSection, "itemrow:first", i + "");
if (i % 2 == 1)
branch.decorators = new DecoratorList( new UIStyleDecorator("") ); // must match the existing CSS class
renderTemplateItemResults(templateItem, evaluation.getId(), i, branch);
displayNumber++;
}
} // end of for loop
//}
}
}
} else {
// invalid view params
throw new IllegalArgumentException("Evaluation id is required to view report");
}
}
|
diff --git a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/ApplicationWorkbenchWindowAdvisor.java b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/ApplicationWorkbenchWindowAdvisor.java
index 5075e6d..2b9b8ea 100644
--- a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/ApplicationWorkbenchWindowAdvisor.java
+++ b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/ApplicationWorkbenchWindowAdvisor.java
@@ -1,265 +1,264 @@
package com.uwusoft.timesheet;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.menus.CommandContributionItem;
import org.eclipse.ui.menus.CommandContributionItemParameter;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import com.uwusoft.timesheet.extensionpoint.StorageService;
import com.uwusoft.timesheet.util.BusinessDayUtil;
import com.uwusoft.timesheet.util.ExtensionManager;
import com.uwusoft.timesheet.util.MessageBox;
public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
private IWorkbenchWindow window;
private TrayItem trayItem;
private Image trayImage;
private ApplicationActionBarAdvisor actionBarAdvisor;
private IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
super(configurer);
}
public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) {
actionBarAdvisor = new ApplicationActionBarAdvisor(configurer);
return actionBarAdvisor;
}
public void preWindowOpen() {
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
configurer.setInitialSize(new Point(400, 300));
configurer.setShowCoolBar(false);
configurer.setShowProgressIndicator(true);
configurer.setTitle("Timesheet");
}
public void postWindowOpen() {
super.postWindowOpen();
window = getWindowConfigurer().getWindow();
window.getShell().addShellListener(new ShellAdapter() {
public void shellIconified(ShellEvent e) { // If the window is minimized hide the window
preWindowShellClose();
}
});
trayItem = initTaskItem();
// Some OS might not support tray items
if (trayItem != null) {
window.getShell().setVisible(false);
StorageService storageService = new ExtensionManager<StorageService>(
StorageService.SERVICE_ID).getService(preferenceStore.getString(StorageService.PROPERTY));
Date startDate = TimesheetApp.startDate;
Date shutdownDate = startDate;
try {
String startTime = preferenceStore.getString(TimesheetApp.SYSTEM_START);
if (!StringUtils.isEmpty(startTime)) {
preferenceStore.setToDefault(TimesheetApp.SYSTEM_START);
startDate = StorageService.formatter.parse(startTime);
}
String shutdownTime = preferenceStore.getString(TimesheetApp.SYSTEM_SHUTDOWN);
if (StringUtils.isEmpty(shutdownTime) || StorageService.formatter.parse(shutdownTime).before(storageService.getLastTaskEntryDate()))
shutdownDate = storageService.getLastTaskEntryDate();
else
shutdownDate = StorageService.formatter.parse(shutdownTime);
} catch (ParseException e) {
MessageBox.setError("Shutdown date", e.getLocalizedMessage());
}
Calendar calDay = Calendar.getInstance();
Calendar calWeek = new GregorianCalendar();
int shutdownDay = 0;
int shutdownWeek = 0;
calDay.setTime(startDate);
calWeek.setTime(startDate);
int startDay = calDay.get(Calendar.DAY_OF_YEAR);
int startWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
calDay.setTime(shutdownDate);
calWeek.setTime(shutdownDate);
shutdownDay = calDay.get(Calendar.DAY_OF_YEAR);
shutdownWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
IHandlerService handlerService = (IHandlerService) window.getService(IHandlerService.class);
ICommandService commandService = (ICommandService) window.getService(ICommandService.class);
if (startDay != shutdownDay && storageService.getLastTask() != null) { // don't automatically check in/out if program is restarted
try { // automatic check out
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("Timesheet.commands.shutdownTime", StorageService.formatter.format(shutdownDate));
handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.checkout"), parameters), null);
} catch (Exception ex) {
MessageBox.setError("Timesheet.checkout command", ex.getLocalizedMessage());
}
}
if (storageService.getLastTask() == null) {
try { // automatic check in
Date end = shutdownDate;
- do
+ while (end.before(startDate))
end = BusinessDayUtil.getNextBusinessDay(end, true); // create missing holidays
- while (!end.after(startDate));
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("Timesheet.commands.startTime", StorageService.formatter.format(startDate));
parameters.put("Timesheet.commands.storeWeekTotal", Boolean.toString(startWeek != shutdownWeek));
handlerService.executeCommand(ParameterizedCommand.generateCommand(
commandService.getCommand("Timesheet.checkin"), parameters), null);
if (startWeek > shutdownWeek) {
parameters.clear();
parameters.put("Timesheet.commands.weekNum", Integer.toString(shutdownWeek));
handlerService.executeCommand(ParameterizedCommand.generateCommand(
commandService.getCommand("Timesheet.submit"), parameters), null);
}
} catch (Exception ex) {
MessageBox.setError("Timesheet.checkin command", ex.getLocalizedMessage());
}
}
hookPopupMenu();
}
}
public boolean preWindowShellClose() {
window.getShell().setVisible(false);
return false; // if window close button pressed only minimize to system tray (don't exit the program)
}
private void hookPopupMenu() {
trayItem.addListener(SWT.MenuDetect, new Listener() {
public void handleEvent(Event event) {
MenuManager trayMenu = new MenuManager();
StorageService storageService = new ExtensionManager<StorageService>(
StorageService.SERVICE_ID).getService(preferenceStore.getString(StorageService.PROPERTY));
if (storageService.getLastTask() == null) {
Map <String, String> parameters = new HashMap<String, String>();
parameters.put("Timesheet.commands.startTime", StorageService.formatter.format(new Date()));
CommandContributionItemParameter p = new CommandContributionItemParameter(window, null, "Timesheet.checkin", CommandContributionItem.STYLE_PUSH);
p.parameters = parameters;
trayMenu.add(new CommandContributionItem(p));
}
else {
trayMenu.add(new CommandContributionItem(
new CommandContributionItemParameter(window, null, "Timesheet.changeTask", CommandContributionItem.STYLE_PUSH)));
trayMenu.add(new CommandContributionItem(
new CommandContributionItemParameter(window, null, "Timesheet.setBreak", CommandContributionItem.STYLE_PUSH)));
MenuManager wholeDayTask = new MenuManager("Set whole day task");
String wholeDayTaskCommandId = "Timesheet.commands.wholeDayTask";
Map <String, String> parameters = new HashMap<String, String>();
parameters.put("Timesheet.commands.task", "task.holiday");
CommandContributionItemParameter p = new CommandContributionItemParameter(window, null, wholeDayTaskCommandId, CommandContributionItem.STYLE_PUSH);
p.label = "Holiday";
p.parameters = parameters;
wholeDayTask.add(new CommandContributionItem(p));
parameters.put("Timesheet.commands.task", "task.vacation");
p = new CommandContributionItemParameter(window, null, wholeDayTaskCommandId, CommandContributionItem.STYLE_PUSH);
p.label = "Vacation";
p.parameters = parameters;
wholeDayTask.add(new CommandContributionItem(p));
parameters.put("Timesheet.commands.task", "task.sick");
p = new CommandContributionItemParameter(window, null, wholeDayTaskCommandId, CommandContributionItem.STYLE_PUSH);
p.label = "Sick Leave";
p.parameters = parameters;
wholeDayTask.add(new CommandContributionItem(p));
trayMenu.add(wholeDayTask);
parameters.clear();
parameters.put("Timesheet.commands.shutdownTime", StorageService.formatter.format(new Date()));
p = new CommandContributionItemParameter(window, null, "Timesheet.checkout", CommandContributionItem.STYLE_PUSH);
p.parameters = parameters;
trayMenu.add(new CommandContributionItem(p));
}
trayMenu.add(new Separator());
trayMenu.add(new CommandContributionItem(
new CommandContributionItemParameter(window, null, "Timesheet.importTasks", CommandContributionItem.STYLE_PUSH)));
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
//cal.setFirstDayOfWeek(Calendar.MONDAY);
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("Timesheet.commands.weekNum", Integer.toString(cal.get(Calendar.WEEK_OF_YEAR) - 1));
CommandContributionItemParameter p = new CommandContributionItemParameter(window, null, "Timesheet.submit", CommandContributionItem.STYLE_PUSH);
p.parameters = parameters;
trayMenu.add(new CommandContributionItem(p));
trayMenu.add(new Separator());
Menu menu = trayMenu.createContextMenu(window.getShell());
actionBarAdvisor.fillTrayItem(trayMenu);
menu.setVisible(true);
}
});
}
private TrayItem initTaskItem() {
final Tray tray = window.getShell().getDisplay().getSystemTray();
final TrayItem trayItem = new TrayItem(tray, SWT.NONE);
ImageDescriptor descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "/icons/clock.png");
if (descriptor != null) {
trayImage = descriptor.createImage();
trayItem.setImage(trayImage);
}
trayItem.setToolTipText("Timesheet");
trayItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
Shell shell = window.getShell();
shell.setVisible(true);
shell.setActive();
shell.setFocus();
shell.setMinimized(false);
//trayItem.dispose();
}
});
return trayItem;
}
// We need to clean-up after ourself
@Override
public void dispose() {
if (trayImage != null) {
trayImage.dispose();
}
if (trayItem != null) {
trayItem.dispose();
}
}
}
| false | true | public void postWindowOpen() {
super.postWindowOpen();
window = getWindowConfigurer().getWindow();
window.getShell().addShellListener(new ShellAdapter() {
public void shellIconified(ShellEvent e) { // If the window is minimized hide the window
preWindowShellClose();
}
});
trayItem = initTaskItem();
// Some OS might not support tray items
if (trayItem != null) {
window.getShell().setVisible(false);
StorageService storageService = new ExtensionManager<StorageService>(
StorageService.SERVICE_ID).getService(preferenceStore.getString(StorageService.PROPERTY));
Date startDate = TimesheetApp.startDate;
Date shutdownDate = startDate;
try {
String startTime = preferenceStore.getString(TimesheetApp.SYSTEM_START);
if (!StringUtils.isEmpty(startTime)) {
preferenceStore.setToDefault(TimesheetApp.SYSTEM_START);
startDate = StorageService.formatter.parse(startTime);
}
String shutdownTime = preferenceStore.getString(TimesheetApp.SYSTEM_SHUTDOWN);
if (StringUtils.isEmpty(shutdownTime) || StorageService.formatter.parse(shutdownTime).before(storageService.getLastTaskEntryDate()))
shutdownDate = storageService.getLastTaskEntryDate();
else
shutdownDate = StorageService.formatter.parse(shutdownTime);
} catch (ParseException e) {
MessageBox.setError("Shutdown date", e.getLocalizedMessage());
}
Calendar calDay = Calendar.getInstance();
Calendar calWeek = new GregorianCalendar();
int shutdownDay = 0;
int shutdownWeek = 0;
calDay.setTime(startDate);
calWeek.setTime(startDate);
int startDay = calDay.get(Calendar.DAY_OF_YEAR);
int startWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
calDay.setTime(shutdownDate);
calWeek.setTime(shutdownDate);
shutdownDay = calDay.get(Calendar.DAY_OF_YEAR);
shutdownWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
IHandlerService handlerService = (IHandlerService) window.getService(IHandlerService.class);
ICommandService commandService = (ICommandService) window.getService(ICommandService.class);
if (startDay != shutdownDay && storageService.getLastTask() != null) { // don't automatically check in/out if program is restarted
try { // automatic check out
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("Timesheet.commands.shutdownTime", StorageService.formatter.format(shutdownDate));
handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.checkout"), parameters), null);
} catch (Exception ex) {
MessageBox.setError("Timesheet.checkout command", ex.getLocalizedMessage());
}
}
if (storageService.getLastTask() == null) {
try { // automatic check in
Date end = shutdownDate;
do
end = BusinessDayUtil.getNextBusinessDay(end, true); // create missing holidays
while (!end.after(startDate));
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("Timesheet.commands.startTime", StorageService.formatter.format(startDate));
parameters.put("Timesheet.commands.storeWeekTotal", Boolean.toString(startWeek != shutdownWeek));
handlerService.executeCommand(ParameterizedCommand.generateCommand(
commandService.getCommand("Timesheet.checkin"), parameters), null);
if (startWeek > shutdownWeek) {
parameters.clear();
parameters.put("Timesheet.commands.weekNum", Integer.toString(shutdownWeek));
handlerService.executeCommand(ParameterizedCommand.generateCommand(
commandService.getCommand("Timesheet.submit"), parameters), null);
}
} catch (Exception ex) {
MessageBox.setError("Timesheet.checkin command", ex.getLocalizedMessage());
}
}
hookPopupMenu();
}
}
| public void postWindowOpen() {
super.postWindowOpen();
window = getWindowConfigurer().getWindow();
window.getShell().addShellListener(new ShellAdapter() {
public void shellIconified(ShellEvent e) { // If the window is minimized hide the window
preWindowShellClose();
}
});
trayItem = initTaskItem();
// Some OS might not support tray items
if (trayItem != null) {
window.getShell().setVisible(false);
StorageService storageService = new ExtensionManager<StorageService>(
StorageService.SERVICE_ID).getService(preferenceStore.getString(StorageService.PROPERTY));
Date startDate = TimesheetApp.startDate;
Date shutdownDate = startDate;
try {
String startTime = preferenceStore.getString(TimesheetApp.SYSTEM_START);
if (!StringUtils.isEmpty(startTime)) {
preferenceStore.setToDefault(TimesheetApp.SYSTEM_START);
startDate = StorageService.formatter.parse(startTime);
}
String shutdownTime = preferenceStore.getString(TimesheetApp.SYSTEM_SHUTDOWN);
if (StringUtils.isEmpty(shutdownTime) || StorageService.formatter.parse(shutdownTime).before(storageService.getLastTaskEntryDate()))
shutdownDate = storageService.getLastTaskEntryDate();
else
shutdownDate = StorageService.formatter.parse(shutdownTime);
} catch (ParseException e) {
MessageBox.setError("Shutdown date", e.getLocalizedMessage());
}
Calendar calDay = Calendar.getInstance();
Calendar calWeek = new GregorianCalendar();
int shutdownDay = 0;
int shutdownWeek = 0;
calDay.setTime(startDate);
calWeek.setTime(startDate);
int startDay = calDay.get(Calendar.DAY_OF_YEAR);
int startWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
calDay.setTime(shutdownDate);
calWeek.setTime(shutdownDate);
shutdownDay = calDay.get(Calendar.DAY_OF_YEAR);
shutdownWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
IHandlerService handlerService = (IHandlerService) window.getService(IHandlerService.class);
ICommandService commandService = (ICommandService) window.getService(ICommandService.class);
if (startDay != shutdownDay && storageService.getLastTask() != null) { // don't automatically check in/out if program is restarted
try { // automatic check out
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("Timesheet.commands.shutdownTime", StorageService.formatter.format(shutdownDate));
handlerService.executeCommand(ParameterizedCommand.generateCommand(commandService.getCommand("Timesheet.checkout"), parameters), null);
} catch (Exception ex) {
MessageBox.setError("Timesheet.checkout command", ex.getLocalizedMessage());
}
}
if (storageService.getLastTask() == null) {
try { // automatic check in
Date end = shutdownDate;
while (end.before(startDate))
end = BusinessDayUtil.getNextBusinessDay(end, true); // create missing holidays
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("Timesheet.commands.startTime", StorageService.formatter.format(startDate));
parameters.put("Timesheet.commands.storeWeekTotal", Boolean.toString(startWeek != shutdownWeek));
handlerService.executeCommand(ParameterizedCommand.generateCommand(
commandService.getCommand("Timesheet.checkin"), parameters), null);
if (startWeek > shutdownWeek) {
parameters.clear();
parameters.put("Timesheet.commands.weekNum", Integer.toString(shutdownWeek));
handlerService.executeCommand(ParameterizedCommand.generateCommand(
commandService.getCommand("Timesheet.submit"), parameters), null);
}
} catch (Exception ex) {
MessageBox.setError("Timesheet.checkin command", ex.getLocalizedMessage());
}
}
hookPopupMenu();
}
}
|
diff --git a/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/parser/EngineIRParserTest.java b/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/parser/EngineIRParserTest.java
index 433895162..0f614089d 100644
--- a/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/parser/EngineIRParserTest.java
+++ b/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/parser/EngineIRParserTest.java
@@ -1,339 +1,339 @@
package org.eclipse.birt.report.engine.parser;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.ir.ActionDesign;
import org.eclipse.birt.report.engine.ir.CellDesign;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.eclipse.birt.report.engine.ir.DrillThroughActionDesign;
import org.eclipse.birt.report.engine.ir.Expression;
import org.eclipse.birt.report.engine.ir.GridItemDesign;
import org.eclipse.birt.report.engine.ir.HighlightDesign;
import org.eclipse.birt.report.engine.ir.HighlightRuleDesign;
import org.eclipse.birt.report.engine.ir.MapDesign;
import org.eclipse.birt.report.engine.ir.MapRuleDesign;
import org.eclipse.birt.report.engine.ir.Report;
import org.eclipse.birt.report.engine.ir.ReportItemDesign;
import org.eclipse.birt.report.engine.ir.RowDesign;
import org.eclipse.birt.report.engine.ir.VisibilityDesign;
import org.eclipse.birt.report.engine.ir.VisibilityRuleDesign;
public class EngineIRParserTest extends TestCase
{
protected Report loadDesign( String design ) throws Exception
{
InputStream in = this.getClass( ).getResourceAsStream( design );
assertTrue( in != null );
ReportParser parser = new ReportParser( );
return parser.parse( "", in );
}
public void testReportItemDesign( ) throws Exception
{
Report report = loadDesign( "report_item_test.rptdesign" );
ReportItemDesign item = report.getContent( 0 );
long ID = item.getID( );
String name = item.getName( );
String extend = item.getExtends( );
String javaClass = item.getJavaClass( );
String styleName = item.getStyleName( );
DimensionType x = item.getX( );
DimensionType y = item.getY( );
DimensionType width = item.getWidth( );
DimensionType height = item.getHeight( );
Expression onCreate = item.getOnCreate( );
Expression onRender = item.getOnRender( );
Expression onPageBreak = item.getOnPageBreak( );
boolean useCachedResult = item.useCachedResult( );
assertEquals( 7, ID );
assertEquals( "name", name );
assertEquals( null, extend );
assertEquals( "javaEventHandle", javaClass );
assertEquals( null, styleName );
assertEquals( "1in", x.toString( ) );
assertEquals( "1in", y.toString( ) );
assertEquals( "1in", width.toString( ) );
assertEquals( "1in", height.toString( ) );
assertEquals( "onCreate", onCreate.getScriptText( ) );
assertEquals( "onRender", onRender.getScriptText( ) );
assertEquals( "onPageBreak", onPageBreak.getScriptText( ) );
assertEquals( false, useCachedResult );
}
public void testBookmark( ) throws Exception
{
Report report = loadDesign( "bookmark_test.rptdesign" );
ReportItemDesign item = report.getContent( 0 );
Expression bookmark = item.getBookmark( );
assertEquals( Expression.SCRIPT, bookmark.getType( ) );
assertEquals( "bookmark-expr", bookmark.getScriptText( ) );
item = report.getContent( 1 );
bookmark = item.getBookmark( );
assertEquals( Expression.CONSTANT, bookmark.getType( ) );
assertEquals( "bookmark-value", bookmark.getScriptText( ) );
}
public void testTOC( ) throws Exception
{
Report report = loadDesign( "toc_test.rptdesign" );
ReportItemDesign item = report.getContent( 0 );
Expression toc = item.getTOC( );
assertEquals( Expression.SCRIPT, toc.getType( ) );
assertEquals( "toc-expr", toc.getScriptText( ) );
item = report.getContent( 1 );
toc = item.getTOC( );
assertEquals( Expression.CONSTANT, toc.getType( ) );
assertEquals( "toc-value", toc.getScriptText( ) );
}
public void testUserProperty( ) throws Exception
{
Report report = loadDesign( "user_property_test.rptdesign" );
Map<String, Expression> exprs = report.getUserProperties( );
assertEquals( 1, exprs.size( ) );
assertExpression( "report_expr", exprs.get( "report_expr" ) );
ReportItemDesign item = report.getContent( 0 );
exprs = item.getUserProperties( );
assertEquals( 7, exprs.size( ) );
assertExpression( "name_expression", exprs.get( "name_expr" ) );
// FIXME: MODEL doens't support the constant yet
assertExpression( "name_value", exprs.get( "name_value" ) );
assertConstant( "string", exprs.get( "name_string" ) );
assertConstant( "1", exprs.get( "name_integer" ) );
assertConstant( "true", exprs.get( "name_boolean" ) );
assertConstant( "2009-06-03 00:00:00", exprs.get( "name_datetime" ) );
assertConstant( "1.0", exprs.get( "name_float" ) );
}
public void testMap( ) throws Exception
{
Report report = loadDesign( "map_test.rptdesign" );
ReportItemDesign item = report.getContent( 0 );
MapDesign map = item.getMap( );
assertEquals( 4, map.getRuleCount( ) );
MapRuleDesign rule = map.getRule( 0 );
assertEquals( "value", rule.getDisplayText( ) );
assertEquals( "value-key", rule.getDisplayKey( ) );
assertEquals( "between", rule.getOperator( ) );
assertConstant( "value", rule.getTestExpression( ) );
assertConstant( "value", rule.getValue1( ) );
assertConstant( "value", rule.getValue2( ) );
rule = map.getRule( 1 );
assertEquals( "expr", rule.getDisplayText( ) );
assertEquals( "expr-key", rule.getDisplayKey( ) );
assertEquals( "between", rule.getOperator( ) );
assertExpression( "expr", rule.getTestExpression( ) );
assertExpression( "expr", rule.getValue1( ) );
assertExpression( "expr", rule.getValue2( ) );
rule = map.getRule( 2 );
assertEquals( "value", rule.getDisplayText( ) );
assertEquals( "value-key", rule.getDisplayKey( ) );
assertEquals( "in", rule.getOperator( ) );
assertConstant( "value", rule.getTestExpression( ) );
List<Expression> exprs = rule.getValue1List( );
assertEquals( 3, exprs.size( ) );
for ( Expression expr : exprs )
{
assertConstant( "value", expr );
}
assertEquals( null, rule.getValue2( ) );
rule = map.getRule( 3 );
assertEquals( "expr", rule.getDisplayText( ) );
assertEquals( "expr-key", rule.getDisplayKey( ) );
assertEquals( "in", rule.getOperator( ) );
assertExpression( "expr", rule.getTestExpression( ) );
exprs = rule.getValue1List( );
assertEquals( 3, exprs.size( ) );
for ( Expression expr : exprs )
{
assertExpression( "expr", expr );
}
assertEquals( null, rule.getValue2( ) );
}
public void testHighlight( ) throws Exception
{
Report report = loadDesign( "highlight_test.rptdesign" );
ReportItemDesign item = report.getContent( 0 );
HighlightDesign highlight = item.getHighlight( );
assertEquals( 1, highlight.getRuleCount( ) );
HighlightRuleDesign rule = highlight.getRule( 0 );
assertEquals( "between", rule.getOperator( ) );
Expression expr = rule.getTestExpression( );
assertEquals( Expression.SCRIPT, expr.getType( ) );
assertEquals( "expr", expr.getScriptText( ) );
expr = rule.getValue1( );
assertEquals( Expression.SCRIPT, expr.getType( ) );
assertEquals( "expr", expr.getScriptText( ) );
expr = rule.getValue2( );
assertEquals( Expression.SCRIPT, expr.getType( ) );
assertEquals( "expr", expr.getScriptText( ) );
IStyle style = rule.getStyle( );
assertEquals( 1, style.getLength( ) );
assertEquals( "serif", style.getFontFamily( ) );
}
public void testVisibility( ) throws Exception
{
Report report = loadDesign( "visibility_test.rptdesign" );
ReportItemDesign item = report.getContent( 0 );
VisibilityDesign visibility = item.getVisibility( );
assertEquals( 1, visibility.count( ) );
VisibilityRuleDesign rule = visibility.getRule( 0 );
Expression expr = rule.getExpression( );
assertEquals( "all", rule.getFormat( ) );
assertEquals( Expression.SCRIPT, expr.getType( ) );
assertEquals( "true", expr.getScriptText( ) );
item = report.getContent( 1 );
visibility = item.getVisibility( );
assertEquals( 1, visibility.count( ) );
rule = visibility.getRule( 0 );
expr = rule.getExpression( );
assertEquals( "all", rule.getFormat( ) );
assertEquals( Expression.CONSTANT, expr.getType( ) );
assertEquals( "true", expr.getScriptText( ) );
}
public void testAction( ) throws Exception
{
Report report = loadDesign( "action_test.rptdesign" );
ActionDesign action = report.getContent( 0 ).getAction( );
assertEquals( ActionDesign.ACTION_HYPERLINK, action.getActionType( ) );
assertEquals( "_blank", action.getTargetWindow( ) );
assertExpression( "uri-expr", action.getHyperlink( ) );
assertEquals( "tooltips", action.getTooltip( ) );
assertEquals( null, action.getBookmark( ) );
assertEquals( null, action.getDrillThrough( ) );
action = report.getContent( 1 ).getAction( );
assertEquals( ActionDesign.ACTION_HYPERLINK, action.getActionType( ) );
assertConstant( "uri-value", action.getHyperlink( ) );
action = report.getContent( 2 ).getAction( );
assertEquals( ActionDesign.ACTION_BOOKMARK, action.getActionType( ) );
assertEquals( null, action.getHyperlink( ) );
assertExpression( "bookmark-expr", action.getBookmark( ) );
assertEquals( null, action.getDrillThrough( ) );
action = report.getContent( 3 ).getAction( );
assertEquals( ActionDesign.ACTION_BOOKMARK, action.getActionType( ) );
assertConstant( "bookmark-value", action.getBookmark( ) );
// drill-through to report design with expression
action = report.getContent( 4 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
assertEquals( null, action.getBookmark( ) );
assertEquals( null, action.getHyperlink( ) );
DrillThroughActionDesign drill = action.getDrillThrough( );
assertEquals( "report-design", drill.getTargetFileType( ) );
// FIXME: should support expression
assertConstant( "design-expr", drill.getReportName( ) );
// assertExpression( "design-expr", drill.getReportName( ) );
assertEquals( true, drill.getBookmarkType( ) );
assertExpression( "bookmark-expr", drill.getBookmark( ) );
assertEquals( "xls", drill.getFormat( ) );
- Map<String, Expression> exprs = drill.getParameters( );
+ Map<String, List<Expression>> exprs = drill.getParameters( );
assertEquals( 2, exprs.size( ) );
- assertExpression( "param-expr", exprs.get( "param-expr" ) );
- assertConstant( "param-value", exprs.get( "param-value" ) );
+ assertExpression( "param-expr", exprs.get( "param-expr" ).get( 0 ) );
+ assertConstant( "param-value", exprs.get( "param-value" ).get( 0 ) );
action = report.getContent( 5 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
drill = action.getDrillThrough( );
assertEquals( "report-design", drill.getTargetFileType( ) );
assertConstant( "design-value", drill.getReportName( ) );
assertEquals( false, drill.getBookmarkType( ) );
assertConstant( "bookmark-value", drill.getBookmark( ) );
action = report.getContent( 6 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
drill = action.getDrillThrough( );
assertEquals( "report-document", drill.getTargetFileType( ) );
// FIXME: should support expression document name
assertConstant( "document-expr", drill.getReportName( ) );
// assertExpression( "document-expr", drill.getReportName( ) );
action = report.getContent( 7 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
drill = action.getDrillThrough( );
assertEquals( "report-document", drill.getTargetFileType( ) );
assertConstant( "document-value", drill.getReportName( ) );
}
public void testCell( ) throws Exception
{
Report report = loadDesign( "cell_test.rptdesign" );
GridItemDesign grid = (GridItemDesign) report.getContent( 0 );
RowDesign row = grid.getRow( 0 );
CellDesign cell = row.getCell( 0 );
assertEquals( "blue", cell.getDiagonalColor( ) );
assertEquals( 1, cell.getDiagonalNumber( ) );
assertEquals( "solid", cell.getDiagonalStyle( ) );
assertEquals( "thick", cell.getDiagonalWidth( ).toString( ) );
assertEquals( "red", cell.getAntidiagonalColor( ) );
assertEquals( 1, cell.getAntidiagonalNumber( ) );
assertEquals( "solid", cell.getAntidiagonalStyle( ) );
assertEquals( "thick", cell.getAntidiagonalWidth( ).toString( ) );
assertEquals( "colgroup", cell.getScope( ) );
assertExpression( "bookmark-expr", cell.getBookmark( ) );
assertExpression( "header-expr", cell.getHeaders( ) );
cell = row.getCell( 1 );
assertConstant( "bookmark-value", cell.getBookmark( ) );
assertConstant( "header-value", cell.getHeaders( ) );
}
static protected void assertConstant( String value, Expression expr )
{
assertEquals( Expression.CONSTANT, expr.getType( ) );
assertEquals( value, expr.getScriptText( ) );
}
static protected void assertExpression( String value, Expression expr )
{
assertEquals( Expression.SCRIPT, expr.getType( ) );
assertEquals( value, expr.getScriptText( ) );
}
}
| false | true | public void testAction( ) throws Exception
{
Report report = loadDesign( "action_test.rptdesign" );
ActionDesign action = report.getContent( 0 ).getAction( );
assertEquals( ActionDesign.ACTION_HYPERLINK, action.getActionType( ) );
assertEquals( "_blank", action.getTargetWindow( ) );
assertExpression( "uri-expr", action.getHyperlink( ) );
assertEquals( "tooltips", action.getTooltip( ) );
assertEquals( null, action.getBookmark( ) );
assertEquals( null, action.getDrillThrough( ) );
action = report.getContent( 1 ).getAction( );
assertEquals( ActionDesign.ACTION_HYPERLINK, action.getActionType( ) );
assertConstant( "uri-value", action.getHyperlink( ) );
action = report.getContent( 2 ).getAction( );
assertEquals( ActionDesign.ACTION_BOOKMARK, action.getActionType( ) );
assertEquals( null, action.getHyperlink( ) );
assertExpression( "bookmark-expr", action.getBookmark( ) );
assertEquals( null, action.getDrillThrough( ) );
action = report.getContent( 3 ).getAction( );
assertEquals( ActionDesign.ACTION_BOOKMARK, action.getActionType( ) );
assertConstant( "bookmark-value", action.getBookmark( ) );
// drill-through to report design with expression
action = report.getContent( 4 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
assertEquals( null, action.getBookmark( ) );
assertEquals( null, action.getHyperlink( ) );
DrillThroughActionDesign drill = action.getDrillThrough( );
assertEquals( "report-design", drill.getTargetFileType( ) );
// FIXME: should support expression
assertConstant( "design-expr", drill.getReportName( ) );
// assertExpression( "design-expr", drill.getReportName( ) );
assertEquals( true, drill.getBookmarkType( ) );
assertExpression( "bookmark-expr", drill.getBookmark( ) );
assertEquals( "xls", drill.getFormat( ) );
Map<String, Expression> exprs = drill.getParameters( );
assertEquals( 2, exprs.size( ) );
assertExpression( "param-expr", exprs.get( "param-expr" ) );
assertConstant( "param-value", exprs.get( "param-value" ) );
action = report.getContent( 5 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
drill = action.getDrillThrough( );
assertEquals( "report-design", drill.getTargetFileType( ) );
assertConstant( "design-value", drill.getReportName( ) );
assertEquals( false, drill.getBookmarkType( ) );
assertConstant( "bookmark-value", drill.getBookmark( ) );
action = report.getContent( 6 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
drill = action.getDrillThrough( );
assertEquals( "report-document", drill.getTargetFileType( ) );
// FIXME: should support expression document name
assertConstant( "document-expr", drill.getReportName( ) );
// assertExpression( "document-expr", drill.getReportName( ) );
action = report.getContent( 7 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
drill = action.getDrillThrough( );
assertEquals( "report-document", drill.getTargetFileType( ) );
assertConstant( "document-value", drill.getReportName( ) );
}
| public void testAction( ) throws Exception
{
Report report = loadDesign( "action_test.rptdesign" );
ActionDesign action = report.getContent( 0 ).getAction( );
assertEquals( ActionDesign.ACTION_HYPERLINK, action.getActionType( ) );
assertEquals( "_blank", action.getTargetWindow( ) );
assertExpression( "uri-expr", action.getHyperlink( ) );
assertEquals( "tooltips", action.getTooltip( ) );
assertEquals( null, action.getBookmark( ) );
assertEquals( null, action.getDrillThrough( ) );
action = report.getContent( 1 ).getAction( );
assertEquals( ActionDesign.ACTION_HYPERLINK, action.getActionType( ) );
assertConstant( "uri-value", action.getHyperlink( ) );
action = report.getContent( 2 ).getAction( );
assertEquals( ActionDesign.ACTION_BOOKMARK, action.getActionType( ) );
assertEquals( null, action.getHyperlink( ) );
assertExpression( "bookmark-expr", action.getBookmark( ) );
assertEquals( null, action.getDrillThrough( ) );
action = report.getContent( 3 ).getAction( );
assertEquals( ActionDesign.ACTION_BOOKMARK, action.getActionType( ) );
assertConstant( "bookmark-value", action.getBookmark( ) );
// drill-through to report design with expression
action = report.getContent( 4 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
assertEquals( null, action.getBookmark( ) );
assertEquals( null, action.getHyperlink( ) );
DrillThroughActionDesign drill = action.getDrillThrough( );
assertEquals( "report-design", drill.getTargetFileType( ) );
// FIXME: should support expression
assertConstant( "design-expr", drill.getReportName( ) );
// assertExpression( "design-expr", drill.getReportName( ) );
assertEquals( true, drill.getBookmarkType( ) );
assertExpression( "bookmark-expr", drill.getBookmark( ) );
assertEquals( "xls", drill.getFormat( ) );
Map<String, List<Expression>> exprs = drill.getParameters( );
assertEquals( 2, exprs.size( ) );
assertExpression( "param-expr", exprs.get( "param-expr" ).get( 0 ) );
assertConstant( "param-value", exprs.get( "param-value" ).get( 0 ) );
action = report.getContent( 5 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
drill = action.getDrillThrough( );
assertEquals( "report-design", drill.getTargetFileType( ) );
assertConstant( "design-value", drill.getReportName( ) );
assertEquals( false, drill.getBookmarkType( ) );
assertConstant( "bookmark-value", drill.getBookmark( ) );
action = report.getContent( 6 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
drill = action.getDrillThrough( );
assertEquals( "report-document", drill.getTargetFileType( ) );
// FIXME: should support expression document name
assertConstant( "document-expr", drill.getReportName( ) );
// assertExpression( "document-expr", drill.getReportName( ) );
action = report.getContent( 7 ).getAction( );
assertEquals( ActionDesign.ACTION_DRILLTHROUGH, action.getActionType( ) );
drill = action.getDrillThrough( );
assertEquals( "report-document", drill.getTargetFileType( ) );
assertConstant( "document-value", drill.getReportName( ) );
}
|
diff --git a/src/com/csipsimple/service/Downloader.java b/src/com/csipsimple/service/Downloader.java
index c8f35d34..1e706c84 100644
--- a/src/com/csipsimple/service/Downloader.java
+++ b/src/com/csipsimple/service/Downloader.java
@@ -1,233 +1,233 @@
/**
* Copyright (C) 2010 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;
import com.csipsimple.R;
import com.csipsimple.ui.SipHome;
import com.csipsimple.utils.Log;
import com.csipsimple.utils.MD5;
public class Downloader extends IntentService {
private final static String THIS_FILE = "Downloader";
public final static String EXTRA_ICON = "icon";
public final static String EXTRA_TITLE = "title";
public final static String EXTRA_OUTPATH = "outpath";
public final static String EXTRA_CHECK_MD5 = "checkMd5";
public final static String EXTRA_PENDING_FINISH_INTENT = "pendingIntent";
private static final int NOTIF_DOWNLOAD = 0;
private NotificationManager notificationManager;
private DefaultHttpClient client;
public Downloader() {
super("Downloader");
}
@Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
client = new DefaultHttpClient();
}
@Override
public void onDestroy() {
super.onDestroy();
client.getConnectionManager().shutdown();
}
@Override
protected void onHandleIntent(Intent intent) {
HttpGet getMethod = new HttpGet(intent.getData().toString());
int result = Activity.RESULT_CANCELED;
String outPath = intent.getStringExtra(EXTRA_OUTPATH);
boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false);
int icon = intent.getIntExtra(EXTRA_ICON, 0);
String title = intent.getStringExtra(EXTRA_TITLE);
boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title));
final Notification notification = showNotif ? new Notification(android.R.drawable.stat_sys_download, title, System.currentTimeMillis()) : null;
if(notification != null) {
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
Intent i = new Intent(this, SipHome.class);
notification.contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_notif);
notification.contentView.setImageViewResource(R.id.status_icon, icon);
notification.contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text));
notification.contentView.setProgressBar(R.id.status_progress, 50, 0, false);
- notification.contentView.setViewVisibility(R.id.status_progress, View.VISIBLE);
+ notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE);
}
if(!TextUtils.isEmpty(outPath)) {
try {
File output = new File(outPath);
if (output.exists()) {
output.delete();
}
if(notification != null) {
notificationManager.notify(NOTIF_DOWNLOAD, notification);
}
ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() {
private int oldState = 0;
@Override
public void run(long progress, long total) {
//Log.d(THIS_FILE, "Progress is "+progress+" on "+total);
int newState = (int) Math.round(progress * 50.0f/total);
if(oldState != newState) {
notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false);
notificationManager.notify(NOTIF_DOWNLOAD, notification);
oldState = newState;
}
}
});
boolean hasReply = client.execute(getMethod, responseHandler);
if(hasReply) {
if(checkMd5) {
URL url = new URL(intent.getData().toString().concat(".md5sum"));
InputStream content = (InputStream) url.getContent();
if(content != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(content));
String downloadedMD5 = "";
try {
downloadedMD5 = br.readLine().split(" ")[0];
} catch (NullPointerException e) {
throw new IOException("md5_verification : no sum on server");
}
if (!MD5.checkMD5(downloadedMD5, output)) {
throw new IOException("md5_verification : incorrect");
}
}
}
PendingIntent pendingIntent = (PendingIntent) intent.getParcelableExtra(EXTRA_PENDING_FINISH_INTENT);
Log.d(THIS_FILE, "Download finished of : " + outPath);
if(pendingIntent != null) {
notification.contentIntent = pendingIntent;
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.icon = android.R.drawable.stat_sys_download_done;
- notification.contentView.setViewVisibility(R.id.status_progress, View.GONE);
+ notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE);
notification.contentView.setTextViewText(R.id.status_text,
getResources().getString(R.string.done)
// TODO should be a parameter of this class
+" - Click to install");
notificationManager.notify(NOTIF_DOWNLOAD, notification);
}else {
Log.w(THIS_FILE, "Invalid pending intent for finish !!!");
}
try {
Runtime.getRuntime().exec("chmod 644 " + outPath);
} catch (IOException e) {
Log.e(THIS_FILE, "Unable to make the apk file readable", e);
}
result = Activity.RESULT_OK;
}
} catch (IOException e) {
Log.e(THIS_FILE, "Exception in download", e);
}
}
if(result == Activity.RESULT_CANCELED) {
notificationManager.cancel(NOTIF_DOWNLOAD);
}
}
public interface Progress {
void run(long progress, long total);
}
private class FileStreamResponseHandler implements ResponseHandler<Boolean> {
private Progress mProgress;
private File mFile;
FileStreamResponseHandler(File outputFile, Progress progress) {
mFile = outputFile;
mProgress = progress;
}
public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
FileOutputStream fos = new FileOutputStream(mFile.getPath());
HttpEntity entity = response.getEntity();
boolean done = false;
try {
if (entity != null) {
Long length = entity.getContentLength();
InputStream input = entity.getContent();
byte[] buffer = new byte[4096];
int size = 0;
int total = 0;
while (true) {
size = input.read(buffer);
if (size == -1) break;
fos.write(buffer, 0, size);
total += size;
mProgress.run(total, length);
}
done = true;
}
}catch(IOException e) {
Log.e(THIS_FILE, "Problem on downloading");
}finally {
fos.close();
}
return done;
}
}
}
| false | true | protected void onHandleIntent(Intent intent) {
HttpGet getMethod = new HttpGet(intent.getData().toString());
int result = Activity.RESULT_CANCELED;
String outPath = intent.getStringExtra(EXTRA_OUTPATH);
boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false);
int icon = intent.getIntExtra(EXTRA_ICON, 0);
String title = intent.getStringExtra(EXTRA_TITLE);
boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title));
final Notification notification = showNotif ? new Notification(android.R.drawable.stat_sys_download, title, System.currentTimeMillis()) : null;
if(notification != null) {
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
Intent i = new Intent(this, SipHome.class);
notification.contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_notif);
notification.contentView.setImageViewResource(R.id.status_icon, icon);
notification.contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text));
notification.contentView.setProgressBar(R.id.status_progress, 50, 0, false);
notification.contentView.setViewVisibility(R.id.status_progress, View.VISIBLE);
}
if(!TextUtils.isEmpty(outPath)) {
try {
File output = new File(outPath);
if (output.exists()) {
output.delete();
}
if(notification != null) {
notificationManager.notify(NOTIF_DOWNLOAD, notification);
}
ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() {
private int oldState = 0;
@Override
public void run(long progress, long total) {
//Log.d(THIS_FILE, "Progress is "+progress+" on "+total);
int newState = (int) Math.round(progress * 50.0f/total);
if(oldState != newState) {
notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false);
notificationManager.notify(NOTIF_DOWNLOAD, notification);
oldState = newState;
}
}
});
boolean hasReply = client.execute(getMethod, responseHandler);
if(hasReply) {
if(checkMd5) {
URL url = new URL(intent.getData().toString().concat(".md5sum"));
InputStream content = (InputStream) url.getContent();
if(content != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(content));
String downloadedMD5 = "";
try {
downloadedMD5 = br.readLine().split(" ")[0];
} catch (NullPointerException e) {
throw new IOException("md5_verification : no sum on server");
}
if (!MD5.checkMD5(downloadedMD5, output)) {
throw new IOException("md5_verification : incorrect");
}
}
}
PendingIntent pendingIntent = (PendingIntent) intent.getParcelableExtra(EXTRA_PENDING_FINISH_INTENT);
Log.d(THIS_FILE, "Download finished of : " + outPath);
if(pendingIntent != null) {
notification.contentIntent = pendingIntent;
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.icon = android.R.drawable.stat_sys_download_done;
notification.contentView.setViewVisibility(R.id.status_progress, View.GONE);
notification.contentView.setTextViewText(R.id.status_text,
getResources().getString(R.string.done)
// TODO should be a parameter of this class
+" - Click to install");
notificationManager.notify(NOTIF_DOWNLOAD, notification);
}else {
Log.w(THIS_FILE, "Invalid pending intent for finish !!!");
}
try {
Runtime.getRuntime().exec("chmod 644 " + outPath);
} catch (IOException e) {
Log.e(THIS_FILE, "Unable to make the apk file readable", e);
}
result = Activity.RESULT_OK;
}
} catch (IOException e) {
Log.e(THIS_FILE, "Exception in download", e);
}
}
if(result == Activity.RESULT_CANCELED) {
notificationManager.cancel(NOTIF_DOWNLOAD);
}
}
| protected void onHandleIntent(Intent intent) {
HttpGet getMethod = new HttpGet(intent.getData().toString());
int result = Activity.RESULT_CANCELED;
String outPath = intent.getStringExtra(EXTRA_OUTPATH);
boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false);
int icon = intent.getIntExtra(EXTRA_ICON, 0);
String title = intent.getStringExtra(EXTRA_TITLE);
boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title));
final Notification notification = showNotif ? new Notification(android.R.drawable.stat_sys_download, title, System.currentTimeMillis()) : null;
if(notification != null) {
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
Intent i = new Intent(this, SipHome.class);
notification.contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_notif);
notification.contentView.setImageViewResource(R.id.status_icon, icon);
notification.contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text));
notification.contentView.setProgressBar(R.id.status_progress, 50, 0, false);
notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE);
}
if(!TextUtils.isEmpty(outPath)) {
try {
File output = new File(outPath);
if (output.exists()) {
output.delete();
}
if(notification != null) {
notificationManager.notify(NOTIF_DOWNLOAD, notification);
}
ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() {
private int oldState = 0;
@Override
public void run(long progress, long total) {
//Log.d(THIS_FILE, "Progress is "+progress+" on "+total);
int newState = (int) Math.round(progress * 50.0f/total);
if(oldState != newState) {
notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false);
notificationManager.notify(NOTIF_DOWNLOAD, notification);
oldState = newState;
}
}
});
boolean hasReply = client.execute(getMethod, responseHandler);
if(hasReply) {
if(checkMd5) {
URL url = new URL(intent.getData().toString().concat(".md5sum"));
InputStream content = (InputStream) url.getContent();
if(content != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(content));
String downloadedMD5 = "";
try {
downloadedMD5 = br.readLine().split(" ")[0];
} catch (NullPointerException e) {
throw new IOException("md5_verification : no sum on server");
}
if (!MD5.checkMD5(downloadedMD5, output)) {
throw new IOException("md5_verification : incorrect");
}
}
}
PendingIntent pendingIntent = (PendingIntent) intent.getParcelableExtra(EXTRA_PENDING_FINISH_INTENT);
Log.d(THIS_FILE, "Download finished of : " + outPath);
if(pendingIntent != null) {
notification.contentIntent = pendingIntent;
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.icon = android.R.drawable.stat_sys_download_done;
notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE);
notification.contentView.setTextViewText(R.id.status_text,
getResources().getString(R.string.done)
// TODO should be a parameter of this class
+" - Click to install");
notificationManager.notify(NOTIF_DOWNLOAD, notification);
}else {
Log.w(THIS_FILE, "Invalid pending intent for finish !!!");
}
try {
Runtime.getRuntime().exec("chmod 644 " + outPath);
} catch (IOException e) {
Log.e(THIS_FILE, "Unable to make the apk file readable", e);
}
result = Activity.RESULT_OK;
}
} catch (IOException e) {
Log.e(THIS_FILE, "Exception in download", e);
}
}
if(result == Activity.RESULT_CANCELED) {
notificationManager.cancel(NOTIF_DOWNLOAD);
}
}
|
diff --git a/src/org/pentaho/di/job/entries/hadoopjobexecutor/JobEntryHadoopJobExecutor.java b/src/org/pentaho/di/job/entries/hadoopjobexecutor/JobEntryHadoopJobExecutor.java
index a39bb793..c1a0e859 100644
--- a/src/org/pentaho/di/job/entries/hadoopjobexecutor/JobEntryHadoopJobExecutor.java
+++ b/src/org/pentaho/di/job/entries/hadoopjobexecutor/JobEntryHadoopJobExecutor.java
@@ -1,843 +1,846 @@
/*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.job.entries.hadoopjobexecutor;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputFormat;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.TaskCompletionEvent;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.annotations.JobEntry;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.Log4jFileAppender;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.job.entries.hadoopjobexecutor.UserDefinedItem;
import org.pentaho.hadoop.jobconf.HadoopConfigurer;
import org.pentaho.hadoop.jobconf.HadoopConfigurerFactory;
import org.w3c.dom.Node;
@JobEntry(id = "HadoopJobExecutorPlugin", name = "Hadoop Job Executor", categoryDescription = "Big Data", description = "Execute MapReduce jobs in Hadoop", image = "HDE.png")
public class JobEntryHadoopJobExecutor extends JobEntryBase implements Cloneable, JobEntryInterface {
private static Class<?> PKG = JobEntryHadoopJobExecutor.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private String hadoopJobName;
private String jarUrl = "";
private boolean isSimple = true;
private String cmdLineArgs;
private String outputKeyClass;
private String outputValueClass;
private String mapperClass;
private String combinerClass;
private String reducerClass;
private String inputFormatClass;
private String outputFormatClass;
private String workingDirectory;
private String hdfsHostname;
private String hdfsPort;
private String jobTrackerHostname;
private String jobTrackerPort;
private String inputPath;
private String outputPath;
private boolean blocking;
private String loggingInterval = "60"; // 60 seconds default
private String numMapTasks = "1";
private String numReduceTasks = "1";
private List<UserDefinedItem> userDefined = new ArrayList<UserDefinedItem>();
private String hadoopDistribution = "generic";
public String getHadoopJobName() {
return hadoopJobName;
}
public void setHadoopJobName(String hadoopJobName) {
this.hadoopJobName = hadoopJobName;
}
public String getJarUrl() {
return jarUrl;
}
public void setJarUrl(String jarUrl) {
this.jarUrl = jarUrl;
}
public boolean isSimple() {
return isSimple;
}
public void setSimple(boolean isSimple) {
this.isSimple = isSimple;
}
public String getCmdLineArgs() {
return cmdLineArgs;
}
public void setCmdLineArgs(String cmdLineArgs) {
this.cmdLineArgs = cmdLineArgs;
}
public String getOutputKeyClass() {
return outputKeyClass;
}
public void setOutputKeyClass(String outputKeyClass) {
this.outputKeyClass = outputKeyClass;
}
public String getOutputValueClass() {
return outputValueClass;
}
public void setOutputValueClass(String outputValueClass) {
this.outputValueClass = outputValueClass;
}
public String getMapperClass() {
return mapperClass;
}
public void setMapperClass(String mapperClass) {
this.mapperClass = mapperClass;
}
public String getCombinerClass() {
return combinerClass;
}
public void setCombinerClass(String combinerClass) {
this.combinerClass = combinerClass;
}
public String getReducerClass() {
return reducerClass;
}
public void setReducerClass(String reducerClass) {
this.reducerClass = reducerClass;
}
public String getInputFormatClass() {
return inputFormatClass;
}
public void setInputFormatClass(String inputFormatClass) {
this.inputFormatClass = inputFormatClass;
}
public String getOutputFormatClass() {
return outputFormatClass;
}
public void setOutputFormatClass(String outputFormatClass) {
this.outputFormatClass = outputFormatClass;
}
public String getWorkingDirectory() {
return workingDirectory;
}
public void setWorkingDirectory(String workingDirectory) {
this.workingDirectory = workingDirectory;
}
public String getHdfsHostname() {
return hdfsHostname;
}
public void setHdfsHostname(String hdfsHostname) {
this.hdfsHostname = hdfsHostname;
}
public String getHdfsPort() {
return hdfsPort;
}
public void setHdfsPort(String hdfsPort) {
this.hdfsPort = hdfsPort;
}
public String getJobTrackerHostname() {
return jobTrackerHostname;
}
public void setJobTrackerHostname(String jobTrackerHostname) {
this.jobTrackerHostname = jobTrackerHostname;
}
public String getJobTrackerPort() {
return jobTrackerPort;
}
public void setJobTrackerPort(String jobTrackerPort) {
this.jobTrackerPort = jobTrackerPort;
}
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public String getOutputPath() {
return outputPath;
}
public void setOutputPath(String outputPath) {
this.outputPath = outputPath;
}
public boolean isBlocking() {
return blocking;
}
public void setBlocking(boolean blocking) {
this.blocking = blocking;
}
public String getLoggingInterval() {
return loggingInterval;
}
public void setLoggingInterval(String loggingInterval) {
this.loggingInterval = loggingInterval;
}
public List<UserDefinedItem> getUserDefined() {
return userDefined;
}
public void setUserDefined(List<UserDefinedItem> userDefined) {
this.userDefined = userDefined;
}
public String getNumMapTasks() {
return numMapTasks;
}
public void setNumMapTasks(String numMapTasks) {
this.numMapTasks = numMapTasks;
}
public String getNumReduceTasks() {
return numReduceTasks;
}
public void setNumReduceTasks(String numReduceTasks) {
this.numReduceTasks = numReduceTasks;
}
public void setHadoopDistribution(String hadoopDistro) {
hadoopDistribution = hadoopDistro;
}
public String getHadoopDistribution() {
return hadoopDistribution;
}
public Result execute(Result result, int arg1) throws KettleException {
result.setNrErrors(0);
Log4jFileAppender appender = null;
String logFileName = "pdi-" + this.getName(); //$NON-NLS-1$
String hadoopDistro = System.getProperty("hadoop.distribution.name", hadoopDistribution);
hadoopDistro = environmentSubstitute(hadoopDistro);
if (Const.isEmpty(hadoopDistro)) {
hadoopDistro = "generic";
}
try
{
appender = LogWriter.createFileAppender(logFileName, true, false);
LogWriter.getInstance().addAppender(appender);
log.setLogLevel(parentJob.getLogLevel());
} catch (Exception e)
{
logError(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.FailedToOpenLogFile", logFileName, e.toString())); //$NON-NLS-1$
logError(Const.getStackTracker(e));
}
try {
URL resolvedJarUrl = null;
String jarUrlS = environmentSubstitute(jarUrl);
if (jarUrlS.indexOf("://") == -1) {
// default to file://
File jarFile = new File(jarUrlS);
resolvedJarUrl = jarFile.toURI().toURL();
} else {
resolvedJarUrl = new URL(jarUrlS);
}
final String cmdLineArgsS = environmentSubstitute(cmdLineArgs);
if (log.isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.ResolvedJar", resolvedJarUrl.toExternalForm()));
if (isSimple) {
- final AtomicInteger taskCount = new AtomicInteger(0);
+ /* final AtomicInteger taskCount = new AtomicInteger(0);
final AtomicInteger successCount = new AtomicInteger(0);
- final AtomicInteger failedCount = new AtomicInteger(0);
+ final AtomicInteger failedCount = new AtomicInteger(0); */
if (log.isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.SimpleMode"));
List<Class<?>> classesWithMains = JarUtility.getClassesInJarWithMain(resolvedJarUrl.toExternalForm(), getClass().getClassLoader());
for (final Class<?> clazz : classesWithMains) {
Runnable r = new Runnable() {
public void run() {
try {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
- taskCount.incrementAndGet();
+// taskCount.incrementAndGet();
Thread.currentThread().setContextClassLoader(clazz.getClassLoader());
Method mainMethod = clazz.getMethod("main", new Class[] { String[].class });
Object[] args = (cmdLineArgsS != null) ? new Object[] { cmdLineArgsS.split(" ") } : new Object[0];
mainMethod.invoke(null, args);
} finally {
Thread.currentThread().setContextClassLoader(cl);
- successCount.incrementAndGet();
- taskCount.decrementAndGet();
+// successCount.incrementAndGet();
+// taskCount.decrementAndGet();
}
} catch (Throwable ignored) {
// skip, try the next one
- logError(ignored.getMessage());
- failedCount.incrementAndGet();
+// logError(ignored.getMessage());
+// failedCount.incrementAndGet();
+ ignored.printStackTrace();
}
}
};
Thread t = new Thread(r);
t.start();
}
// uncomment to implement blocking
/* if (blocking) {
while (taskCount.get() > 0 && !parentJob.isStopped()) {
Thread.sleep(1000);
}
if (!parentJob.isStopped()) {
result.setResult(successCount.get() > 0);
result.setNrErrors((successCount.get() > 0) ? 0 : 1);
} else {
// we can't really know at this stage if
// the hadoop job will finish successfully
// because we have to stop now
result.setResult(true); // look on the bright side of life :-)...
result.setNrErrors(0);
}
} else { */
// non-blocking - just set success equal to no failures arising
// from invocation
- result.setResult(failedCount.get() == 0);
- result.setNrErrors(failedCount.get());
+// result.setResult(failedCount.get() == 0);
+// result.setNrErrors(failedCount.get());
+ result.setResult(true);
+ result.setNrErrors(0);
/* } */
} else {
if (log.isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.AdvancedMode"));
URL[] urls = new URL[] { resolvedJarUrl };
URLClassLoader loader = new URLClassLoader(urls, getClass().getClassLoader());
JobConf conf = new JobConf();
String hadoopJobNameS = environmentSubstitute(hadoopJobName);
conf.setJobName(hadoopJobNameS);
String outputKeyClassS = environmentSubstitute(outputKeyClass);
conf.setOutputKeyClass(loader.loadClass(outputKeyClassS));
String outputValueClassS = environmentSubstitute(outputValueClass);
conf.setOutputValueClass(loader.loadClass(outputValueClassS));
if(mapperClass != null) {
String mapperClassS = environmentSubstitute(mapperClass);
Class<? extends Mapper> mapper = (Class<? extends Mapper>) loader.loadClass(mapperClassS);
conf.setMapperClass(mapper);
}
if(combinerClass != null) {
String combinerClassS = environmentSubstitute(combinerClass);
Class<? extends Reducer> combiner = (Class<? extends Reducer>) loader.loadClass(combinerClassS);
conf.setCombinerClass(combiner);
}
if(reducerClass != null) {
String reducerClassS = environmentSubstitute(reducerClass);
Class<? extends Reducer> reducer = (Class<? extends Reducer>) loader.loadClass(reducerClassS);
conf.setReducerClass(reducer);
}
if(inputFormatClass != null) {
String inputFormatClassS = environmentSubstitute(inputFormatClass);
Class<? extends InputFormat> inputFormat = (Class<? extends InputFormat>) loader.loadClass(inputFormatClassS);
conf.setInputFormat(inputFormat);
}
if(outputFormatClass != null) {
String outputFormatClassS = environmentSubstitute(outputFormatClass);
Class<? extends OutputFormat> outputFormat = (Class<? extends OutputFormat>) loader.loadClass(outputFormatClassS);
conf.setOutputFormat(outputFormat);
}
String hdfsHostnameS = environmentSubstitute(hdfsHostname);
String hdfsPortS = environmentSubstitute(hdfsPort);
String jobTrackerHostnameS = environmentSubstitute(jobTrackerHostname);
String jobTrackerPortS = environmentSubstitute(jobTrackerPort);
// See if we can auto detect the distribution first
HadoopConfigurer configurer = HadoopConfigurerFactory.locateConfigurer();
if (configurer == null) {
// go with what has been selected by the user
configurer = HadoopConfigurerFactory.getConfigurer(hadoopDistro);
// if the user-specified distribution is detectable, make sure it is still
// the current distribution!
if (configurer != null && configurer.isDetectable()) {
if (!configurer.isAvailable()) {
throw new KettleException(BaseMessages.getString(PKG,
"JobEntryHadoopJobExecutor.Error.DistroNoLongerPresent", configurer.distributionName()));
}
}
}
if (configurer == null) {
throw new KettleException(BaseMessages.
getString(PKG, "JobEntryHadoopJobExecutor.Error.UnknownHadoopDistribution",
hadoopDistro));
}
logBasic(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.Message.DistroConfigMessage",
configurer.distributionName()));
List<String> configMessages = new ArrayList<String>();
configurer.configure(hdfsHostnameS, hdfsPortS,
jobTrackerHostnameS, jobTrackerPortS, conf, configMessages);
for (String m : configMessages) {
logBasic(m);
}
String inputPathS = environmentSubstitute(inputPath);
String[] inputPathParts = inputPathS.split(",");
List<Path> paths = new ArrayList<Path>();
for (String path : inputPathParts) {
paths.add(new Path(configurer.getFilesystemURL() + path));
}
Path[] finalPaths = paths.toArray(new Path[paths.size()]);
//FileInputFormat.setInputPaths(conf, new Path(configurer.getFilesystemURL() + inputPathS));
FileInputFormat.setInputPaths(conf, finalPaths);
String outputPathS = environmentSubstitute(outputPath);
FileOutputFormat.setOutputPath(conf, new Path(configurer.getFilesystemURL() + outputPathS));
// process user defined values
for (UserDefinedItem item : userDefined) {
if (item.getName() != null && !"".equals(item.getName()) && item.getValue() != null && !"".equals(item.getValue())) {
String nameS = environmentSubstitute(item.getName());
String valueS = environmentSubstitute(item.getValue());
conf.set(nameS, valueS);
}
}
String workingDirectoryS = environmentSubstitute(workingDirectory);
conf.setWorkingDirectory(new Path(configurer.getFilesystemURL() + workingDirectoryS));
conf.setJar(jarUrl);
String numMapTasksS = environmentSubstitute(numMapTasks);
String numReduceTasksS = environmentSubstitute(numReduceTasks);
int numM = 1;
try {
numM = Integer.parseInt(numMapTasksS);
} catch (NumberFormatException e) {
logError("Can't parse number of map tasks '" + numMapTasksS + "'. Setting num" +
"map tasks to 1");
}
int numR = 1;
try {
numR = Integer.parseInt(numReduceTasksS);
} catch (NumberFormatException e) {
logError("Can't parse number of reduce tasks '" + numReduceTasksS + "'. Setting num" +
"reduce tasks to 1");
}
conf.setNumMapTasks(numM);
conf.setNumReduceTasks(numR);
JobClient jobClient = new JobClient(conf);
RunningJob runningJob = jobClient.submitJob(conf);
String loggingIntervalS = environmentSubstitute(loggingInterval);
int logIntv = 60;
try {
logIntv = Integer.parseInt(loggingIntervalS);
} catch (NumberFormatException e) {
logError("Can't parse logging interval '" + loggingIntervalS + "'. Setting " +
"logging interval to 60");
}
if (blocking) {
try {
int taskCompletionEventIndex = 0;
while (!parentJob.isStopped() && !runningJob.isComplete()) {
if (logIntv >= 1) {
printJobStatus(runningJob);
taskCompletionEventIndex = logTaskMessages(runningJob, taskCompletionEventIndex);
Thread.sleep(logIntv * 1000);
} else {
Thread.sleep(60000);
}
}
if (parentJob.isStopped() && !runningJob.isComplete()) {
// We must stop the job running on Hadoop
runningJob.killJob();
// Indicate this job entry did not complete
result.setResult(false);
}
printJobStatus(runningJob);
// Log any messages we may have missed while polling
logTaskMessages(runningJob, taskCompletionEventIndex);
} catch (InterruptedException ie) {
logError(ie.getMessage(), ie);
}
// Entry is successful if the MR job is successful overall
result.setResult(runningJob.isSuccessful());
}
}
} catch (Throwable t) {
t.printStackTrace();
result.setStopped(true);
result.setNrErrors(1);
result.setResult(false);
logError(t.getMessage(), t);
}
if (appender != null)
{
LogWriter.getInstance().removeAppender(appender);
appender.close();
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, appender.getFile(), parentJob.getJobname(), getName());
result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
}
return result;
}
/**
* Log messages indicating completion (success/failure) of component tasks for the provided running job.
*
* @param runningJob Running job to poll for completion events
* @param startIndex Start at this event index to poll from
* @return Total events consumed
* @throws IOException Error fetching events
*/
private int logTaskMessages(RunningJob runningJob, int startIndex) throws IOException {
TaskCompletionEvent[] tcEvents = runningJob.getTaskCompletionEvents(startIndex);
for(int i = 0; i < tcEvents.length; i++) {
String[] diags = runningJob.getTaskDiagnostics(tcEvents[i].getTaskAttemptId());
StringBuilder diagsOutput = new StringBuilder();
if(diags != null && diags.length > 0) {
diagsOutput.append(Const.CR);
for(String s : diags) {
diagsOutput.append(s);
diagsOutput.append(Const.CR);
}
}
switch(tcEvents[i].getTaskStatus()) {
case KILLED: {
logError(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.TaskDetails", TaskCompletionEvent.Status.KILLED, tcEvents[i].getTaskAttemptId().getTaskID().getId(), tcEvents[i].getTaskAttemptId().getId(), tcEvents[i].getEventId(), diagsOutput)); //$NON-NLS-1$
}break;
case FAILED: {
logError(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.TaskDetails", TaskCompletionEvent.Status.FAILED, tcEvents[i].getTaskAttemptId().getTaskID().getId(), tcEvents[i].getTaskAttemptId().getId(), tcEvents[i].getEventId(), diagsOutput)); //$NON-NLS-1$
}break;
case SUCCEEDED: {
logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.TaskDetails", TaskCompletionEvent.Status.SUCCEEDED, tcEvents[i].getTaskAttemptId().getTaskID().getId(), tcEvents[i].getTaskAttemptId().getId(), tcEvents[i].getEventId(), diagsOutput)); //$NON-NLS-1$
}break;
}
}
return tcEvents.length;
}
public void printJobStatus(RunningJob runningJob) throws IOException {
if (log.isBasic()) {
float setupPercent = runningJob.setupProgress() * 100f;
float mapPercent = runningJob.mapProgress() * 100f;
float reducePercent = runningJob.reduceProgress() * 100f;
logBasic(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.RunningPercent", setupPercent, mapPercent, reducePercent));
}
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException {
super.loadXML(entrynode, databases, slaveServers);
hadoopJobName = XMLHandler.getTagValue(entrynode, "hadoop_job_name");
if (!Const.isEmpty(XMLHandler.getTagValue(entrynode, "hadoop_distribution"))) {
hadoopDistribution = XMLHandler.getTagValue(entrynode, "hadoop_distribution");
}
isSimple = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "simple"));
jarUrl = XMLHandler.getTagValue(entrynode, "jar_url");
cmdLineArgs = XMLHandler.getTagValue(entrynode, "command_line_args");
blocking = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "blocking"));
/*try {
loggingInterval = Integer.parseInt(XMLHandler.getTagValue(entrynode, "logging_interval"));
} catch (NumberFormatException nfe) {
} */
loggingInterval = XMLHandler.getTagValue(entrynode, "logging_interval");
mapperClass = XMLHandler.getTagValue(entrynode, "mapper_class");
combinerClass = XMLHandler.getTagValue(entrynode, "combiner_class");
reducerClass = XMLHandler.getTagValue(entrynode, "reducer_class");
inputPath = XMLHandler.getTagValue(entrynode, "input_path");
inputFormatClass = XMLHandler.getTagValue(entrynode, "input_format_class");
outputPath = XMLHandler.getTagValue(entrynode, "output_path");
outputKeyClass = XMLHandler.getTagValue(entrynode, "output_key_class");
outputValueClass = XMLHandler.getTagValue(entrynode, "output_value_class");
outputFormatClass = XMLHandler.getTagValue(entrynode, "output_format_class");
hdfsHostname = XMLHandler.getTagValue(entrynode, "hdfs_hostname");
hdfsPort = XMLHandler.getTagValue(entrynode, "hdfs_port");
jobTrackerHostname = XMLHandler.getTagValue(entrynode, "job_tracker_hostname");
jobTrackerPort = XMLHandler.getTagValue(entrynode, "job_tracker_port");
//numMapTasks = Integer.parseInt(XMLHandler.getTagValue(entrynode, "num_map_tasks"));
numMapTasks = XMLHandler.getTagValue(entrynode, "num_map_tasks");
//numReduceTasks = Integer.parseInt(XMLHandler.getTagValue(entrynode, "num_reduce_tasks"));
numReduceTasks = XMLHandler.getTagValue(entrynode, "num_reduce_tasks");
workingDirectory = XMLHandler.getTagValue(entrynode, "working_dir");
// How many user defined elements?
userDefined = new ArrayList<UserDefinedItem>();
Node userDefinedList = XMLHandler.getSubNode(entrynode, "user_defined_list");
int nrUserDefined = XMLHandler.countNodes(userDefinedList, "user_defined");
for (int i = 0; i < nrUserDefined; i++) {
Node userDefinedNode = XMLHandler.getSubNodeByNr(userDefinedList, "user_defined", i);
String name = XMLHandler.getTagValue(userDefinedNode, "name");
String value = XMLHandler.getTagValue(userDefinedNode, "value");
UserDefinedItem item = new UserDefinedItem();
item.setName(name);
item.setValue(value);
userDefined.add(item);
}
}
public String getXML() {
StringBuffer retval = new StringBuffer(1024);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("hadoop_job_name", hadoopJobName));
retval.append(" ").append(XMLHandler.addTagValue("hadoop_distribution", hadoopDistribution));
retval.append(" ").append(XMLHandler.addTagValue("simple", isSimple));
retval.append(" ").append(XMLHandler.addTagValue("jar_url", jarUrl));
retval.append(" ").append(XMLHandler.addTagValue("command_line_args", cmdLineArgs));
retval.append(" ").append(XMLHandler.addTagValue("blocking", blocking));
retval.append(" ").append(XMLHandler.addTagValue("logging_interval", loggingInterval));
retval.append(" ").append(XMLHandler.addTagValue("hadoop_job_name", hadoopJobName));
retval.append(" ").append(XMLHandler.addTagValue("mapper_class", mapperClass));
retval.append(" ").append(XMLHandler.addTagValue("combiner_class", combinerClass));
retval.append(" ").append(XMLHandler.addTagValue("reducer_class", reducerClass));
retval.append(" ").append(XMLHandler.addTagValue("input_path", inputPath));
retval.append(" ").append(XMLHandler.addTagValue("input_format_class", inputFormatClass));
retval.append(" ").append(XMLHandler.addTagValue("output_path", outputPath));
retval.append(" ").append(XMLHandler.addTagValue("output_key_class", outputKeyClass));
retval.append(" ").append(XMLHandler.addTagValue("output_value_class", outputValueClass));
retval.append(" ").append(XMLHandler.addTagValue("output_format_class", outputFormatClass));
retval.append(" ").append(XMLHandler.addTagValue("hdfs_hostname", hdfsHostname));
retval.append(" ").append(XMLHandler.addTagValue("hdfs_port", hdfsPort));
retval.append(" ").append(XMLHandler.addTagValue("job_tracker_hostname", jobTrackerHostname));
retval.append(" ").append(XMLHandler.addTagValue("job_tracker_port", jobTrackerPort));
retval.append(" ").append(XMLHandler.addTagValue("num_map_tasks", numMapTasks));
retval.append(" ").append(XMLHandler.addTagValue("num_reduce_tasks", numReduceTasks));
retval.append(" ").append(XMLHandler.addTagValue("working_dir", workingDirectory));
retval.append(" <user_defined_list>").append(Const.CR);
if (userDefined != null) {
for (UserDefinedItem item : userDefined) {
if (item.getName() != null && !"".equals(item.getName()) && item.getValue() != null && !"".equals(item.getValue())) {
retval.append(" <user_defined>").append(Const.CR);
retval.append(" ").append(XMLHandler.addTagValue("name", item.getName()));
retval.append(" ").append(XMLHandler.addTagValue("value", item.getValue()));
retval.append(" </user_defined>").append(Const.CR);
}
}
}
retval.append(" </user_defined_list>").append(Const.CR);
return retval.toString();
}
public void loadRep(Repository rep, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException {
if(rep != null) {
super.loadRep(rep, id_jobentry, databases, slaveServers);
setHadoopJobName(rep.getJobEntryAttributeString(id_jobentry, "hadoop_job_name"));
if (!Const.isEmpty(rep.getJobEntryAttributeString(id_jobentry, "hadoop_distribution"))) {
setHadoopDistribution(rep.getJobEntryAttributeString(id_jobentry, "hadoop_distribution"));
}
setSimple(rep.getJobEntryAttributeBoolean(id_jobentry, "simple"));
setJarUrl(rep.getJobEntryAttributeString(id_jobentry, "jar_url"));
setCmdLineArgs(rep.getJobEntryAttributeString(id_jobentry, "command_line_args"));
setBlocking(rep.getJobEntryAttributeBoolean(id_jobentry, "blocking"));
//setLoggingInterval(new Long(rep.getJobEntryAttributeInteger(id_jobentry, "logging_interval")).intValue());
setLoggingInterval(rep.getJobEntryAttributeString(id_jobentry, "logging_interval"));
setMapperClass(rep.getJobEntryAttributeString(id_jobentry, "mapper_class"));
setCombinerClass(rep.getJobEntryAttributeString(id_jobentry, "combiner_class"));
setReducerClass(rep.getJobEntryAttributeString(id_jobentry, "reducer_class"));
setInputPath(rep.getJobEntryAttributeString(id_jobentry, "input_path"));
setInputFormatClass(rep.getJobEntryAttributeString(id_jobentry, "input_format_class"));
setOutputPath(rep.getJobEntryAttributeString(id_jobentry, "output_path"));
setOutputKeyClass(rep.getJobEntryAttributeString(id_jobentry, "output_key_class"));
setOutputValueClass(rep.getJobEntryAttributeString(id_jobentry, "output_value_class"));
setOutputFormatClass(rep.getJobEntryAttributeString(id_jobentry, "output_format_class"));
setHdfsHostname(rep.getJobEntryAttributeString(id_jobentry, "hdfs_hostname"));
setHdfsPort(rep.getJobEntryAttributeString(id_jobentry, "hdfs_port"));
setJobTrackerHostname(rep.getJobEntryAttributeString(id_jobentry, "job_tracker_hostname"));
setJobTrackerPort(rep.getJobEntryAttributeString(id_jobentry, "job_tracker_port"));
//setNumMapTasks(new Long(rep.getJobEntryAttributeInteger(id_jobentry, "num_map_tasks")).intValue());
setNumMapTasks(rep.getJobEntryAttributeString(id_jobentry, "num_map_tasks"));
// setNumReduceTasks(new Long(rep.getJobEntryAttributeInteger(id_jobentry, "num_reduce_tasks")).intValue());
setNumReduceTasks(rep.getJobEntryAttributeString(id_jobentry, "num_reduce_tasks"));
setWorkingDirectory(rep.getJobEntryAttributeString(id_jobentry, "working_dir"));
int argnr = rep.countNrJobEntryAttributes(id_jobentry, "user_defined_name");//$NON-NLS-1$
if(argnr > 0) {
userDefined = new ArrayList<UserDefinedItem>();
UserDefinedItem item = null;
for(int i = 0; i < argnr; i++) {
item = new UserDefinedItem();
item.setName(rep.getJobEntryAttributeString(id_jobentry, i,"user_defined_name")); //$NON-NLS-1$
item.setValue(rep.getJobEntryAttributeString(id_jobentry, i,"user_defined_value")); //$NON-NLS-1$
userDefined.add(item);
}
}
} else {
throw new KettleException("Unable to save to a repository. The repository is null."); //$NON-NLS-1$
}
}
public void saveRep(Repository rep, ObjectId id_job) throws KettleException {
if(rep != null) {
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getObjectId(),"hadoop_job_name", hadoopJobName); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"hadoop_distribution", hadoopDistribution); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"simple", isSimple); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"jar_url", jarUrl); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"command_line_args", cmdLineArgs); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"blocking", blocking); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"logging_interval", loggingInterval); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"hadoop_job_name", hadoopJobName); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"mapper_class", mapperClass); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"combiner_class", combinerClass); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"reducer_class", reducerClass); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"input_path", inputPath); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"input_format_class", inputFormatClass); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"output_path", outputPath); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"output_key_class", outputKeyClass); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"output_value_class", outputValueClass); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"output_format_class", outputFormatClass); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"hdfs_hostname", hdfsHostname); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"hdfs_port", hdfsPort); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"job_tracker_hostname", jobTrackerHostname); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"job_tracker_port", jobTrackerPort); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"num_map_tasks", numMapTasks); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"num_reduce_tasks", numReduceTasks); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(),"working_dir", workingDirectory); //$NON-NLS-1$
if (userDefined != null) {
for (int i = 0; i < userDefined.size(); i++) {
UserDefinedItem item = userDefined.get(i);
if (item.getName() != null && !"".equals(item.getName()) && item.getValue() != null && !"".equals(item.getValue())) { //$NON-NLS-1$ //$NON-NLS-2$
rep.saveJobEntryAttribute(id_job, getObjectId(), i,"user_defined_name", item.getName()); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getObjectId(), i,"user_defined_value", item.getValue()); //$NON-NLS-1$
}
}
}
} else {
throw new KettleException("Unable to save to a repository. The repository is null."); //$NON-NLS-1$
}
}
public boolean evaluates()
{
return true;
}
public boolean isUnconditional()
{
return true;
}
}
| false | true | public Result execute(Result result, int arg1) throws KettleException {
result.setNrErrors(0);
Log4jFileAppender appender = null;
String logFileName = "pdi-" + this.getName(); //$NON-NLS-1$
String hadoopDistro = System.getProperty("hadoop.distribution.name", hadoopDistribution);
hadoopDistro = environmentSubstitute(hadoopDistro);
if (Const.isEmpty(hadoopDistro)) {
hadoopDistro = "generic";
}
try
{
appender = LogWriter.createFileAppender(logFileName, true, false);
LogWriter.getInstance().addAppender(appender);
log.setLogLevel(parentJob.getLogLevel());
} catch (Exception e)
{
logError(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.FailedToOpenLogFile", logFileName, e.toString())); //$NON-NLS-1$
logError(Const.getStackTracker(e));
}
try {
URL resolvedJarUrl = null;
String jarUrlS = environmentSubstitute(jarUrl);
if (jarUrlS.indexOf("://") == -1) {
// default to file://
File jarFile = new File(jarUrlS);
resolvedJarUrl = jarFile.toURI().toURL();
} else {
resolvedJarUrl = new URL(jarUrlS);
}
final String cmdLineArgsS = environmentSubstitute(cmdLineArgs);
if (log.isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.ResolvedJar", resolvedJarUrl.toExternalForm()));
if (isSimple) {
final AtomicInteger taskCount = new AtomicInteger(0);
final AtomicInteger successCount = new AtomicInteger(0);
final AtomicInteger failedCount = new AtomicInteger(0);
if (log.isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.SimpleMode"));
List<Class<?>> classesWithMains = JarUtility.getClassesInJarWithMain(resolvedJarUrl.toExternalForm(), getClass().getClassLoader());
for (final Class<?> clazz : classesWithMains) {
Runnable r = new Runnable() {
public void run() {
try {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
taskCount.incrementAndGet();
Thread.currentThread().setContextClassLoader(clazz.getClassLoader());
Method mainMethod = clazz.getMethod("main", new Class[] { String[].class });
Object[] args = (cmdLineArgsS != null) ? new Object[] { cmdLineArgsS.split(" ") } : new Object[0];
mainMethod.invoke(null, args);
} finally {
Thread.currentThread().setContextClassLoader(cl);
successCount.incrementAndGet();
taskCount.decrementAndGet();
}
} catch (Throwable ignored) {
// skip, try the next one
logError(ignored.getMessage());
failedCount.incrementAndGet();
}
}
};
Thread t = new Thread(r);
t.start();
}
// uncomment to implement blocking
/* if (blocking) {
while (taskCount.get() > 0 && !parentJob.isStopped()) {
Thread.sleep(1000);
}
if (!parentJob.isStopped()) {
result.setResult(successCount.get() > 0);
result.setNrErrors((successCount.get() > 0) ? 0 : 1);
} else {
// we can't really know at this stage if
// the hadoop job will finish successfully
// because we have to stop now
result.setResult(true); // look on the bright side of life :-)...
result.setNrErrors(0);
}
} else { */
// non-blocking - just set success equal to no failures arising
// from invocation
result.setResult(failedCount.get() == 0);
result.setNrErrors(failedCount.get());
/* } */
} else {
if (log.isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.AdvancedMode"));
URL[] urls = new URL[] { resolvedJarUrl };
URLClassLoader loader = new URLClassLoader(urls, getClass().getClassLoader());
JobConf conf = new JobConf();
String hadoopJobNameS = environmentSubstitute(hadoopJobName);
conf.setJobName(hadoopJobNameS);
String outputKeyClassS = environmentSubstitute(outputKeyClass);
conf.setOutputKeyClass(loader.loadClass(outputKeyClassS));
String outputValueClassS = environmentSubstitute(outputValueClass);
conf.setOutputValueClass(loader.loadClass(outputValueClassS));
if(mapperClass != null) {
String mapperClassS = environmentSubstitute(mapperClass);
Class<? extends Mapper> mapper = (Class<? extends Mapper>) loader.loadClass(mapperClassS);
conf.setMapperClass(mapper);
}
if(combinerClass != null) {
String combinerClassS = environmentSubstitute(combinerClass);
Class<? extends Reducer> combiner = (Class<? extends Reducer>) loader.loadClass(combinerClassS);
conf.setCombinerClass(combiner);
}
if(reducerClass != null) {
String reducerClassS = environmentSubstitute(reducerClass);
Class<? extends Reducer> reducer = (Class<? extends Reducer>) loader.loadClass(reducerClassS);
conf.setReducerClass(reducer);
}
if(inputFormatClass != null) {
String inputFormatClassS = environmentSubstitute(inputFormatClass);
Class<? extends InputFormat> inputFormat = (Class<? extends InputFormat>) loader.loadClass(inputFormatClassS);
conf.setInputFormat(inputFormat);
}
if(outputFormatClass != null) {
String outputFormatClassS = environmentSubstitute(outputFormatClass);
Class<? extends OutputFormat> outputFormat = (Class<? extends OutputFormat>) loader.loadClass(outputFormatClassS);
conf.setOutputFormat(outputFormat);
}
String hdfsHostnameS = environmentSubstitute(hdfsHostname);
String hdfsPortS = environmentSubstitute(hdfsPort);
String jobTrackerHostnameS = environmentSubstitute(jobTrackerHostname);
String jobTrackerPortS = environmentSubstitute(jobTrackerPort);
// See if we can auto detect the distribution first
HadoopConfigurer configurer = HadoopConfigurerFactory.locateConfigurer();
if (configurer == null) {
// go with what has been selected by the user
configurer = HadoopConfigurerFactory.getConfigurer(hadoopDistro);
// if the user-specified distribution is detectable, make sure it is still
// the current distribution!
if (configurer != null && configurer.isDetectable()) {
if (!configurer.isAvailable()) {
throw new KettleException(BaseMessages.getString(PKG,
"JobEntryHadoopJobExecutor.Error.DistroNoLongerPresent", configurer.distributionName()));
}
}
}
if (configurer == null) {
throw new KettleException(BaseMessages.
getString(PKG, "JobEntryHadoopJobExecutor.Error.UnknownHadoopDistribution",
hadoopDistro));
}
logBasic(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.Message.DistroConfigMessage",
configurer.distributionName()));
List<String> configMessages = new ArrayList<String>();
configurer.configure(hdfsHostnameS, hdfsPortS,
jobTrackerHostnameS, jobTrackerPortS, conf, configMessages);
for (String m : configMessages) {
logBasic(m);
}
String inputPathS = environmentSubstitute(inputPath);
String[] inputPathParts = inputPathS.split(",");
List<Path> paths = new ArrayList<Path>();
for (String path : inputPathParts) {
paths.add(new Path(configurer.getFilesystemURL() + path));
}
Path[] finalPaths = paths.toArray(new Path[paths.size()]);
//FileInputFormat.setInputPaths(conf, new Path(configurer.getFilesystemURL() + inputPathS));
FileInputFormat.setInputPaths(conf, finalPaths);
String outputPathS = environmentSubstitute(outputPath);
FileOutputFormat.setOutputPath(conf, new Path(configurer.getFilesystemURL() + outputPathS));
// process user defined values
for (UserDefinedItem item : userDefined) {
if (item.getName() != null && !"".equals(item.getName()) && item.getValue() != null && !"".equals(item.getValue())) {
String nameS = environmentSubstitute(item.getName());
String valueS = environmentSubstitute(item.getValue());
conf.set(nameS, valueS);
}
}
String workingDirectoryS = environmentSubstitute(workingDirectory);
conf.setWorkingDirectory(new Path(configurer.getFilesystemURL() + workingDirectoryS));
conf.setJar(jarUrl);
String numMapTasksS = environmentSubstitute(numMapTasks);
String numReduceTasksS = environmentSubstitute(numReduceTasks);
int numM = 1;
try {
numM = Integer.parseInt(numMapTasksS);
} catch (NumberFormatException e) {
logError("Can't parse number of map tasks '" + numMapTasksS + "'. Setting num" +
"map tasks to 1");
}
int numR = 1;
try {
numR = Integer.parseInt(numReduceTasksS);
} catch (NumberFormatException e) {
logError("Can't parse number of reduce tasks '" + numReduceTasksS + "'. Setting num" +
"reduce tasks to 1");
}
conf.setNumMapTasks(numM);
conf.setNumReduceTasks(numR);
JobClient jobClient = new JobClient(conf);
RunningJob runningJob = jobClient.submitJob(conf);
String loggingIntervalS = environmentSubstitute(loggingInterval);
int logIntv = 60;
try {
logIntv = Integer.parseInt(loggingIntervalS);
} catch (NumberFormatException e) {
logError("Can't parse logging interval '" + loggingIntervalS + "'. Setting " +
"logging interval to 60");
}
if (blocking) {
try {
int taskCompletionEventIndex = 0;
while (!parentJob.isStopped() && !runningJob.isComplete()) {
if (logIntv >= 1) {
printJobStatus(runningJob);
taskCompletionEventIndex = logTaskMessages(runningJob, taskCompletionEventIndex);
Thread.sleep(logIntv * 1000);
} else {
Thread.sleep(60000);
}
}
if (parentJob.isStopped() && !runningJob.isComplete()) {
// We must stop the job running on Hadoop
runningJob.killJob();
// Indicate this job entry did not complete
result.setResult(false);
}
printJobStatus(runningJob);
// Log any messages we may have missed while polling
logTaskMessages(runningJob, taskCompletionEventIndex);
} catch (InterruptedException ie) {
logError(ie.getMessage(), ie);
}
// Entry is successful if the MR job is successful overall
result.setResult(runningJob.isSuccessful());
}
}
} catch (Throwable t) {
t.printStackTrace();
result.setStopped(true);
result.setNrErrors(1);
result.setResult(false);
logError(t.getMessage(), t);
}
if (appender != null)
{
LogWriter.getInstance().removeAppender(appender);
appender.close();
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, appender.getFile(), parentJob.getJobname(), getName());
result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
}
return result;
}
| public Result execute(Result result, int arg1) throws KettleException {
result.setNrErrors(0);
Log4jFileAppender appender = null;
String logFileName = "pdi-" + this.getName(); //$NON-NLS-1$
String hadoopDistro = System.getProperty("hadoop.distribution.name", hadoopDistribution);
hadoopDistro = environmentSubstitute(hadoopDistro);
if (Const.isEmpty(hadoopDistro)) {
hadoopDistro = "generic";
}
try
{
appender = LogWriter.createFileAppender(logFileName, true, false);
LogWriter.getInstance().addAppender(appender);
log.setLogLevel(parentJob.getLogLevel());
} catch (Exception e)
{
logError(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.FailedToOpenLogFile", logFileName, e.toString())); //$NON-NLS-1$
logError(Const.getStackTracker(e));
}
try {
URL resolvedJarUrl = null;
String jarUrlS = environmentSubstitute(jarUrl);
if (jarUrlS.indexOf("://") == -1) {
// default to file://
File jarFile = new File(jarUrlS);
resolvedJarUrl = jarFile.toURI().toURL();
} else {
resolvedJarUrl = new URL(jarUrlS);
}
final String cmdLineArgsS = environmentSubstitute(cmdLineArgs);
if (log.isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.ResolvedJar", resolvedJarUrl.toExternalForm()));
if (isSimple) {
/* final AtomicInteger taskCount = new AtomicInteger(0);
final AtomicInteger successCount = new AtomicInteger(0);
final AtomicInteger failedCount = new AtomicInteger(0); */
if (log.isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.SimpleMode"));
List<Class<?>> classesWithMains = JarUtility.getClassesInJarWithMain(resolvedJarUrl.toExternalForm(), getClass().getClassLoader());
for (final Class<?> clazz : classesWithMains) {
Runnable r = new Runnable() {
public void run() {
try {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
// taskCount.incrementAndGet();
Thread.currentThread().setContextClassLoader(clazz.getClassLoader());
Method mainMethod = clazz.getMethod("main", new Class[] { String[].class });
Object[] args = (cmdLineArgsS != null) ? new Object[] { cmdLineArgsS.split(" ") } : new Object[0];
mainMethod.invoke(null, args);
} finally {
Thread.currentThread().setContextClassLoader(cl);
// successCount.incrementAndGet();
// taskCount.decrementAndGet();
}
} catch (Throwable ignored) {
// skip, try the next one
// logError(ignored.getMessage());
// failedCount.incrementAndGet();
ignored.printStackTrace();
}
}
};
Thread t = new Thread(r);
t.start();
}
// uncomment to implement blocking
/* if (blocking) {
while (taskCount.get() > 0 && !parentJob.isStopped()) {
Thread.sleep(1000);
}
if (!parentJob.isStopped()) {
result.setResult(successCount.get() > 0);
result.setNrErrors((successCount.get() > 0) ? 0 : 1);
} else {
// we can't really know at this stage if
// the hadoop job will finish successfully
// because we have to stop now
result.setResult(true); // look on the bright side of life :-)...
result.setNrErrors(0);
}
} else { */
// non-blocking - just set success equal to no failures arising
// from invocation
// result.setResult(failedCount.get() == 0);
// result.setNrErrors(failedCount.get());
result.setResult(true);
result.setNrErrors(0);
/* } */
} else {
if (log.isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.AdvancedMode"));
URL[] urls = new URL[] { resolvedJarUrl };
URLClassLoader loader = new URLClassLoader(urls, getClass().getClassLoader());
JobConf conf = new JobConf();
String hadoopJobNameS = environmentSubstitute(hadoopJobName);
conf.setJobName(hadoopJobNameS);
String outputKeyClassS = environmentSubstitute(outputKeyClass);
conf.setOutputKeyClass(loader.loadClass(outputKeyClassS));
String outputValueClassS = environmentSubstitute(outputValueClass);
conf.setOutputValueClass(loader.loadClass(outputValueClassS));
if(mapperClass != null) {
String mapperClassS = environmentSubstitute(mapperClass);
Class<? extends Mapper> mapper = (Class<? extends Mapper>) loader.loadClass(mapperClassS);
conf.setMapperClass(mapper);
}
if(combinerClass != null) {
String combinerClassS = environmentSubstitute(combinerClass);
Class<? extends Reducer> combiner = (Class<? extends Reducer>) loader.loadClass(combinerClassS);
conf.setCombinerClass(combiner);
}
if(reducerClass != null) {
String reducerClassS = environmentSubstitute(reducerClass);
Class<? extends Reducer> reducer = (Class<? extends Reducer>) loader.loadClass(reducerClassS);
conf.setReducerClass(reducer);
}
if(inputFormatClass != null) {
String inputFormatClassS = environmentSubstitute(inputFormatClass);
Class<? extends InputFormat> inputFormat = (Class<? extends InputFormat>) loader.loadClass(inputFormatClassS);
conf.setInputFormat(inputFormat);
}
if(outputFormatClass != null) {
String outputFormatClassS = environmentSubstitute(outputFormatClass);
Class<? extends OutputFormat> outputFormat = (Class<? extends OutputFormat>) loader.loadClass(outputFormatClassS);
conf.setOutputFormat(outputFormat);
}
String hdfsHostnameS = environmentSubstitute(hdfsHostname);
String hdfsPortS = environmentSubstitute(hdfsPort);
String jobTrackerHostnameS = environmentSubstitute(jobTrackerHostname);
String jobTrackerPortS = environmentSubstitute(jobTrackerPort);
// See if we can auto detect the distribution first
HadoopConfigurer configurer = HadoopConfigurerFactory.locateConfigurer();
if (configurer == null) {
// go with what has been selected by the user
configurer = HadoopConfigurerFactory.getConfigurer(hadoopDistro);
// if the user-specified distribution is detectable, make sure it is still
// the current distribution!
if (configurer != null && configurer.isDetectable()) {
if (!configurer.isAvailable()) {
throw new KettleException(BaseMessages.getString(PKG,
"JobEntryHadoopJobExecutor.Error.DistroNoLongerPresent", configurer.distributionName()));
}
}
}
if (configurer == null) {
throw new KettleException(BaseMessages.
getString(PKG, "JobEntryHadoopJobExecutor.Error.UnknownHadoopDistribution",
hadoopDistro));
}
logBasic(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.Message.DistroConfigMessage",
configurer.distributionName()));
List<String> configMessages = new ArrayList<String>();
configurer.configure(hdfsHostnameS, hdfsPortS,
jobTrackerHostnameS, jobTrackerPortS, conf, configMessages);
for (String m : configMessages) {
logBasic(m);
}
String inputPathS = environmentSubstitute(inputPath);
String[] inputPathParts = inputPathS.split(",");
List<Path> paths = new ArrayList<Path>();
for (String path : inputPathParts) {
paths.add(new Path(configurer.getFilesystemURL() + path));
}
Path[] finalPaths = paths.toArray(new Path[paths.size()]);
//FileInputFormat.setInputPaths(conf, new Path(configurer.getFilesystemURL() + inputPathS));
FileInputFormat.setInputPaths(conf, finalPaths);
String outputPathS = environmentSubstitute(outputPath);
FileOutputFormat.setOutputPath(conf, new Path(configurer.getFilesystemURL() + outputPathS));
// process user defined values
for (UserDefinedItem item : userDefined) {
if (item.getName() != null && !"".equals(item.getName()) && item.getValue() != null && !"".equals(item.getValue())) {
String nameS = environmentSubstitute(item.getName());
String valueS = environmentSubstitute(item.getValue());
conf.set(nameS, valueS);
}
}
String workingDirectoryS = environmentSubstitute(workingDirectory);
conf.setWorkingDirectory(new Path(configurer.getFilesystemURL() + workingDirectoryS));
conf.setJar(jarUrl);
String numMapTasksS = environmentSubstitute(numMapTasks);
String numReduceTasksS = environmentSubstitute(numReduceTasks);
int numM = 1;
try {
numM = Integer.parseInt(numMapTasksS);
} catch (NumberFormatException e) {
logError("Can't parse number of map tasks '" + numMapTasksS + "'. Setting num" +
"map tasks to 1");
}
int numR = 1;
try {
numR = Integer.parseInt(numReduceTasksS);
} catch (NumberFormatException e) {
logError("Can't parse number of reduce tasks '" + numReduceTasksS + "'. Setting num" +
"reduce tasks to 1");
}
conf.setNumMapTasks(numM);
conf.setNumReduceTasks(numR);
JobClient jobClient = new JobClient(conf);
RunningJob runningJob = jobClient.submitJob(conf);
String loggingIntervalS = environmentSubstitute(loggingInterval);
int logIntv = 60;
try {
logIntv = Integer.parseInt(loggingIntervalS);
} catch (NumberFormatException e) {
logError("Can't parse logging interval '" + loggingIntervalS + "'. Setting " +
"logging interval to 60");
}
if (blocking) {
try {
int taskCompletionEventIndex = 0;
while (!parentJob.isStopped() && !runningJob.isComplete()) {
if (logIntv >= 1) {
printJobStatus(runningJob);
taskCompletionEventIndex = logTaskMessages(runningJob, taskCompletionEventIndex);
Thread.sleep(logIntv * 1000);
} else {
Thread.sleep(60000);
}
}
if (parentJob.isStopped() && !runningJob.isComplete()) {
// We must stop the job running on Hadoop
runningJob.killJob();
// Indicate this job entry did not complete
result.setResult(false);
}
printJobStatus(runningJob);
// Log any messages we may have missed while polling
logTaskMessages(runningJob, taskCompletionEventIndex);
} catch (InterruptedException ie) {
logError(ie.getMessage(), ie);
}
// Entry is successful if the MR job is successful overall
result.setResult(runningJob.isSuccessful());
}
}
} catch (Throwable t) {
t.printStackTrace();
result.setStopped(true);
result.setNrErrors(1);
result.setResult(false);
logError(t.getMessage(), t);
}
if (appender != null)
{
LogWriter.getInstance().removeAppender(appender);
appender.close();
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, appender.getFile(), parentJob.getJobname(), getName());
result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
}
return result;
}
|
diff --git a/frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/presenter/tab/MainTabVolumePresenter.java b/frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/presenter/tab/MainTabVolumePresenter.java
index 1da522bd8..cfa671261 100644
--- a/frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/presenter/tab/MainTabVolumePresenter.java
+++ b/frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/presenter/tab/MainTabVolumePresenter.java
@@ -1,63 +1,63 @@
package org.ovirt.engine.ui.webadmin.section.main.presenter.tab;
import java.util.List;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeEntity;
import org.ovirt.engine.ui.common.uicommon.model.MainModelProvider;
import org.ovirt.engine.ui.common.widget.tab.ModelBoundTabData;
import org.ovirt.engine.ui.uicommonweb.models.volumes.VolumeListModel;
import org.ovirt.engine.ui.webadmin.gin.ClientGinjector;
import org.ovirt.engine.ui.webadmin.place.ApplicationPlaces;
import org.ovirt.engine.ui.webadmin.section.main.presenter.AbstractMainTabWithDetailsPresenter;
import org.ovirt.engine.ui.webadmin.section.main.presenter.MainTabPanelPresenter;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.gwtplatform.dispatch.annotation.GenEvent;
import com.gwtplatform.mvp.client.TabData;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.annotations.TabInfo;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.TabContentProxyPlace;
public class MainTabVolumePresenter extends AbstractMainTabWithDetailsPresenter<GlusterVolumeEntity, VolumeListModel, MainTabVolumePresenter.ViewDef, MainTabVolumePresenter.ProxyDef> {
@GenEvent
public static class VolumeSelectionChange {
List<GlusterVolumeEntity> selectedItems;
}
@ProxyCodeSplit
@NameToken(ApplicationPlaces.volumeMainTabPlace)
public interface ProxyDef extends TabContentProxyPlace<MainTabVolumePresenter> {
}
public interface ViewDef extends AbstractMainTabWithDetailsPresenter.ViewDef<GlusterVolumeEntity> {
}
@TabInfo(container = MainTabPanelPresenter.class)
static TabData getTabData(ClientGinjector ginjector) {
return new ModelBoundTabData(ginjector.getApplicationConstants().volumeMainTabLabel(), 11,
- ginjector.getMainTabVirtualMachineModelProvider());
+ ginjector.getMainTabVolumeModelProvider());
}
@Inject
public MainTabVolumePresenter(EventBus eventBus, ViewDef view, ProxyDef proxy,
PlaceManager placeManager, MainModelProvider<GlusterVolumeEntity, VolumeListModel> modelProvider) {
super(eventBus, view, proxy, placeManager, modelProvider);
}
@Override
protected void fireTableSelectionChangeEvent() {
VolumeSelectionChangeEvent.fire(this, getSelectedItems());
}
@Override
protected PlaceRequest getMainTabRequest() {
return new PlaceRequest(ApplicationPlaces.volumeMainTabPlace);
}
}
| true | true | static TabData getTabData(ClientGinjector ginjector) {
return new ModelBoundTabData(ginjector.getApplicationConstants().volumeMainTabLabel(), 11,
ginjector.getMainTabVirtualMachineModelProvider());
}
| static TabData getTabData(ClientGinjector ginjector) {
return new ModelBoundTabData(ginjector.getApplicationConstants().volumeMainTabLabel(), 11,
ginjector.getMainTabVolumeModelProvider());
}
|
diff --git a/hyracks-control-common/src/main/java/edu/uci/ics/hyracks/control/common/application/ApplicationContext.java b/hyracks-control-common/src/main/java/edu/uci/ics/hyracks/control/common/application/ApplicationContext.java
index f2c296d2d..c1b467485 100644
--- a/hyracks-control-common/src/main/java/edu/uci/ics/hyracks/control/common/application/ApplicationContext.java
+++ b/hyracks-control-common/src/main/java/edu/uci/ics/hyracks/control/common/application/ApplicationContext.java
@@ -1,181 +1,183 @@
/*
* Copyright 2009-2010 by The Regents of the University of California
* 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 from
*
* 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 edu.uci.ics.hyracks.control.common.application;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import edu.uci.ics.hyracks.api.application.IApplicationContext;
import edu.uci.ics.hyracks.api.application.IBootstrap;
import edu.uci.ics.hyracks.control.common.context.ServerContext;
public class ApplicationContext implements IApplicationContext {
private static final String APPLICATION_ROOT = "applications";
private static final String CLUSTER_CONTROLLER_BOOTSTRAP_CLASS_KEY = "cc.bootstrap.class";
private static final String NODE_CONTROLLER_BOOTSTRAP_CLASS_KEY = "nc.bootstrap.class";
private ServerContext serverCtx;
private final String appName;
private final File applicationRootDir;
private ClassLoader classLoader;
private ApplicationStatus status;
private Properties deploymentDescriptor;
private IBootstrap bootstrap;
public ApplicationContext(ServerContext serverCtx, String appName) throws IOException {
this.serverCtx = serverCtx;
this.appName = appName;
this.applicationRootDir = new File(new File(serverCtx.getBaseDir(), APPLICATION_ROOT), appName);
status = ApplicationStatus.CREATED;
FileUtils.deleteDirectory(applicationRootDir);
applicationRootDir.mkdirs();
}
public String getApplicationName() {
return appName;
}
public void initialize() throws Exception {
if (status != ApplicationStatus.CREATED) {
throw new IllegalStateException();
}
if (expandArchive()) {
File expandedFolder = getExpandedFolder();
List<URL> urls = new ArrayList<URL>();
findJarFiles(expandedFolder, urls);
classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]));
deploymentDescriptor = parseDeploymentDescriptor();
String bootstrapClass = null;
switch (serverCtx.getServerType()) {
case CLUSTER_CONTROLLER: {
bootstrapClass = deploymentDescriptor.getProperty(CLUSTER_CONTROLLER_BOOTSTRAP_CLASS_KEY);
+ break;
}
case NODE_CONTROLLER: {
bootstrapClass = deploymentDescriptor.getProperty(NODE_CONTROLLER_BOOTSTRAP_CLASS_KEY);
+ break;
}
}
if (bootstrapClass != null) {
bootstrap = (IBootstrap) classLoader.loadClass(bootstrapClass).newInstance();
bootstrap.setApplicationContext(this);
bootstrap.start();
}
} else {
classLoader = getClass().getClassLoader();
}
status = ApplicationStatus.INITIALIZED;
}
private void findJarFiles(File dir, List<URL> urls) throws MalformedURLException {
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
findJarFiles(f, urls);
} else if (f.getName().endsWith(".jar") || f.getName().endsWith(".zip")) {
urls.add(f.toURI().toURL());
}
}
}
private Properties parseDeploymentDescriptor() throws IOException {
InputStream in = classLoader.getResourceAsStream("hyracks-deployment.properties");
Properties props = new Properties();
if (in != null) {
try {
props.load(in);
} finally {
in.close();
}
}
return props;
}
private boolean expandArchive() throws IOException {
File archiveFile = getArchiveFile();
if (archiveFile.exists()) {
File expandedFolder = getExpandedFolder();
FileUtils.deleteDirectory(expandedFolder);
ZipFile zf = new ZipFile(archiveFile);
for (Enumeration<? extends ZipEntry> i = zf.entries(); i.hasMoreElements();) {
ZipEntry ze = i.nextElement();
String name = ze.getName();
if (name.endsWith("/")) {
continue;
}
InputStream is = zf.getInputStream(ze);
OutputStream os = FileUtils.openOutputStream(new File(expandedFolder, name));
try {
IOUtils.copyLarge(is, os);
} finally {
os.close();
is.close();
}
}
return true;
}
return false;
}
private File getExpandedFolder() {
return new File(applicationRootDir, "expanded");
}
public void deinitialize() throws Exception {
status = ApplicationStatus.DEINITIALIZED;
if (bootstrap != null) {
bootstrap.stop();
}
File expandedFolder = getExpandedFolder();
FileUtils.deleteDirectory(expandedFolder);
}
public Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ClassLoaderObjectInputStream(new ByteArrayInputStream(bytes), classLoader);
return ois.readObject();
}
public OutputStream getHarOutputStream() throws IOException {
return new FileOutputStream(getArchiveFile());
}
private File getArchiveFile() {
return new File(applicationRootDir, "application.har");
}
public InputStream getHarInputStream() throws IOException {
return new FileInputStream(getArchiveFile());
}
public boolean containsHar() {
return getArchiveFile().exists();
}
}
| false | true | public void initialize() throws Exception {
if (status != ApplicationStatus.CREATED) {
throw new IllegalStateException();
}
if (expandArchive()) {
File expandedFolder = getExpandedFolder();
List<URL> urls = new ArrayList<URL>();
findJarFiles(expandedFolder, urls);
classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]));
deploymentDescriptor = parseDeploymentDescriptor();
String bootstrapClass = null;
switch (serverCtx.getServerType()) {
case CLUSTER_CONTROLLER: {
bootstrapClass = deploymentDescriptor.getProperty(CLUSTER_CONTROLLER_BOOTSTRAP_CLASS_KEY);
}
case NODE_CONTROLLER: {
bootstrapClass = deploymentDescriptor.getProperty(NODE_CONTROLLER_BOOTSTRAP_CLASS_KEY);
}
}
if (bootstrapClass != null) {
bootstrap = (IBootstrap) classLoader.loadClass(bootstrapClass).newInstance();
bootstrap.setApplicationContext(this);
bootstrap.start();
}
} else {
classLoader = getClass().getClassLoader();
}
status = ApplicationStatus.INITIALIZED;
}
| public void initialize() throws Exception {
if (status != ApplicationStatus.CREATED) {
throw new IllegalStateException();
}
if (expandArchive()) {
File expandedFolder = getExpandedFolder();
List<URL> urls = new ArrayList<URL>();
findJarFiles(expandedFolder, urls);
classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]));
deploymentDescriptor = parseDeploymentDescriptor();
String bootstrapClass = null;
switch (serverCtx.getServerType()) {
case CLUSTER_CONTROLLER: {
bootstrapClass = deploymentDescriptor.getProperty(CLUSTER_CONTROLLER_BOOTSTRAP_CLASS_KEY);
break;
}
case NODE_CONTROLLER: {
bootstrapClass = deploymentDescriptor.getProperty(NODE_CONTROLLER_BOOTSTRAP_CLASS_KEY);
break;
}
}
if (bootstrapClass != null) {
bootstrap = (IBootstrap) classLoader.loadClass(bootstrapClass).newInstance();
bootstrap.setApplicationContext(this);
bootstrap.start();
}
} else {
classLoader = getClass().getClassLoader();
}
status = ApplicationStatus.INITIALIZED;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.