diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/soot/jimple/paddle/BDDFactory.java b/src/soot/jimple/paddle/BDDFactory.java
index b2b80377..cdfb75c0 100644
--- a/src/soot/jimple/paddle/BDDFactory.java
+++ b/src/soot/jimple/paddle/BDDFactory.java
@@ -1,227 +1,227 @@
/* Soot - a J*va Optimization Framework
* Copyright (C) 2005 Ondrej Lhotak
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package soot.jimple.paddle;
import soot.jimple.paddle.queue.*;
import soot.jimple.toolkits.pointer.util.NativeMethodDriver;
import soot.options.PaddleOptions;
/** Factory that constructs Paddle components.
* @author Ondrej Lhotak
*/
public class BDDFactory extends AbsFactory
{
public AbsCallEdgeContextifier CallEdgeContextifier(
AbsNodeInfo ni,
Rsrcm_stmt_kind_tgtm_src_dst parms,
Rsrcm_stmt_kind_tgtm_src_dst rets,
Rsrcc_srcm_stmt_kind_tgtc_tgtm calls,
Qsrcc_src_dstc_dst csimple
) {
return new BDDCallEdgeContextifier((BDDNodeInfo) ni, parms, rets, calls, csimple);
}
public AbsCallEdgeHandler CallEdgeHandler(
Rsrcm_stmt_kind_tgtm in,
Qsrcm_stmt_kind_tgtm_src_dst parms,
Qsrcm_stmt_kind_tgtm_src_dst rets,
NodeFactory gnf,
boolean processThis
) {
return new TradCallEdgeHandler(in, parms, rets, gnf, processThis);
}
public AbsCallGraph CallGraph(
Rsrcc_srcm_stmt_kind_tgtc_tgtm in,
Qsrcm_stmt_kind_tgtm ciout,
Qsrcc_srcm_stmt_kind_tgtc_tgtm csout
) {
return new BDDCallGraph(in, ciout, csout);
}
public AbsClassHierarchyAnalysis ClassHierarchyAnalysis(
Rvar_srcm_stmt_dtp_signature_kind receivers,
Rvar_srcm_stmt_tgtm specials,
Qobj_var out
) {
return new TradClassHierarchyAnalysis(receivers, specials, out);
}
public AbsContextCallGraphBuilder ContextCallGraphBuilder(
Rctxt_method methodsIn,
Rsrcm_stmt_kind_tgtm edgesIn,
Qsrcc_srcm_stmt_kind_tgtc_tgtm out
) {
return new BDDContextCallGraphBuilder(methodsIn, edgesIn, out);
}
public AbsMethodPAGBuilder MethodPAGBuilder(
Rmethod in,
Qsrc_dst simple,
Qsrc_fld_dst load,
Qsrc_dst_fld store,
Qobj_var alloc,
NodeFactory gnf,
NativeMethodDriver nativeMethodDriver
) {
return new TradMethodPAGBuilder(in, simple, load, store, alloc, gnf, nativeMethodDriver);
}
public AbsMethodPAGContextifier MethodPAGContextifier(
AbsNodeInfo ni,
Rsrc_dst simple,
Rsrc_fld_dst load,
Rsrc_dst_fld store,
Robj_var alloc,
Rctxt_method rcout,
Qsrcc_src_dstc_dst csimple,
Qsrcc_src_fld_dstc_dst cload,
Qsrcc_src_dstc_dst_fld cstore,
Qobjc_obj_varc_var calloc
) {
return new BDDMethodPAGContextifier((BDDNodeInfo) ni,
simple, load, store, alloc,
rcout, csimple, cload, cstore, calloc);
}
public AbsNodeInfo NodeInfo(
Rvar_method_type locals,
Rvar_type globals,
Robj_method_type localallocs,
Robj_type globalallocs
) {
return new BDDNodeInfo(locals, globals, localallocs, globalallocs);
}
public AbsPAG PAG(
Rsrcc_src_dstc_dst simple,
Rsrcc_src_fld_dstc_dst load,
Rsrcc_src_dstc_dst_fld store,
Robjc_obj_varc_var alloc
) {
return new BDDPAG(simple, load, store, alloc);
}
public AbsPropagator Propagator(
int kind,
Rsrcc_src_dstc_dst simple,
Rsrcc_src_fld_dstc_dst load,
Rsrcc_src_dstc_dst_fld store,
Robjc_obj_varc_var alloc,
Qvarc_var_objc_obj propout,
AbsPAG pag
) {
switch( kind ) {
case PaddleOptions.propagator_worklist:
return new PropWorklist(simple, load, store, alloc, propout, pag);
case PaddleOptions.propagator_iter:
return new PropIter(simple, load, store, alloc, propout, pag);
case PaddleOptions.propagator_alias:
return new PropAlias(simple, load, store, alloc, propout, pag);
- case PaddleOptions.propagator_auto:
case PaddleOptions.propagator_bdd:
return new PropBDD(simple, load, store, alloc, propout, pag);
+ case PaddleOptions.propagator_auto:
case PaddleOptions.propagator_incbdd:
return new PropBDDInc(simple, load, store, alloc, propout, pag);
default:
throw new RuntimeException( "Unimplemented propagator specified "+kind );
}
}
public AbsReachableMethods ReachableMethods(
Rsrcc_srcm_stmt_kind_tgtc_tgtm edgesIn,
Rctxt_method methodsIn,
Qmethod mout,
Qctxt_method cmout,
AbsCallGraph cg
) {
return new BDDReachableMethods(edgesIn, methodsIn, mout, cmout, cg);
}
public AbsReachableMethodsAdapter ReachableMethodsAdapter(
Rsrcc_srcm_stmt_kind_tgtc_tgtm edgesIn,
Qctxt_method cmout
) {
return new BDDReachableMethodsAdapter(edgesIn, cmout);
}
public AbsStaticCallBuilder StaticCallBuilder(
Rmethod in,
Qsrcm_stmt_kind_tgtm out,
Qvar_srcm_stmt_dtp_signature_kind receivers,
Qvar_srcm_stmt_tgtm specials,
NodeFactory gnf
) {
return new TradStaticCallBuilder(in, out, receivers, specials, gnf);
}
public AbsStaticContextManager StaticContextManager(
int kind,
Rsrcc_srcm_stmt_kind_tgtc_tgtm in,
Qsrcc_srcm_stmt_kind_tgtc_tgtm out,
int k
) {
switch(kind) {
case PaddleOptions.context_insens:
return new BDDInsensitiveStaticContextManager(in, out);
case PaddleOptions.context_1cfa:
return new BDD1CFAStaticContextManager(in, out);
case PaddleOptions.context_objsens:
return new BDDObjSensStaticContextManager(in, out);
case PaddleOptions.context_kcfa:
return new BDDKCFAStaticContextManager(in, out, k);
case PaddleOptions.context_kobjsens:
case PaddleOptions.context_uniqkobjsens:
return new BDDKObjSensStaticContextManager(in, out, k);
default:
throw new RuntimeException( "Unhandled kind of context-sensitivity "+kind );
}
}
public AbsTypeManager TypeManager(
Rvar_method_type locals,
Rvar_type globals,
Robj_method_type localallocs,
Robj_type globalallocs
) {
return new BDDTypeManager(locals, globals, localallocs, globalallocs);
}
public AbsVirtualCalls VirtualCalls(
Rvarc_var_objc_obj pt,
Rvar_srcm_stmt_dtp_signature_kind receivers,
Rvar_srcm_stmt_tgtm specials,
Qvarc_var_objc_obj_srcm_stmt_kind_tgtm out,
Qsrcc_srcm_stmt_kind_tgtc_tgtm statics,
AbsP2Sets p2sets
) {
return new BDDVirtualCalls(pt, receivers, specials, out, statics, p2sets);
}
public AbsVirtualContextManager VirtualContextManager(
int kind,
Rvarc_var_objc_obj_srcm_stmt_kind_tgtm in,
Qsrcc_srcm_stmt_kind_tgtc_tgtm out,
Qobjc_obj_varc_var thisOut,
NodeFactory gnf,
int k
) {
switch(kind) {
case PaddleOptions.context_insens:
return new BDDInsensitiveVirtualContextManager(in, out, thisOut, gnf);
case PaddleOptions.context_1cfa:
return new BDD1CFAVirtualContextManager(in, out, thisOut, gnf);
case PaddleOptions.context_objsens:
return new BDDObjSensVirtualContextManager(in, out, thisOut, gnf);
case PaddleOptions.context_kcfa:
return new BDDKCFAVirtualContextManager(in, out, thisOut, gnf, k);
case PaddleOptions.context_kobjsens:
return new BDDKObjSensVirtualContextManager(in, out, thisOut, gnf, k);
case PaddleOptions.context_uniqkobjsens:
return new BDDUniqKObjSensVirtualContextManager(in, out, thisOut, gnf, k);
default:
throw new RuntimeException( "Unhandled kind of context-sensitivity "+kind );
}
}
}
| false | true | public AbsPropagator Propagator(
int kind,
Rsrcc_src_dstc_dst simple,
Rsrcc_src_fld_dstc_dst load,
Rsrcc_src_dstc_dst_fld store,
Robjc_obj_varc_var alloc,
Qvarc_var_objc_obj propout,
AbsPAG pag
) {
switch( kind ) {
case PaddleOptions.propagator_worklist:
return new PropWorklist(simple, load, store, alloc, propout, pag);
case PaddleOptions.propagator_iter:
return new PropIter(simple, load, store, alloc, propout, pag);
case PaddleOptions.propagator_alias:
return new PropAlias(simple, load, store, alloc, propout, pag);
case PaddleOptions.propagator_auto:
case PaddleOptions.propagator_bdd:
return new PropBDD(simple, load, store, alloc, propout, pag);
case PaddleOptions.propagator_incbdd:
return new PropBDDInc(simple, load, store, alloc, propout, pag);
default:
throw new RuntimeException( "Unimplemented propagator specified "+kind );
}
}
| public AbsPropagator Propagator(
int kind,
Rsrcc_src_dstc_dst simple,
Rsrcc_src_fld_dstc_dst load,
Rsrcc_src_dstc_dst_fld store,
Robjc_obj_varc_var alloc,
Qvarc_var_objc_obj propout,
AbsPAG pag
) {
switch( kind ) {
case PaddleOptions.propagator_worklist:
return new PropWorklist(simple, load, store, alloc, propout, pag);
case PaddleOptions.propagator_iter:
return new PropIter(simple, load, store, alloc, propout, pag);
case PaddleOptions.propagator_alias:
return new PropAlias(simple, load, store, alloc, propout, pag);
case PaddleOptions.propagator_bdd:
return new PropBDD(simple, load, store, alloc, propout, pag);
case PaddleOptions.propagator_auto:
case PaddleOptions.propagator_incbdd:
return new PropBDDInc(simple, load, store, alloc, propout, pag);
default:
throw new RuntimeException( "Unimplemented propagator specified "+kind );
}
}
|
diff --git a/src/java/fedora/server/storage/types/DatastreamReferencedContent.java b/src/java/fedora/server/storage/types/DatastreamReferencedContent.java
index e01b30c0f..32de82f3b 100755
--- a/src/java/fedora/server/storage/types/DatastreamReferencedContent.java
+++ b/src/java/fedora/server/storage/types/DatastreamReferencedContent.java
@@ -1,66 +1,66 @@
package fedora.server.storage.types;
import fedora.server.errors.StreamIOException;
import java.io.InputStream;
import fedora.common.http.HttpInputStream;
import fedora.common.http.WebClient;
/**
*
* <p><b>Title:</b> DatastreamReferencedContent.java</p>
* <p><b>Description:</b> Referenced Content.</p>
*
* @author [email protected]
* @version $Id$
*/
public class DatastreamReferencedContent
extends Datastream {
private static WebClient s_http;
static {
s_http = new WebClient();
}
public DatastreamReferencedContent() {
}
public Datastream copy() {
DatastreamReferencedContent ds = new DatastreamReferencedContent();
copy(ds);
return ds;
}
/**
* Gets an InputStream to the content of this externally-referenced
* datastream.
* <p></p>
* The DSLocation of this datastream must be non-null before invoking
* this method.
* <p></p>
* If successful, the DSMIME type is automatically set based on the
* web server's response header. If the web server doesn't send a
* valid Content-type: header, as a last resort, the content-type
* is guessed by using a map of common extensions to mime-types.
* <p></p>
* If the content-length header is present in the response, DSSize
* will be set accordingly.
*/
public InputStream getContentStream()
throws StreamIOException {
HttpInputStream contentStream = null;
try {
- contentStream = s_http.get(DSLocation, true, null, null);
+ contentStream = s_http.get(DSLocation, true);
DSSize = new Long(contentStream.getResponseHeaderValue("content-length","0")).longValue();
} catch (Throwable th) {
th.printStackTrace();
throw new StreamIOException("[DatastreamReferencedContent] "
+ "returned an error. The underlying error was a "
+ th.getClass().getName() + " The message "
+ "was \"" + th.getMessage() + "\" . ");
}
return(contentStream);
}
}
| true | true | public InputStream getContentStream()
throws StreamIOException {
HttpInputStream contentStream = null;
try {
contentStream = s_http.get(DSLocation, true, null, null);
DSSize = new Long(contentStream.getResponseHeaderValue("content-length","0")).longValue();
} catch (Throwable th) {
th.printStackTrace();
throw new StreamIOException("[DatastreamReferencedContent] "
+ "returned an error. The underlying error was a "
+ th.getClass().getName() + " The message "
+ "was \"" + th.getMessage() + "\" . ");
}
return(contentStream);
}
| public InputStream getContentStream()
throws StreamIOException {
HttpInputStream contentStream = null;
try {
contentStream = s_http.get(DSLocation, true);
DSSize = new Long(contentStream.getResponseHeaderValue("content-length","0")).longValue();
} catch (Throwable th) {
th.printStackTrace();
throw new StreamIOException("[DatastreamReferencedContent] "
+ "returned an error. The underlying error was a "
+ th.getClass().getName() + " The message "
+ "was \"" + th.getMessage() + "\" . ");
}
return(contentStream);
}
|
diff --git a/src/com/matburt/mobileorg/MobileOrgActivity.java b/src/com/matburt/mobileorg/MobileOrgActivity.java
index ec03e25..39f1fcb 100644
--- a/src/com/matburt/mobileorg/MobileOrgActivity.java
+++ b/src/com/matburt/mobileorg/MobileOrgActivity.java
@@ -1,319 +1,320 @@
package com.matburt.mobileorg;
import android.app.ListActivity;
import android.app.Application;
import android.app.ProgressDialog;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.AdapterView;
import android.content.Intent;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.util.Log;
import java.util.ArrayList;
import java.lang.Runnable;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class MobileOrgActivity extends ListActivity
{
private static class OrgViewAdapter extends BaseAdapter {
public Node topNode;
public Node thisNode;
public ArrayList<Integer> nodeSelection;
private Context context;
private LayoutInflater lInflator;
public OrgViewAdapter(Context context, Node ndx,
ArrayList<Integer> selection) {
this.topNode = ndx;
this.thisNode = ndx;
this.lInflator = LayoutInflater.from(context);
this.nodeSelection = selection;
this.context = context;
Log.d("OVA", "Selection Stack");
if (selection != null) {
for (int idx = 0; idx < selection.size(); idx++) {
this.thisNode = this.thisNode.subNodes.get(
selection.get(idx));
Log.d("OVA", this.thisNode.nodeName);
}
}
}
public int getCount() {
return this.thisNode.subNodes.size();
}
/**
* Since the data comes from an array, just returning the index is
* sufficent to get at the data. If we were using a more complex data
* structure, we would return whatever object represents one row in the
* list.
*
* @see android.widget.ListAdapter#getItem(int)
*/
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = this.lInflator.inflate(R.layout.main, null);
}
TextView thisView = (TextView)convertView.findViewById(R.id.orgItem);
TextView todoView = (TextView)convertView.findViewById(R.id.todoState);
LinearLayout tagsLayout = (LinearLayout)convertView.findViewById(R.id.tagsLayout);
String todo = this.thisNode.subNodes.get(position).todo;
if (TextUtils.isEmpty(todo)) {
todoView.setVisibility(View.GONE);
} else {
todoView.setText(todo);
todoView.setVisibility(View.VISIBLE);
}
thisView.setText(this.thisNode.subNodes.get(position).nodeName);
tagsLayout.removeAllViews();
for (String tag : this.thisNode.subNodes.get(position).tags) {
TextView tagView = new TextView(this.context);
tagView.setText(tag);
tagView.setPadding(0, 0, 5, 0);
tagsLayout.addView(tagView);
}
Log.d("MobileOrg", "Returning view item: " +
this.thisNode.subNodes.get(position).nodeName);
convertView.setTag(thisView);
return convertView;
}
}
private static final int OP_MENU_SETTINGS = 1;
private static final int OP_MENU_SYNC = 2;
private static final int OP_MENU_OUTLINE = 3;
private static final int OP_MENU_CAPTURE = 4;
private static final String LT = "MobileOrg";
private ProgressDialog syncDialog;
final Handler syncHandler = new Handler();
final Runnable syncUpdateResults = new Runnable() {
public void run() {
postSynchronize();
}
};
public boolean syncResults;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.initializeTables();
ListView lv = this.getListView();
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener
(){
@Override
public boolean onItemLongClick(AdapterView<?> av, View v,
int pos, long id) {
onLongListItemClick(v,pos,id);
return true;
}
});
}
public void runParser() {
MobileOrgApplication appInst = (MobileOrgApplication)this.getApplication();
ArrayList<String> allOrgList = this.getOrgFiles();
OrgFileParser ofp = new OrgFileParser(allOrgList);
ofp.parse();
appInst.rootNode = ofp.rootNode;
}
@Override
public void onResume() {
super.onResume();
MobileOrgApplication appInst = (MobileOrgApplication)this.getApplication();
if (appInst.rootNode == null) {
this.runParser();
}
Intent nodeIntent = getIntent();
appInst.nodeSelection = nodeIntent.getIntegerArrayListExtra("nodePath");
this.setListAdapter(new OrgViewAdapter(this,
appInst.rootNode,
appInst.nodeSelection));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MobileOrgActivity.OP_MENU_OUTLINE, 0, "Outline");
menu.add(0, MobileOrgActivity.OP_MENU_CAPTURE, 0, "Capture");
menu.add(0, MobileOrgActivity.OP_MENU_SYNC, 0, "Sync");
menu.add(0, MobileOrgActivity.OP_MENU_SETTINGS, 0, "Settings");
return true;
}
protected void onLongListItemClick(View av, int pos, long id) {
Intent dispIntent = new Intent();
MobileOrgApplication appInst = (MobileOrgApplication)this.getApplication();
dispIntent.setClassName("com.matburt.mobileorg",
"com.matburt.mobileorg.OrgContextMenu");
if (appInst.nodeSelection == null) {
appInst.nodeSelection = new ArrayList<Integer>();
}
appInst.nodeSelection.add(new Integer(pos));
dispIntent.putIntegerArrayListExtra("nodePath", appInst.nodeSelection);
startActivity(dispIntent);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent dispIntent = new Intent();
MobileOrgApplication appInst = (MobileOrgApplication)this.getApplication();
dispIntent.setClassName("com.matburt.mobileorg",
"com.matburt.mobileorg.MobileOrgActivity");
if (appInst.nodeSelection == null) {
appInst.nodeSelection = new ArrayList<Integer>();
}
- appInst.nodeSelection.add(new Integer(position));
+ ArrayList<Integer> selection = new ArrayList<Integer>(appInst.nodeSelection);
+ selection.add(new Integer(position));
Node thisNode = appInst.rootNode;
- if (appInst.nodeSelection != null) {
- for (int idx = 0; idx < appInst.nodeSelection.size(); idx++) {
- thisNode = thisNode.subNodes.get(appInst.nodeSelection.get(idx));
+ if (selection != null) {
+ for (int idx = 0; idx < selection.size(); idx++) {
+ thisNode = thisNode.subNodes.get(selection.get(idx));
}
}
if (thisNode.subNodes.size() < 1) {
Intent textIntent = new Intent();
String docBuffer = thisNode.nodeName + "\n\n" +
thisNode.nodePayload;
textIntent.setClassName("com.matburt.mobileorg",
"com.matburt.mobileorg.SimpleTextDisplay");
textIntent.putExtra("txtValue", docBuffer);
startActivity(textIntent);
}
else {
- dispIntent.putIntegerArrayListExtra("nodePath", appInst.nodeSelection);
+ dispIntent.putIntegerArrayListExtra("nodePath", selection);
startActivityForResult(dispIntent, 1);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
MobileOrgApplication appInst = (MobileOrgApplication)this.getApplication();
appInst.nodeSelection.remove(appInst.nodeSelection.size()-1);
}
public boolean onShowSettings() {
Intent settingsIntent = new Intent();
settingsIntent.setClassName("com.matburt.mobileorg",
"com.matburt.mobileorg.SettingsActivity");
startActivity(settingsIntent);
return true;
}
public void runSynchronizer() {
final Synchronizer appSync = new Synchronizer(this);
Thread syncThread = new Thread() {
public void run() {
syncResults = appSync.pull();
syncHandler.post(syncUpdateResults);
}
};
syncThread.start();
syncDialog = ProgressDialog.show(this, "",
"Synchronizing. Please wait...", true);
}
public void postSynchronize() {
syncDialog.dismiss();
if (!this.syncResults) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Synchronization Failed, try again?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
runSynchronizer();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
else {
this.runParser();
this.onResume();
}
}
/* Handles item selections */
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MobileOrgActivity.OP_MENU_SYNC:
this.runSynchronizer();
return true;
case MobileOrgActivity.OP_MENU_SETTINGS:
return this.onShowSettings();
case MobileOrgActivity.OP_MENU_OUTLINE:
return true;
case MobileOrgActivity.OP_MENU_CAPTURE:
return true;
}
return false;
}
public ArrayList<String> getOrgFiles() {
ArrayList<String> allFiles = new ArrayList<String>();
SQLiteDatabase appdb = this.openOrCreateDatabase("MobileOrg",
MODE_PRIVATE, null);
Cursor result = appdb.rawQuery("SELECT file FROM files", null);
if (result != null) {
if (result.getCount() > 0) {
result.moveToFirst();
do {
Log.d(LT, "pulled " + result.getString(0));
allFiles.add(result.getString(0));
} while(result.moveToNext());
}
}
appdb.close();
result.close();
return allFiles;
//return (String[])allFiles.toArray(new String[0]);
}
public void initializeTables() {
SQLiteDatabase appdb = this.openOrCreateDatabase("MobileOrg",
MODE_PRIVATE, null);
appdb.execSQL("CREATE TABLE IF NOT EXISTS settings"
+ " (key VARCHAR, val VARCHAR)");
appdb.execSQL("CREATE TABLE IF NOT EXISTS files"
+ " (file VARCHAR, name VARCHAR,"
+ " checksum VARCHAR);");
appdb.close();
}
}
| false | true | public void onListItemClick(ListView l, View v, int position, long id) {
Intent dispIntent = new Intent();
MobileOrgApplication appInst = (MobileOrgApplication)this.getApplication();
dispIntent.setClassName("com.matburt.mobileorg",
"com.matburt.mobileorg.MobileOrgActivity");
if (appInst.nodeSelection == null) {
appInst.nodeSelection = new ArrayList<Integer>();
}
appInst.nodeSelection.add(new Integer(position));
Node thisNode = appInst.rootNode;
if (appInst.nodeSelection != null) {
for (int idx = 0; idx < appInst.nodeSelection.size(); idx++) {
thisNode = thisNode.subNodes.get(appInst.nodeSelection.get(idx));
}
}
if (thisNode.subNodes.size() < 1) {
Intent textIntent = new Intent();
String docBuffer = thisNode.nodeName + "\n\n" +
thisNode.nodePayload;
textIntent.setClassName("com.matburt.mobileorg",
"com.matburt.mobileorg.SimpleTextDisplay");
textIntent.putExtra("txtValue", docBuffer);
startActivity(textIntent);
}
else {
dispIntent.putIntegerArrayListExtra("nodePath", appInst.nodeSelection);
startActivityForResult(dispIntent, 1);
}
}
| public void onListItemClick(ListView l, View v, int position, long id) {
Intent dispIntent = new Intent();
MobileOrgApplication appInst = (MobileOrgApplication)this.getApplication();
dispIntent.setClassName("com.matburt.mobileorg",
"com.matburt.mobileorg.MobileOrgActivity");
if (appInst.nodeSelection == null) {
appInst.nodeSelection = new ArrayList<Integer>();
}
ArrayList<Integer> selection = new ArrayList<Integer>(appInst.nodeSelection);
selection.add(new Integer(position));
Node thisNode = appInst.rootNode;
if (selection != null) {
for (int idx = 0; idx < selection.size(); idx++) {
thisNode = thisNode.subNodes.get(selection.get(idx));
}
}
if (thisNode.subNodes.size() < 1) {
Intent textIntent = new Intent();
String docBuffer = thisNode.nodeName + "\n\n" +
thisNode.nodePayload;
textIntent.setClassName("com.matburt.mobileorg",
"com.matburt.mobileorg.SimpleTextDisplay");
textIntent.putExtra("txtValue", docBuffer);
startActivity(textIntent);
}
else {
dispIntent.putIntegerArrayListExtra("nodePath", selection);
startActivityForResult(dispIntent, 1);
}
}
|
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java b/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java
index 48d0dc844..536b1cfe4 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java
@@ -1,370 +1,371 @@
package org.apache.lucene.index;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.TextField;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
public class TestDocsAndPositions extends LuceneTestCase {
private String fieldName;
@Override
public void setUp() throws Exception {
super.setUp();
fieldName = "field" + random().nextInt();
}
/**
* Simple testcase for {@link DocsAndPositionsEnum}
*/
public void testPositionsSimple() throws IOException {
Directory directory = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), directory,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
for (int i = 0; i < 39; i++) {
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
doc.add(newField(fieldName, "1 2 3 4 5 6 7 8 9 10 "
+ "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 "
+ "1 2 3 4 5 6 7 8 9 10", customType));
writer.addDocument(doc);
}
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("1");
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) {
DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions(
atomicReaderContext.reader(), bytes, null);
assertNotNull(docsAndPosEnum);
if (atomicReaderContext.reader().maxDoc() == 0) {
continue;
}
final int advance = docsAndPosEnum.advance(random().nextInt(atomicReaderContext.reader().maxDoc()));
do {
String msg = "Advanced to: " + advance + " current doc: "
+ docsAndPosEnum.docID(); // TODO: + " usePayloads: " + usePayload;
assertEquals(msg, 4, docsAndPosEnum.freq());
assertEquals(msg, 0, docsAndPosEnum.nextPosition());
assertEquals(msg, 4, docsAndPosEnum.freq());
assertEquals(msg, 10, docsAndPosEnum.nextPosition());
assertEquals(msg, 4, docsAndPosEnum.freq());
assertEquals(msg, 20, docsAndPosEnum.nextPosition());
assertEquals(msg, 4, docsAndPosEnum.freq());
assertEquals(msg, 30, docsAndPosEnum.nextPosition());
} while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.close();
directory.close();
}
public DocsAndPositionsEnum getDocsAndPositions(AtomicReader reader,
BytesRef bytes, Bits liveDocs) throws IOException {
return reader.termPositionsEnum(null, fieldName, bytes, false);
}
/**
* this test indexes random numbers within a range into a field and checks
* their occurrences by searching for a number from that range selected at
* random. All positions for that number are saved up front and compared to
* the enums positions.
*/
public void testRandomPositions() throws IOException {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));
int numDocs = atLeast(47);
int max = 1051;
int term = random().nextInt(max);
Integer[][] positionsInDoc = new Integer[numDocs][];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
ArrayList<Integer> positions = new ArrayList<Integer>();
StringBuilder builder = new StringBuilder();
int num = atLeast(131);
for (int j = 0; j < num; j++) {
int nextInt = random().nextInt(max);
builder.append(nextInt).append(" ");
if (nextInt == term) {
positions.add(Integer.valueOf(j));
}
}
if (positions.size() == 0) {
builder.append(term);
positions.add(num);
}
doc.add(newField(fieldName, builder.toString(), customType));
positionsInDoc[i] = positions.toArray(new Integer[0]);
writer.addDocument(doc);
}
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) {
DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions(
atomicReaderContext.reader(), bytes, null);
assertNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.reader().maxDoc();
// initially advance or do next doc
if (random().nextBoolean()) {
initDoc = docsAndPosEnum.nextDoc();
} else {
initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc));
}
// now run through the scorer and check if all positions are there...
do {
int docID = docsAndPosEnum.docID();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
break;
}
Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID];
assertEquals(pos.length, docsAndPosEnum.freq());
// number of positions read should be random - don't read all of them
// allways
final int howMany = random().nextInt(20) == 0 ? pos.length
- random().nextInt(pos.length) : pos.length;
for (int j = 0; j < howMany; j++) {
assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: "
+ docID + " base: " + atomicReaderContext.docBase
+ " positions: " + Arrays.toString(pos) /* TODO: + " usePayloads: "
+ usePayload*/, pos[j].intValue(), docsAndPosEnum.nextPosition());
}
if (random().nextInt(10) == 0) { // once is a while advance
- docsAndPosEnum
- .advance(docID + 1 + random().nextInt((maxDoc - docID)));
+ if (docsAndPosEnum.advance(docID + 1 + random().nextInt((maxDoc - docID))) == DocIdSetIterator.NO_MORE_DOCS) {
+ break;
+ }
}
} while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.close();
dir.close();
}
public void testRandomDocs() throws IOException {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));
int numDocs = atLeast(49);
int max = 15678;
int term = random().nextInt(max);
int[] freqInDoc = new int[numDocs];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
StringBuilder builder = new StringBuilder();
for (int j = 0; j < 199; j++) {
int nextInt = random().nextInt(max);
builder.append(nextInt).append(' ');
if (nextInt == term) {
freqInDoc[i]++;
}
}
doc.add(newField(fieldName, builder.toString(), customType));
writer.addDocument(doc);
}
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext context : topReaderContext.leaves()) {
int maxDoc = context.reader().maxDoc();
DocsEnum docsEnum = _TestUtil.docs(random(), context.reader(), fieldName, bytes, null, null, true);
if (findNext(freqInDoc, context.docBase, context.docBase + maxDoc) == Integer.MAX_VALUE) {
assertNull(docsEnum);
continue;
}
assertNotNull(docsEnum);
docsEnum.nextDoc();
for (int j = 0; j < maxDoc; j++) {
if (freqInDoc[context.docBase + j] != 0) {
assertEquals(j, docsEnum.docID());
assertEquals(docsEnum.freq(), freqInDoc[context.docBase +j]);
if (i % 2 == 0 && random().nextInt(10) == 0) {
int next = findNext(freqInDoc, context.docBase+j+1, context.docBase + maxDoc) - context.docBase;
int advancedTo = docsEnum.advance(next);
if (next >= maxDoc) {
assertEquals(DocIdSetIterator.NO_MORE_DOCS, advancedTo);
} else {
assertTrue("advanced to: " +advancedTo + " but should be <= " + next, next >= advancedTo);
}
} else {
docsEnum.nextDoc();
}
}
}
assertEquals("docBase: " + context.docBase + " maxDoc: " + maxDoc + " " + docsEnum.getClass(), DocIdSetIterator.NO_MORE_DOCS, docsEnum.docID());
}
}
reader.close();
dir.close();
}
private static int findNext(int[] docs, int pos, int max) {
for (int i = pos; i < max; i++) {
if( docs[i] != 0) {
return i;
}
}
return Integer.MAX_VALUE;
}
/**
* tests retrieval of positions for terms that have a large number of
* occurrences to force test of buffer refill during positions iteration.
*/
public void testLargeNumberOfPositions() throws IOException {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
int howMany = 1000;
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
for (int i = 0; i < 39; i++) {
Document doc = new Document();
StringBuilder builder = new StringBuilder();
for (int j = 0; j < howMany; j++) {
if (j % 2 == 0) {
builder.append("even ");
} else {
builder.append("odd ");
}
}
doc.add(newField(fieldName, builder.toString(), customType));
writer.addDocument(doc);
}
// now do searches
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("even");
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) {
DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions(
atomicReaderContext.reader(), bytes, null);
assertNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.reader().maxDoc();
// initially advance or do next doc
if (random().nextBoolean()) {
initDoc = docsAndPosEnum.nextDoc();
} else {
initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc));
}
String msg = "Iteration: " + i + " initDoc: " + initDoc; // TODO: + " payloads: " + usePayload;
assertEquals(howMany / 2, docsAndPosEnum.freq());
for (int j = 0; j < howMany; j += 2) {
assertEquals("position missmatch index: " + j + " with freq: "
+ docsAndPosEnum.freq() + " -- " + msg, j,
docsAndPosEnum.nextPosition());
}
}
}
reader.close();
dir.close();
}
public void testDocsEnumStart() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
Document doc = new Document();
doc.add(newStringField("foo", "bar", Field.Store.NO));
writer.addDocument(doc);
DirectoryReader reader = writer.getReader();
AtomicReader r = getOnlySegmentReader(reader);
DocsEnum disi = _TestUtil.docs(random(), r, "foo", new BytesRef("bar"), null, null, false);
int docid = disi.docID();
assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS);
assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
// now reuse and check again
TermsEnum te = r.terms("foo").iterator(null);
assertTrue(te.seekExact(new BytesRef("bar"), true));
disi = _TestUtil.docs(random(), te, null, disi, false);
docid = disi.docID();
assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS);
assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
writer.close();
r.close();
dir.close();
}
public void testDocsAndPositionsEnumStart() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
Document doc = new Document();
doc.add(newTextField("foo", "bar", Field.Store.NO));
writer.addDocument(doc);
DirectoryReader reader = writer.getReader();
AtomicReader r = getOnlySegmentReader(reader);
DocsAndPositionsEnum disi = r.termPositionsEnum(null, "foo", new BytesRef("bar"), false);
int docid = disi.docID();
assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS);
assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
// now reuse and check again
TermsEnum te = r.terms("foo").iterator(null);
assertTrue(te.seekExact(new BytesRef("bar"), true));
disi = te.docsAndPositions(null, disi, false);
docid = disi.docID();
assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS);
assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
writer.close();
r.close();
dir.close();
}
}
| true | true | public void testRandomPositions() throws IOException {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));
int numDocs = atLeast(47);
int max = 1051;
int term = random().nextInt(max);
Integer[][] positionsInDoc = new Integer[numDocs][];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
ArrayList<Integer> positions = new ArrayList<Integer>();
StringBuilder builder = new StringBuilder();
int num = atLeast(131);
for (int j = 0; j < num; j++) {
int nextInt = random().nextInt(max);
builder.append(nextInt).append(" ");
if (nextInt == term) {
positions.add(Integer.valueOf(j));
}
}
if (positions.size() == 0) {
builder.append(term);
positions.add(num);
}
doc.add(newField(fieldName, builder.toString(), customType));
positionsInDoc[i] = positions.toArray(new Integer[0]);
writer.addDocument(doc);
}
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) {
DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions(
atomicReaderContext.reader(), bytes, null);
assertNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.reader().maxDoc();
// initially advance or do next doc
if (random().nextBoolean()) {
initDoc = docsAndPosEnum.nextDoc();
} else {
initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc));
}
// now run through the scorer and check if all positions are there...
do {
int docID = docsAndPosEnum.docID();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
break;
}
Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID];
assertEquals(pos.length, docsAndPosEnum.freq());
// number of positions read should be random - don't read all of them
// allways
final int howMany = random().nextInt(20) == 0 ? pos.length
- random().nextInt(pos.length) : pos.length;
for (int j = 0; j < howMany; j++) {
assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: "
+ docID + " base: " + atomicReaderContext.docBase
+ " positions: " + Arrays.toString(pos) /* TODO: + " usePayloads: "
+ usePayload*/, pos[j].intValue(), docsAndPosEnum.nextPosition());
}
if (random().nextInt(10) == 0) { // once is a while advance
docsAndPosEnum
.advance(docID + 1 + random().nextInt((maxDoc - docID)));
}
} while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.close();
dir.close();
}
| public void testRandomPositions() throws IOException {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));
int numDocs = atLeast(47);
int max = 1051;
int term = random().nextInt(max);
Integer[][] positionsInDoc = new Integer[numDocs][];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
ArrayList<Integer> positions = new ArrayList<Integer>();
StringBuilder builder = new StringBuilder();
int num = atLeast(131);
for (int j = 0; j < num; j++) {
int nextInt = random().nextInt(max);
builder.append(nextInt).append(" ");
if (nextInt == term) {
positions.add(Integer.valueOf(j));
}
}
if (positions.size() == 0) {
builder.append(term);
positions.add(num);
}
doc.add(newField(fieldName, builder.toString(), customType));
positionsInDoc[i] = positions.toArray(new Integer[0]);
writer.addDocument(doc);
}
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) {
DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions(
atomicReaderContext.reader(), bytes, null);
assertNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.reader().maxDoc();
// initially advance or do next doc
if (random().nextBoolean()) {
initDoc = docsAndPosEnum.nextDoc();
} else {
initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc));
}
// now run through the scorer and check if all positions are there...
do {
int docID = docsAndPosEnum.docID();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
break;
}
Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID];
assertEquals(pos.length, docsAndPosEnum.freq());
// number of positions read should be random - don't read all of them
// allways
final int howMany = random().nextInt(20) == 0 ? pos.length
- random().nextInt(pos.length) : pos.length;
for (int j = 0; j < howMany; j++) {
assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: "
+ docID + " base: " + atomicReaderContext.docBase
+ " positions: " + Arrays.toString(pos) /* TODO: + " usePayloads: "
+ usePayload*/, pos[j].intValue(), docsAndPosEnum.nextPosition());
}
if (random().nextInt(10) == 0) { // once is a while advance
if (docsAndPosEnum.advance(docID + 1 + random().nextInt((maxDoc - docID))) == DocIdSetIterator.NO_MORE_DOCS) {
break;
}
}
} while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.close();
dir.close();
}
|
diff --git a/src/com/todotxt/todotxttouch/TodoTxtTouch.java b/src/com/todotxt/todotxttouch/TodoTxtTouch.java
index 078b05d..0f203b9 100644
--- a/src/com/todotxt/todotxttouch/TodoTxtTouch.java
+++ b/src/com/todotxt/todotxttouch/TodoTxtTouch.java
@@ -1,631 +1,629 @@
package com.todotxt.todotxttouch;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.SpannableString;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.dropbox.client.DropboxClient;
import com.dropbox.client.DropboxClientHelper;
import com.todotxt.todotxttouch.Util.OnMultiChoiceDialogListener;
public class TodoTxtTouch extends ListActivity implements
OnSharedPreferenceChangeListener {
private final static String TAG = TodoTxtTouch.class.getSimpleName();
private final static int SORT_PRIO = 0;
private final static int SORT_ID = 1;
private final static int SORT_TEXT = 2;
private ProgressDialog m_ProgressDialog = null;
private ArrayList<Task> m_tasks = new ArrayList<Task>();
private TaskAdapter m_adapter;
private TodoApplication m_app;
// filter variables
private ArrayList<String> m_prios = new ArrayList<String>();
private ArrayList<String> m_contexts = new ArrayList<String>();
private ArrayList<String> m_projects = new ArrayList<String>();
private String m_search;
private int m_pos = Constants.INVALID_POSITION;
private int m_sort = SORT_PRIO;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
m_app = (TodoApplication) getApplication();
m_app.m_prefs.registerOnSharedPreferenceChangeListener(this);
m_adapter = new TaskAdapter(this, R.layout.list_item, m_tasks,
getLayoutInflater());
setListAdapter(this.m_adapter);
// FIXME adapter implements Filterable?
ListView lv = getListView();
lv.setTextFilterEnabled(true);
getListView().setOnCreateContextMenuListener(this);
boolean firstrun = m_app.m_prefs.getBoolean(Constants.PREF_FIRSTRUN,
true);
if (firstrun) {
Log.i(TAG, "Initializing app");
Editor editor = m_app.m_prefs.edit();
editor.putBoolean(Constants.PREF_FIRSTRUN, false);
editor.commit();
populateFromExternal();
} else {
populateFromFile();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
m_app.m_prefs.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
protected void onResume() {
super.onResume();
setFilteredTasks(true);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Log.v(TAG, "onSharedPreferenceChanged key=" + key);
if (Constants.PREF_ACCESSTOKEN_SECRET.equals(key)) {
Log.i(TAG, "New access token secret. Syncing!");
populateFromExternal();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("sort", m_sort);
}
@Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
m_sort = state.getInt("sort");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_long, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
Log.v(TAG, "onContextItemSelected");
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
int menuid = item.getItemId();
final int pos;
if (m_pos != Constants.INVALID_POSITION) {
pos = m_pos;
m_pos = Constants.INVALID_POSITION;
} else {
pos = menuInfo.position;
}
if (menuid == R.id.update) {
Log.v(TAG, "update");
final Task backup = m_adapter.getItem(pos);
Intent intent = new Intent(this, AddTask.class);
intent.putExtra(Constants.EXTRA_TASK, (Serializable) backup);
startActivity(intent);
} else if (menuid == R.id.delete) {
Log.v(TAG, "delete");
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Task task = m_adapter.getItem(pos);
new AsyncTask<Void, Void, Boolean>() {
protected void onPreExecute() {
m_ProgressDialog = ProgressDialog.show(
TodoTxtTouch.this, "Delete",
"Please wait...", true);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
DropboxClient client = m_app
.getClient(TodoTxtTouch.this);
if (client != null) {
return DropboxUtil.updateTask(client,
TaskHelper.NONE, "", task);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return false;
}
protected void onPostExecute(Boolean result) {
m_ProgressDialog.dismiss();
if (result) {
Util.showToastLong(
TodoTxtTouch.this,
"Deleted task "
+ TaskHelper.toFileFormat(task));
} else {
Util.showToastLong(
TodoTxtTouch.this,
"Could not delete task "
+ TaskHelper.toFileFormat(task));
}
setFilteredTasks(true);
}
}.execute();
}
};
Util.showConfirmationDialog(this, R.string.areyousure, listener);
} else if (menuid == R.id.done) {
Log.v(TAG, "done");
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Task task = m_adapter.getItem(pos);
new AsyncTask<Void, Void, Boolean>() {
protected void onPreExecute() {
m_ProgressDialog = ProgressDialog.show(
TodoTxtTouch.this, "Done",
"Please wait...", true);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
if (task.text.startsWith(TaskHelper.COMPLETED)) {
return true;
} else {
String format = TaskHelper.DATEFORMAT
.format(new Date());
String text = TaskHelper.COMPLETED + format
+ task.text;
DropboxClient client = m_app
.getClient(TodoTxtTouch.this);
if (client != null) {
return DropboxUtil.updateTask(client,
TaskHelper.NONE, text, task);
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return false;
}
protected void onPostExecute(Boolean result) {
m_ProgressDialog.dismiss();
if (result) {
Util.showToastLong(
TodoTxtTouch.this,
"Completed task "
+ TaskHelper.toFileFormat(task));
} else {
Util.showToastLong(
TodoTxtTouch.this,
"Could not complete task "
+ TaskHelper.toFileFormat(task));
}
setFilteredTasks(true);
}
}.execute();
}
};
Util.showConfirmationDialog(this, R.string.areyousure, listener);
} else if (menuid == R.id.priority) {
Log.v(TAG, "priority");
- final String[] prioArr = new String['Z' - 'A' + 1];
- prioArr[0] = "" + TaskHelper.NONE;
- for (char c = 0; c < prioArr.length; c++) {
- prioArr[1 + c] = "" + ('A' + c);
- }
+ final String[] prioArr = { "" + TaskHelper.NONE, "A", "B", "C" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setSingleChoiceItems(prioArr, -1, new OnClickListener() {
+ builder.setSingleChoiceItems(prioArr, 0, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, final int which) {
final Task task = m_adapter.getItem(pos);
+ dialog.dismiss();
new AsyncTask<Void, Void, Boolean>() {
protected void onPreExecute() {
m_ProgressDialog = ProgressDialog.show(
- TodoTxtTouch.this, "Priority",
+ TodoTxtTouch.this, "Setting Priority",
"Please wait...", true);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
DropboxClient client = m_app
.getClient(TodoTxtTouch.this);
if (client != null) {
return DropboxUtil.updateTask(client,
prioArr[which].charAt(0),
task.text, task);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return false;
}
protected void onPostExecute(Boolean result) {
m_ProgressDialog.dismiss();
if (result) {
Util.showToastLong(
TodoTxtTouch.this,
"Prioritized task "
- + TaskHelper.toFileFormat(task));
+ + task.text);
} else {
Util.showToastLong(TodoTxtTouch.this,
"Could not prioritize task "
+ TaskHelper.toFileFormat(task));
}
setFilteredTasks(true);
}
}.execute();
}
});
+ builder.show();
}
return super.onContextItemSelected(item);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
Log.v(TAG, "onMenuItemSelected: " + item.getItemId());
switch (item.getItemId()) {
case R.id.add_new:
Intent intent = new Intent(this, AddTask.class);
startActivity(intent);
break;
case R.id.sync:
Log.v(TAG, "onMenuItemSelected: sync");
populateFromExternal();
break;
case R.id.preferences:
Intent settingsActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(settingsActivity);
break;
case R.id.filter:
Intent i = new Intent(this, Filter.class);
i.putStringArrayListExtra(Constants.EXTRA_PRIORITIES,
TaskHelper.getPrios(m_tasks));
i.putStringArrayListExtra(Constants.EXTRA_PROJECTS,
TaskHelper.getProjects(m_tasks));
i.putStringArrayListExtra(Constants.EXTRA_CONTEXTS,
TaskHelper.getContexts(m_tasks));
i.putStringArrayListExtra(Constants.EXTRA_PRIORITIES_SELECTED,
m_prios);
i.putStringArrayListExtra(Constants.EXTRA_PROJECTS_SELECTED,
m_projects);
i.putStringArrayListExtra(Constants.EXTRA_CONTEXTS_SELECTED,
m_contexts);
i.putExtra(Constants.EXTRA_SEARCH, m_search);
startActivityIfNeeded(i, 0);
break;
case R.id.sort:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setSingleChoiceItems(R.array.sort, m_sort,
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.v(TAG, "onClick " + which);
m_sort = which;
dialog.dismiss();
setFilteredTasks(false);
}
});
builder.show();
break;
default:
return super.onMenuItemSelected(featureId, item);
}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v(TAG, "onActivityResult: resultCode=" + resultCode + " i=" + data);
if (resultCode == Activity.RESULT_OK) {
m_prios = data.getStringArrayListExtra(Constants.EXTRA_PRIORITIES);
m_projects = data.getStringArrayListExtra(Constants.EXTRA_PROJECTS);
m_contexts = data.getStringArrayListExtra(Constants.EXTRA_CONTEXTS);
m_search = data.getStringExtra(Constants.EXTRA_SEARCH);
setFilteredTasks(false);
}
}
@Override
protected Dialog onCreateDialog(int id) {
final Dialog d;
if (R.id.priority == id) {
final List<String> pStrs = TaskHelper.getPrios(m_tasks);
int size = pStrs.size();
boolean[] values = new boolean[size];
for (String prio : m_prios) {
int index = pStrs.indexOf(prio);
if (index != -1) {
values[index] = true;
}
}
d = Util.createMultiChoiceDialog(this,
pStrs.toArray(new String[size]), values, null, null,
new OnMultiChoiceDialogListener() {
@Override
public void onClick(boolean[] selected) {
m_prios.clear();
for (int i = 0; i < selected.length; i++) {
if (selected[i]) {
m_prios.add(pStrs.get(i));
}
}
setFilteredTasks(false);
removeDialog(R.id.priority);
}
});
d.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
removeDialog(R.id.priority);
}
});
return d;
} else {
return null;
}
}
private void clearFilter() {
m_prios = new ArrayList<String>(); // Collections.emptyList();
m_contexts = new ArrayList<String>(); // Collections.emptyList();
m_projects = new ArrayList<String>(); // Collections.emptyList();
m_search = "";
}
private void setFilteredTasks(boolean reload) {
if (reload) {
try {
m_tasks = TodoUtil.loadTasksFromFile();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
List<Task> tasks = m_tasks;
if (m_prios.size() > 0) {
tasks = TaskHelper.getByPrio(tasks, m_prios);
}
if (m_contexts.size() > 0) {
tasks = TaskHelper.getByContext(tasks, m_contexts);
}
if (m_projects.size() > 0) {
tasks = TaskHelper.getByProject(tasks, m_projects);
}
if (!Util.isEmpty(m_search)) {
tasks = TaskHelper.getByTextIgnoreCase(tasks, m_search);
}
if (tasks != null) {
if (m_sort == SORT_PRIO) {
Collections.sort(tasks, TaskHelper.byPrio);
} else if (m_sort == SORT_ID) {
Collections.sort(tasks, TaskHelper.byId);
} else if (m_sort == SORT_TEXT) {
Collections.sort(tasks, TaskHelper.byText);
}
m_adapter.clear();
int size = tasks.size();
for (int i = 0; i < size; i++) {
m_adapter.add(tasks.get(i));
}
m_adapter.notifyDataSetChanged();
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
m_pos = position;
openContextMenu(getListView());
}
private void populateFromFile() {
Log.d(TAG, "populateFromFile");
clearFilter();
setFilteredTasks(true);
}
private void populateFromExternal() {
new AsyncTask<Void, Void, Boolean>() {
@Override
protected void onPreExecute() {
m_ProgressDialog = ProgressDialog.show(TodoTxtTouch.this,
"Please wait...", "Retrieving todo.txt ...", true);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
DropboxClient client = m_app.getClient(TodoTxtTouch.this);
if (client != null) {
try {
InputStream is = DropboxClientHelper.getFileStream(
client, Constants.REMOTE_FILE);
m_tasks = TodoUtil.loadTasksFromStream(is);
} catch (Exception e) {
Log.w(TAG,
"Failed to fetch todo.txt file while initializing Dropbox support! "
+ e.getMessage());
if (!Constants.TODOFILE.exists()) {
Util.createParentDirectory(Constants.TODOFILE);
Constants.TODOFILE.createNewFile();
}
DropboxClientHelper.putFile(client, "/",
Constants.TODOFILE);
runOnUiThread(new Runnable() {
@Override
public void run() {
Util.showToastLong(TodoTxtTouch.this,
R.string.initialized_dropbox);
}
});
}
} else {
Log.w(TAG, "Could not get tasks!");
}
TodoUtil.writeToFile(m_tasks, Constants.TODOFILE);
return true;
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
m_ProgressDialog.dismiss();
clearFilter();
setFilteredTasks(false);
Log.d(TAG, "populateFromUrl size=" + m_tasks.size());
if (!result) {
Util.showToastLong(TodoTxtTouch.this, "Sync failed");
} else {
Util.showToastShort(TodoTxtTouch.this, m_tasks.size()
+ " items");
}
}
}.execute();
}
public class TaskAdapter extends ArrayAdapter<Task> {
private ArrayList<Task> items;
private LayoutInflater m_inflater;
public TaskAdapter(Context context, int textViewResourceId,
ArrayList<Task> items, LayoutInflater inflater) {
super(context, textViewResourceId, items);
this.items = items;
this.m_inflater = inflater;
}
@Override
public long getItemId(int position) {
return items.get(position).id;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = m_inflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.taskid = (TextView) convertView
.findViewById(R.id.taskid);
holder.taskprio = (TextView) convertView
.findViewById(R.id.taskprio);
holder.tasktext = (TextView) convertView
.findViewById(R.id.tasktext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Task task = items.get(position);
if (task != null) {
holder.taskid.setText(String.format("%02d", task.id + 1));
if (TaskHelper.toString(task.prio).equalsIgnoreCase("")) {
holder.taskprio.setText(" ");
} else {
holder.taskprio.setText("("
+ TaskHelper.toString(task.prio) + ")");
}
SpannableString ss = new SpannableString(task.text);
Util.setBold(ss, TaskHelper.getProjects(task.text));
Util.setBold(ss, TaskHelper.getContexts(task.text));
holder.tasktext.setText(ss);
Resources res = getResources();
switch (task.prio) {
case 'A':
holder.taskprio.setTextColor(res.getColor(R.color.gold));
break;
case 'B':
holder.taskprio.setTextColor(res.getColor(R.color.green));
break;
case 'C':
holder.taskprio.setTextColor(res.getColor(R.color.blue));
break;
default:
holder.taskprio.setTextColor(res.getColor(R.color.black));
}
// hide ID unless it's highlighted for a cleaner interface
holder.taskid.setTextColor(res.getColor(R.color.black));
}
return convertView;
}
}
private static class ViewHolder {
private TextView taskid;
private TextView taskprio;
private TextView tasktext;
}
}
| false | true | public boolean onContextItemSelected(MenuItem item) {
Log.v(TAG, "onContextItemSelected");
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
int menuid = item.getItemId();
final int pos;
if (m_pos != Constants.INVALID_POSITION) {
pos = m_pos;
m_pos = Constants.INVALID_POSITION;
} else {
pos = menuInfo.position;
}
if (menuid == R.id.update) {
Log.v(TAG, "update");
final Task backup = m_adapter.getItem(pos);
Intent intent = new Intent(this, AddTask.class);
intent.putExtra(Constants.EXTRA_TASK, (Serializable) backup);
startActivity(intent);
} else if (menuid == R.id.delete) {
Log.v(TAG, "delete");
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Task task = m_adapter.getItem(pos);
new AsyncTask<Void, Void, Boolean>() {
protected void onPreExecute() {
m_ProgressDialog = ProgressDialog.show(
TodoTxtTouch.this, "Delete",
"Please wait...", true);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
DropboxClient client = m_app
.getClient(TodoTxtTouch.this);
if (client != null) {
return DropboxUtil.updateTask(client,
TaskHelper.NONE, "", task);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return false;
}
protected void onPostExecute(Boolean result) {
m_ProgressDialog.dismiss();
if (result) {
Util.showToastLong(
TodoTxtTouch.this,
"Deleted task "
+ TaskHelper.toFileFormat(task));
} else {
Util.showToastLong(
TodoTxtTouch.this,
"Could not delete task "
+ TaskHelper.toFileFormat(task));
}
setFilteredTasks(true);
}
}.execute();
}
};
Util.showConfirmationDialog(this, R.string.areyousure, listener);
} else if (menuid == R.id.done) {
Log.v(TAG, "done");
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Task task = m_adapter.getItem(pos);
new AsyncTask<Void, Void, Boolean>() {
protected void onPreExecute() {
m_ProgressDialog = ProgressDialog.show(
TodoTxtTouch.this, "Done",
"Please wait...", true);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
if (task.text.startsWith(TaskHelper.COMPLETED)) {
return true;
} else {
String format = TaskHelper.DATEFORMAT
.format(new Date());
String text = TaskHelper.COMPLETED + format
+ task.text;
DropboxClient client = m_app
.getClient(TodoTxtTouch.this);
if (client != null) {
return DropboxUtil.updateTask(client,
TaskHelper.NONE, text, task);
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return false;
}
protected void onPostExecute(Boolean result) {
m_ProgressDialog.dismiss();
if (result) {
Util.showToastLong(
TodoTxtTouch.this,
"Completed task "
+ TaskHelper.toFileFormat(task));
} else {
Util.showToastLong(
TodoTxtTouch.this,
"Could not complete task "
+ TaskHelper.toFileFormat(task));
}
setFilteredTasks(true);
}
}.execute();
}
};
Util.showConfirmationDialog(this, R.string.areyousure, listener);
} else if (menuid == R.id.priority) {
Log.v(TAG, "priority");
final String[] prioArr = new String['Z' - 'A' + 1];
prioArr[0] = "" + TaskHelper.NONE;
for (char c = 0; c < prioArr.length; c++) {
prioArr[1 + c] = "" + ('A' + c);
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setSingleChoiceItems(prioArr, -1, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, final int which) {
final Task task = m_adapter.getItem(pos);
new AsyncTask<Void, Void, Boolean>() {
protected void onPreExecute() {
m_ProgressDialog = ProgressDialog.show(
TodoTxtTouch.this, "Priority",
"Please wait...", true);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
DropboxClient client = m_app
.getClient(TodoTxtTouch.this);
if (client != null) {
return DropboxUtil.updateTask(client,
prioArr[which].charAt(0),
task.text, task);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return false;
}
protected void onPostExecute(Boolean result) {
m_ProgressDialog.dismiss();
if (result) {
Util.showToastLong(
TodoTxtTouch.this,
"Prioritized task "
+ TaskHelper.toFileFormat(task));
} else {
Util.showToastLong(TodoTxtTouch.this,
"Could not prioritize task "
+ TaskHelper.toFileFormat(task));
}
setFilteredTasks(true);
}
}.execute();
}
});
}
return super.onContextItemSelected(item);
}
| public boolean onContextItemSelected(MenuItem item) {
Log.v(TAG, "onContextItemSelected");
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
int menuid = item.getItemId();
final int pos;
if (m_pos != Constants.INVALID_POSITION) {
pos = m_pos;
m_pos = Constants.INVALID_POSITION;
} else {
pos = menuInfo.position;
}
if (menuid == R.id.update) {
Log.v(TAG, "update");
final Task backup = m_adapter.getItem(pos);
Intent intent = new Intent(this, AddTask.class);
intent.putExtra(Constants.EXTRA_TASK, (Serializable) backup);
startActivity(intent);
} else if (menuid == R.id.delete) {
Log.v(TAG, "delete");
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Task task = m_adapter.getItem(pos);
new AsyncTask<Void, Void, Boolean>() {
protected void onPreExecute() {
m_ProgressDialog = ProgressDialog.show(
TodoTxtTouch.this, "Delete",
"Please wait...", true);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
DropboxClient client = m_app
.getClient(TodoTxtTouch.this);
if (client != null) {
return DropboxUtil.updateTask(client,
TaskHelper.NONE, "", task);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return false;
}
protected void onPostExecute(Boolean result) {
m_ProgressDialog.dismiss();
if (result) {
Util.showToastLong(
TodoTxtTouch.this,
"Deleted task "
+ TaskHelper.toFileFormat(task));
} else {
Util.showToastLong(
TodoTxtTouch.this,
"Could not delete task "
+ TaskHelper.toFileFormat(task));
}
setFilteredTasks(true);
}
}.execute();
}
};
Util.showConfirmationDialog(this, R.string.areyousure, listener);
} else if (menuid == R.id.done) {
Log.v(TAG, "done");
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Task task = m_adapter.getItem(pos);
new AsyncTask<Void, Void, Boolean>() {
protected void onPreExecute() {
m_ProgressDialog = ProgressDialog.show(
TodoTxtTouch.this, "Done",
"Please wait...", true);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
if (task.text.startsWith(TaskHelper.COMPLETED)) {
return true;
} else {
String format = TaskHelper.DATEFORMAT
.format(new Date());
String text = TaskHelper.COMPLETED + format
+ task.text;
DropboxClient client = m_app
.getClient(TodoTxtTouch.this);
if (client != null) {
return DropboxUtil.updateTask(client,
TaskHelper.NONE, text, task);
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return false;
}
protected void onPostExecute(Boolean result) {
m_ProgressDialog.dismiss();
if (result) {
Util.showToastLong(
TodoTxtTouch.this,
"Completed task "
+ TaskHelper.toFileFormat(task));
} else {
Util.showToastLong(
TodoTxtTouch.this,
"Could not complete task "
+ TaskHelper.toFileFormat(task));
}
setFilteredTasks(true);
}
}.execute();
}
};
Util.showConfirmationDialog(this, R.string.areyousure, listener);
} else if (menuid == R.id.priority) {
Log.v(TAG, "priority");
final String[] prioArr = { "" + TaskHelper.NONE, "A", "B", "C" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setSingleChoiceItems(prioArr, 0, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, final int which) {
final Task task = m_adapter.getItem(pos);
dialog.dismiss();
new AsyncTask<Void, Void, Boolean>() {
protected void onPreExecute() {
m_ProgressDialog = ProgressDialog.show(
TodoTxtTouch.this, "Setting Priority",
"Please wait...", true);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
DropboxClient client = m_app
.getClient(TodoTxtTouch.this);
if (client != null) {
return DropboxUtil.updateTask(client,
prioArr[which].charAt(0),
task.text, task);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return false;
}
protected void onPostExecute(Boolean result) {
m_ProgressDialog.dismiss();
if (result) {
Util.showToastLong(
TodoTxtTouch.this,
"Prioritized task "
+ task.text);
} else {
Util.showToastLong(TodoTxtTouch.this,
"Could not prioritize task "
+ TaskHelper.toFileFormat(task));
}
setFilteredTasks(true);
}
}.execute();
}
});
builder.show();
}
return super.onContextItemSelected(item);
}
|
diff --git a/src/main/java/net/pms/io/ProcessWrapperImpl.java b/src/main/java/net/pms/io/ProcessWrapperImpl.java
index eaf527e3f..dfe437245 100644
--- a/src/main/java/net/pms/io/ProcessWrapperImpl.java
+++ b/src/main/java/net/pms/io/ProcessWrapperImpl.java
@@ -1,308 +1,309 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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; version 2
* of the License only.
*
* 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 net.pms.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.pms.PMS;
import net.pms.encoders.AviDemuxerInputStream;
import net.pms.util.ProcessUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProcessWrapperImpl extends Thread implements ProcessWrapper {
private static final Logger LOGGER = LoggerFactory.getLogger(ProcessWrapperImpl.class);
@Override
public String toString() {
return super.getName();
}
private boolean success;
public boolean isSuccess() {
return success;
}
private String cmdLine;
private Process process;
private OutputConsumer outConsumer;
private OutputConsumer stderrConsumer;
private OutputParams params;
private boolean destroyed;
private String[] cmdArray;
private boolean nullable;
private ArrayList<ProcessWrapper> attachedProcesses;
private BufferedOutputFile bo = null;
private boolean keepStdout;
private boolean keepStderr;
private static int processCounter = 0;
public ProcessWrapperImpl(String cmdArray[], OutputParams params) {
this(cmdArray, params, false, false);
}
public ProcessWrapperImpl(String cmdArray[], OutputParams params, boolean keepOutput) {
this(cmdArray, params, keepOutput, keepOutput);
}
public ProcessWrapperImpl(String cmdArray[], OutputParams params, boolean keepStdout, boolean keepStderr) {
super();
// Determine a suitable thread name for this process:
// use the command name, but remove its path first.
String threadName = cmdArray[0];
if (threadName.indexOf("/") >= 0) {
threadName = threadName.substring(threadName.lastIndexOf("/") + 1);
}
if (threadName.indexOf("\\") >= 0) {
threadName = threadName.substring(threadName.lastIndexOf("\\") + 1);
}
setName(threadName + "-" + getProcessCounter());
File exec = new File(cmdArray[0]);
if (exec.exists() && exec.isFile()) {
cmdArray[0] = exec.getAbsolutePath();
}
this.cmdArray = cmdArray;
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < cmdArray.length; i++) {
if (i > 0) {
sb.append(" ");
}
if (cmdArray[i] != null && cmdArray[i].indexOf(" ") >= 0) {
sb.append("\"" + cmdArray[i] + "\"");
} else {
sb.append(cmdArray[i]);
}
}
cmdLine = sb.toString();
this.params = params;
this.keepStdout = keepStdout;
this.keepStderr = keepStderr;
attachedProcesses = new ArrayList<ProcessWrapper>();
}
private synchronized int getProcessCounter() {
return processCounter++;
}
public void attachProcess(ProcessWrapper process) {
attachedProcesses.add(process);
}
public void run() {
ProcessBuilder pb = new ProcessBuilder(cmdArray);
try {
LOGGER.debug("Starting " + cmdLine);
if (params.outputFile != null && params.outputFile.getParentFile().isDirectory()) {
pb.directory(params.outputFile.getParentFile());
}
if (params.workDir != null && params.workDir.isDirectory()) {
pb.directory(params.workDir);
}
if (params.env != null && !params.env.isEmpty()) {
Map<String,String> environment = pb.environment();
- params.env.put("PATH", params.env.get("PATH") + File.pathSeparator + environment.get("PATH"));
+ String PATH = params.env.get("PATH") + File.pathSeparator + environment.get("PATH");
environment.putAll(params.env);
+ environment.put("PATH", PATH);
}
process = pb.start();
PMS.get().currentProcesses.add(process);
stderrConsumer = keepStderr
? new OutputTextConsumer(process.getErrorStream(), true)
: new OutputTextLogger(process.getErrorStream());
stderrConsumer.start();
outConsumer = null;
if (params.outputFile != null) {
LOGGER.debug("Writing in " + params.outputFile.getAbsolutePath());
outConsumer = keepStdout
? new OutputTextConsumer(process.getInputStream(), false)
: new OutputTextLogger(process.getInputStream());
} else if (params.input_pipes[0] != null) {
LOGGER.debug("Reading pipe: " + params.input_pipes[0].getInputPipe());
bo = params.input_pipes[0].getDirectBuffer();
if (bo == null || params.losslessaudio || params.lossyaudio || params.no_videoencode) {
InputStream is = params.input_pipes[0].getInputStream();
outConsumer = new OutputBufferConsumer((params.avidemux) ? new AviDemuxerInputStream(is, params, attachedProcesses) : is, params);
bo = outConsumer.getBuffer();
}
bo.attachThread(this);
new OutputTextLogger(process.getInputStream()).start();
} else if (params.log) {
outConsumer = keepStdout
? new OutputTextConsumer(process.getInputStream(), true)
: new OutputTextLogger(process.getInputStream());
} else {
outConsumer = new OutputBufferConsumer(process.getInputStream(), params);
bo = outConsumer.getBuffer();
bo.attachThread(this);
}
if (params.stdin != null) {
params.stdin.push(process.getOutputStream());
}
if (outConsumer != null) {
outConsumer.start();
}
Integer pid = ProcessUtil.getProcessID(process);
if (pid != null) {
LOGGER.debug("Unix process ID (" + cmdArray[0] + "): " + pid);
}
ProcessUtil.waitFor(process);
try {
if (outConsumer != null) {
outConsumer.join(1000);
}
} catch (InterruptedException e) {
}
if (bo != null) {
bo.close();
}
} catch (Exception e) {
LOGGER.error("Fatal error in process initialization: ", e);
stopProcess();
} finally {
if (!destroyed && !params.noexitcheck) {
try {
success = true;
if (process != null && process.exitValue() != 0) {
LOGGER.info("Process " + cmdArray[0] + " has a return code of " + process.exitValue() + "! Maybe an error occurred... check the log file");
success = false;
}
} catch (IllegalThreadStateException itse) {
LOGGER.error("An error occurred", itse);
}
}
if (attachedProcesses != null) {
for (ProcessWrapper pw : attachedProcesses) {
if (pw != null) {
pw.stopProcess();
}
}
}
PMS.get().currentProcesses.remove(process);
}
}
/**
* Same as {@link #start()}, merely making the intention explicit in the
* method name.
* @see #runInSameThread()
*/
public void runInNewThread() {
this.start();
}
/**
* Same as {@link #run()}, merely making the intention explicit in the
* method name.
* @see #runInNewThread()
*/
public void runInSameThread() {
this.run();
}
public InputStream getInputStream(long seek) throws IOException {
if (bo != null) {
return bo.getInputStream(seek);
} else if (outConsumer != null && outConsumer.getBuffer() != null) {
return outConsumer.getBuffer().getInputStream(seek);
} else if (params.outputFile != null) {
BlockerFileInputStream fIn = new BlockerFileInputStream(this, params.outputFile, params.minFileSize);
fIn.skip(seek);
return fIn;
}
return null;
}
public List<String> getOtherResults() {
if (outConsumer == null) {
return null;
}
try {
outConsumer.join(1000);
} catch (InterruptedException e) {
}
return outConsumer.getResults();
}
public List<String> getResults() {
try {
stderrConsumer.join(1000);
} catch (InterruptedException e) {
}
return stderrConsumer.getResults();
}
public synchronized void stopProcess() {
if (!destroyed) {
destroyed = true;
if (process != null) {
Integer pid = ProcessUtil.getProcessID(process);
if (pid != null) {
LOGGER.debug("Stopping Unix process " + pid + ": " + this);
} else {
LOGGER.debug("Stopping process: " + this);
}
ProcessUtil.destroy(process);
}
if (attachedProcesses != null) {
for (ProcessWrapper pw : attachedProcesses) {
if (pw != null) {
pw.stopProcess();
}
}
}
if (outConsumer != null && outConsumer.getBuffer() != null) {
outConsumer.getBuffer().reset();
}
}
}
public boolean isDestroyed() {
return destroyed;
}
public boolean isReadyToStop() {
return nullable;
}
public void setReadyToStop(boolean nullable) {
if (nullable != this.nullable) {
LOGGER.trace("Ready to Stop: " + nullable);
}
this.nullable = nullable;
}
}
| false | true | public void run() {
ProcessBuilder pb = new ProcessBuilder(cmdArray);
try {
LOGGER.debug("Starting " + cmdLine);
if (params.outputFile != null && params.outputFile.getParentFile().isDirectory()) {
pb.directory(params.outputFile.getParentFile());
}
if (params.workDir != null && params.workDir.isDirectory()) {
pb.directory(params.workDir);
}
if (params.env != null && !params.env.isEmpty()) {
Map<String,String> environment = pb.environment();
params.env.put("PATH", params.env.get("PATH") + File.pathSeparator + environment.get("PATH"));
environment.putAll(params.env);
}
process = pb.start();
PMS.get().currentProcesses.add(process);
stderrConsumer = keepStderr
? new OutputTextConsumer(process.getErrorStream(), true)
: new OutputTextLogger(process.getErrorStream());
stderrConsumer.start();
outConsumer = null;
if (params.outputFile != null) {
LOGGER.debug("Writing in " + params.outputFile.getAbsolutePath());
outConsumer = keepStdout
? new OutputTextConsumer(process.getInputStream(), false)
: new OutputTextLogger(process.getInputStream());
} else if (params.input_pipes[0] != null) {
LOGGER.debug("Reading pipe: " + params.input_pipes[0].getInputPipe());
bo = params.input_pipes[0].getDirectBuffer();
if (bo == null || params.losslessaudio || params.lossyaudio || params.no_videoencode) {
InputStream is = params.input_pipes[0].getInputStream();
outConsumer = new OutputBufferConsumer((params.avidemux) ? new AviDemuxerInputStream(is, params, attachedProcesses) : is, params);
bo = outConsumer.getBuffer();
}
bo.attachThread(this);
new OutputTextLogger(process.getInputStream()).start();
} else if (params.log) {
outConsumer = keepStdout
? new OutputTextConsumer(process.getInputStream(), true)
: new OutputTextLogger(process.getInputStream());
} else {
outConsumer = new OutputBufferConsumer(process.getInputStream(), params);
bo = outConsumer.getBuffer();
bo.attachThread(this);
}
if (params.stdin != null) {
params.stdin.push(process.getOutputStream());
}
if (outConsumer != null) {
outConsumer.start();
}
Integer pid = ProcessUtil.getProcessID(process);
if (pid != null) {
LOGGER.debug("Unix process ID (" + cmdArray[0] + "): " + pid);
}
ProcessUtil.waitFor(process);
try {
if (outConsumer != null) {
outConsumer.join(1000);
}
} catch (InterruptedException e) {
}
if (bo != null) {
bo.close();
}
} catch (Exception e) {
LOGGER.error("Fatal error in process initialization: ", e);
stopProcess();
} finally {
if (!destroyed && !params.noexitcheck) {
try {
success = true;
if (process != null && process.exitValue() != 0) {
LOGGER.info("Process " + cmdArray[0] + " has a return code of " + process.exitValue() + "! Maybe an error occurred... check the log file");
success = false;
}
} catch (IllegalThreadStateException itse) {
LOGGER.error("An error occurred", itse);
}
}
if (attachedProcesses != null) {
for (ProcessWrapper pw : attachedProcesses) {
if (pw != null) {
pw.stopProcess();
}
}
}
PMS.get().currentProcesses.remove(process);
}
}
| public void run() {
ProcessBuilder pb = new ProcessBuilder(cmdArray);
try {
LOGGER.debug("Starting " + cmdLine);
if (params.outputFile != null && params.outputFile.getParentFile().isDirectory()) {
pb.directory(params.outputFile.getParentFile());
}
if (params.workDir != null && params.workDir.isDirectory()) {
pb.directory(params.workDir);
}
if (params.env != null && !params.env.isEmpty()) {
Map<String,String> environment = pb.environment();
String PATH = params.env.get("PATH") + File.pathSeparator + environment.get("PATH");
environment.putAll(params.env);
environment.put("PATH", PATH);
}
process = pb.start();
PMS.get().currentProcesses.add(process);
stderrConsumer = keepStderr
? new OutputTextConsumer(process.getErrorStream(), true)
: new OutputTextLogger(process.getErrorStream());
stderrConsumer.start();
outConsumer = null;
if (params.outputFile != null) {
LOGGER.debug("Writing in " + params.outputFile.getAbsolutePath());
outConsumer = keepStdout
? new OutputTextConsumer(process.getInputStream(), false)
: new OutputTextLogger(process.getInputStream());
} else if (params.input_pipes[0] != null) {
LOGGER.debug("Reading pipe: " + params.input_pipes[0].getInputPipe());
bo = params.input_pipes[0].getDirectBuffer();
if (bo == null || params.losslessaudio || params.lossyaudio || params.no_videoencode) {
InputStream is = params.input_pipes[0].getInputStream();
outConsumer = new OutputBufferConsumer((params.avidemux) ? new AviDemuxerInputStream(is, params, attachedProcesses) : is, params);
bo = outConsumer.getBuffer();
}
bo.attachThread(this);
new OutputTextLogger(process.getInputStream()).start();
} else if (params.log) {
outConsumer = keepStdout
? new OutputTextConsumer(process.getInputStream(), true)
: new OutputTextLogger(process.getInputStream());
} else {
outConsumer = new OutputBufferConsumer(process.getInputStream(), params);
bo = outConsumer.getBuffer();
bo.attachThread(this);
}
if (params.stdin != null) {
params.stdin.push(process.getOutputStream());
}
if (outConsumer != null) {
outConsumer.start();
}
Integer pid = ProcessUtil.getProcessID(process);
if (pid != null) {
LOGGER.debug("Unix process ID (" + cmdArray[0] + "): " + pid);
}
ProcessUtil.waitFor(process);
try {
if (outConsumer != null) {
outConsumer.join(1000);
}
} catch (InterruptedException e) {
}
if (bo != null) {
bo.close();
}
} catch (Exception e) {
LOGGER.error("Fatal error in process initialization: ", e);
stopProcess();
} finally {
if (!destroyed && !params.noexitcheck) {
try {
success = true;
if (process != null && process.exitValue() != 0) {
LOGGER.info("Process " + cmdArray[0] + " has a return code of " + process.exitValue() + "! Maybe an error occurred... check the log file");
success = false;
}
} catch (IllegalThreadStateException itse) {
LOGGER.error("An error occurred", itse);
}
}
if (attachedProcesses != null) {
for (ProcessWrapper pw : attachedProcesses) {
if (pw != null) {
pw.stopProcess();
}
}
}
PMS.get().currentProcesses.remove(process);
}
}
|
diff --git a/src/main/java/org/eweb4j/spiderman/spider/Spider.java b/src/main/java/org/eweb4j/spiderman/spider/Spider.java
index f5507dc..18e806d 100644
--- a/src/main/java/org/eweb4j/spiderman/spider/Spider.java
+++ b/src/main/java/org/eweb4j/spiderman/spider/Spider.java
@@ -1,252 +1,254 @@
package org.eweb4j.spiderman.spider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.eweb4j.spiderman.fetcher.FetchResult;
import org.eweb4j.spiderman.fetcher.Page;
import org.eweb4j.spiderman.plugin.BeginPoint;
import org.eweb4j.spiderman.plugin.DigPoint;
import org.eweb4j.spiderman.plugin.DoneException;
import org.eweb4j.spiderman.plugin.DupRemovalPoint;
import org.eweb4j.spiderman.plugin.EndPoint;
import org.eweb4j.spiderman.plugin.FetchPoint;
import org.eweb4j.spiderman.plugin.ParsePoint;
import org.eweb4j.spiderman.plugin.PojoPoint;
import org.eweb4j.spiderman.plugin.TargetPoint;
import org.eweb4j.spiderman.plugin.TaskPushPoint;
import org.eweb4j.spiderman.plugin.TaskSortPoint;
import org.eweb4j.spiderman.task.Task;
import org.eweb4j.spiderman.url.SourceUrlChecker;
import org.eweb4j.spiderman.xml.Target;
import org.eweb4j.util.CommonUtil;
/**
* 网络蜘蛛
* @author weiwei
*
*/
public class Spider implements Runnable{
public Task task;
public SpiderListener listener;
public void init(Task task, SpiderListener listener) {
this.task = task;
this.listener = listener;
}
public void run() {
try {
//扩展点:begin 蜘蛛开始
Collection<BeginPoint> beginPoints = task.site.beginPointImpls;
if (beginPoints != null && !beginPoints.isEmpty()){
for (BeginPoint point : beginPoints){
task = point.confirmTask(task);
}
}
if (task == null) return ;
if (task.site.isStop)
return ;
//扩展点:fetch 获取HTTP内容
FetchResult result = null;
Collection<FetchPoint> fetchPoints = task.site.fetchPointImpls;
if (fetchPoints != null && !fetchPoints.isEmpty()){
for (FetchPoint point : fetchPoints){
// point.context(task);
result = point.fetch(task, result);
}
}
if (result == null || result.getPage() == null || result.getPage().getContent() == null || result.getPage().getContent().trim().length() == 0) {
listener.onInfo(Thread.currentThread(), task, " spider stop cause the fetch result->+"+result+" of task["+task+"] is null");
//这时候认为完成了一个task,将其加入到db中标记已抓过的url
task.site.db.newDocID(task.url);
return ;
}
listener.onFetch(Thread.currentThread(), task, result);
if (task.site.isStop)
return ;
//扩展点:dig new url 发觉新URL
Collection<String> newUrls = null;
Collection<DigPoint> digPoints = task.site.digPointImpls;
if (digPoints != null && !digPoints.isEmpty()){
for (DigPoint point : digPoints){
// point.context(result, task);
newUrls = point.digNewUrls(result, task, newUrls);
}
}
if (newUrls != null && !newUrls.isEmpty())
this.listener.onNewUrls(Thread.currentThread(), task, newUrls);
else
newUrls = new ArrayList<String>();
if (task.site.isStop)
return ;
//扩展点:dup_removal URL去重,然后变成Task
Collection<Task> validTasks = null;
Collection<DupRemovalPoint> dupRemovalPoints = task.site.dupRemovalPointImpls;
if (dupRemovalPoints != null && !dupRemovalPoints.isEmpty()){
for (DupRemovalPoint point : dupRemovalPoints){
// point.context(task, newUrls);
validTasks = point.removeDuplicateTask(task, newUrls, validTasks);
}
}
if (newUrls != null && !newUrls.isEmpty())
this.listener.onDupRemoval(Thread.currentThread(), task, validTasks);
if (validTasks == null)
validTasks = new ArrayList<Task>();
if (task.site.isStop)
return ;
//扩展点:task_sort 给任务排序
Collection<TaskSortPoint> taskSortPoints = task.site.taskSortPointImpls;
if (taskSortPoints != null && !taskSortPoints.isEmpty()){
for (TaskSortPoint point : taskSortPoints){
validTasks = point.sortTasks(validTasks);
}
}
if (validTasks == null)
validTasks = new ArrayList<Task>();
if (task.site.isStop)
return ;
//扩展点:task_push 将任务放入队列
validTasks = pushTask(validTasks);
if (validTasks != null && !validTasks.isEmpty())
this.listener.onNewTasks(Thread.currentThread(), task, validTasks);
Page page = result.getPage();
if (page == null) {
listener.onInfo(Thread.currentThread(), task, " spider stop cause the fetch result.page is null");
//这时候认为完成了一个task,将其加入到db中标记已抓过的url
task.site.db.newDocID(task.url);
return ;
}
if (task.site.isStop)
return ;
//扩展点:target 确认当前的Task.url符不符合目标期望
Target target = null;
Collection<TargetPoint> targetPoints = task.site.targetPointImpls;
if (targetPoints != null && !targetPoints.isEmpty()){
for (TargetPoint point : targetPoints){
// point.context(task);
target = point.confirmTarget(task, target);
}
}
if (target == null) {
listener.onInfo(Thread.currentThread(), task, " spider stop cause the task->"+task+" is not the target");
+ //这时候认为完成了一个task,将其加入到db中标记已抓过的url
+ task.site.db.newDocID(task.url);
return ;
}
this.listener.onTargetPage(Thread.currentThread(), task, page);
if (task.site.isStop)
return ;
//检查sourceUrl
boolean isSourceUrlOk = SourceUrlChecker.checkSourceUrl(target.getSourceRules(), task.sourceUrl);
if (!isSourceUrlOk){
listener.onInfo(Thread.currentThread(), task, " spider stop cause the task->"+task+" is not match the rules");
return ;
}
//这时候认为完成了一个task,将其加入到db中标记已抓过的url
task.site.db.newDocID(task.url);
//扩展点:parse 把已确认好的目标页面解析成为Map对象
List<Map<String, Object>> models = null;
Collection<ParsePoint> parsePoints = task.site.parsePointImpls;
if (parsePoints != null && !parsePoints.isEmpty()){
for (ParsePoint point : parsePoints){
// point.context(task, target, page);
models = point.parse(task, target, page, models);
}
}
if (models != null) {
listener.onInfo(Thread.currentThread(), task, "models.size -> " + models.size());
} else {
listener.onInfo(Thread.currentThread(), task, "models is null from task->" + task);
return ;
}
for (Map<String,Object> model : models)
model.put("task_url", task.url);
// 统计任务完成数+1
this.task.site.counter.plus();
listener.onParse(Thread.currentThread(), task, models);
listener.onInfo(Thread.currentThread(), task, "site -> " + task.site.getName() + " task parse finished count ->" + task.site.counter.getCount());
if (task.site.isStop)
return ;
//扩展点:pojo 将Map数据映射为POJO
String modelCls = target.getModel().getClazz();
Class<?> cls = null;
if (modelCls != null)
cls = Class.forName(modelCls);
List<Object> pojos = null;
Collection<PojoPoint> pojoPoints = task.site.pojoPointImpls;
if (pojoPoints != null && !pojoPoints.isEmpty()){
for (PojoPoint point : pojoPoints){
// point.context();
pojos = point.mapping(task, cls, models, pojos);
}
}
if (pojos != null)
listener.onPojo(Thread.currentThread(), task, pojos);
if (task.site.isStop)
return ;
//扩展点:end 蜘蛛完成工作,该收尾了
Collection<EndPoint> endPoints = task.site.endPointImpls;
if (endPoints != null && !endPoints.isEmpty()){
for (EndPoint point : endPoints){
// point.context(task, models);
models = point.complete(task, models);
}
}
} catch (DoneException e){
this.listener.onInfo(Thread.currentThread(), task, "Spiderman has shutdown already...");
} catch(Exception e){
if (this.listener != null)
this.listener.onError(Thread.currentThread(), task, CommonUtil.getExceptionString(e), e);
}
}
public Collection<Task> pushTask(Collection<Task> validTasks) throws Exception {
Collection<TaskPushPoint> taskPushPoints = task.site.taskPushPointImpls;
if (taskPushPoints != null && !taskPushPoints.isEmpty()){
for (TaskPushPoint point : taskPushPoints){
validTasks = point.pushTask(validTasks);
}
}
return validTasks;
}
}
| true | true | public void run() {
try {
//扩展点:begin 蜘蛛开始
Collection<BeginPoint> beginPoints = task.site.beginPointImpls;
if (beginPoints != null && !beginPoints.isEmpty()){
for (BeginPoint point : beginPoints){
task = point.confirmTask(task);
}
}
if (task == null) return ;
if (task.site.isStop)
return ;
//扩展点:fetch 获取HTTP内容
FetchResult result = null;
Collection<FetchPoint> fetchPoints = task.site.fetchPointImpls;
if (fetchPoints != null && !fetchPoints.isEmpty()){
for (FetchPoint point : fetchPoints){
// point.context(task);
result = point.fetch(task, result);
}
}
if (result == null || result.getPage() == null || result.getPage().getContent() == null || result.getPage().getContent().trim().length() == 0) {
listener.onInfo(Thread.currentThread(), task, " spider stop cause the fetch result->+"+result+" of task["+task+"] is null");
//这时候认为完成了一个task,将其加入到db中标记已抓过的url
task.site.db.newDocID(task.url);
return ;
}
listener.onFetch(Thread.currentThread(), task, result);
if (task.site.isStop)
return ;
//扩展点:dig new url 发觉新URL
Collection<String> newUrls = null;
Collection<DigPoint> digPoints = task.site.digPointImpls;
if (digPoints != null && !digPoints.isEmpty()){
for (DigPoint point : digPoints){
// point.context(result, task);
newUrls = point.digNewUrls(result, task, newUrls);
}
}
if (newUrls != null && !newUrls.isEmpty())
this.listener.onNewUrls(Thread.currentThread(), task, newUrls);
else
newUrls = new ArrayList<String>();
if (task.site.isStop)
return ;
//扩展点:dup_removal URL去重,然后变成Task
Collection<Task> validTasks = null;
Collection<DupRemovalPoint> dupRemovalPoints = task.site.dupRemovalPointImpls;
if (dupRemovalPoints != null && !dupRemovalPoints.isEmpty()){
for (DupRemovalPoint point : dupRemovalPoints){
// point.context(task, newUrls);
validTasks = point.removeDuplicateTask(task, newUrls, validTasks);
}
}
if (newUrls != null && !newUrls.isEmpty())
this.listener.onDupRemoval(Thread.currentThread(), task, validTasks);
if (validTasks == null)
validTasks = new ArrayList<Task>();
if (task.site.isStop)
return ;
//扩展点:task_sort 给任务排序
Collection<TaskSortPoint> taskSortPoints = task.site.taskSortPointImpls;
if (taskSortPoints != null && !taskSortPoints.isEmpty()){
for (TaskSortPoint point : taskSortPoints){
validTasks = point.sortTasks(validTasks);
}
}
if (validTasks == null)
validTasks = new ArrayList<Task>();
if (task.site.isStop)
return ;
//扩展点:task_push 将任务放入队列
validTasks = pushTask(validTasks);
if (validTasks != null && !validTasks.isEmpty())
this.listener.onNewTasks(Thread.currentThread(), task, validTasks);
Page page = result.getPage();
if (page == null) {
listener.onInfo(Thread.currentThread(), task, " spider stop cause the fetch result.page is null");
//这时候认为完成了一个task,将其加入到db中标记已抓过的url
task.site.db.newDocID(task.url);
return ;
}
if (task.site.isStop)
return ;
//扩展点:target 确认当前的Task.url符不符合目标期望
Target target = null;
Collection<TargetPoint> targetPoints = task.site.targetPointImpls;
if (targetPoints != null && !targetPoints.isEmpty()){
for (TargetPoint point : targetPoints){
// point.context(task);
target = point.confirmTarget(task, target);
}
}
if (target == null) {
listener.onInfo(Thread.currentThread(), task, " spider stop cause the task->"+task+" is not the target");
return ;
}
this.listener.onTargetPage(Thread.currentThread(), task, page);
if (task.site.isStop)
return ;
//检查sourceUrl
boolean isSourceUrlOk = SourceUrlChecker.checkSourceUrl(target.getSourceRules(), task.sourceUrl);
if (!isSourceUrlOk){
listener.onInfo(Thread.currentThread(), task, " spider stop cause the task->"+task+" is not match the rules");
return ;
}
//这时候认为完成了一个task,将其加入到db中标记已抓过的url
task.site.db.newDocID(task.url);
//扩展点:parse 把已确认好的目标页面解析成为Map对象
List<Map<String, Object>> models = null;
Collection<ParsePoint> parsePoints = task.site.parsePointImpls;
if (parsePoints != null && !parsePoints.isEmpty()){
for (ParsePoint point : parsePoints){
// point.context(task, target, page);
models = point.parse(task, target, page, models);
}
}
if (models != null) {
listener.onInfo(Thread.currentThread(), task, "models.size -> " + models.size());
} else {
listener.onInfo(Thread.currentThread(), task, "models is null from task->" + task);
return ;
}
for (Map<String,Object> model : models)
model.put("task_url", task.url);
// 统计任务完成数+1
this.task.site.counter.plus();
listener.onParse(Thread.currentThread(), task, models);
listener.onInfo(Thread.currentThread(), task, "site -> " + task.site.getName() + " task parse finished count ->" + task.site.counter.getCount());
if (task.site.isStop)
return ;
//扩展点:pojo 将Map数据映射为POJO
String modelCls = target.getModel().getClazz();
Class<?> cls = null;
if (modelCls != null)
cls = Class.forName(modelCls);
List<Object> pojos = null;
Collection<PojoPoint> pojoPoints = task.site.pojoPointImpls;
if (pojoPoints != null && !pojoPoints.isEmpty()){
for (PojoPoint point : pojoPoints){
// point.context();
pojos = point.mapping(task, cls, models, pojos);
}
}
if (pojos != null)
listener.onPojo(Thread.currentThread(), task, pojos);
if (task.site.isStop)
return ;
//扩展点:end 蜘蛛完成工作,该收尾了
Collection<EndPoint> endPoints = task.site.endPointImpls;
if (endPoints != null && !endPoints.isEmpty()){
for (EndPoint point : endPoints){
// point.context(task, models);
models = point.complete(task, models);
}
}
} catch (DoneException e){
this.listener.onInfo(Thread.currentThread(), task, "Spiderman has shutdown already...");
} catch(Exception e){
if (this.listener != null)
this.listener.onError(Thread.currentThread(), task, CommonUtil.getExceptionString(e), e);
}
}
| public void run() {
try {
//扩展点:begin 蜘蛛开始
Collection<BeginPoint> beginPoints = task.site.beginPointImpls;
if (beginPoints != null && !beginPoints.isEmpty()){
for (BeginPoint point : beginPoints){
task = point.confirmTask(task);
}
}
if (task == null) return ;
if (task.site.isStop)
return ;
//扩展点:fetch 获取HTTP内容
FetchResult result = null;
Collection<FetchPoint> fetchPoints = task.site.fetchPointImpls;
if (fetchPoints != null && !fetchPoints.isEmpty()){
for (FetchPoint point : fetchPoints){
// point.context(task);
result = point.fetch(task, result);
}
}
if (result == null || result.getPage() == null || result.getPage().getContent() == null || result.getPage().getContent().trim().length() == 0) {
listener.onInfo(Thread.currentThread(), task, " spider stop cause the fetch result->+"+result+" of task["+task+"] is null");
//这时候认为完成了一个task,将其加入到db中标记已抓过的url
task.site.db.newDocID(task.url);
return ;
}
listener.onFetch(Thread.currentThread(), task, result);
if (task.site.isStop)
return ;
//扩展点:dig new url 发觉新URL
Collection<String> newUrls = null;
Collection<DigPoint> digPoints = task.site.digPointImpls;
if (digPoints != null && !digPoints.isEmpty()){
for (DigPoint point : digPoints){
// point.context(result, task);
newUrls = point.digNewUrls(result, task, newUrls);
}
}
if (newUrls != null && !newUrls.isEmpty())
this.listener.onNewUrls(Thread.currentThread(), task, newUrls);
else
newUrls = new ArrayList<String>();
if (task.site.isStop)
return ;
//扩展点:dup_removal URL去重,然后变成Task
Collection<Task> validTasks = null;
Collection<DupRemovalPoint> dupRemovalPoints = task.site.dupRemovalPointImpls;
if (dupRemovalPoints != null && !dupRemovalPoints.isEmpty()){
for (DupRemovalPoint point : dupRemovalPoints){
// point.context(task, newUrls);
validTasks = point.removeDuplicateTask(task, newUrls, validTasks);
}
}
if (newUrls != null && !newUrls.isEmpty())
this.listener.onDupRemoval(Thread.currentThread(), task, validTasks);
if (validTasks == null)
validTasks = new ArrayList<Task>();
if (task.site.isStop)
return ;
//扩展点:task_sort 给任务排序
Collection<TaskSortPoint> taskSortPoints = task.site.taskSortPointImpls;
if (taskSortPoints != null && !taskSortPoints.isEmpty()){
for (TaskSortPoint point : taskSortPoints){
validTasks = point.sortTasks(validTasks);
}
}
if (validTasks == null)
validTasks = new ArrayList<Task>();
if (task.site.isStop)
return ;
//扩展点:task_push 将任务放入队列
validTasks = pushTask(validTasks);
if (validTasks != null && !validTasks.isEmpty())
this.listener.onNewTasks(Thread.currentThread(), task, validTasks);
Page page = result.getPage();
if (page == null) {
listener.onInfo(Thread.currentThread(), task, " spider stop cause the fetch result.page is null");
//这时候认为完成了一个task,将其加入到db中标记已抓过的url
task.site.db.newDocID(task.url);
return ;
}
if (task.site.isStop)
return ;
//扩展点:target 确认当前的Task.url符不符合目标期望
Target target = null;
Collection<TargetPoint> targetPoints = task.site.targetPointImpls;
if (targetPoints != null && !targetPoints.isEmpty()){
for (TargetPoint point : targetPoints){
// point.context(task);
target = point.confirmTarget(task, target);
}
}
if (target == null) {
listener.onInfo(Thread.currentThread(), task, " spider stop cause the task->"+task+" is not the target");
//这时候认为完成了一个task,将其加入到db中标记已抓过的url
task.site.db.newDocID(task.url);
return ;
}
this.listener.onTargetPage(Thread.currentThread(), task, page);
if (task.site.isStop)
return ;
//检查sourceUrl
boolean isSourceUrlOk = SourceUrlChecker.checkSourceUrl(target.getSourceRules(), task.sourceUrl);
if (!isSourceUrlOk){
listener.onInfo(Thread.currentThread(), task, " spider stop cause the task->"+task+" is not match the rules");
return ;
}
//这时候认为完成了一个task,将其加入到db中标记已抓过的url
task.site.db.newDocID(task.url);
//扩展点:parse 把已确认好的目标页面解析成为Map对象
List<Map<String, Object>> models = null;
Collection<ParsePoint> parsePoints = task.site.parsePointImpls;
if (parsePoints != null && !parsePoints.isEmpty()){
for (ParsePoint point : parsePoints){
// point.context(task, target, page);
models = point.parse(task, target, page, models);
}
}
if (models != null) {
listener.onInfo(Thread.currentThread(), task, "models.size -> " + models.size());
} else {
listener.onInfo(Thread.currentThread(), task, "models is null from task->" + task);
return ;
}
for (Map<String,Object> model : models)
model.put("task_url", task.url);
// 统计任务完成数+1
this.task.site.counter.plus();
listener.onParse(Thread.currentThread(), task, models);
listener.onInfo(Thread.currentThread(), task, "site -> " + task.site.getName() + " task parse finished count ->" + task.site.counter.getCount());
if (task.site.isStop)
return ;
//扩展点:pojo 将Map数据映射为POJO
String modelCls = target.getModel().getClazz();
Class<?> cls = null;
if (modelCls != null)
cls = Class.forName(modelCls);
List<Object> pojos = null;
Collection<PojoPoint> pojoPoints = task.site.pojoPointImpls;
if (pojoPoints != null && !pojoPoints.isEmpty()){
for (PojoPoint point : pojoPoints){
// point.context();
pojos = point.mapping(task, cls, models, pojos);
}
}
if (pojos != null)
listener.onPojo(Thread.currentThread(), task, pojos);
if (task.site.isStop)
return ;
//扩展点:end 蜘蛛完成工作,该收尾了
Collection<EndPoint> endPoints = task.site.endPointImpls;
if (endPoints != null && !endPoints.isEmpty()){
for (EndPoint point : endPoints){
// point.context(task, models);
models = point.complete(task, models);
}
}
} catch (DoneException e){
this.listener.onInfo(Thread.currentThread(), task, "Spiderman has shutdown already...");
} catch(Exception e){
if (this.listener != null)
this.listener.onError(Thread.currentThread(), task, CommonUtil.getExceptionString(e), e);
}
}
|
diff --git a/src/main/java/me/taylorkelly/bigbrother/BigBrother.java b/src/main/java/me/taylorkelly/bigbrother/BigBrother.java
index 0d331b6..8b62bfb 100644
--- a/src/main/java/me/taylorkelly/bigbrother/BigBrother.java
+++ b/src/main/java/me/taylorkelly/bigbrother/BigBrother.java
@@ -1,433 +1,440 @@
package me.taylorkelly.bigbrother;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import me.taylorkelly.bigbrother.datablock.BBDataBlock;
import me.taylorkelly.bigbrother.datasource.ConnectionManager;
import me.taylorkelly.bigbrother.datasource.DataBlockSender;
import me.taylorkelly.bigbrother.finder.Finder;
import me.taylorkelly.bigbrother.finder.Sticker;
import me.taylorkelly.bigbrother.fixes.Fix;
import me.taylorkelly.bigbrother.fixes.Fix13;
import me.taylorkelly.bigbrother.fixes.Fix14;
import me.taylorkelly.bigbrother.griefcraft.util.Updater;
import me.taylorkelly.bigbrother.listeners.BBBlockListener;
import me.taylorkelly.bigbrother.listeners.BBEntityListener;
import me.taylorkelly.bigbrother.listeners.BBPlayerListener;
import me.taylorkelly.bigbrother.rollback.Rollback;
import me.taylorkelly.bigbrother.rollback.RollbackConfirmation;
import me.taylorkelly.bigbrother.rollback.RollbackInterpreter;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
public class BigBrother extends JavaPlugin {
private BBPlayerListener playerListener;
private BBBlockListener blockListener;
private BBEntityListener entityListener;
private StickListener stickListener;
private Watcher watcher;
private Sticker sticker;
private WorldManager worldManager;
public static final Logger log = Logger.getLogger("Minecraft");
public String name;
public String version;
public final static String premessage = ChatColor.AQUA + "[BBROTHER]: " + ChatColor.WHITE;
private Updater updater;
@Override
public void onDisable() {
DataBlockSender.disable();
}
@Override
public void onEnable() {
// TODO More verbose enabling
// Stuff that was in Constructor
name = this.getDescription().getName();
version = this.getDescription().getVersion();
// Initialize Settings
BBSettings.initialize(getDataFolder());
// Download dependencies...
updater = new Updater();
try {
updater.check();
updater.update();
} catch (Throwable e) {
log.log(Level.SEVERE, "[BBROTHER] Could not download dependencies", e);
}
// Create Connection
Connection conn = ConnectionManager.createConnection();
if (conn == null) {
log.log(Level.SEVERE, "[BBROTHER] Could not establish SQL connection. Disabling BigBrother");
getServer().getPluginManager().disablePlugin(this);
return;
} else {
try {
conn.close();
} catch (SQLException e) {
log.log(Level.SEVERE, "[BBROTHER] Could not close connection", e);
}
}
// Initialize tables
// TODO Move this out of BBDataBlock
BBDataBlock.initialize();
worldManager = new WorldManager();
// Initialize Listeners
playerListener = new BBPlayerListener(this);
blockListener = new BBBlockListener(this);
entityListener = new BBEntityListener(this);
stickListener = new StickListener(this);
sticker = new Sticker(getServer(), worldManager);
// Update settings from old versions of BB
if (new File("BigBrother").exists()) {
updateSettings(getDataFolder());
} else if (!getDataFolder().exists()) {
getDataFolder().mkdirs();
}
// Apply fixes to DB for old BB
Fix fix = new Fix13(getDataFolder());
fix.apply();
Fix fix2 = new Fix14(getDataFolder());
fix2.apply();
// Initialize Permissions, Stats
BBPermissions.initialize(getServer());
Stats.initialize();
// Register Events
registerEvents();
// Initialize Player Watching
watcher = BBSettings.getWatcher(getServer(), getDataFolder());
// Initialize DataBlockSender
DataBlockSender.initialize(getDataFolder(), worldManager);
// Done!
// TODO Not concatenate..
log.log(Level.INFO, name + " " + version + "initialized");
}
private void updateSettings(File dataFolder) {
File oldDirectory = new File("BigBrother");
dataFolder.getParentFile().mkdirs();
oldDirectory.renameTo(dataFolder);
}
private void registerEvents() {
// TODO Only register events that are being listened to
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_COMMAND, playerListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_QUIT, playerListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_ITEM, playerListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_CHAT, playerListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_TELEPORT, playerListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_PLACED, blockListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_DAMAGED, blockListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_IGNITE, blockListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_INTERACT, blockListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.LEAVES_DECAY, blockListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_BURN, blockListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.ENTITY_EXPLODE, entityListener, Priority.Monitor, this);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_RIGHTCLICKED, stickListener, Priority.Low, this);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_PLACED, stickListener, Priority.Low, this);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_INTERACT, stickListener, Priority.Low, this);
}
public boolean watching(Player player) {
return watcher.watching(player);
}
public boolean toggleWatch(String player) {
return watcher.toggleWatch(player);
}
public String getWatchedPlayers() {
return watcher.getWatchedPlayers();
}
public boolean haveSeen(Player player) {
return watcher.haveSeen(player);
}
public void markSeen(Player player) {
watcher.markSeen(player);
}
public void watchPlayer(Player player) {
watcher.watchPlayer(player);
}
public String getUnwatchedPlayers() {
return watcher.getUnwatchedPlayers();
}
@Override
@SuppressWarnings("CallToThreadDumpStack")
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
try {
String[] split = args;
String commandName = command.getName().toLowerCase();
if (sender instanceof Player) {
Player player = (Player) sender;
+ // TODO: Make this more modular. If-trees drive me nuts. - N3X
if (commandName.equals("bb")) {
if (split.length == 0) {
return false;
}
if (split[0].equalsIgnoreCase("watch") && BBPermissions.watch(player)) {
if (split.length == 2) {
List<Player> targets = getServer().matchPlayer(split[1]);
Player watchee = null;
if (targets.size() == 1) {
watchee = targets.get(0);
}
String playerName = (watchee == null) ? split[1] : watchee.getName();
if (toggleWatch(playerName)) {
String status = (watchee == null) ? " (offline)" : " (online)";
player.sendMessage(BigBrother.premessage + "Now watching " + playerName + status);
} else {
String status = (watchee == null) ? " (offline)" : " (online)";
player.sendMessage(BigBrother.premessage + "No longer watching " + playerName + status);
}
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb watch <player>");
}
} else if (split[0].equalsIgnoreCase("watched") && BBPermissions.info(player)) {
String watchedPlayers = getWatchedPlayers();
if (watchedPlayers.equals("")) {
- player.sendMessage(BigBrother.premessage + "Not currently watching anyone.");
+ player.sendMessage(BigBrother.premessage + "Not watching anyone.");
} else {
player.sendMessage(BigBrother.premessage + "Now watching:");
player.sendMessage(watchedPlayers);
}
} else if (split[0].equalsIgnoreCase("stats") && BBPermissions.info(player)) {
Stats.report(player);
} else if (split[0].equalsIgnoreCase("unwatched") && BBPermissions.info(player)) {
String unwatchedPlayers = getUnwatchedPlayers();
if (unwatchedPlayers.equals("")) {
player.sendMessage(BigBrother.premessage + "Everyone on is being watched.");
} else {
- player.sendMessage(BigBrother.premessage + "Not currently watching:");
+ player.sendMessage(BigBrother.premessage + "Currently not watching:");
player.sendMessage(unwatchedPlayers);
}
} else if (split[0].equalsIgnoreCase("rollback") && BBPermissions.rollback(player)) {
if (split.length > 1) {
RollbackInterpreter interpreter = new RollbackInterpreter(player, split, getServer(), worldManager);
Boolean passed = interpreter.interpret();
if (passed != null) {
if (passed) {
interpreter.send();
} else {
player.sendMessage(BigBrother.premessage + ChatColor.RED + "Warning: " + ChatColor.WHITE + "You are rolling back without a time or radius argument.");
player.sendMessage("Use " + ChatColor.RED + "/bb confirm" + ChatColor.WHITE + " to confirm the rollback.");
player.sendMessage("Use " + ChatColor.RED + "/bb delete" + ChatColor.WHITE + " to delete it.");
RollbackConfirmation.setRI(player, interpreter);
}
}
} else {
- // TODO Better help
- player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb rollback <arg1> <arg2>");
+ player.sendMessage(BigBrother.premessage + "Usage is: " + ChatColor.RED + "/bb rollback name1 [name2] [options]");
+ player.sendMessage(BigBrother.premessage + "Please read the full command documentation at https://github.com/tkelly910/BigBrother/wiki/Commands");
}
} else if (split[0].equalsIgnoreCase("confirm") && BBPermissions.rollback(player)) {
if (split.length == 1) {
if (RollbackConfirmation.hasRI(player)) {
RollbackInterpreter interpret = RollbackConfirmation.getRI(player);
interpret.send();
} else {
player.sendMessage(BigBrother.premessage + "You have no rollback to confirm.");
}
} else {
// TODO Better help
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb confirm");
}
} else if (split[0].equalsIgnoreCase("delete") && BBPermissions.rollback(player)) {
if (split.length == 1) {
if (RollbackConfirmation.hasRI(player)) {
RollbackConfirmation.deleteRI(player);
player.sendMessage(BigBrother.premessage + "You have deleted your rollback.");
} else {
player.sendMessage(BigBrother.premessage + "You have no rollback to delete.");
}
} else {
// TODO Better help
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb delete");
}
} else if (split[0].equalsIgnoreCase("undo") && BBPermissions.rollback(player)) {
if (split.length == 1) {
if (Rollback.canUndo()) {
int size = Rollback.undoSize();
player.sendMessage(BigBrother.premessage + "Undo-ing last rollback of " + size + " blocks");
Rollback.undo(getServer(), player);
player.sendMessage(BigBrother.premessage + "Undo successful");
} else {
player.sendMessage(BigBrother.premessage + "No rollback to undo");
}
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb undo");
}
} else if (split[0].equalsIgnoreCase("stick") && BBPermissions.info(player)) {
if (split.length == 1) {
sticker.setMode(player, 1);
player.sendMessage(BigBrother.premessage + "Your current stick mode is " + sticker.descMode(player));
player.sendMessage("Use " + ChatColor.RED + "/bb stick 0" + ChatColor.WHITE + " to turn it off");
} else if (split.length == 2 && isInteger(split[1])) {
sticker.setMode(player, Integer.parseInt(split[1]));
if (Integer.parseInt(split[1]) > 0) {
player.sendMessage(BigBrother.premessage + "Your current stick mode is " + sticker.descMode(player));
player.sendMessage("Use " + ChatColor.RED + "/bb stick 0" + ChatColor.WHITE + " to turn it off");
}
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb stick (#)");
}
} else if (split[0].equalsIgnoreCase("here") && BBPermissions.info(player)) {
if (split.length == 1) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.addReciever(player);
finder.find();
} else if (isNumber(split[1]) && split.length == 2) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[1]));
finder.addReciever(player);
finder.find();
} else if (split.length == 2) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[1]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[1] : findee.getName());
} else if (isNumber(split[2]) && split.length == 3) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[2]));
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[1]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[1] : findee.getName());
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb here");
player.sendMessage("or " + ChatColor.RED + "/bb here <radius>");
player.sendMessage("or " + ChatColor.RED + "/bb here <name>");
player.sendMessage("or " + ChatColor.RED + "/bb here <name> <radius>");
}
} else if (split[0].equalsIgnoreCase("find") && BBPermissions.info(player)) {
if (split.length == 4 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.addReciever(player);
finder.find();
} else if (split.length == 5 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3]) && isNumber(split[4])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[4]));
finder.addReciever(player);
finder.find();
} else if (split.length == 5 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[4]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[4] : findee.getName());
} else if (split.length == 6 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3]) && isNumber(split[5])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[5]));
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[4]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[4] : findee.getName());
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb find <x> <y> <z>");
player.sendMessage("or " + ChatColor.RED + "/bb find <x> <y> <z> <radius>");
player.sendMessage("or " + ChatColor.RED + "/bb find <x> <y> <z> <name>");
player.sendMessage("or " + ChatColor.RED + "/bb find <x> <y> <z> <name> <radius>");
}
} else if (split[0].equalsIgnoreCase("help")) {
- player.sendMessage(BigBrother.premessage + "help!");
+ player.sendMessage(BigBrother.premessage + "BigBrother version 1.6 help"); // TODO: Find version variable and use it
+ player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb stick (0|1|2)"+ChatColor.WHITE+" - Gives you a stick (1), a log you can place (2), or disables either (0).");
+ player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb here"+ChatColor.WHITE+" - See changes that took place in the area you are standing in.");
+ player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb undo"+ChatColor.WHITE+" - Great for fixing bad rollbacks. It's like it never happened!");
+ player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb delete"+ChatColor.WHITE+" - Delete your rollback."); // TODO: Clarify what /bb delete does
+ player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb rollback name1 [name2] [options]"+ChatColor.WHITE+" - A command you should study in length via our helpful online wiki.");
+ player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb find x y z"+ChatColor.WHITE+""); // TODO: Clarify /bb find docs
} else {
return false;
}
return true;
}
}
return false;
} catch (Throwable ex) {
ex.printStackTrace();
return true;
}
}
public static boolean isInteger(String string) {
try {
Integer.parseInt(string);
} catch (Throwable e) {
return false;
}
return true;
}
public static boolean isNumber(String string) {
try {
Double.parseDouble(string);
} catch (Throwable e) {
return false;
}
return true;
}
public boolean hasStick(Player player, ItemStack itemStack) {
return sticker.hasStick(player, itemStack);
}
public void stick(Player player, Block block) {
sticker.stick(player, block);
}
public boolean rightClickStick(Player player) {
return sticker.rightClickStick(player);
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
try {
String[] split = args;
String commandName = command.getName().toLowerCase();
if (sender instanceof Player) {
Player player = (Player) sender;
if (commandName.equals("bb")) {
if (split.length == 0) {
return false;
}
if (split[0].equalsIgnoreCase("watch") && BBPermissions.watch(player)) {
if (split.length == 2) {
List<Player> targets = getServer().matchPlayer(split[1]);
Player watchee = null;
if (targets.size() == 1) {
watchee = targets.get(0);
}
String playerName = (watchee == null) ? split[1] : watchee.getName();
if (toggleWatch(playerName)) {
String status = (watchee == null) ? " (offline)" : " (online)";
player.sendMessage(BigBrother.premessage + "Now watching " + playerName + status);
} else {
String status = (watchee == null) ? " (offline)" : " (online)";
player.sendMessage(BigBrother.premessage + "No longer watching " + playerName + status);
}
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb watch <player>");
}
} else if (split[0].equalsIgnoreCase("watched") && BBPermissions.info(player)) {
String watchedPlayers = getWatchedPlayers();
if (watchedPlayers.equals("")) {
player.sendMessage(BigBrother.premessage + "Not currently watching anyone.");
} else {
player.sendMessage(BigBrother.premessage + "Now watching:");
player.sendMessage(watchedPlayers);
}
} else if (split[0].equalsIgnoreCase("stats") && BBPermissions.info(player)) {
Stats.report(player);
} else if (split[0].equalsIgnoreCase("unwatched") && BBPermissions.info(player)) {
String unwatchedPlayers = getUnwatchedPlayers();
if (unwatchedPlayers.equals("")) {
player.sendMessage(BigBrother.premessage + "Everyone on is being watched.");
} else {
player.sendMessage(BigBrother.premessage + "Not currently watching:");
player.sendMessage(unwatchedPlayers);
}
} else if (split[0].equalsIgnoreCase("rollback") && BBPermissions.rollback(player)) {
if (split.length > 1) {
RollbackInterpreter interpreter = new RollbackInterpreter(player, split, getServer(), worldManager);
Boolean passed = interpreter.interpret();
if (passed != null) {
if (passed) {
interpreter.send();
} else {
player.sendMessage(BigBrother.premessage + ChatColor.RED + "Warning: " + ChatColor.WHITE + "You are rolling back without a time or radius argument.");
player.sendMessage("Use " + ChatColor.RED + "/bb confirm" + ChatColor.WHITE + " to confirm the rollback.");
player.sendMessage("Use " + ChatColor.RED + "/bb delete" + ChatColor.WHITE + " to delete it.");
RollbackConfirmation.setRI(player, interpreter);
}
}
} else {
// TODO Better help
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb rollback <arg1> <arg2>");
}
} else if (split[0].equalsIgnoreCase("confirm") && BBPermissions.rollback(player)) {
if (split.length == 1) {
if (RollbackConfirmation.hasRI(player)) {
RollbackInterpreter interpret = RollbackConfirmation.getRI(player);
interpret.send();
} else {
player.sendMessage(BigBrother.premessage + "You have no rollback to confirm.");
}
} else {
// TODO Better help
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb confirm");
}
} else if (split[0].equalsIgnoreCase("delete") && BBPermissions.rollback(player)) {
if (split.length == 1) {
if (RollbackConfirmation.hasRI(player)) {
RollbackConfirmation.deleteRI(player);
player.sendMessage(BigBrother.premessage + "You have deleted your rollback.");
} else {
player.sendMessage(BigBrother.premessage + "You have no rollback to delete.");
}
} else {
// TODO Better help
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb delete");
}
} else if (split[0].equalsIgnoreCase("undo") && BBPermissions.rollback(player)) {
if (split.length == 1) {
if (Rollback.canUndo()) {
int size = Rollback.undoSize();
player.sendMessage(BigBrother.premessage + "Undo-ing last rollback of " + size + " blocks");
Rollback.undo(getServer(), player);
player.sendMessage(BigBrother.premessage + "Undo successful");
} else {
player.sendMessage(BigBrother.premessage + "No rollback to undo");
}
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb undo");
}
} else if (split[0].equalsIgnoreCase("stick") && BBPermissions.info(player)) {
if (split.length == 1) {
sticker.setMode(player, 1);
player.sendMessage(BigBrother.premessage + "Your current stick mode is " + sticker.descMode(player));
player.sendMessage("Use " + ChatColor.RED + "/bb stick 0" + ChatColor.WHITE + " to turn it off");
} else if (split.length == 2 && isInteger(split[1])) {
sticker.setMode(player, Integer.parseInt(split[1]));
if (Integer.parseInt(split[1]) > 0) {
player.sendMessage(BigBrother.premessage + "Your current stick mode is " + sticker.descMode(player));
player.sendMessage("Use " + ChatColor.RED + "/bb stick 0" + ChatColor.WHITE + " to turn it off");
}
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb stick (#)");
}
} else if (split[0].equalsIgnoreCase("here") && BBPermissions.info(player)) {
if (split.length == 1) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.addReciever(player);
finder.find();
} else if (isNumber(split[1]) && split.length == 2) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[1]));
finder.addReciever(player);
finder.find();
} else if (split.length == 2) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[1]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[1] : findee.getName());
} else if (isNumber(split[2]) && split.length == 3) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[2]));
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[1]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[1] : findee.getName());
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb here");
player.sendMessage("or " + ChatColor.RED + "/bb here <radius>");
player.sendMessage("or " + ChatColor.RED + "/bb here <name>");
player.sendMessage("or " + ChatColor.RED + "/bb here <name> <radius>");
}
} else if (split[0].equalsIgnoreCase("find") && BBPermissions.info(player)) {
if (split.length == 4 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.addReciever(player);
finder.find();
} else if (split.length == 5 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3]) && isNumber(split[4])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[4]));
finder.addReciever(player);
finder.find();
} else if (split.length == 5 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[4]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[4] : findee.getName());
} else if (split.length == 6 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3]) && isNumber(split[5])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[5]));
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[4]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[4] : findee.getName());
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb find <x> <y> <z>");
player.sendMessage("or " + ChatColor.RED + "/bb find <x> <y> <z> <radius>");
player.sendMessage("or " + ChatColor.RED + "/bb find <x> <y> <z> <name>");
player.sendMessage("or " + ChatColor.RED + "/bb find <x> <y> <z> <name> <radius>");
}
} else if (split[0].equalsIgnoreCase("help")) {
player.sendMessage(BigBrother.premessage + "help!");
} else {
return false;
}
return true;
}
}
return false;
} catch (Throwable ex) {
ex.printStackTrace();
return true;
}
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
try {
String[] split = args;
String commandName = command.getName().toLowerCase();
if (sender instanceof Player) {
Player player = (Player) sender;
// TODO: Make this more modular. If-trees drive me nuts. - N3X
if (commandName.equals("bb")) {
if (split.length == 0) {
return false;
}
if (split[0].equalsIgnoreCase("watch") && BBPermissions.watch(player)) {
if (split.length == 2) {
List<Player> targets = getServer().matchPlayer(split[1]);
Player watchee = null;
if (targets.size() == 1) {
watchee = targets.get(0);
}
String playerName = (watchee == null) ? split[1] : watchee.getName();
if (toggleWatch(playerName)) {
String status = (watchee == null) ? " (offline)" : " (online)";
player.sendMessage(BigBrother.premessage + "Now watching " + playerName + status);
} else {
String status = (watchee == null) ? " (offline)" : " (online)";
player.sendMessage(BigBrother.premessage + "No longer watching " + playerName + status);
}
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb watch <player>");
}
} else if (split[0].equalsIgnoreCase("watched") && BBPermissions.info(player)) {
String watchedPlayers = getWatchedPlayers();
if (watchedPlayers.equals("")) {
player.sendMessage(BigBrother.premessage + "Not watching anyone.");
} else {
player.sendMessage(BigBrother.premessage + "Now watching:");
player.sendMessage(watchedPlayers);
}
} else if (split[0].equalsIgnoreCase("stats") && BBPermissions.info(player)) {
Stats.report(player);
} else if (split[0].equalsIgnoreCase("unwatched") && BBPermissions.info(player)) {
String unwatchedPlayers = getUnwatchedPlayers();
if (unwatchedPlayers.equals("")) {
player.sendMessage(BigBrother.premessage + "Everyone on is being watched.");
} else {
player.sendMessage(BigBrother.premessage + "Currently not watching:");
player.sendMessage(unwatchedPlayers);
}
} else if (split[0].equalsIgnoreCase("rollback") && BBPermissions.rollback(player)) {
if (split.length > 1) {
RollbackInterpreter interpreter = new RollbackInterpreter(player, split, getServer(), worldManager);
Boolean passed = interpreter.interpret();
if (passed != null) {
if (passed) {
interpreter.send();
} else {
player.sendMessage(BigBrother.premessage + ChatColor.RED + "Warning: " + ChatColor.WHITE + "You are rolling back without a time or radius argument.");
player.sendMessage("Use " + ChatColor.RED + "/bb confirm" + ChatColor.WHITE + " to confirm the rollback.");
player.sendMessage("Use " + ChatColor.RED + "/bb delete" + ChatColor.WHITE + " to delete it.");
RollbackConfirmation.setRI(player, interpreter);
}
}
} else {
player.sendMessage(BigBrother.premessage + "Usage is: " + ChatColor.RED + "/bb rollback name1 [name2] [options]");
player.sendMessage(BigBrother.premessage + "Please read the full command documentation at https://github.com/tkelly910/BigBrother/wiki/Commands");
}
} else if (split[0].equalsIgnoreCase("confirm") && BBPermissions.rollback(player)) {
if (split.length == 1) {
if (RollbackConfirmation.hasRI(player)) {
RollbackInterpreter interpret = RollbackConfirmation.getRI(player);
interpret.send();
} else {
player.sendMessage(BigBrother.premessage + "You have no rollback to confirm.");
}
} else {
// TODO Better help
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb confirm");
}
} else if (split[0].equalsIgnoreCase("delete") && BBPermissions.rollback(player)) {
if (split.length == 1) {
if (RollbackConfirmation.hasRI(player)) {
RollbackConfirmation.deleteRI(player);
player.sendMessage(BigBrother.premessage + "You have deleted your rollback.");
} else {
player.sendMessage(BigBrother.premessage + "You have no rollback to delete.");
}
} else {
// TODO Better help
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb delete");
}
} else if (split[0].equalsIgnoreCase("undo") && BBPermissions.rollback(player)) {
if (split.length == 1) {
if (Rollback.canUndo()) {
int size = Rollback.undoSize();
player.sendMessage(BigBrother.premessage + "Undo-ing last rollback of " + size + " blocks");
Rollback.undo(getServer(), player);
player.sendMessage(BigBrother.premessage + "Undo successful");
} else {
player.sendMessage(BigBrother.premessage + "No rollback to undo");
}
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb undo");
}
} else if (split[0].equalsIgnoreCase("stick") && BBPermissions.info(player)) {
if (split.length == 1) {
sticker.setMode(player, 1);
player.sendMessage(BigBrother.premessage + "Your current stick mode is " + sticker.descMode(player));
player.sendMessage("Use " + ChatColor.RED + "/bb stick 0" + ChatColor.WHITE + " to turn it off");
} else if (split.length == 2 && isInteger(split[1])) {
sticker.setMode(player, Integer.parseInt(split[1]));
if (Integer.parseInt(split[1]) > 0) {
player.sendMessage(BigBrother.premessage + "Your current stick mode is " + sticker.descMode(player));
player.sendMessage("Use " + ChatColor.RED + "/bb stick 0" + ChatColor.WHITE + " to turn it off");
}
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb stick (#)");
}
} else if (split[0].equalsIgnoreCase("here") && BBPermissions.info(player)) {
if (split.length == 1) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.addReciever(player);
finder.find();
} else if (isNumber(split[1]) && split.length == 2) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[1]));
finder.addReciever(player);
finder.find();
} else if (split.length == 2) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[1]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[1] : findee.getName());
} else if (isNumber(split[2]) && split.length == 3) {
Finder finder = new Finder(player.getLocation(), getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[2]));
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[1]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[1] : findee.getName());
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb here");
player.sendMessage("or " + ChatColor.RED + "/bb here <radius>");
player.sendMessage("or " + ChatColor.RED + "/bb here <name>");
player.sendMessage("or " + ChatColor.RED + "/bb here <name> <radius>");
}
} else if (split[0].equalsIgnoreCase("find") && BBPermissions.info(player)) {
if (split.length == 4 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.addReciever(player);
finder.find();
} else if (split.length == 5 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3]) && isNumber(split[4])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[4]));
finder.addReciever(player);
finder.find();
} else if (split.length == 5 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[4]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[4] : findee.getName());
} else if (split.length == 6 && isNumber(split[1]) && isNumber(split[2]) && isNumber(split[3]) && isNumber(split[5])) {
World currentWorld = player.getWorld();
Location loc = new Location(currentWorld, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]));
Finder finder = new Finder(loc, getServer().getWorlds(), worldManager);
finder.setRadius(Double.parseDouble(split[5]));
finder.addReciever(player);
List<Player> targets = getServer().matchPlayer(split[4]);
Player findee = null;
if (targets.size() == 1) {
findee = targets.get(0);
}
finder.find((findee == null) ? split[4] : findee.getName());
} else {
player.sendMessage(BigBrother.premessage + "usage is " + ChatColor.RED + "/bb find <x> <y> <z>");
player.sendMessage("or " + ChatColor.RED + "/bb find <x> <y> <z> <radius>");
player.sendMessage("or " + ChatColor.RED + "/bb find <x> <y> <z> <name>");
player.sendMessage("or " + ChatColor.RED + "/bb find <x> <y> <z> <name> <radius>");
}
} else if (split[0].equalsIgnoreCase("help")) {
player.sendMessage(BigBrother.premessage + "BigBrother version 1.6 help"); // TODO: Find version variable and use it
player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb stick (0|1|2)"+ChatColor.WHITE+" - Gives you a stick (1), a log you can place (2), or disables either (0).");
player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb here"+ChatColor.WHITE+" - See changes that took place in the area you are standing in.");
player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb undo"+ChatColor.WHITE+" - Great for fixing bad rollbacks. It's like it never happened!");
player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb delete"+ChatColor.WHITE+" - Delete your rollback."); // TODO: Clarify what /bb delete does
player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb rollback name1 [name2] [options]"+ChatColor.WHITE+" - A command you should study in length via our helpful online wiki.");
player.sendMessage(BigBrother.premessage + " "+ChatColor.RED+"/bb find x y z"+ChatColor.WHITE+""); // TODO: Clarify /bb find docs
} else {
return false;
}
return true;
}
}
return false;
} catch (Throwable ex) {
ex.printStackTrace();
return true;
}
}
|
diff --git a/src/org/apache/fop/fonts/TTFFile.java b/src/org/apache/fop/fonts/TTFFile.java
index 682233dbc..0cd0521b8 100644
--- a/src/org/apache/fop/fonts/TTFFile.java
+++ b/src/org/apache/fop/fonts/TTFFile.java
@@ -1,1094 +1,1094 @@
/* -- $Id$ --
*
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources."
*/
package org.apache.fop.fonts;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* Reads a TrueType file or a TrueType Collection.
* The TrueType spec can be found at the Microsoft
* Typography site: http://www.microsoft.com/truetype/
*/
public class TTFFile {
static final byte NTABS = 24;
static final int NMACGLYPHS = 258;
static final int MAX_CHAR_CODE = 255;
static final int ENC_BUF_SIZE = 1024;
static String encoding = "WinAnsiEncoding"; // Deafult encoding
short firstChar = 0;
boolean is_embeddable = true;
boolean hasSerifs = true;
Hashtable dirTabs; // Table directory
Hashtable kerningTab; // for CIDs
Hashtable ansiKerningTab; // For winAnsiEncoding
Vector cmaps;
Vector unicodeMapping; //
int upem; // unitsPerEm from "head" table
int nhmtx; // Number of horizontal metrics
int post_format;
int loca_format;
long lastLoca = 0; // offset to last loca
int nglyphs; // Number of glyphs in font (read from "maxp" table)
int nmglyphs; // Used in fixWidths - remove?
TTFMtxEntry mtx_tab[]; // Contains glyph data
int[] mtx_encoded = null;
String fontName = "";
String fullName = "";
String notice = "";
String familyName = "";
String subFamilyName = "";
long italicAngle = 0;
long isFixedPitch = 0;
int fontBBox1 = 0;
int fontBBox2 = 0;
int fontBBox3 = 0;
int fontBBox4 = 0;
int capHeight = 0;
int underlinePosition = 0;
int underlineThickness = 0;
int xHeight = 0;
int ascender = 0;
int descender = 0;
short lastChar = 0;
int ansiWidth[];
Hashtable ansiIndex;
/** Position inputstream to position indicated
in the dirtab offset + offset */
void seek_tab(FontFileReader in, String name,
long offset) throws IOException {
TTFDirTabEntry dt = (TTFDirTabEntry) dirTabs.get(name);
if (dt == null) {
System.out.println("Dirtab " + name + " not found.");
return;
}
in.seek_set(dt.offset + offset);
}
/** Convert from truetype unit to pdf unit based on the
* unitsPerEm field in the "head" table
@param n truetype unit
@return pdf unit
*/
int get_ttf_funit(int n) {
int ret;
if (n < 0) {
long rest1 = n % upem;
long storrest = 1000 * rest1;
long ledd2 = rest1 / storrest;
ret = -((-1000 * n) / upem - (int) ledd2);
} else {
ret = (n / upem) * 1000 + ((n % upem) * 1000) / upem;
}
return ret;
}
/** Read the cmap table,
* return false if the table is not present or only unsupported
* tables are present. Currently only unicode cmaps are supported.
* Set the unicodeIndex in the TTFMtxEntries and fills in the
* cmaps vector.
*/
private boolean readCMAP(FontFileReader in) throws IOException {
unicodeMapping = new Vector();
/** Read CMAP table and correct mtx_tab.index*/
int mtxPtr = 0;
seek_tab(in, "cmap", 2);
int num_cmap = in.readTTFUShort(); // Number of cmap subtables
long cmap_unioffset = 0;
//System.out.println(num_cmap+" cmap tables");
/* Read offset for all tables
We are only interested in the unicode table
*/
for (int i = 0; i < num_cmap; i++) {
int cmap_pid = in.readTTFUShort();
int cmap_eid = in.readTTFUShort();
long cmap_offset = in.readTTFULong();
//System.out.println("Platform ID: "+cmap_pid+
// " Encoding: "+cmap_eid);
if (cmap_pid == 3 && cmap_eid == 1)
cmap_unioffset = cmap_offset;
}
if (cmap_unioffset <= 0) {
System.out.println("Unicode cmap table not present");
return false;
}
// Read unicode cmap
seek_tab(in, "cmap", cmap_unioffset);
int cmap_format = in.readTTFUShort();
int cmap_length = in.readTTFUShort();
//System.out.println("CMAP format: "+cmap_format);
if (cmap_format == 4) {
in.skip(2); // Skip version number
int cmap_segCountX2 = in.readTTFUShort();
int cmap_searchRange = in.readTTFUShort();
int cmap_entrySelector = in.readTTFUShort();
int cmap_rangeShift = in.readTTFUShort();
/*
System.out.println("segCountX2 : "+cmap_segCountX2);
System.out.println("searchRange : "+cmap_searchRange);
System.out.println("entrySelector: "+cmap_entrySelector);
System.out.println("rangeShift : "+cmap_rangeShift);
*/
int cmap_endCounts[] = new int[cmap_segCountX2 / 2];
int cmap_startCounts[] = new int[cmap_segCountX2 / 2];
int cmap_deltas[] = new int[cmap_segCountX2 / 2];
int cmap_rangeOffsets[] = new int[cmap_segCountX2 / 2];
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_endCounts[i] = in.readTTFUShort();
}
in.skip(2); // Skip reservedPad
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_startCounts[i] = in.readTTFUShort();
}
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_deltas[i] = in.readTTFShort();
}
int startRangeOffset = in.getCurrentPos();
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
- cmap_rangeOffsets[i] = in.readTTFShort();
+ cmap_rangeOffsets[i] = in.readTTFUShort();
}
int glyphIdArrayOffset = in.getCurrentPos();
// Insert the unicode id for the glyphs in mtx_tab
// and fill in the cmaps Vector
for (int i = 0; i < cmap_startCounts.length; i++) {
/*
System.out.println(i+ ": "+cmap_startCounts[i]+
" - "+cmap_endCounts[i]);
*/
for (int j = cmap_startCounts[i];
j <= cmap_endCounts[i]; j++) {
// Update lastChar
if (j < 256 && j > lastChar)
lastChar = (short) j;
if (mtxPtr < mtx_tab.length) {
if (cmap_rangeOffsets[i] != 0) {
int glyphOffset = glyphIdArrayOffset +
((cmap_rangeOffsets[i] / 2) +
(j - cmap_startCounts[i]) + (i) -
cmap_segCountX2 / 2) * 2;
in.seek_set(glyphOffset);
int glyphIdx = (in.readTTFUShort() +
cmap_deltas[i]) & 0xffff;
unicodeMapping.addElement(
new UnicodeMapping(glyphIdx, j));
mtx_tab[glyphIdx].unicodeIndex.addElement(
new Integer(j));
// Also add winAnsiWidth
if (false) {
int d = j;
if (j > 127)
d = (int)
org.apache.fop.render.pdf.CodePointMapping.map[j];
if (d < ansiWidth.length)
ansiWidth[d] = mtx_tab[glyphIdx].wx;
} else {
Vector v = (Vector) ansiIndex.get(
new Integer(j));
if (v != null) {
for (Enumeration e = v.elements();
e.hasMoreElements();) {
Integer aIdx =
(Integer) e.nextElement();
ansiWidth[aIdx.intValue()] =
mtx_tab[glyphIdx].wx;
/*
System.out.println("Added width "+
mtx_tab[glyphIdx].wx +
" uni: " + j +
" ansi: " + aIdx.intValue());
*/
}
}
}
/*
System.out.println("Idx: "+
glyphIdx +
" Delta: " + cmap_deltas[i]+
" Unicode: " + j +
" name: " +
mtx_tab[glyphIdx].name);
*/
}
else {
int glyphIdx = (j + cmap_deltas[i]) & 0xffff;
if (glyphIdx < mtx_tab.length)
mtx_tab[glyphIdx] .unicodeIndex.addElement(
new Integer(j));
else
System.out.println("Glyph " +
glyphIdx + " out of range: " +
mtx_tab.length);
unicodeMapping.addElement(
new UnicodeMapping(glyphIdx, j));
if (glyphIdx < mtx_tab.length)
mtx_tab[glyphIdx] .unicodeIndex.addElement(
new Integer(j));
else
System.out.println("Glyph " +
glyphIdx + " out of range: " +
mtx_tab.length);
// Also add winAnsiWidth
if (false) {
int d = j;
if (j > 127)
d = (int)
org.apache.fop.render.pdf.CodePointMapping.map[j];
if (d < ansiWidth.length)
ansiWidth[d] = mtx_tab[glyphIdx].wx;
} else {
Vector v = (Vector) ansiIndex.get(
new Integer(j));
if (v != null) {
for (Enumeration e = v.elements();
e.hasMoreElements();) {
Integer aIdx =
(Integer) e.nextElement();
ansiWidth[aIdx.intValue()] =
mtx_tab[glyphIdx].wx;
}
}
}
/*
System.out.println("IIdx: "+
mtxPtr +
" Delta: " + cmap_deltas[i]+
" Unicode: " + j +
" name: " +
mtx_tab[(j+cmap_deltas[i]) & 0xffff].name);
*/
}
mtxPtr++;
}
}
}
}
return true;
}
/**
* Print first char/last char
*/
private void print_max_min() {
int min = 255;
int max = 0;
for (int i = 0; i < mtx_tab.length; i++) {
if (mtx_tab[i].index < min)
min = mtx_tab[i].index;
if (mtx_tab[i].index > max)
max = mtx_tab[i].index;
}
System.out.println("Min: "+min);
System.out.println("Max: "+max);
}
public void readFont(FontFileReader in) throws IOException {
readFont(in, (String) null);
}
/** initialize the ansiWidths array (for winAnsiEncoding)
* and fill with the missingwidth
*/
private void initAnsiWidths() {
ansiWidth = new int[256];
for (int i = 0; i < 256; i++)
ansiWidth[i] = mtx_tab[0].wx;
// Create an index hash to the ansiWidth
// Can't just index the winAnsiEncoding when inserting widths
// same char (eg bullet) is repeated more than one place
ansiIndex = new Hashtable();
for (int i = 32; i < Glyphs.winAnsiEncoding.length; i++) {
Integer ansi = new Integer(i);
Integer uni = new Integer((int) Glyphs.winAnsiEncoding[i]);
Vector v = (Vector) ansiIndex.get(uni);
if (v == null) {
v = new Vector();
ansiIndex.put(uni, v);
}
v.addElement(ansi);
}
}
/**
* Read the font data
* If the fontfile is a TrueType Collection (.ttc file)
* The name of the font to read data for must be supplied,
* else the name is ignored
*/
public void readFont(FontFileReader in,
String name) throws IOException {
/* Check if TrueType collection, and that the name
exists in the collection
*/
if (!checkTTC(in, name, true))
throw new IOException("Failed to read font");
readDirTabs(in);
readFontHeader(in);
getNumGlyphs(in);
System.out.println("Number of glyphs in font: " + nglyphs);
readHorizontalHeader(in);
readHorizontalMetrics(in);
initAnsiWidths();
readPostscript(in);
readOS2(in);
readIndexToLocation(in);
readGlyf(in);
readName(in);
readPCLT(in);
readCMAP(in); // Read cmap table and fill in ansiwidths
createCMaps(); // Create cmaps for bfentries
//print_max_min();
readKerning(in);
}
private void createCMaps() {
cmaps = new Vector();
TTFCmapEntry tce = new TTFCmapEntry();
Enumeration e = unicodeMapping.elements();
UnicodeMapping um = (UnicodeMapping) e.nextElement();
UnicodeMapping lastMapping = um;
tce.unicodeStart = um.uIdx;
tce.glyphStartIndex = um.gIdx;
while (e.hasMoreElements()) {
um = (UnicodeMapping) e.nextElement();
if (((lastMapping.uIdx + 1) != um.uIdx) ||
((lastMapping.gIdx + 1) != um.gIdx)) {
tce.unicodeEnd = lastMapping.uIdx;
cmaps.addElement(tce);
tce = new TTFCmapEntry();
tce.unicodeStart = um.uIdx;
tce.glyphStartIndex = um.gIdx;
}
lastMapping = um;
}
tce.unicodeEnd = um.uIdx;
cmaps.addElement(tce);
}
public void printStuff() {
System.out.println("Font name: " + fontName);
System.out.println("Full name: " + fullName);
System.out.println("Family name: " + familyName);
System.out.println("Subfamily name: " + subFamilyName);
System.out.println("Notice: " + notice);
System.out.println("xHeight: " + (int) get_ttf_funit(xHeight));
System.out.println("capheight: " + (int) get_ttf_funit(capHeight));
int italic = (int)(italicAngle >> 16);
System.out.println("Italic: " + italic);
System.out.print("ItalicAngle: " + (short)(italicAngle / 0x10000));
if ((italicAngle % 0x10000) > 0)
System.out.print("."+
(short)((italicAngle % 0x10000) * 1000) / 0x10000);
System.out.println();
System.out.println("Ascender: " + get_ttf_funit(ascender));
System.out.println("Descender: " + get_ttf_funit(descender));
System.out.println("FontBBox: [" +
(int) get_ttf_funit(fontBBox1) + " " +
(int) get_ttf_funit(fontBBox2) + " " +
(int) get_ttf_funit(fontBBox3) + " " +
(int) get_ttf_funit(fontBBox4) + "]");
}
public static void main(String[] args) {
try {
TTFFile ttfFile = new TTFFile();
FontFileReader reader = new FontFileReader(args[0]);
String name = null;
if (args.length >= 2)
name = args[1];
ttfFile.readFont(reader, name);
ttfFile.printStuff();
} catch (IOException ioe) {
System.out.println(ioe.toString());
}
}
public String getWindowsName() {
return new String(familyName + ","+subFamilyName);
}
public String getPostscriptName() {
if ("Regular".equals(subFamilyName) ||
"Roman".equals(subFamilyName))
return familyName;
else
return familyName + ","+subFamilyName;
}
public String getFamilyName() {
return familyName;
}
public String getCharSetName() {
return encoding;
}
public int getCapHeight() {
return (int) get_ttf_funit(capHeight);
}
public int getXHeight() {
return (int) get_ttf_funit(xHeight);
}
public int getFlags() {
int flags = 32; // Use Adobe Standard charset
if (italicAngle != 0)
flags = flags | 64;
if (isFixedPitch != 0)
flags = flags | 2;
if (hasSerifs)
flags = flags | 1;
return flags;
}
public String getStemV() {
return "0";
}
public String getItalicAngle() {
String ia = Short.toString((short)(italicAngle / 0x10000));
// This is the correct italic angle, however only int italic
// angles are supported at the moment so this is commented out.
/*
if ((italicAngle % 0x10000) > 0 )
ia=ia+(comma+Short.toString((short)((short)((italicAngle % 0x10000)*1000)/0x10000)));
*/
return ia;
}
public int[] getFontBBox() {
int[] fbb = new int[4];
fbb[0] = (int) get_ttf_funit(fontBBox1);
fbb[1] = (int) get_ttf_funit(fontBBox2);
fbb[2] = (int) get_ttf_funit(fontBBox3);
fbb[3] = (int) get_ttf_funit(fontBBox4);
return fbb;
}
public int getLowerCaseAscent() {
return (int) get_ttf_funit(ascender);
}
public int getLowerCaseDescent() {
return (int) get_ttf_funit(descender);
}
// This is only for WinAnsiEncoding, so the last char is
// the last char < 256
public short getLastChar() {
return lastChar;
}
public short getFirstChar() {
return firstChar;
}
public int[] getWidths() {
int[] wx = new int[mtx_tab.length];
for (int i = 0; i < wx.length; i++)
wx[i] = (int) get_ttf_funit(mtx_tab[i].wx);
return wx;
}
public int getCharWidth(int idx) {
return (int) get_ttf_funit(ansiWidth[idx]);
}
public Hashtable getKerning() {
return kerningTab;
}
public Hashtable getAnsiKerning() {
return ansiKerningTab;
}
public boolean isEmbeddable() {
return is_embeddable;
}
/**
* Read Table Directory from the current position in the
* FontFileReader and fill the global Hashtable dirTabs
* with the table name (String) as key and a TTFDirTabEntry
* as value.
*/
protected void readDirTabs(FontFileReader in) throws IOException {
in.skip(4); // TTF_FIXED_SIZE
int ntabs = in.readTTFUShort();
in.skip(6); // 3xTTF_USHORT_SIZE
dirTabs = new Hashtable();
TTFDirTabEntry[] pd = new TTFDirTabEntry[ntabs];
//System.out.println("Reading " + ntabs + " dir tables");
for (int i = 0; i < ntabs; i++) {
pd[i] = new TTFDirTabEntry();
dirTabs.put(pd[i].read(in), pd[i]);
}
}
/**
* Read the "head" table, this reads the bounding box and
* sets the upem (unitsPerEM) variable
*/
protected void readFontHeader(FontFileReader in) throws IOException {
seek_tab(in, "head", 2 * 4 + 2 * 4 + 2);
upem = in.readTTFUShort();
in.skip(16);
fontBBox1 = in.readTTFShort();
fontBBox2 = in.readTTFShort();
fontBBox3 = in.readTTFShort();
fontBBox4 = in.readTTFShort();
in.skip(2 + 2 + 2);
loca_format = in.readTTFShort();
}
/**
* Read the number of glyphs from the "maxp" table
*/
protected void getNumGlyphs(FontFileReader in) throws IOException {
seek_tab(in, "maxp", 4);
nglyphs = in.readTTFUShort();
}
/** Read the "hhea" table to find the ascender and descender and
* size of "hmtx" table, i.e. a fixed size font might have only
* one width
*/
protected void readHorizontalHeader(FontFileReader in)
throws IOException {
seek_tab(in, "hhea", 4);
ascender = in.readTTFShort(); // Use sTypoAscender in "OS/2" table?
descender = in.readTTFShort(); // Use sTypoDescender in "OS/2" table?
in.skip(2 + 2 + 3 * 2 + 8 * 2);
nhmtx = in.readTTFUShort();
//System.out.println("Number of horizontal metrics: " + nhmtx);
}
/**
* Read "hmtx" table and put the horizontal metrics
* in the mtx_tab array. If the number of metrics is less
* than the number of glyphs (eg fixed size fonts), extend
* the mtx_tab array and fill in the missing widths
*/
protected void readHorizontalMetrics(FontFileReader in)
throws IOException {
seek_tab(in, "hmtx", 0);
int mtx_size = (nglyphs > nhmtx) ? nglyphs : nhmtx;
mtx_tab = new TTFMtxEntry[mtx_size];
//System.out.println("*** Widths array: \n");
for (int i = 0; i < mtx_size; i++)
mtx_tab[i] = new TTFMtxEntry();
for (int i = 0; i < nhmtx; i++) {
mtx_tab[i].wx = in.readTTFUShort();
mtx_tab[i].lsb = in.readTTFUShort();
/*
System.out.println(" width["+i+"] = "+
get_ttf_funit(mtx_tab[i].wx)+";");
*/
}
if (nhmtx < mtx_size) {
// Fill in the missing widths
int lastWidth = mtx_tab[nhmtx - 1].wx;
for (int i = nhmtx; i < mtx_size; i++) {
mtx_tab[i].wx = lastWidth;
mtx_tab[i].lsb = in.readTTFUShort();
}
}
}
/**
* Read the "post" table
* containing the postscript names of the glyphs.
*/
private final void readPostscript(FontFileReader in)
throws IOException {
String[] ps_glyphs_buf;
int i, k, l;
seek_tab(in, "post", 0);
post_format = in.readTTFLong();
italicAngle = in.readTTFULong();
underlinePosition = in.readTTFShort();
underlineThickness = in.readTTFShort();
isFixedPitch = in.readTTFULong();
in.skip(4 * 4);
//System.out.println("Post format: "+post_format);
switch (post_format) {
case 0x00010000:
//System.out.println("Postscript format 1");
for (i = 0; i < Glyphs.mac_glyph_names.length; i++) {
mtx_tab[i].name = Glyphs.mac_glyph_names[i];
}
break;
case 0x00020000:
//System.out.println("Postscript format 2");
int numGlyphStrings = 0;
l = in.readTTFUShort(); // Num Glyphs
//short minIndex=256;
for (i = 0; i < l ; i++) { // Read indexes
mtx_tab[i].index = in.readTTFUShort();
//if (minIndex > mtx_tab[i].index)
//minIndex=(short)mtx_tab[i].index;
if (mtx_tab[i].index > 257)
numGlyphStrings++;
//System.out.println("Post index: "+mtx_tab[i].index);
}
//firstChar=minIndex;
ps_glyphs_buf = new String[numGlyphStrings];
//System.out.println("Reading " + numGlyphStrings +
// " glyphnames"+
// ", was n num glyphs="+l);
for (i = 0; i < ps_glyphs_buf.length; i++) {
ps_glyphs_buf[i] = in.readTTFString(in.readTTFUByte());
}
for (i = 0; i < l; i++) {
if (mtx_tab[i].index < NMACGLYPHS) {
mtx_tab[i].name =
Glyphs.mac_glyph_names[mtx_tab[i].index];
} else {
k = mtx_tab[i].index - NMACGLYPHS ;
/*
System.out.println(k+" i="+i+" mtx="+mtx_tab.length+
" ps="+ps_glyphs_buf.length);
*/
mtx_tab[i].name = ps_glyphs_buf[k];
}
}
break;
case 0x00030000:
// Postscript format 3 contains no glyph names
System.out.println("Postscript format 3");
break;
default:
System.out.println("Unknown Postscript format : " +
post_format);
}
}
/**
* Read the "OS/2" table
*/
private final void readOS2(FontFileReader in) throws IOException {
// Check if font is embeddable
if (dirTabs.get("OS/2") != null) {
seek_tab(in, "OS/2", 2 * 4);
int fsType = in.readTTFUShort();
if (fsType == 2)
is_embeddable = false;
else
is_embeddable = true;
} else
is_embeddable = true;
}
/**
* Read the "loca" table
*/
protected final void readIndexToLocation(FontFileReader in)
throws IOException {
seek_tab(in, "loca", 0);
for (int i = 0; i < nglyphs ; i++) {
mtx_tab[i].offset = (loca_format == 1 ? in.readTTFULong() :
(in.readTTFUShort() << 1));
}
lastLoca = (loca_format == 1 ? in.readTTFULong() :
(in.readTTFUShort() << 1));
}
/**
* Read the "glyf" table to find the bounding boxes
*/
private final void readGlyf(FontFileReader in) throws IOException {
TTFDirTabEntry dirTab = (TTFDirTabEntry) dirTabs.get("glyf");
for (int i = 0; i < (nglyphs - 1); i++) {
if (mtx_tab[i].offset != mtx_tab[i + 1].offset) {
in.seek_set(dirTab.offset + mtx_tab[i].offset);
in.skip(2);
mtx_tab[i].bbox[0] = in.readTTFShort();
mtx_tab[i].bbox[1] = in.readTTFShort();
mtx_tab[i].bbox[2] = in.readTTFShort();
mtx_tab[i].bbox[3] = in.readTTFShort();
} else {
mtx_tab[i].bbox[0] = mtx_tab[0].bbox[0];
mtx_tab[i].bbox[1] = mtx_tab[0].bbox[1];
mtx_tab[i].bbox[2] = mtx_tab[0].bbox[2];
mtx_tab[i].bbox[3] = mtx_tab[0].bbox[3];
}
}
long n = ((TTFDirTabEntry) dirTabs.get("glyf")).offset;
for (int i = 0; i < nglyphs; i++) {
if ((i + 1) >= mtx_tab.length ||
mtx_tab[i].offset != mtx_tab[i + 1].offset) {
in.seek_set(n + mtx_tab[i].offset);
in.skip(2);
mtx_tab[i].bbox[0] = in.readTTFShort();
mtx_tab[i].bbox[1] = in.readTTFShort();
mtx_tab[i].bbox[2] = in.readTTFShort();
mtx_tab[i].bbox[3] = in.readTTFShort();
} else {
mtx_tab[i].bbox[0] = mtx_tab[0].bbox[0];
mtx_tab[i].bbox[1] = mtx_tab[0].bbox[0];
mtx_tab[i].bbox[2] = mtx_tab[0].bbox[0];
mtx_tab[i].bbox[3] = mtx_tab[0].bbox[0];
}
//System.out.println(mtx_tab[i].toString(this));
}
}
/**
* Read the "name" table
*/
private final void readName(FontFileReader in) throws IOException {
int platform_id, encoding_id, language_id;
seek_tab(in, "name", 2);
int i = in.getCurrentPos();
int n = in.readTTFUShort();
int j = in.readTTFUShort() + i - 2;
i += 2 * 2;
while (n-- > 0) {
//System.out.println("Iteration: "+n);
in.seek_set(i);
platform_id = in.readTTFUShort();
encoding_id = in.readTTFUShort();
language_id = in.readTTFUShort();
int k = in.readTTFUShort();
int l = in.readTTFUShort();
if (((platform_id == 1 || platform_id == 3) &&
(encoding_id == 0 || encoding_id == 1)) &&
(k == 1 || k == 2 || k == 0 || k == 4 || k == 6)) {
// if (k==1 || k==2 || k==0 || k==4 || k==6) {
in.seek_set(j + in.readTTFUShort());
String txt = in.readTTFString(l);
//System.out.println(platform_id+" "+encoding_id+
//" "+k+" "+txt);
switch (k) {
case 0:
notice = txt;
break;
case 1:
familyName = txt;
break;
case 2:
subFamilyName = txt;
break;
case 4:
fullName = txt;
break;
case 6:
fontName = txt;
break;
}
if (!notice.equals("") && !fullName.equals("") &&
!fontName.equals("") && !familyName.equals("") &&
!subFamilyName.equals("")) {
break;
}
}
i += 6 * 2;
}
}
/**
* Read the "PCLT" table to find xHeight and capHeight
*/
private final void readPCLT(FontFileReader in) throws IOException {
TTFDirTabEntry dirTab = (TTFDirTabEntry) dirTabs.get("PCLT");
if (dirTab != null) {
in.seek_set(dirTab.offset + 4 + 4 + 2);
xHeight = in.readTTFUShort();
in.skip(2 * 2);
capHeight = in.readTTFUShort();
in.skip(2 + 16 + 8 + 6 + 1 + 1);
int serifStyle = in.readTTFUByte();
serifStyle = serifStyle >> 6;
serifStyle = serifStyle & 3;
if (serifStyle == 1)
hasSerifs = false;
else
hasSerifs = true;
} else {
// Approximate capHeight from height of "H"
// It's most unlikly that a font misses the PCLT table
// This also assumes that psocriptnames exists ("H")
// Should look it up int the cmap (that wouldn't help
// for charsets without H anyway...)
for (int i = 0; i < mtx_tab.length; i++) {
if ("H".equals(mtx_tab[i].name))
capHeight = mtx_tab[i].bbox[3] - mtx_tab[i].bbox[1];
}
}
}
/**
* Read the kerning table, create a table for both CIDs and
* winAnsiEncoding
*/
private final void readKerning(FontFileReader in) throws IOException {
// Read kerning
kerningTab = new Hashtable();
ansiKerningTab = new Hashtable();
TTFDirTabEntry dirTab = (TTFDirTabEntry) dirTabs.get("kern");
if (dirTab != null) {
seek_tab(in, "kern", 2);
for (int n = in.readTTFUShort(); n > 0 ; n--) {
in.skip(2 * 2);
int k = in.readTTFUShort();
if (!((k & 1) != 0) || (k & 2) != 0 || (k & 4) != 0)
return;
if ((k >> 8) != 0)
continue;
k = in.readTTFUShort();
in.skip(3 * 2);
while (k-- > 0) {
int i = in.readTTFUShort();
int j = in.readTTFUShort();
int kpx = in.readTTFShort();
if (kpx != 0) {
// CID table
Integer iObj = new Integer(i);
Hashtable adjTab = (Hashtable) kerningTab.get(iObj);
if (adjTab == null)
adjTab = new java.util.Hashtable();
adjTab.put(new Integer(j),
new Integer((int) get_ttf_funit(kpx)));
kerningTab.put(iObj, adjTab);
}
}
}
//System.out.println(kerningTab.toString());
// Create winAnsiEncoded kerning table
for (Enumeration ae = kerningTab.keys();
ae.hasMoreElements();) {
Integer cidKey = (Integer) ae.nextElement();
Hashtable akpx = new Hashtable();
Hashtable ckpx = (Hashtable) kerningTab.get(cidKey);
for (Enumeration aee = ckpx.keys();
aee.hasMoreElements();) {
Integer cidKey2 = (Integer) aee.nextElement();
Integer kern = (Integer) ckpx.get(cidKey2);
for (Enumeration uniMap = mtx_tab[cidKey2.intValue()]
.unicodeIndex.elements();
uniMap.hasMoreElements();) {
Integer unicodeKey = (Integer) uniMap.nextElement();
Integer[] ansiKeys =
unicodeToWinAnsi(unicodeKey.intValue());
for (int u = 0; u < ansiKeys.length; u++) {
akpx.put(ansiKeys[u], kern);
}
}
}
if (akpx.size() > 0)
for (Enumeration uniMap = mtx_tab[cidKey.intValue()]
.unicodeIndex.elements();
uniMap.hasMoreElements();) {
Integer unicodeKey = (Integer) uniMap.nextElement();
Integer[] ansiKeys =
unicodeToWinAnsi(unicodeKey.intValue());
for (int u = 0; u < ansiKeys.length; u++) {
ansiKerningTab.put(ansiKeys[u], akpx);
}
}
}
}
}
/** Return a vector with TTFCmapEntry
*/
public Vector getCMaps() {
return cmaps;
}
/**
* Check if this is a TrueType collection and that the given
* name exists in the collection.
* If it does, set offset in fontfile to the beginning of
* the Table Directory for that font
@ return true if not collection or font name present, false
otherwise
*/
protected final boolean checkTTC(FontFileReader in, String name,
boolean verbose) throws IOException {
String tag = in.readTTFString(4);
if ("ttcf".equals(tag)) {
// This is a TrueType Collection
in.skip(4);
// Read directory offsets
int numDirectories = (int) in.readTTFULong();
//int numDirectories=in.readTTFUShort();
long[] dirOffsets = new long[numDirectories];
for (int i = 0; i < numDirectories; i++) {
dirOffsets[i] = in.readTTFULong();
}
if (verbose) {
System.out.println("This is a TrueType collection file with"+
numDirectories + " fonts");
System.out.println("Containing the following fonts: ");
}
// Read all the directories and name tables to check
// If the font exists - this is a bit ugly, but...
boolean found = false;
// Iterate through all name tables even if font
// Is found, just to show all the names
long dirTabOffset = 0;
for (int i = 0; (i < numDirectories); i++) {
in.seek_set(dirOffsets[i]);
readDirTabs(in);
readName(in);
if (fullName.equals(name)) {
found = true;
dirTabOffset = dirOffsets[i];
if (verbose)
System.out.println("* " + fullName);
} else {
if (verbose)
System.out.println(fullName);
}
// Reset names
notice = "";
fullName = "";
familyName = "";
fontName = "";
subFamilyName = "";
}
in.seek_set(dirTabOffset);
return found;
}
else {
in.seek_set(0);
return true;
}
}
/* Helper classes, they are not very efficient, but that really
doesn't matter... */
private Integer[] unicodeToWinAnsi(int unicode) {
Vector ret = new Vector();
for (int i = 32; i < Glyphs.winAnsiEncoding.length; i++)
if (unicode == Glyphs.winAnsiEncoding[i])
ret.addElement(new Integer(i));
Integer[] itg = new Integer[ret.size()];
ret.copyInto(itg);
return itg;
}
}
/**
* Key-value helper class
*/
class UnicodeMapping {
int uIdx;
int gIdx;
UnicodeMapping(int gIdx, int uIdx) {
this.uIdx = uIdx;
this.gIdx = gIdx;
}
}
| true | true | private boolean readCMAP(FontFileReader in) throws IOException {
unicodeMapping = new Vector();
/** Read CMAP table and correct mtx_tab.index*/
int mtxPtr = 0;
seek_tab(in, "cmap", 2);
int num_cmap = in.readTTFUShort(); // Number of cmap subtables
long cmap_unioffset = 0;
//System.out.println(num_cmap+" cmap tables");
/* Read offset for all tables
We are only interested in the unicode table
*/
for (int i = 0; i < num_cmap; i++) {
int cmap_pid = in.readTTFUShort();
int cmap_eid = in.readTTFUShort();
long cmap_offset = in.readTTFULong();
//System.out.println("Platform ID: "+cmap_pid+
// " Encoding: "+cmap_eid);
if (cmap_pid == 3 && cmap_eid == 1)
cmap_unioffset = cmap_offset;
}
if (cmap_unioffset <= 0) {
System.out.println("Unicode cmap table not present");
return false;
}
// Read unicode cmap
seek_tab(in, "cmap", cmap_unioffset);
int cmap_format = in.readTTFUShort();
int cmap_length = in.readTTFUShort();
//System.out.println("CMAP format: "+cmap_format);
if (cmap_format == 4) {
in.skip(2); // Skip version number
int cmap_segCountX2 = in.readTTFUShort();
int cmap_searchRange = in.readTTFUShort();
int cmap_entrySelector = in.readTTFUShort();
int cmap_rangeShift = in.readTTFUShort();
/*
System.out.println("segCountX2 : "+cmap_segCountX2);
System.out.println("searchRange : "+cmap_searchRange);
System.out.println("entrySelector: "+cmap_entrySelector);
System.out.println("rangeShift : "+cmap_rangeShift);
*/
int cmap_endCounts[] = new int[cmap_segCountX2 / 2];
int cmap_startCounts[] = new int[cmap_segCountX2 / 2];
int cmap_deltas[] = new int[cmap_segCountX2 / 2];
int cmap_rangeOffsets[] = new int[cmap_segCountX2 / 2];
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_endCounts[i] = in.readTTFUShort();
}
in.skip(2); // Skip reservedPad
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_startCounts[i] = in.readTTFUShort();
}
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_deltas[i] = in.readTTFShort();
}
int startRangeOffset = in.getCurrentPos();
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_rangeOffsets[i] = in.readTTFShort();
}
int glyphIdArrayOffset = in.getCurrentPos();
// Insert the unicode id for the glyphs in mtx_tab
// and fill in the cmaps Vector
for (int i = 0; i < cmap_startCounts.length; i++) {
/*
System.out.println(i+ ": "+cmap_startCounts[i]+
" - "+cmap_endCounts[i]);
*/
for (int j = cmap_startCounts[i];
j <= cmap_endCounts[i]; j++) {
// Update lastChar
if (j < 256 && j > lastChar)
lastChar = (short) j;
if (mtxPtr < mtx_tab.length) {
if (cmap_rangeOffsets[i] != 0) {
int glyphOffset = glyphIdArrayOffset +
((cmap_rangeOffsets[i] / 2) +
(j - cmap_startCounts[i]) + (i) -
cmap_segCountX2 / 2) * 2;
in.seek_set(glyphOffset);
int glyphIdx = (in.readTTFUShort() +
cmap_deltas[i]) & 0xffff;
unicodeMapping.addElement(
new UnicodeMapping(glyphIdx, j));
mtx_tab[glyphIdx].unicodeIndex.addElement(
new Integer(j));
// Also add winAnsiWidth
if (false) {
int d = j;
if (j > 127)
d = (int)
org.apache.fop.render.pdf.CodePointMapping.map[j];
if (d < ansiWidth.length)
ansiWidth[d] = mtx_tab[glyphIdx].wx;
} else {
Vector v = (Vector) ansiIndex.get(
new Integer(j));
if (v != null) {
for (Enumeration e = v.elements();
e.hasMoreElements();) {
Integer aIdx =
(Integer) e.nextElement();
ansiWidth[aIdx.intValue()] =
mtx_tab[glyphIdx].wx;
/*
System.out.println("Added width "+
mtx_tab[glyphIdx].wx +
" uni: " + j +
" ansi: " + aIdx.intValue());
*/
}
}
}
/*
System.out.println("Idx: "+
glyphIdx +
" Delta: " + cmap_deltas[i]+
" Unicode: " + j +
" name: " +
mtx_tab[glyphIdx].name);
*/
}
else {
int glyphIdx = (j + cmap_deltas[i]) & 0xffff;
if (glyphIdx < mtx_tab.length)
mtx_tab[glyphIdx] .unicodeIndex.addElement(
new Integer(j));
else
System.out.println("Glyph " +
glyphIdx + " out of range: " +
mtx_tab.length);
unicodeMapping.addElement(
new UnicodeMapping(glyphIdx, j));
if (glyphIdx < mtx_tab.length)
mtx_tab[glyphIdx] .unicodeIndex.addElement(
new Integer(j));
else
System.out.println("Glyph " +
glyphIdx + " out of range: " +
mtx_tab.length);
// Also add winAnsiWidth
if (false) {
int d = j;
if (j > 127)
d = (int)
org.apache.fop.render.pdf.CodePointMapping.map[j];
if (d < ansiWidth.length)
ansiWidth[d] = mtx_tab[glyphIdx].wx;
} else {
Vector v = (Vector) ansiIndex.get(
new Integer(j));
if (v != null) {
for (Enumeration e = v.elements();
e.hasMoreElements();) {
Integer aIdx =
(Integer) e.nextElement();
ansiWidth[aIdx.intValue()] =
mtx_tab[glyphIdx].wx;
}
}
}
/*
System.out.println("IIdx: "+
mtxPtr +
" Delta: " + cmap_deltas[i]+
" Unicode: " + j +
" name: " +
mtx_tab[(j+cmap_deltas[i]) & 0xffff].name);
*/
}
mtxPtr++;
}
}
}
}
return true;
}
| private boolean readCMAP(FontFileReader in) throws IOException {
unicodeMapping = new Vector();
/** Read CMAP table and correct mtx_tab.index*/
int mtxPtr = 0;
seek_tab(in, "cmap", 2);
int num_cmap = in.readTTFUShort(); // Number of cmap subtables
long cmap_unioffset = 0;
//System.out.println(num_cmap+" cmap tables");
/* Read offset for all tables
We are only interested in the unicode table
*/
for (int i = 0; i < num_cmap; i++) {
int cmap_pid = in.readTTFUShort();
int cmap_eid = in.readTTFUShort();
long cmap_offset = in.readTTFULong();
//System.out.println("Platform ID: "+cmap_pid+
// " Encoding: "+cmap_eid);
if (cmap_pid == 3 && cmap_eid == 1)
cmap_unioffset = cmap_offset;
}
if (cmap_unioffset <= 0) {
System.out.println("Unicode cmap table not present");
return false;
}
// Read unicode cmap
seek_tab(in, "cmap", cmap_unioffset);
int cmap_format = in.readTTFUShort();
int cmap_length = in.readTTFUShort();
//System.out.println("CMAP format: "+cmap_format);
if (cmap_format == 4) {
in.skip(2); // Skip version number
int cmap_segCountX2 = in.readTTFUShort();
int cmap_searchRange = in.readTTFUShort();
int cmap_entrySelector = in.readTTFUShort();
int cmap_rangeShift = in.readTTFUShort();
/*
System.out.println("segCountX2 : "+cmap_segCountX2);
System.out.println("searchRange : "+cmap_searchRange);
System.out.println("entrySelector: "+cmap_entrySelector);
System.out.println("rangeShift : "+cmap_rangeShift);
*/
int cmap_endCounts[] = new int[cmap_segCountX2 / 2];
int cmap_startCounts[] = new int[cmap_segCountX2 / 2];
int cmap_deltas[] = new int[cmap_segCountX2 / 2];
int cmap_rangeOffsets[] = new int[cmap_segCountX2 / 2];
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_endCounts[i] = in.readTTFUShort();
}
in.skip(2); // Skip reservedPad
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_startCounts[i] = in.readTTFUShort();
}
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_deltas[i] = in.readTTFShort();
}
int startRangeOffset = in.getCurrentPos();
for (int i = 0; i < (cmap_segCountX2 / 2); i++) {
cmap_rangeOffsets[i] = in.readTTFUShort();
}
int glyphIdArrayOffset = in.getCurrentPos();
// Insert the unicode id for the glyphs in mtx_tab
// and fill in the cmaps Vector
for (int i = 0; i < cmap_startCounts.length; i++) {
/*
System.out.println(i+ ": "+cmap_startCounts[i]+
" - "+cmap_endCounts[i]);
*/
for (int j = cmap_startCounts[i];
j <= cmap_endCounts[i]; j++) {
// Update lastChar
if (j < 256 && j > lastChar)
lastChar = (short) j;
if (mtxPtr < mtx_tab.length) {
if (cmap_rangeOffsets[i] != 0) {
int glyphOffset = glyphIdArrayOffset +
((cmap_rangeOffsets[i] / 2) +
(j - cmap_startCounts[i]) + (i) -
cmap_segCountX2 / 2) * 2;
in.seek_set(glyphOffset);
int glyphIdx = (in.readTTFUShort() +
cmap_deltas[i]) & 0xffff;
unicodeMapping.addElement(
new UnicodeMapping(glyphIdx, j));
mtx_tab[glyphIdx].unicodeIndex.addElement(
new Integer(j));
// Also add winAnsiWidth
if (false) {
int d = j;
if (j > 127)
d = (int)
org.apache.fop.render.pdf.CodePointMapping.map[j];
if (d < ansiWidth.length)
ansiWidth[d] = mtx_tab[glyphIdx].wx;
} else {
Vector v = (Vector) ansiIndex.get(
new Integer(j));
if (v != null) {
for (Enumeration e = v.elements();
e.hasMoreElements();) {
Integer aIdx =
(Integer) e.nextElement();
ansiWidth[aIdx.intValue()] =
mtx_tab[glyphIdx].wx;
/*
System.out.println("Added width "+
mtx_tab[glyphIdx].wx +
" uni: " + j +
" ansi: " + aIdx.intValue());
*/
}
}
}
/*
System.out.println("Idx: "+
glyphIdx +
" Delta: " + cmap_deltas[i]+
" Unicode: " + j +
" name: " +
mtx_tab[glyphIdx].name);
*/
}
else {
int glyphIdx = (j + cmap_deltas[i]) & 0xffff;
if (glyphIdx < mtx_tab.length)
mtx_tab[glyphIdx] .unicodeIndex.addElement(
new Integer(j));
else
System.out.println("Glyph " +
glyphIdx + " out of range: " +
mtx_tab.length);
unicodeMapping.addElement(
new UnicodeMapping(glyphIdx, j));
if (glyphIdx < mtx_tab.length)
mtx_tab[glyphIdx] .unicodeIndex.addElement(
new Integer(j));
else
System.out.println("Glyph " +
glyphIdx + " out of range: " +
mtx_tab.length);
// Also add winAnsiWidth
if (false) {
int d = j;
if (j > 127)
d = (int)
org.apache.fop.render.pdf.CodePointMapping.map[j];
if (d < ansiWidth.length)
ansiWidth[d] = mtx_tab[glyphIdx].wx;
} else {
Vector v = (Vector) ansiIndex.get(
new Integer(j));
if (v != null) {
for (Enumeration e = v.elements();
e.hasMoreElements();) {
Integer aIdx =
(Integer) e.nextElement();
ansiWidth[aIdx.intValue()] =
mtx_tab[glyphIdx].wx;
}
}
}
/*
System.out.println("IIdx: "+
mtxPtr +
" Delta: " + cmap_deltas[i]+
" Unicode: " + j +
" name: " +
mtx_tab[(j+cmap_deltas[i]) & 0xffff].name);
*/
}
mtxPtr++;
}
}
}
}
return true;
}
|
diff --git a/src/com/cse755/SExpression.java b/src/com/cse755/SExpression.java
index 0d2ad8f..e956792 100644
--- a/src/com/cse755/SExpression.java
+++ b/src/com/cse755/SExpression.java
@@ -1,184 +1,185 @@
package com.cse755;
/**
* Class to represent an S-expression or an atom. If atom is non-null, contents
* of leftChild and rightChild should be ignored because this object represents
* an atom.
*
* @author Dan Ziemba
*/
public class SExpression {
private Atom atom;
private SExpression leftChild;
private SExpression rightChild;
private SExpression parent;
private boolean hasDot;
private Boolean isList = null;
/**
* Create empty s-expression.
*/
public SExpression() {
}
/**
* Create an s-expression that is just an atom.
*/
public SExpression(Atom atom) {
this.atom = atom;
}
/**
* @return the atom
*/
public Atom getAtom() {
return atom;
}
/**
* @param atom
* the atom to set. Don't do this if left or right child are set.
*/
public void setAtom(Atom atom) {
this.atom = atom;
if (this.leftChild != null || this.rightChild != null) {
// TODO: remove warnings
System.out.println("WARNING: Atom set on non-empty s-expression");
}
}
/**
* @return the leftChild
*/
public SExpression getLeftChild() {
return leftChild;
}
/**
* Set left child. Also sets left child's parent to this.
*
* @param leftChild
* the s-expression to set as left child
*/
public void setLeftChild(SExpression leftChild) {
this.leftChild = leftChild;
this.leftChild.setParent(this);
if (this.atom != null) {
// TODO: remove warnings
System.out.println("WARNING: Left-child set on atom");
}
}
/**
* @return the rightChild
*/
public SExpression getRightChild() {
return rightChild;
}
/**
* Set right child. Also sets right child's parent to this.
*
* @param rightChild
* the s-expression to set as right child
*/
public void setRightChild(SExpression rightChild) {
this.rightChild = rightChild;
this.rightChild.setParent(this);
if (this.atom != null) {
// TODO: remove warnings
System.out.println("WARNING: Right-child set on atom");
}
}
/**
* @return the parent s-expression. A value of null indicates this is the
* root s-expression.
*/
public SExpression getParent() {
return parent;
}
/**
* @param parent
* the parent s-expression. Leave null to indicate this is root.
*/
public void setParent(SExpression parent) {
this.parent = parent;
}
/**
* @return True if this s-expression had a dot in the middle
*/
public boolean hasDot() {
return hasDot;
}
/**
* @param hasDot
* True if this s-expression had a dot in the middle
*/
public void setHasDot(boolean hasDot) {
this.hasDot = hasDot;
}
@Override
public String toString() {
StringBuilder tabs = new StringBuilder();
SExpression temp = this;
while ((temp = temp.getParent()) != null) {
tabs.append('\t');
}
return (isList() ? "*" : "")
+ "SExpression ["
+ (atom != null ? "atom=" + atom + ", " : "")
+ (leftChild != null ? "\n" + tabs + "\tleftChild=" + leftChild
+ ", " : "")
+ (rightChild != null ? "\n" + tabs + "\trightChild="
+ rightChild : "") + "]";
}
public void print() {
if (this.atom != null) {
atom.print();
} else if (isList()) {
boolean isListRoot = false;
- isListRoot = (parent == null || (parent != null && !parent.isList()));
+ // First node of list is always the left child of its parent
+ isListRoot = (parent == null || (parent != null && parent.leftChild == this));
if (isListRoot)
System.out.print('(');
leftChild.print();
if (!(rightChild.isAtom() && rightChild.getAtom().isNil())) {
System.out.print(' ');
rightChild.print();
}
if (isListRoot)
System.out.print(')');
} else {
System.out.print('(');
leftChild.print();
System.out.print(" . ");
rightChild.print();
System.out.print(')');
}
// Print newline if this is root
if (parent == null)
System.out.println();
}
public boolean isAtom() {
return (atom != null);
}
public boolean isList() {
if (atom != null && atom.isNil()) {
isList = Boolean.TRUE;
} else if (rightChild != null && rightChild.isList()) {
isList = Boolean.TRUE;
} else {
isList = Boolean.FALSE;
}
return isList.booleanValue();
}
}
| true | true | public void print() {
if (this.atom != null) {
atom.print();
} else if (isList()) {
boolean isListRoot = false;
isListRoot = (parent == null || (parent != null && !parent.isList()));
if (isListRoot)
System.out.print('(');
leftChild.print();
if (!(rightChild.isAtom() && rightChild.getAtom().isNil())) {
System.out.print(' ');
rightChild.print();
}
if (isListRoot)
System.out.print(')');
} else {
System.out.print('(');
leftChild.print();
System.out.print(" . ");
rightChild.print();
System.out.print(')');
}
// Print newline if this is root
if (parent == null)
System.out.println();
}
| public void print() {
if (this.atom != null) {
atom.print();
} else if (isList()) {
boolean isListRoot = false;
// First node of list is always the left child of its parent
isListRoot = (parent == null || (parent != null && parent.leftChild == this));
if (isListRoot)
System.out.print('(');
leftChild.print();
if (!(rightChild.isAtom() && rightChild.getAtom().isNil())) {
System.out.print(' ');
rightChild.print();
}
if (isListRoot)
System.out.print(')');
} else {
System.out.print('(');
leftChild.print();
System.out.print(" . ");
rightChild.print();
System.out.print(')');
}
// Print newline if this is root
if (parent == null)
System.out.println();
}
|
diff --git a/src/plugin/tools/sed/Sed.java b/src/plugin/tools/sed/Sed.java
index 8f8bab9..7e31788 100644
--- a/src/plugin/tools/sed/Sed.java
+++ b/src/plugin/tools/sed/Sed.java
@@ -1,269 +1,269 @@
package plugin.tools.sed;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Stack;
import core.event.Message;
import core.plugin.Plugin;
import core.utils.Colour;
import core.utils.Details;
import core.utils.IRC;
/**
* Sed plugin.
*
* Handles messages of the form: s/<search>/<replacement>/
* s/<search>/<replacement> <username>: s/<search>/<replacement>/ <username>:
* s/<search>/<replacement>
*/
public class Sed extends Plugin {
/**
* The max number of Message objects stored per user.
*/
private static final int CACHE_SIZE = 10;
/**
* The ASCII SOH character.
*/
private static final char ASCII_SOH = '\001';
/**
* The first group of the sed regex.
*/
private static final int SED_USERNAME_GROUP = 1;
/**
* The second group of the sed regex.
*/
private static final int SED_SEARCH_GROUP = 2;
/**
* The third group of the sed regex.
*/
private static final int SED_REPLACEMENT_GROUP = 3;
/**
* Details instance.
*/
private Details details_ = Details.getInstance();
/**
* IRC instance.
*/
private IRC irc_ = IRC.getInstance();
/**
* Stores Messages objects per-user.
*/
private Map<String, Stack<Message>> cache_ = new HashMap<String, Stack<Message>>();
public final void onMessage(final Message messageObj) throws Exception {
String message = messageObj.getMessage();
String channel = messageObj.getChannel();
String user = messageObj.getUser();
// debug commands
if (message.equals(".seddumpcache") && details_.isAdmin(user)) {
dumpCache(user, channel);
return;
}
if (message.equals(".seddropcache") && details_.isAdmin(user)) {
dropCache(user, channel);
return;
}
// set up sed finding regex
// (?: starts a non-capture group
// ([\\w]+) captures the username
// )? makes the group optional
// ([^/]+) captures the search string
// ([^/]*) captures the replacement
Pattern sedFinder = Pattern
.compile("^(?:([\\w]+): )?s/([^/]+)/([^/]*)/?");
Matcher m = sedFinder.matcher(message);
// it's sed time, baby
if (m.find()) {
String targetUser = new String();
if (m.group(SED_USERNAME_GROUP) != null) {
targetUser = m.group(SED_USERNAME_GROUP);
}
String search = m.group(SED_SEARCH_GROUP);
String replacement = m.group(SED_REPLACEMENT_GROUP);
Stack<Message> userCache = new Stack<Message>();
boolean hasTarget = (!targetUser.equals(new String()) && !targetUser
.equals(user));
if (!hasTarget) {
// no target, use last message from
// sourceUser's cache (or do nothing)
userCache = getUserCache(user);
} else {
// target specified, run through the cache
// (most recent first) and either match and
// replace or do nothing
userCache = getUserCache(targetUser);
}
while (!userCache.empty()) {
Message tempMessage = userCache.pop();
String text = tempMessage.getMessage();
if (isActionMessage(text)) {
text = processActionMessage(text, tempMessage.getUser());
}
m = Pattern.compile(search,
Pattern.CASE_INSENSITIVE | Pattern.DOTALL)
.matcher(text);
if (m.find()) {
String reply = new String();
if (hasTarget) {
reply = user + " thought ";
}
reply += "%s meant: %s";
try {
text = text.replace(search, replacement);
- } catch (StringIndexOutOfBoundsException e) {
- throw new SedException(e.getMessage());
- }
+ } catch (StringIndexOutOfBoundsException e) {
+ throw new SedException(e.getMessage());
+ }
irc_.sendPrivmsg(channel,
String.format(reply, tempMessage.getUser(), text));
break;
}
}
} else {
// no dice, add message to history queue
addToCache(messageObj);
}
}
/**
* Identifies ACTION messages.
*
* @param msg
* The message string
* @return true if msg is an ACTION message
*/
private boolean isActionMessage(final String msg) {
return msg.startsWith(ASCII_SOH + "ACTION")
&& msg.endsWith(Character.toString(ASCII_SOH));
}
/**
* Converts an ACTION message into a friendlier form.
*
* @param msg
* The message string
* @param user
* The speaker
* @return The modified message string
*/
private String processActionMessage(final String msg, final String user) {
if (!isActionMessage(msg)) {
return msg;
}
// remove special chars
String newMsg = msg.substring(1);
newMsg = newMsg.substring(0, newMsg.length() - 1);
// format for output
newMsg = newMsg.replace("ACTION",
Colour.colour("* " + user, Colour.MAGENTA));
return newMsg;
}
/**
* Adds a message object to the cache.
*
* @param msg
* The message object
*/
private void addToCache(final Message msg) {
String userName = msg.getUser();
if (!cache_.containsKey(userName)) {
cache_.put(userName, new Stack<Message>());
}
cache_.get(userName).push(msg);
if (cache_.get(userName).size() > CACHE_SIZE) {
cache_.get(userName).remove(0);
}
}
/**
* Stack of messages from a single user.
*
* @param userName
* The name of the user
* @return The user's cache
*/
private Stack<Message> getUserCache(final String userName) {
Stack<Message> userCache = new Stack<Message>();
if (cache_.containsKey(userName)) {
userCache.addAll(cache_.get(userName));
}
return userCache;
}
/**
* Dumps entire cache into query window.
*
* @param target
* The username of the requester
* @param channel
* The channel originating the request
* @throws Exception
* Inherited badness from core
*/
private void dumpCache(final String target, final String channel)
throws Exception {
irc_.sendPrivmsg(target, "sed cache for " + channel);
for (String user : cache_.keySet()) {
Stack<Message> userCache = getUserCache(user);
irc_.sendPrivmsg(target, " ");
irc_.sendPrivmsg(target, user + ": " + userCache.size() + "/"
+ CACHE_SIZE);
for (Message msg : userCache) {
irc_.sendPrivmsg(target, "\"" + msg.getMessage() + "\"");
}
}
}
/**
* Drops the entire sed cache and reinstantiates cache.
*
* @param target
* The username of the requester
* @param channel
* The channel originating the request
* @throws Exception
* Inherited badness from core
*/
private void dropCache(final String target, final String channel)
throws Exception {
cache_ = new HashMap<String, Stack<Message>>();
irc_.sendPrivmsg(target, "dropped sed cache for " + channel);
}
public final String getHelpString() {
return "SED: \n"
+ "\t[<username>: ]s/<search>/<replacement>/ - "
+ "e.g XeTK: s/.*/hello/ is used to "
+ "replace the previous statement with hello";
}
public class SedException extends Exception {
public SedException(String message) {
super(message);
}
}
}
| true | true | public final void onMessage(final Message messageObj) throws Exception {
String message = messageObj.getMessage();
String channel = messageObj.getChannel();
String user = messageObj.getUser();
// debug commands
if (message.equals(".seddumpcache") && details_.isAdmin(user)) {
dumpCache(user, channel);
return;
}
if (message.equals(".seddropcache") && details_.isAdmin(user)) {
dropCache(user, channel);
return;
}
// set up sed finding regex
// (?: starts a non-capture group
// ([\\w]+) captures the username
// )? makes the group optional
// ([^/]+) captures the search string
// ([^/]*) captures the replacement
Pattern sedFinder = Pattern
.compile("^(?:([\\w]+): )?s/([^/]+)/([^/]*)/?");
Matcher m = sedFinder.matcher(message);
// it's sed time, baby
if (m.find()) {
String targetUser = new String();
if (m.group(SED_USERNAME_GROUP) != null) {
targetUser = m.group(SED_USERNAME_GROUP);
}
String search = m.group(SED_SEARCH_GROUP);
String replacement = m.group(SED_REPLACEMENT_GROUP);
Stack<Message> userCache = new Stack<Message>();
boolean hasTarget = (!targetUser.equals(new String()) && !targetUser
.equals(user));
if (!hasTarget) {
// no target, use last message from
// sourceUser's cache (or do nothing)
userCache = getUserCache(user);
} else {
// target specified, run through the cache
// (most recent first) and either match and
// replace or do nothing
userCache = getUserCache(targetUser);
}
while (!userCache.empty()) {
Message tempMessage = userCache.pop();
String text = tempMessage.getMessage();
if (isActionMessage(text)) {
text = processActionMessage(text, tempMessage.getUser());
}
m = Pattern.compile(search,
Pattern.CASE_INSENSITIVE | Pattern.DOTALL)
.matcher(text);
if (m.find()) {
String reply = new String();
if (hasTarget) {
reply = user + " thought ";
}
reply += "%s meant: %s";
try {
text = text.replace(search, replacement);
} catch (StringIndexOutOfBoundsException e) {
throw new SedException(e.getMessage());
}
irc_.sendPrivmsg(channel,
String.format(reply, tempMessage.getUser(), text));
break;
}
}
} else {
// no dice, add message to history queue
addToCache(messageObj);
}
}
| public final void onMessage(final Message messageObj) throws Exception {
String message = messageObj.getMessage();
String channel = messageObj.getChannel();
String user = messageObj.getUser();
// debug commands
if (message.equals(".seddumpcache") && details_.isAdmin(user)) {
dumpCache(user, channel);
return;
}
if (message.equals(".seddropcache") && details_.isAdmin(user)) {
dropCache(user, channel);
return;
}
// set up sed finding regex
// (?: starts a non-capture group
// ([\\w]+) captures the username
// )? makes the group optional
// ([^/]+) captures the search string
// ([^/]*) captures the replacement
Pattern sedFinder = Pattern
.compile("^(?:([\\w]+): )?s/([^/]+)/([^/]*)/?");
Matcher m = sedFinder.matcher(message);
// it's sed time, baby
if (m.find()) {
String targetUser = new String();
if (m.group(SED_USERNAME_GROUP) != null) {
targetUser = m.group(SED_USERNAME_GROUP);
}
String search = m.group(SED_SEARCH_GROUP);
String replacement = m.group(SED_REPLACEMENT_GROUP);
Stack<Message> userCache = new Stack<Message>();
boolean hasTarget = (!targetUser.equals(new String()) && !targetUser
.equals(user));
if (!hasTarget) {
// no target, use last message from
// sourceUser's cache (or do nothing)
userCache = getUserCache(user);
} else {
// target specified, run through the cache
// (most recent first) and either match and
// replace or do nothing
userCache = getUserCache(targetUser);
}
while (!userCache.empty()) {
Message tempMessage = userCache.pop();
String text = tempMessage.getMessage();
if (isActionMessage(text)) {
text = processActionMessage(text, tempMessage.getUser());
}
m = Pattern.compile(search,
Pattern.CASE_INSENSITIVE | Pattern.DOTALL)
.matcher(text);
if (m.find()) {
String reply = new String();
if (hasTarget) {
reply = user + " thought ";
}
reply += "%s meant: %s";
try {
text = text.replace(search, replacement);
} catch (StringIndexOutOfBoundsException e) {
throw new SedException(e.getMessage());
}
irc_.sendPrivmsg(channel,
String.format(reply, tempMessage.getUser(), text));
break;
}
}
} else {
// no dice, add message to history queue
addToCache(messageObj);
}
}
|
diff --git a/core/src/main/java/com/findwise/hydra/StageRunner.java b/core/src/main/java/com/findwise/hydra/StageRunner.java
index 402944b..8fbffd1 100644
--- a/core/src/main/java/com/findwise/hydra/StageRunner.java
+++ b/core/src/main/java/com/findwise/hydra/StageRunner.java
@@ -1,351 +1,351 @@
package com.findwise.hydra;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.ProcessDestroyer;
import org.apache.commons.exec.launcher.CommandLauncher;
import org.apache.commons.exec.launcher.CommandLauncherFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.findwise.hydra.stage.GroupStarter;
public class StageRunner extends Thread {
private StageGroup stageGroup;
private Logger logger = LoggerFactory.getLogger(getClass());
private StageDestroyer stageDestroyer;
private boolean prepared = false;
private int timesToRetry = -1;
private int timesStarted;
private int pipelinePort;
private List<File> files = null;
private String jvmParameters = null;
private String startupArgsString = null;
private String classPathString = null;
private String java = "java";
private boolean hasQueried = false;
private File targetDirectory;
private File baseDirectory;
private boolean performanceLogging = false;;
private int loggingPort;
private boolean started;
private boolean wasKilled = false;;
public synchronized void setHasQueried() {
hasQueried = true;
}
public synchronized boolean hasQueried() {
return hasQueried;
}
public StageRunner(StageGroup stageGroup, File baseDirectory, int pipelinePort, boolean performanceLogging, int loggingPort) {
this.stageGroup = stageGroup;
this.baseDirectory = baseDirectory;
this.targetDirectory = new File(baseDirectory, stageGroup.getName());
this.pipelinePort = pipelinePort;
this.performanceLogging = performanceLogging;
this.loggingPort = loggingPort;
timesStarted = 0;
}
/**
* This method must be called prior to a call to start()
* @throws IOException
*/
public void prepare() throws IOException {
files = new ArrayList<File>();
if((!baseDirectory.isDirectory() && !baseDirectory.mkdir()) ||
(!targetDirectory.isDirectory() && !targetDirectory.mkdir())) {
throw new IOException("Unable to write files, target ("+targetDirectory.getAbsolutePath()+") is not a directory");
}
for(DatabaseFile df : stageGroup.getDatabaseFiles()) {
File f = new File(targetDirectory, df.getFilename());
files.add(f);
IOUtils.copy(df.getInputStream(), new FileOutputStream(f));
}
stageDestroyer = new StageDestroyer();
setParameters(stageGroup.toPropertiesMap());
if(stageGroup.getStages().size()==1) {
//If there is only a single stage in this group, it's configuration takes precedent
setParameters(stageGroup.getStages().iterator().next().getProperties());
};
prepared = true;
}
public final void setParameters(Map<String, Object> conf) {
if (conf.containsKey(StageGroup.JVM_PARAMETERS_KEY) && conf.get(StageGroup.JVM_PARAMETERS_KEY)!=null) {
jvmParameters = (String) conf.get(StageGroup.JVM_PARAMETERS_KEY);
} else {
jvmParameters = null;
}
if (conf.containsKey(StageGroup.JAVA_LOCATION_KEY) && conf.get(StageGroup.JAVA_LOCATION_KEY)!=null) {
java = (String) conf.get(StageGroup.JAVA_LOCATION_KEY);
} else {
java = "java";
}
if (conf.containsKey(StageGroup.RETRIES_KEY) && conf.get(StageGroup.RETRIES_KEY)!=null) {
timesToRetry = (Integer) conf.get(StageGroup.RETRIES_KEY);
} else {
timesToRetry = -1;
}
}
public void run() {
started = true;
if(!prepared) {
logger.error("The StageRunner was not prepared prior to being started. Aborting!");
return;
}
if(stageGroup.getStages().size()<1) {
logger.info("Stage group "+stageGroup.getName() + " has no stages, and can not be started.");
return;
}
do {
logger.info("Starting stage group " + stageGroup.getName()
+ ". Times started so far: " + timesStarted);
timesStarted++;
boolean cleanShutdown = runGroup();
if (cleanShutdown) {
return;
}
if (!hasQueried()) {
logger.error("The stage group " + stageGroup.getName() + " did not start. It will not be restarted until configuration changes.");
return;
}
} while (timesToRetry == -1 || timesToRetry >= timesStarted);
logger.error("Stage group " + stageGroup.getName()
+ " has failed and cannot be restarted. ");
}
public void printJavaVersion() {
CommandLine cmdLine = new CommandLine("java");
cmdLine.addArgument("-version");
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
Executor executor = new DefaultExecutor();
try {
executor.execute(cmdLine, resultHandler);
} catch (ExecuteException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Launches this stage and waits for process termination.
*
* @return true if the stage was killed by a call to the destroy()-method. false otherwise.
*/
private boolean runGroup() {
CommandLine cmdLine = new CommandLine(java);
cmdLine.addArgument(jvmParameters, false);
String cp = getClassPath();
cmdLine.addArgument("-cp");
cmdLine.addArgument("${classpath}");
cmdLine.addArgument(GroupStarter.class.getCanonicalName());
cmdLine.addArgument(stageGroup.getName());
cmdLine.addArgument("localhost");
cmdLine.addArgument("" + pipelinePort);
cmdLine.addArgument("" + performanceLogging);
cmdLine.addArgument("" + loggingPort);
cmdLine.addArgument(startupArgsString);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("classpath", cp);
cmdLine.setSubstitutionMap(map);
logger.info("Launching with command " + cmdLine.toString());
CommandLauncher cl = CommandLauncherFactory.createVMLauncher();
int exitValue = 0;
try {
Process p = cl.exec(cmdLine, null);
new StreamLogger(
- String.format("%s (stdin)", stageGroup.getName()),
+ String.format("%s (stdout)", stageGroup.getName()),
p.getInputStream()
).start();
new StreamLogger(
String.format("%s (stderr)", stageGroup.getName()),
p.getErrorStream()
).start();
stageDestroyer.add(p);
exitValue = p.waitFor();
} catch (InterruptedException e) {
throw new IllegalStateException("Caught Interrupt while waiting for process exit", e);
} catch (IOException e) {
logger.error("Caught IOException while running command", e);
return false;
}
if(!wasKilled) {
logger.error("Stage group " + stageGroup.getName()
+ " terminated unexpectedly with exit value " + exitValue);
return false;
}
return true;
}
private String getClassPath() {
if(classPathString==null) {
return getAllJars();
} else {
return classPathString+File.pathSeparator+getAllJars();
}
}
private String getAllJars() {
String jars="";
for(String s : targetDirectory.list()) {
jars+=targetDirectory.getAbsolutePath()+File.separator+s+File.pathSeparator;
}
return jars.substring(0, jars.length()-1);
}
/**
* Destroys the JVM running this stage and removes it's working files.
* Should a JVM shutdown fail, it will throw an IllegalStateException.
*/
public void destroy() {
logger.debug("Attempting to destroy JVM running stage group "
+ stageGroup.getName());
boolean success = stageDestroyer.killAll();
if (success) {
logger.debug("... destruction successful");
} else {
logger.error("JVM running stage group " + stageGroup.getName()
+ " was not killed");
throw new IllegalStateException("Orphaned process for "
+ stageGroup.getName());
}
removeFiles();
wasKilled = true;
}
private void removeFiles() {
long start = System.currentTimeMillis();
IOException ex = null;
do {
try {
FileUtils.deleteDirectory(targetDirectory);
return;
} catch(IOException e) {
ex = e;
try {
Thread.sleep(50);
} catch (InterruptedException e1) {
logger.error("Interrupted while waiting on delete");
Thread.currentThread().interrupt();
return;
}
}
} while (start + 5000 > System.currentTimeMillis());
logger.error("Unable to delete the directory "
+ targetDirectory.getAbsolutePath()
+ ", containing Stage Group " + stageGroup.getName(), ex);
}
public StageGroup getStageGroup() {
return stageGroup;
}
public boolean isStarted() {
return started;
}
/**
* Manages the destruction of any Stages launched in this wrapper.
* Automatically binds to the Runtime to shut down along with the master
* JVM.
*
* @author joel.westberg
*
*/
static class StageDestroyer extends Thread implements ProcessDestroyer {
private final List<Process> processes = new ArrayList<Process>();
public StageDestroyer() {
Runtime.getRuntime().addShutdownHook(this);
}
@Override
public boolean add(Process p) {
/**
* Register this destroyer to Runtime in order to avoid orphaned
* processes if the main JVM dies
*/
processes.add(p);
return true;
}
@Override
public boolean remove(Process p) {
return processes.remove(p);
}
@Override
public int size() {
return processes.size();
}
/**
* Invoked by the runtime ShutdownHook on JVM exit
*/
public void run() {
killAll();
}
public boolean killAll() {
boolean success = true;
synchronized (processes) {
for (Process process : processes) {
try {
process.destroy();
} catch (RuntimeException t) {
success = false;
}
}
}
return success;
}
}
public void setStageDestroyer(StageDestroyer sd) {
stageDestroyer = sd;
}
}
| true | true | private boolean runGroup() {
CommandLine cmdLine = new CommandLine(java);
cmdLine.addArgument(jvmParameters, false);
String cp = getClassPath();
cmdLine.addArgument("-cp");
cmdLine.addArgument("${classpath}");
cmdLine.addArgument(GroupStarter.class.getCanonicalName());
cmdLine.addArgument(stageGroup.getName());
cmdLine.addArgument("localhost");
cmdLine.addArgument("" + pipelinePort);
cmdLine.addArgument("" + performanceLogging);
cmdLine.addArgument("" + loggingPort);
cmdLine.addArgument(startupArgsString);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("classpath", cp);
cmdLine.setSubstitutionMap(map);
logger.info("Launching with command " + cmdLine.toString());
CommandLauncher cl = CommandLauncherFactory.createVMLauncher();
int exitValue = 0;
try {
Process p = cl.exec(cmdLine, null);
new StreamLogger(
String.format("%s (stdin)", stageGroup.getName()),
p.getInputStream()
).start();
new StreamLogger(
String.format("%s (stderr)", stageGroup.getName()),
p.getErrorStream()
).start();
stageDestroyer.add(p);
exitValue = p.waitFor();
} catch (InterruptedException e) {
throw new IllegalStateException("Caught Interrupt while waiting for process exit", e);
} catch (IOException e) {
logger.error("Caught IOException while running command", e);
return false;
}
if(!wasKilled) {
logger.error("Stage group " + stageGroup.getName()
+ " terminated unexpectedly with exit value " + exitValue);
return false;
}
return true;
}
| private boolean runGroup() {
CommandLine cmdLine = new CommandLine(java);
cmdLine.addArgument(jvmParameters, false);
String cp = getClassPath();
cmdLine.addArgument("-cp");
cmdLine.addArgument("${classpath}");
cmdLine.addArgument(GroupStarter.class.getCanonicalName());
cmdLine.addArgument(stageGroup.getName());
cmdLine.addArgument("localhost");
cmdLine.addArgument("" + pipelinePort);
cmdLine.addArgument("" + performanceLogging);
cmdLine.addArgument("" + loggingPort);
cmdLine.addArgument(startupArgsString);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("classpath", cp);
cmdLine.setSubstitutionMap(map);
logger.info("Launching with command " + cmdLine.toString());
CommandLauncher cl = CommandLauncherFactory.createVMLauncher();
int exitValue = 0;
try {
Process p = cl.exec(cmdLine, null);
new StreamLogger(
String.format("%s (stdout)", stageGroup.getName()),
p.getInputStream()
).start();
new StreamLogger(
String.format("%s (stderr)", stageGroup.getName()),
p.getErrorStream()
).start();
stageDestroyer.add(p);
exitValue = p.waitFor();
} catch (InterruptedException e) {
throw new IllegalStateException("Caught Interrupt while waiting for process exit", e);
} catch (IOException e) {
logger.error("Caught IOException while running command", e);
return false;
}
if(!wasKilled) {
logger.error("Stage group " + stageGroup.getName()
+ " terminated unexpectedly with exit value " + exitValue);
return false;
}
return true;
}
|
diff --git a/src/java/org/smoothbuild/task/PluginTask.java b/src/java/org/smoothbuild/task/PluginTask.java
index f0a6c095..bf6398c4 100644
--- a/src/java/org/smoothbuild/task/PluginTask.java
+++ b/src/java/org/smoothbuild/task/PluginTask.java
@@ -1,68 +1,67 @@
package org.smoothbuild.task;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import org.smoothbuild.fs.base.exc.FileSystemException;
import org.smoothbuild.function.base.Name;
import org.smoothbuild.function.base.Signature;
import org.smoothbuild.function.base.Type;
import org.smoothbuild.function.plugin.PluginInvoker;
import org.smoothbuild.plugin.Sandbox;
import org.smoothbuild.task.err.FileSystemError;
import org.smoothbuild.task.err.NullResultError;
import org.smoothbuild.task.err.ReflexiveInternalError;
import org.smoothbuild.task.err.UnexpectedError;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
public class PluginTask extends AbstractTask {
private final Signature signature;
private final PluginInvoker pluginInvoker;
public PluginTask(Signature signature, PluginInvoker pluginInvoker, Map<String, Task> dependencies) {
super(dependencies);
this.signature = signature;
this.pluginInvoker = pluginInvoker;
}
@Override
public void calculateResult(Sandbox sandbox) {
- // TODO improve problems messages and test all cases
try {
Object result = pluginInvoker.invoke(sandbox, calculateArguments(dependencies()));
if (result == null && !isNullResultAllowed()) {
sandbox.report(new NullResultError(functionName()));
} else {
setResult(result);
}
} catch (IllegalAccessException e) {
sandbox.report(new ReflexiveInternalError(functionName(), e));
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof FileSystemException) {
sandbox.report(new FileSystemError(functionName(), cause));
} else {
sandbox.report(new UnexpectedError(functionName(), cause));
}
}
}
private Name functionName() {
return signature.name();
}
private boolean isNullResultAllowed() {
return signature.type() == Type.VOID;
}
private static ImmutableMap<String, Object> calculateArguments(
ImmutableMap<String, Task> dependencies) {
Builder<String, Object> builder = ImmutableMap.builder();
for (Map.Entry<String, Task> entry : dependencies.entrySet()) {
builder.put(entry.getKey(), entry.getValue().result());
}
return builder.build();
}
}
| true | true | public void calculateResult(Sandbox sandbox) {
// TODO improve problems messages and test all cases
try {
Object result = pluginInvoker.invoke(sandbox, calculateArguments(dependencies()));
if (result == null && !isNullResultAllowed()) {
sandbox.report(new NullResultError(functionName()));
} else {
setResult(result);
}
} catch (IllegalAccessException e) {
sandbox.report(new ReflexiveInternalError(functionName(), e));
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof FileSystemException) {
sandbox.report(new FileSystemError(functionName(), cause));
} else {
sandbox.report(new UnexpectedError(functionName(), cause));
}
}
}
| public void calculateResult(Sandbox sandbox) {
try {
Object result = pluginInvoker.invoke(sandbox, calculateArguments(dependencies()));
if (result == null && !isNullResultAllowed()) {
sandbox.report(new NullResultError(functionName()));
} else {
setResult(result);
}
} catch (IllegalAccessException e) {
sandbox.report(new ReflexiveInternalError(functionName(), e));
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof FileSystemException) {
sandbox.report(new FileSystemError(functionName(), cause));
} else {
sandbox.report(new UnexpectedError(functionName(), cause));
}
}
}
|
diff --git a/instance/core/src/test/java/org/apache/karaf/instance/core/internal/InstanceServiceImplTest.java b/instance/core/src/test/java/org/apache/karaf/instance/core/internal/InstanceServiceImplTest.java
index 7cf284be9..650cbd239 100644
--- a/instance/core/src/test/java/org/apache/karaf/instance/core/internal/InstanceServiceImplTest.java
+++ b/instance/core/src/test/java/org/apache/karaf/instance/core/internal/InstanceServiceImplTest.java
@@ -1,118 +1,118 @@
/*
* 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.karaf.instance.core.internal;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.karaf.instance.core.Instance;
import org.apache.karaf.instance.core.InstanceSettings;
import org.apache.karaf.instance.core.internal.InstanceServiceImpl;
public class InstanceServiceImplTest extends TestCase {
public void testHandleFeatures() throws Exception {
InstanceServiceImpl as = new InstanceServiceImpl();
File f = File.createTempFile(getName(), ".test");
try {
Properties p = new Properties();
p.put("featuresBoot", "abc,def ");
p.put("featuresRepositories", "somescheme://xyz");
OutputStream os = new FileOutputStream(f);
try {
p.store(os, "Test comment");
} finally {
os.close();
}
InstanceSettings s = new InstanceSettings(8122, 1122, 44444, null, null, null, Arrays.asList("test"));
as.addFeaturesFromSettings(f, s);
Properties p2 = new Properties();
InputStream is = new FileInputStream(f);
try {
p2.load(is);
} finally {
is.close();
}
assertEquals(2, p2.size());
- assertEquals("abc,def,test", p2.get("featuresBoot"));
+ assertEquals("abc,def,ssh,test", p2.get("featuresBoot"));
assertEquals("somescheme://xyz", p2.get("featuresRepositories"));
} finally {
f.delete();
}
}
/**
* Ensure the instance:create generates all the required configuration files
* //TODO: fix this test so it can run in an IDE
*/
public void testConfigurationFiles() throws Exception {
InstanceServiceImpl service = new InstanceServiceImpl();
service.setStorageLocation(new File("target/instances/" + System.currentTimeMillis()));
System.setProperty("karaf.base", new File("target/test-classes/").getAbsolutePath());
InstanceSettings settings = new InstanceSettings(8122, 1122, 44444, getName(), null, null, null);
Instance instance = service.createInstance(getName(), settings, true);
assertFileExists(instance.getLocation(), "etc/config.properties");
assertFileExists(instance.getLocation(), "etc/users.properties");
assertFileExists(instance.getLocation(), "etc/startup.properties");
assertFileExists(instance.getLocation(), "etc/java.util.logging.properties");
assertFileExists(instance.getLocation(), "etc/org.apache.karaf.features.cfg");
assertFileExists(instance.getLocation(), "etc/org.apache.felix.fileinstall-deploy.cfg");
assertFileExists(instance.getLocation(), "etc/org.apache.karaf.log.cfg");
assertFileExists(instance.getLocation(), "etc/org.apache.karaf.management.cfg");
assertFileExists(instance.getLocation(), "etc/org.ops4j.pax.logging.cfg");
assertFileExists(instance.getLocation(), "etc/org.ops4j.pax.url.mvn.cfg");
}
/**
* <p>
* Test the renaming of an existing instance.
* </p>
*/
public void testRenameInstance() throws Exception {
InstanceServiceImpl service = new InstanceServiceImpl();
service.setStorageLocation(new File("target/instances/" + System.currentTimeMillis()));
System.setProperty("karaf.base", new File("target/test-classes/").getAbsolutePath());
InstanceSettings settings = new InstanceSettings(8122, 1122, 44444, getName(), null, null, null);
service.createInstance(getName(), settings, true);
service.renameInstance(getName(), getName() + "b", true);
assertNotNull(service.getInstance(getName() + "b"));
}
private void assertFileExists(String path, String name) throws IOException {
File file = new File(path, name);
assertTrue("Expected " + file.getCanonicalPath() + " to exist",
file.exists());
}
}
| true | true | public void testHandleFeatures() throws Exception {
InstanceServiceImpl as = new InstanceServiceImpl();
File f = File.createTempFile(getName(), ".test");
try {
Properties p = new Properties();
p.put("featuresBoot", "abc,def ");
p.put("featuresRepositories", "somescheme://xyz");
OutputStream os = new FileOutputStream(f);
try {
p.store(os, "Test comment");
} finally {
os.close();
}
InstanceSettings s = new InstanceSettings(8122, 1122, 44444, null, null, null, Arrays.asList("test"));
as.addFeaturesFromSettings(f, s);
Properties p2 = new Properties();
InputStream is = new FileInputStream(f);
try {
p2.load(is);
} finally {
is.close();
}
assertEquals(2, p2.size());
assertEquals("abc,def,test", p2.get("featuresBoot"));
assertEquals("somescheme://xyz", p2.get("featuresRepositories"));
} finally {
f.delete();
}
}
| public void testHandleFeatures() throws Exception {
InstanceServiceImpl as = new InstanceServiceImpl();
File f = File.createTempFile(getName(), ".test");
try {
Properties p = new Properties();
p.put("featuresBoot", "abc,def ");
p.put("featuresRepositories", "somescheme://xyz");
OutputStream os = new FileOutputStream(f);
try {
p.store(os, "Test comment");
} finally {
os.close();
}
InstanceSettings s = new InstanceSettings(8122, 1122, 44444, null, null, null, Arrays.asList("test"));
as.addFeaturesFromSettings(f, s);
Properties p2 = new Properties();
InputStream is = new FileInputStream(f);
try {
p2.load(is);
} finally {
is.close();
}
assertEquals(2, p2.size());
assertEquals("abc,def,ssh,test", p2.get("featuresBoot"));
assertEquals("somescheme://xyz", p2.get("featuresRepositories"));
} finally {
f.delete();
}
}
|
diff --git a/src/test/java/cn/sunjiachao/s7common/arithmetic/search/BinarySearch1Test.java b/src/test/java/cn/sunjiachao/s7common/arithmetic/search/BinarySearch1Test.java
index e9f7a50..058f512 100644
--- a/src/test/java/cn/sunjiachao/s7common/arithmetic/search/BinarySearch1Test.java
+++ b/src/test/java/cn/sunjiachao/s7common/arithmetic/search/BinarySearch1Test.java
@@ -1,20 +1,19 @@
package cn.sunjiachao.s7common.arithmetic.search;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static org.junit.Assert.*;
@RunWith(JUnit4.class)
public class BinarySearch1Test {
@Test
public void testBinarySearch() {
int[] array = { 1, 12, 23, 34, 45, 66, 76, 86, 96, 1066 };
BinarySearch1 app = new BinarySearch1(array);
int result = app.search(34);
assertEquals(3, result);
-// assertEquals(4, result);
}
}
| true | true | public void testBinarySearch() {
int[] array = { 1, 12, 23, 34, 45, 66, 76, 86, 96, 1066 };
BinarySearch1 app = new BinarySearch1(array);
int result = app.search(34);
assertEquals(3, result);
// assertEquals(4, result);
}
| public void testBinarySearch() {
int[] array = { 1, 12, 23, 34, 45, 66, 76, 86, 96, 1066 };
BinarySearch1 app = new BinarySearch1(array);
int result = app.search(34);
assertEquals(3, result);
}
|
diff --git a/src/main/java/org/jahia/modules/pagehit/PageHitService.java b/src/main/java/org/jahia/modules/pagehit/PageHitService.java
index 5e75f70..103859a 100644
--- a/src/main/java/org/jahia/modules/pagehit/PageHitService.java
+++ b/src/main/java/org/jahia/modules/pagehit/PageHitService.java
@@ -1,158 +1,169 @@
package org.jahia.modules.pagehit;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.ProcessorEndpoint;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.SessionFactoryImpl;
import org.jahia.services.SpringContextSingleton;
import org.jahia.services.content.*;
import org.springframework.beans.factory.InitializingBean;
import org.apache.camel.Processor;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import javax.jcr.RepositoryException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by IntelliJ IDEA.
* User: Dorth
* Date: 26 ao�t 2010
* Time: 11:11:05
* To change this template use File | Settings | File Templates.
*/
public class PageHitService implements Processor, InitializingBean, CamelContextAware {
private transient static Logger logger = Logger.getLogger(PageHitService.class);
private org.hibernate.impl.SessionFactoryImpl sessionFactoryBean;
private Class mappingClass;
private static PageHitService instance;
private Pattern pattern = Pattern.compile(
"([0-9\\-]+ [0-9:,]+) user ([[email protected]_\\-]+) ip ([0-9.:]+) session ([a-zA-Z@0-9_\\-\\/]+) path (.*) nodetype ([a-zA-Z:]+) page viewed with (.*)");
private CamelContext camelContext;
private String from;
public void setSessionFactoryBean(SessionFactoryImpl sessionFactoryBean) {
this.sessionFactoryBean = sessionFactoryBean;
}
public void setMappingClass(Class mappingClass) {
this.mappingClass = mappingClass;
}
public static PageHitService getInstance() {
if (instance == null) {
instance = new PageHitService();
}
return instance;
}
public void start() {
}
public void process(Exchange exchange) throws Exception {
final String message = (String) exchange.getIn().getBody();
final Matcher matcher = pattern.matcher(message);
if (matcher.matches()) {
final String path = matcher.group(5);
final JCRTemplate tpl = JCRTemplate.getInstance();
- JCRNodeWrapper node = tpl.doExecuteWithSystemSession(new JCRCallback<JCRNodeWrapper>() {
- public JCRNodeWrapper doInJCR(JCRSessionWrapper session) throws RepositoryException {
- return session.getNode(path);
- }
- });
+ JCRNodeWrapper node;
+ try {
+ node = tpl.doExecuteWithSystemSession(new JCRCallback<JCRNodeWrapper>() {
+ public JCRNodeWrapper doInJCR(JCRSessionWrapper session) throws RepositoryException {
+ return session.getNode(path);
+ }
+ });
+ } catch (RepositoryException e) {
+ // Node not found might be due to old logs so fail silently
+ return;
+ }
+ if(node==null) {
+ // stupid security check should not happen
+ logger.warn("Node not found in system but it has not thrown an exception strange");
+ return;
+ }
final String uuid = node.getIdentifier();
Session session = sessionFactoryBean.openSession();
- Criteria criteria = session.createCriteria(PageHit.class);
- criteria.add(Restrictions.eq("uuid", uuid));
try {
+ Criteria criteria = session.createCriteria(PageHit.class);
+ criteria.add(Restrictions.eq("uuid", uuid));
PageHit pageHit = (PageHit) criteria.uniqueResult();
// Found update object
if (pageHit != null) {
pageHit.setHit(pageHit.getHit() + 1);
if(!pageHit.getPath().equals(path)){
pageHit.setPath(path);
logger.debug("Update into database pageHit page's path as change to: " + pageHit.getPath());
}
logger.debug("Update into database pageHit page's path: " + pageHit.getPath() + " with number of view: " + pageHit.getHit());
}
// Not found new object
else {
pageHit = new PageHit();
Long hit = (long) 1;
pageHit.setHit(hit);
pageHit.setPath(path);
pageHit.setUuid(uuid);
session.save(pageHit);
logger.debug("Insert into database pageHit page's path: " + pageHit.getPath() + " with number of view: " + pageHit.getHit());
}
} catch (HibernateException e) {
logger.error(e.getMessage(), e);
} finally {
session.flush();
session.close();
}
}
}
public long getNumberOfHits(JCRNodeWrapper node) {
Session session = sessionFactoryBean.openSession();
Criteria criteria = session.createCriteria(PageHit.class);
try {
criteria.add(Restrictions.eq("uuid", node.getIdentifier()));
PageHit pageHit = (PageHit) criteria.uniqueResult();
return pageHit.getHit();
} catch (Exception e) {
return 0;
} finally {
session.close();
}
}
public void afterPropertiesSet() throws Exception {
ApplicationContext context = SpringContextSingleton.getInstance().getContext();
AnnotationSessionFactoryBean localSessionFactoryBean = (AnnotationSessionFactoryBean) context.getBeansOfType(
AnnotationSessionFactoryBean.class).get("&sessionFactory");
localSessionFactoryBean.setAnnotatedClasses(new Class[]{mappingClass});
localSessionFactoryBean.afterPropertiesSet();
localSessionFactoryBean.updateDatabaseSchema();
sessionFactoryBean = (SessionFactoryImpl) localSessionFactoryBean.getObject();
}
public void setCamelContext(final CamelContext camelContext) {
this.camelContext = camelContext;
final PageHitService pageHitService = this;
try {
camelContext.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from(from).filter("groovy", "request.body.contains(\"page viewed\")").to(new ProcessorEndpoint(
"pageHitService", camelContext, pageHitService));
}
});
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
public CamelContext getCamelContext() {
return camelContext; //To change body of implemented methods use File | Settings | File Templates.
}
public void setFrom(String from) {
this.from = from;
}
}
| false | true | public void process(Exchange exchange) throws Exception {
final String message = (String) exchange.getIn().getBody();
final Matcher matcher = pattern.matcher(message);
if (matcher.matches()) {
final String path = matcher.group(5);
final JCRTemplate tpl = JCRTemplate.getInstance();
JCRNodeWrapper node = tpl.doExecuteWithSystemSession(new JCRCallback<JCRNodeWrapper>() {
public JCRNodeWrapper doInJCR(JCRSessionWrapper session) throws RepositoryException {
return session.getNode(path);
}
});
final String uuid = node.getIdentifier();
Session session = sessionFactoryBean.openSession();
Criteria criteria = session.createCriteria(PageHit.class);
criteria.add(Restrictions.eq("uuid", uuid));
try {
PageHit pageHit = (PageHit) criteria.uniqueResult();
// Found update object
if (pageHit != null) {
pageHit.setHit(pageHit.getHit() + 1);
if(!pageHit.getPath().equals(path)){
pageHit.setPath(path);
logger.debug("Update into database pageHit page's path as change to: " + pageHit.getPath());
}
logger.debug("Update into database pageHit page's path: " + pageHit.getPath() + " with number of view: " + pageHit.getHit());
}
// Not found new object
else {
pageHit = new PageHit();
Long hit = (long) 1;
pageHit.setHit(hit);
pageHit.setPath(path);
pageHit.setUuid(uuid);
session.save(pageHit);
logger.debug("Insert into database pageHit page's path: " + pageHit.getPath() + " with number of view: " + pageHit.getHit());
}
} catch (HibernateException e) {
logger.error(e.getMessage(), e);
} finally {
session.flush();
session.close();
}
}
}
| public void process(Exchange exchange) throws Exception {
final String message = (String) exchange.getIn().getBody();
final Matcher matcher = pattern.matcher(message);
if (matcher.matches()) {
final String path = matcher.group(5);
final JCRTemplate tpl = JCRTemplate.getInstance();
JCRNodeWrapper node;
try {
node = tpl.doExecuteWithSystemSession(new JCRCallback<JCRNodeWrapper>() {
public JCRNodeWrapper doInJCR(JCRSessionWrapper session) throws RepositoryException {
return session.getNode(path);
}
});
} catch (RepositoryException e) {
// Node not found might be due to old logs so fail silently
return;
}
if(node==null) {
// stupid security check should not happen
logger.warn("Node not found in system but it has not thrown an exception strange");
return;
}
final String uuid = node.getIdentifier();
Session session = sessionFactoryBean.openSession();
try {
Criteria criteria = session.createCriteria(PageHit.class);
criteria.add(Restrictions.eq("uuid", uuid));
PageHit pageHit = (PageHit) criteria.uniqueResult();
// Found update object
if (pageHit != null) {
pageHit.setHit(pageHit.getHit() + 1);
if(!pageHit.getPath().equals(path)){
pageHit.setPath(path);
logger.debug("Update into database pageHit page's path as change to: " + pageHit.getPath());
}
logger.debug("Update into database pageHit page's path: " + pageHit.getPath() + " with number of view: " + pageHit.getHit());
}
// Not found new object
else {
pageHit = new PageHit();
Long hit = (long) 1;
pageHit.setHit(hit);
pageHit.setPath(path);
pageHit.setUuid(uuid);
session.save(pageHit);
logger.debug("Insert into database pageHit page's path: " + pageHit.getPath() + " with number of view: " + pageHit.getHit());
}
} catch (HibernateException e) {
logger.error(e.getMessage(), e);
} finally {
session.flush();
session.close();
}
}
}
|
diff --git a/gnu/testlet/java/net/URL/newURL.java b/gnu/testlet/java/net/URL/newURL.java
index 09476ad7..176f5186 100644
--- a/gnu/testlet/java/net/URL/newURL.java
+++ b/gnu/testlet/java/net/URL/newURL.java
@@ -1,139 +1,142 @@
// Tags: JDK1.0
// Contributed by Mark Wielaard ([email protected])
// Based on a kaffe regression test.
// 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.net.URL;
import gnu.testlet.Testlet;
import gnu.testlet.TestHarness;
import java.net.MalformedURLException;
import java.net.URL;
public class newURL implements Testlet
{
private TestHarness harness;
public void test (TestHarness harness)
{
this.harness = harness;
check(null,
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
check(null,
"http://www.kaffe.org",
"http://www.kaffe.org");
check(null,
"http://www.kaffe.org:8080#ref",
"http://www.kaffe.org:8080#ref");
check("http://www.kaffe.org",
"foo/bar",
"http://www.kaffe.org/foo/bar");
check("http://www.kaffe.org/foo/bar#baz",
"jan/far",
"http://www.kaffe.org/foo/jan/far");
check("http://www.kaffe.org/foo/bar",
"/jan/far",
"http://www.kaffe.org/jan/far");
check("http://www.kaffe.org/foo/bar",
"",
"http://www.kaffe.org/foo/bar");
check(null,
"foo/bar",
null);
check("file:/foo/bar",
"barf#jow",
"file:/foo/barf#jow");
check("file:/foo/bar#fly",
"jabawaba",
"file:/foo/jabawaba");
check(null,
"jar:file:/usr/local/share/kaffe/Klasses.jar!/kaffe/lang/unicode.tbl",
"jar:file:/usr/local/share/kaffe/Klasses.jar!/kaffe/lang/unicode.tbl");
check(null,
"jar:http://www.kaffe.org/foo/bar.jar",
null);
check("jar:http://www.kaffe.org/foo/bar.jar!/path/name",
"float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/path/float/boat");
check("jar:http://www.kaffe.org/foo/bar.jar!/",
"float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
check("jar:http://www.kaffe.org/foo/bar.jar!/path/name",
"/float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
check("jar:http://www.kaffe.org/foo/bar.jar!/",
"/float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
+ check("jar:http://www.kaffe.org/foo/bar.jar!/float",
+ "#boat",
+ "jar:http://www.kaffe.org/foo/bar.jar!/float#boat");
check(null,
"http://www.kaffe.org:99999/foo/bar",
"http://www.kaffe.org:99999/foo/bar");
check(null,
"jar:abc!/eat/me",
null);
URL u = check(null,
"http://anonymous:anonymous@host/",
"http://anonymous:anonymous@host/");
harness.check(u.getHost(), "host");
harness.check(u.getUserInfo(), "anonymous:anonymous");
}
// Checks that the URL created from the context plus the url gives
// the string result. Or when the result is null, whether the
// contruction throws a exception. Returns the generated URL or null.
private URL check(String context, String url, String string)
{
harness.checkPoint(context + " + " + url + " = " + string);
URL c;
if (context != null)
{
try
{
c = new URL(context);
}
catch (MalformedURLException mue)
{
harness.debug(mue);
harness.check(false);
return null;
}
}
else
c = null;
try
{
URL u = new URL(c, url);
harness.check(u.toString(), string);
return u;
}
catch (MalformedURLException mue)
{
boolean expected = (string == null);
if (!expected)
harness.debug(mue);
harness.check(expected);
return null;
}
}
}
| true | true | public void test (TestHarness harness)
{
this.harness = harness;
check(null,
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
check(null,
"http://www.kaffe.org",
"http://www.kaffe.org");
check(null,
"http://www.kaffe.org:8080#ref",
"http://www.kaffe.org:8080#ref");
check("http://www.kaffe.org",
"foo/bar",
"http://www.kaffe.org/foo/bar");
check("http://www.kaffe.org/foo/bar#baz",
"jan/far",
"http://www.kaffe.org/foo/jan/far");
check("http://www.kaffe.org/foo/bar",
"/jan/far",
"http://www.kaffe.org/jan/far");
check("http://www.kaffe.org/foo/bar",
"",
"http://www.kaffe.org/foo/bar");
check(null,
"foo/bar",
null);
check("file:/foo/bar",
"barf#jow",
"file:/foo/barf#jow");
check("file:/foo/bar#fly",
"jabawaba",
"file:/foo/jabawaba");
check(null,
"jar:file:/usr/local/share/kaffe/Klasses.jar!/kaffe/lang/unicode.tbl",
"jar:file:/usr/local/share/kaffe/Klasses.jar!/kaffe/lang/unicode.tbl");
check(null,
"jar:http://www.kaffe.org/foo/bar.jar",
null);
check("jar:http://www.kaffe.org/foo/bar.jar!/path/name",
"float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/path/float/boat");
check("jar:http://www.kaffe.org/foo/bar.jar!/",
"float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
check("jar:http://www.kaffe.org/foo/bar.jar!/path/name",
"/float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
check("jar:http://www.kaffe.org/foo/bar.jar!/",
"/float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
check(null,
"http://www.kaffe.org:99999/foo/bar",
"http://www.kaffe.org:99999/foo/bar");
check(null,
"jar:abc!/eat/me",
null);
URL u = check(null,
"http://anonymous:anonymous@host/",
"http://anonymous:anonymous@host/");
harness.check(u.getHost(), "host");
harness.check(u.getUserInfo(), "anonymous:anonymous");
}
| public void test (TestHarness harness)
{
this.harness = harness;
check(null,
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
check(null,
"http://www.kaffe.org",
"http://www.kaffe.org");
check(null,
"http://www.kaffe.org:8080#ref",
"http://www.kaffe.org:8080#ref");
check("http://www.kaffe.org",
"foo/bar",
"http://www.kaffe.org/foo/bar");
check("http://www.kaffe.org/foo/bar#baz",
"jan/far",
"http://www.kaffe.org/foo/jan/far");
check("http://www.kaffe.org/foo/bar",
"/jan/far",
"http://www.kaffe.org/jan/far");
check("http://www.kaffe.org/foo/bar",
"",
"http://www.kaffe.org/foo/bar");
check(null,
"foo/bar",
null);
check("file:/foo/bar",
"barf#jow",
"file:/foo/barf#jow");
check("file:/foo/bar#fly",
"jabawaba",
"file:/foo/jabawaba");
check(null,
"jar:file:/usr/local/share/kaffe/Klasses.jar!/kaffe/lang/unicode.tbl",
"jar:file:/usr/local/share/kaffe/Klasses.jar!/kaffe/lang/unicode.tbl");
check(null,
"jar:http://www.kaffe.org/foo/bar.jar",
null);
check("jar:http://www.kaffe.org/foo/bar.jar!/path/name",
"float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/path/float/boat");
check("jar:http://www.kaffe.org/foo/bar.jar!/",
"float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
check("jar:http://www.kaffe.org/foo/bar.jar!/path/name",
"/float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
check("jar:http://www.kaffe.org/foo/bar.jar!/",
"/float/boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float/boat");
check("jar:http://www.kaffe.org/foo/bar.jar!/float",
"#boat",
"jar:http://www.kaffe.org/foo/bar.jar!/float#boat");
check(null,
"http://www.kaffe.org:99999/foo/bar",
"http://www.kaffe.org:99999/foo/bar");
check(null,
"jar:abc!/eat/me",
null);
URL u = check(null,
"http://anonymous:anonymous@host/",
"http://anonymous:anonymous@host/");
harness.check(u.getHost(), "host");
harness.check(u.getUserInfo(), "anonymous:anonymous");
}
|
diff --git a/src/main/java/ru/histone/evaluator/functions/node/number/ToFixed.java b/src/main/java/ru/histone/evaluator/functions/node/number/ToFixed.java
index ded80f8..7cfbb40 100644
--- a/src/main/java/ru/histone/evaluator/functions/node/number/ToFixed.java
+++ b/src/main/java/ru/histone/evaluator/functions/node/number/ToFixed.java
@@ -1,51 +1,52 @@
/**
* Copyright 2012 MegaFon
*
* 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 ru.histone.evaluator.functions.node.number;
import java.math.BigDecimal;
import java.math.RoundingMode;
import ru.histone.evaluator.functions.node.NodeFunction;
import ru.histone.evaluator.nodes.Node;
import ru.histone.evaluator.nodes.NodeFactory;
import ru.histone.evaluator.nodes.NumberHistoneNode;
import ru.histone.evaluator.nodes.NumberHistoneNode;
/**
* Format a number up to required decimal places.
*/
public class ToFixed extends NodeFunction<NumberHistoneNode> {
public ToFixed(NodeFactory nodeFactory) {
super(nodeFactory);
}
@Override
public String getName() {
return "toFixed";
}
@Override
public Node execute(NumberHistoneNode target, Node... args) {
BigDecimal value = target.getValue();
if (args.length != 0) {
NumberHistoneNode start = args[0].getAsNumber();
int scale = start.getValue().intValue();
- value = value.setScale(scale, RoundingMode.HALF_UP);
+ if (scale >= 0)
+ value = value.setScale(scale, RoundingMode.HALF_UP);
}
return getNodeFactory().number(value);
}
}
| true | true | public Node execute(NumberHistoneNode target, Node... args) {
BigDecimal value = target.getValue();
if (args.length != 0) {
NumberHistoneNode start = args[0].getAsNumber();
int scale = start.getValue().intValue();
value = value.setScale(scale, RoundingMode.HALF_UP);
}
return getNodeFactory().number(value);
}
| public Node execute(NumberHistoneNode target, Node... args) {
BigDecimal value = target.getValue();
if (args.length != 0) {
NumberHistoneNode start = args[0].getAsNumber();
int scale = start.getValue().intValue();
if (scale >= 0)
value = value.setScale(scale, RoundingMode.HALF_UP);
}
return getNodeFactory().number(value);
}
|
diff --git a/compass2/core/src/main/java/no/ovitas/compass2/util/TopicUtil.java b/compass2/core/src/main/java/no/ovitas/compass2/util/TopicUtil.java
index a0f7fd0..476fb4a 100644
--- a/compass2/core/src/main/java/no/ovitas/compass2/util/TopicUtil.java
+++ b/compass2/core/src/main/java/no/ovitas/compass2/util/TopicUtil.java
@@ -1,154 +1,154 @@
package no.ovitas.compass2.util;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import no.ovitas.compass2.model.Relation;
import no.ovitas.compass2.model.Topic;
import no.ovitas.compass2.model.TopicTreeNode;
public class TopicUtil {
private static class TopicNode{
Topic parent;
Topic topic;
double distance;
public TopicNode(Topic topic, Topic parent, double distance) {
this.topic = topic;
this.parent = parent;
this.distance = distance;
}
}
private static class TopicLinkNode {
Topic topic;
double cost;
public TopicLinkNode(Topic topic, double distance) {
this.topic = topic;
this.cost = distance;
}
}
private static abstract class TopicExpander {
List<TopicLinkNode> expand(Topic topic) {
List<TopicLinkNode> ret = new ArrayList<TopicLinkNode>();
List<Relation> relations = topic.getRelations();
if (relations != null) {
for (Relation relation : relations) {
Topic otherTopic = relation.getSource();
if (otherTopic == topic) otherTopic = relation.getTarget();
ret.add(new TopicLinkNode(otherTopic, getDistance(relation)));
}
}
return ret;
}
List<TopicLinkNode> contract(Topic topic) {
List<TopicLinkNode> ret = new ArrayList<TopicLinkNode>();
List<Relation> relations = topic.getRelations();
if (relations != null) {
for (Relation relation : relations) {
Topic otherTopic = relation.getTarget();
if (otherTopic == topic) otherTopic = relation.getSource();
ret.add(new TopicLinkNode(otherTopic, getDistance(relation)));
}
}
return ret;
}
protected abstract double getDistance(Relation relation);
}
private static class TopicExpanderForMinHopCount extends TopicExpander {
protected double getDistance(Relation relation) {
return 1;
}
}
private static class TopicExpanderForMaxWeight extends TopicExpander {
protected double getDistance(Relation relation) {
return -Math.log(relation.getRelationType().getWeight());
}
}
private static final Comparator<TopicNode> comparator = new Comparator<TopicNode>() {
public int compare(TopicNode left, TopicNode right) {
double ret = left.distance - right.distance;
return ret < 0 ? -1 : ret > 0 ? 1 : 0;
}
};
public static TopicTreeNode dijkstra(Topic rootTopic, TopicExpander expander, double limit, int maxTopicNumberToExpand) {
PriorityQueue<TopicNode> queue = new PriorityQueue<TopicNode>(10, comparator);
HashMap<Topic, TopicNode> topicNodes = new HashMap<Topic, TopicNode>();
List<TopicNode> finalTopicNodes = new LinkedList<TopicNode>();
TopicNode rootTopicNode = new TopicNode(rootTopic, null, 0);
topicNodes.put(rootTopicNode.topic, rootTopicNode);
queue.add(rootTopicNode);
int idx = 0;
while (queue.size() > 0 && idx++ < maxTopicNumberToExpand) {
TopicNode topicNode = queue.poll();
// Get source -> target nodes
- List<TopicLinkNode> topicLinkNodes = expander.contract(topicNode.topic);
+ List<TopicLinkNode> topicLinkNodes = expander.expand(topicNode.topic);
// Get target -> source nodes and merge into topicLinkNodes
List<TopicLinkNode> topicLinkNodesBack = expander.contract(topicNode.topic);
for(TopicLinkNode node : topicLinkNodesBack) {
if (!topicLinkNodes.contains(node)) {
topicLinkNodes.add(node);
}
}
for (TopicLinkNode topicLinkNode : topicLinkNodes) {
Topic aTopic = topicLinkNode.topic;
TopicNode aTopicNode = topicNodes.get(aTopic);
double dist = topicNode.distance + topicLinkNode.cost;
if (dist > limit) continue;
if (aTopicNode == null) {
aTopicNode = new TopicNode(aTopic, topicNode.topic, dist);
topicNodes.put(aTopic, aTopicNode);
queue.add(aTopicNode);
} else if (queue.contains(aTopicNode) && aTopicNode.distance > dist) {
queue.remove(aTopicNode);
aTopicNode.parent = topicNode.topic;
aTopicNode.distance = dist;
queue.add(aTopicNode);
}
}
finalTopicNodes.add(topicNode);
}
Map<Topic, TopicTreeNode> ret = new HashMap<Topic, TopicTreeNode>();
for (TopicNode topicNode: finalTopicNodes) {
if (topicNode.distance <= limit)
ret.put(topicNode.topic, new TopicTreeNode(topicNode.topic));
}
for (TopicNode topicNode: finalTopicNodes) {
if (topicNode.distance <= limit)
ret.get(topicNode.topic).setParent(ret.get(topicNode.parent));
}
return ret.get(rootTopic);
}
public static TopicTreeNode expandTopicsForMinHopCount(Topic topic, int maxHopCount, int maxTopicNumberToExpand) {
return dijkstra(topic, new TopicExpanderForMinHopCount(), maxHopCount, maxTopicNumberToExpand);
}
public static TopicTreeNode expandTopicsForMaxWeight(Topic topic, double minWeight, int maxTopicNumberToExpand) {
return dijkstra(topic, new TopicExpanderForMaxWeight(), -Math.log(minWeight), maxTopicNumberToExpand);
}
}
| true | true | public static TopicTreeNode dijkstra(Topic rootTopic, TopicExpander expander, double limit, int maxTopicNumberToExpand) {
PriorityQueue<TopicNode> queue = new PriorityQueue<TopicNode>(10, comparator);
HashMap<Topic, TopicNode> topicNodes = new HashMap<Topic, TopicNode>();
List<TopicNode> finalTopicNodes = new LinkedList<TopicNode>();
TopicNode rootTopicNode = new TopicNode(rootTopic, null, 0);
topicNodes.put(rootTopicNode.topic, rootTopicNode);
queue.add(rootTopicNode);
int idx = 0;
while (queue.size() > 0 && idx++ < maxTopicNumberToExpand) {
TopicNode topicNode = queue.poll();
// Get source -> target nodes
List<TopicLinkNode> topicLinkNodes = expander.contract(topicNode.topic);
// Get target -> source nodes and merge into topicLinkNodes
List<TopicLinkNode> topicLinkNodesBack = expander.contract(topicNode.topic);
for(TopicLinkNode node : topicLinkNodesBack) {
if (!topicLinkNodes.contains(node)) {
topicLinkNodes.add(node);
}
}
for (TopicLinkNode topicLinkNode : topicLinkNodes) {
Topic aTopic = topicLinkNode.topic;
TopicNode aTopicNode = topicNodes.get(aTopic);
double dist = topicNode.distance + topicLinkNode.cost;
if (dist > limit) continue;
if (aTopicNode == null) {
aTopicNode = new TopicNode(aTopic, topicNode.topic, dist);
topicNodes.put(aTopic, aTopicNode);
queue.add(aTopicNode);
} else if (queue.contains(aTopicNode) && aTopicNode.distance > dist) {
queue.remove(aTopicNode);
aTopicNode.parent = topicNode.topic;
aTopicNode.distance = dist;
queue.add(aTopicNode);
}
}
finalTopicNodes.add(topicNode);
}
Map<Topic, TopicTreeNode> ret = new HashMap<Topic, TopicTreeNode>();
for (TopicNode topicNode: finalTopicNodes) {
if (topicNode.distance <= limit)
ret.put(topicNode.topic, new TopicTreeNode(topicNode.topic));
}
for (TopicNode topicNode: finalTopicNodes) {
if (topicNode.distance <= limit)
ret.get(topicNode.topic).setParent(ret.get(topicNode.parent));
}
return ret.get(rootTopic);
}
| public static TopicTreeNode dijkstra(Topic rootTopic, TopicExpander expander, double limit, int maxTopicNumberToExpand) {
PriorityQueue<TopicNode> queue = new PriorityQueue<TopicNode>(10, comparator);
HashMap<Topic, TopicNode> topicNodes = new HashMap<Topic, TopicNode>();
List<TopicNode> finalTopicNodes = new LinkedList<TopicNode>();
TopicNode rootTopicNode = new TopicNode(rootTopic, null, 0);
topicNodes.put(rootTopicNode.topic, rootTopicNode);
queue.add(rootTopicNode);
int idx = 0;
while (queue.size() > 0 && idx++ < maxTopicNumberToExpand) {
TopicNode topicNode = queue.poll();
// Get source -> target nodes
List<TopicLinkNode> topicLinkNodes = expander.expand(topicNode.topic);
// Get target -> source nodes and merge into topicLinkNodes
List<TopicLinkNode> topicLinkNodesBack = expander.contract(topicNode.topic);
for(TopicLinkNode node : topicLinkNodesBack) {
if (!topicLinkNodes.contains(node)) {
topicLinkNodes.add(node);
}
}
for (TopicLinkNode topicLinkNode : topicLinkNodes) {
Topic aTopic = topicLinkNode.topic;
TopicNode aTopicNode = topicNodes.get(aTopic);
double dist = topicNode.distance + topicLinkNode.cost;
if (dist > limit) continue;
if (aTopicNode == null) {
aTopicNode = new TopicNode(aTopic, topicNode.topic, dist);
topicNodes.put(aTopic, aTopicNode);
queue.add(aTopicNode);
} else if (queue.contains(aTopicNode) && aTopicNode.distance > dist) {
queue.remove(aTopicNode);
aTopicNode.parent = topicNode.topic;
aTopicNode.distance = dist;
queue.add(aTopicNode);
}
}
finalTopicNodes.add(topicNode);
}
Map<Topic, TopicTreeNode> ret = new HashMap<Topic, TopicTreeNode>();
for (TopicNode topicNode: finalTopicNodes) {
if (topicNode.distance <= limit)
ret.put(topicNode.topic, new TopicTreeNode(topicNode.topic));
}
for (TopicNode topicNode: finalTopicNodes) {
if (topicNode.distance <= limit)
ret.get(topicNode.topic).setParent(ret.get(topicNode.parent));
}
return ret.get(rootTopic);
}
|
diff --git a/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_deathgroup.java b/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_deathgroup.java
index e1782a4..468fedb 100644
--- a/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_deathgroup.java
+++ b/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_deathgroup.java
@@ -1,133 +1,134 @@
package com.github.zathrus_writer.commandsex.handlers;
import static com.github.zathrus_writer.commandsex.Language._;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import com.github.zathrus_writer.commandsex.CommandsEX;
import com.github.zathrus_writer.commandsex.SQLManager;
import com.github.zathrus_writer.commandsex.Vault;
import com.github.zathrus_writer.commandsex.helpers.LogHelper;
import com.github.zathrus_writer.commandsex.helpers.Permissions;
import com.github.zathrus_writer.commandsex.helpers.Utils;
import com.github.zathrus_writer.commandsex.helpers.scripting.CommanderCommandSender;
public class Handler_deathgroup implements Listener {
public static Map<String, String> oldPlayerGroups = new HashMap<String, String>();
/***
* Check if a database of old groups exists and activate event listener.
*/
public Handler_deathgroup() {
// check for Vault permissions
if (!Vault.permsEnabled()) {
LogHelper.logWarning("[CommandsEX] " + _("afterDeathVaultMissing", ""));
return;
}
if (CommandsEX.sqlEnabled) {
// create old groups table if it's not present yet
SQLManager.query("CREATE TABLE IF NOT EXISTS "+ SQLManager.prefix +"old_groups (player_name varchar(32) NOT NULL" + (SQLManager.sqlType.equals("mysql") ? "" : " COLLATE 'NOCASE'") + ", group_name varchar(50) NOT NULL, PRIMARY KEY (player_name))" + (SQLManager.sqlType.equals("mysql") ? " ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='stores old player groups where players belonged when they died, so we can revive them back into those groups'" : ""));
// load old player groups from database and delete the ones that did not play for a configured amount of time
ResultSet res = SQLManager.query_res("SELECT * FROM "+ SQLManager.prefix +"old_groups");
List<String> remPlayers = new ArrayList<String>();
try {
while (res.next()) {
OfflinePlayer op = Bukkit.getOfflinePlayer(res.getString("player_name"));
if ((CommandsEX.getConf().getInt("deathGroupsCleanupTime", 14) > 0) && ((Utils.getUnixTimestamp(0L) - (int) (op.getLastPlayed() / 1000)) > (CommandsEX.getConf().getInt("deathGroupsCleanupTime", 14) * 60 * 60 * 24))) {
// if a player did not play for given number of days, remove his previous group from database
remPlayers.add(res.getString("player_name"));
} else {
oldPlayerGroups.put(res.getString("player_name"), res.getString("group_name"));
}
}
res.close();
Integer remSize = remPlayers.size();
if (remSize > 0) {
SQLManager.query("DELETE FROM "+ SQLManager.prefix +"old_groups WHERE player_name IN (\"" + Utils.implode(remPlayers, "\", \"") + "\")");
LogHelper.logInfo("[CommandsEX] " + _("afterDeathGroupsCleanupComplete", "") + remSize);
}
} catch (Throwable e) {
// unable to load groups
LogHelper.logSevere("[CommandsEX] " + _("afterDeathCannotLoadData", ""));
LogHelper.logDebug("Message: " + e.getMessage() + ", cause: " + e.getCause());
return;
}
}
CommandsEX.plugin.getServer().getPluginManager().registerEvents(this, CommandsEX.plugin);
}
/***
* When a player dies, his group is changed based on settings in a config file.
* @param e
* @return
*/
@EventHandler(priority = EventPriority.MONITOR)
public void passChat(PlayerDeathEvent e) {
// load groups information from config and check if our player belongs to any of them, then change his group
Player p = (Player) e.getEntity();
if (Permissions.checkPermEx(p, "cex.deathgroup.ignore")) return;
FileConfiguration f = CommandsEX.getConf();
ConfigurationSection configGroups = f.getConfigurationSection("deathGroupChanges");
+ if (configGroups == null){ return; }
Set<String> groups = configGroups.getKeys(false);
String pName = p.getName();
String toGroup = null;
String command = null;
List<String> removedGroups = new ArrayList<String>();
final CommanderCommandSender ccs = new CommanderCommandSender();
LogHelper.logDebug("groups: " + Utils.implode(Vault.perms.getPlayerGroups(p), ", "));
for (String group : groups) {
LogHelper.logDebug("testing against " + group);
if (Vault.perms.playerInGroup(p, group)) {
LogHelper.logDebug("test ok");
// make sure that these are not null and don't cause problems
if (f.getString("deathGroupChanges." + group + ".toGroup", "") != null && f.getString("deathGroupChanges." + group + ".command", "") != null){
toGroup = f.getString("deathGroupChanges." + group + ".toGroup", "");
command = f.getString("deathGroupChanges." + group + ".command", "");
// change player's group based on config
if (!toGroup.equals("")) {
removedGroups.add(group + "##" + toGroup);
Vault.perms.playerRemoveGroup(p, group);
Vault.perms.playerAddGroup(p, toGroup);
}
// check if we should execute a command
if ((command != null) && !command.equals("")) {
command = Utils.replaceChatColors(command).replace("$p", pName);
CommandsEX.plugin.getServer().dispatchCommand(ccs, command);
}
}
}
}
if (removedGroups.size() > 0) {
LogHelper.logDebug("removed groups: " + Utils.implode(removedGroups, ", "));
// store our changes into database
String imploded = Utils.implode(removedGroups, ";;;");
SQLManager.query("INSERT "+ (SQLManager.sqlType.equals("mysql") ? "" : "OR REPLACE ") +"INTO " + SQLManager.prefix + "old_groups VALUES(?, ?)" + (SQLManager.sqlType.equals("mysql") ? " ON DUPLICATE KEY UPDATE group_name = VALUES(group_name)" : ""), pName, imploded);
oldPlayerGroups.put(pName, imploded);
}
}
}
| true | true | public void passChat(PlayerDeathEvent e) {
// load groups information from config and check if our player belongs to any of them, then change his group
Player p = (Player) e.getEntity();
if (Permissions.checkPermEx(p, "cex.deathgroup.ignore")) return;
FileConfiguration f = CommandsEX.getConf();
ConfigurationSection configGroups = f.getConfigurationSection("deathGroupChanges");
Set<String> groups = configGroups.getKeys(false);
String pName = p.getName();
String toGroup = null;
String command = null;
List<String> removedGroups = new ArrayList<String>();
final CommanderCommandSender ccs = new CommanderCommandSender();
LogHelper.logDebug("groups: " + Utils.implode(Vault.perms.getPlayerGroups(p), ", "));
for (String group : groups) {
LogHelper.logDebug("testing against " + group);
if (Vault.perms.playerInGroup(p, group)) {
LogHelper.logDebug("test ok");
// make sure that these are not null and don't cause problems
if (f.getString("deathGroupChanges." + group + ".toGroup", "") != null && f.getString("deathGroupChanges." + group + ".command", "") != null){
toGroup = f.getString("deathGroupChanges." + group + ".toGroup", "");
command = f.getString("deathGroupChanges." + group + ".command", "");
// change player's group based on config
if (!toGroup.equals("")) {
removedGroups.add(group + "##" + toGroup);
Vault.perms.playerRemoveGroup(p, group);
Vault.perms.playerAddGroup(p, toGroup);
}
// check if we should execute a command
if ((command != null) && !command.equals("")) {
command = Utils.replaceChatColors(command).replace("$p", pName);
CommandsEX.plugin.getServer().dispatchCommand(ccs, command);
}
}
}
}
if (removedGroups.size() > 0) {
LogHelper.logDebug("removed groups: " + Utils.implode(removedGroups, ", "));
// store our changes into database
String imploded = Utils.implode(removedGroups, ";;;");
SQLManager.query("INSERT "+ (SQLManager.sqlType.equals("mysql") ? "" : "OR REPLACE ") +"INTO " + SQLManager.prefix + "old_groups VALUES(?, ?)" + (SQLManager.sqlType.equals("mysql") ? " ON DUPLICATE KEY UPDATE group_name = VALUES(group_name)" : ""), pName, imploded);
oldPlayerGroups.put(pName, imploded);
}
}
| public void passChat(PlayerDeathEvent e) {
// load groups information from config and check if our player belongs to any of them, then change his group
Player p = (Player) e.getEntity();
if (Permissions.checkPermEx(p, "cex.deathgroup.ignore")) return;
FileConfiguration f = CommandsEX.getConf();
ConfigurationSection configGroups = f.getConfigurationSection("deathGroupChanges");
if (configGroups == null){ return; }
Set<String> groups = configGroups.getKeys(false);
String pName = p.getName();
String toGroup = null;
String command = null;
List<String> removedGroups = new ArrayList<String>();
final CommanderCommandSender ccs = new CommanderCommandSender();
LogHelper.logDebug("groups: " + Utils.implode(Vault.perms.getPlayerGroups(p), ", "));
for (String group : groups) {
LogHelper.logDebug("testing against " + group);
if (Vault.perms.playerInGroup(p, group)) {
LogHelper.logDebug("test ok");
// make sure that these are not null and don't cause problems
if (f.getString("deathGroupChanges." + group + ".toGroup", "") != null && f.getString("deathGroupChanges." + group + ".command", "") != null){
toGroup = f.getString("deathGroupChanges." + group + ".toGroup", "");
command = f.getString("deathGroupChanges." + group + ".command", "");
// change player's group based on config
if (!toGroup.equals("")) {
removedGroups.add(group + "##" + toGroup);
Vault.perms.playerRemoveGroup(p, group);
Vault.perms.playerAddGroup(p, toGroup);
}
// check if we should execute a command
if ((command != null) && !command.equals("")) {
command = Utils.replaceChatColors(command).replace("$p", pName);
CommandsEX.plugin.getServer().dispatchCommand(ccs, command);
}
}
}
}
if (removedGroups.size() > 0) {
LogHelper.logDebug("removed groups: " + Utils.implode(removedGroups, ", "));
// store our changes into database
String imploded = Utils.implode(removedGroups, ";;;");
SQLManager.query("INSERT "+ (SQLManager.sqlType.equals("mysql") ? "" : "OR REPLACE ") +"INTO " + SQLManager.prefix + "old_groups VALUES(?, ?)" + (SQLManager.sqlType.equals("mysql") ? " ON DUPLICATE KEY UPDATE group_name = VALUES(group_name)" : ""), pName, imploded);
oldPlayerGroups.put(pName, imploded);
}
}
|
diff --git a/src/frontend/org/voltdb/RealVoltDB.java b/src/frontend/org/voltdb/RealVoltDB.java
index 93e768574..51e833f8a 100644
--- a/src/frontend/org/voltdb/RealVoltDB.java
+++ b/src/frontend/org/voltdb/RealVoltDB.java
@@ -1,1740 +1,1740 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2011 VoltDB Inc.
*
* VoltDB 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.
*
* VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
import java.io.BufferedReader;
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.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
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.Random;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Site;
import org.voltdb.client.Client;
import org.voltdb.client.ClientConfig;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import org.voltdb.dtxn.TransactionInitiator;
import org.voltdb.export.ExportManager;
import org.voltdb.fault.FaultDistributor;
import org.voltdb.fault.FaultDistributorInterface;
import org.voltdb.fault.FaultHandler;
import org.voltdb.fault.NodeFailureFault;
import org.voltdb.fault.VoltFault;
import org.voltdb.fault.VoltFault.FaultType;
import org.voltdb.logging.Level;
import org.voltdb.logging.VoltLogger;
import org.voltdb.messaging.HostMessenger;
import org.voltdb.messaging.InitiateTaskMessage;
import org.voltdb.messaging.Mailbox;
import org.voltdb.messaging.Messenger;
import org.voltdb.network.VoltNetwork;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.DumpManager;
import org.voltdb.utils.HTTPAdminListener;
import org.voltdb.utils.LogKeys;
import org.voltdb.utils.LogReader;
import org.voltdb.utils.PlatformProperties;
import org.voltdb.utils.VoltSampler;
public class RealVoltDB implements VoltDBInterface
{
private static final VoltLogger log = new VoltLogger(VoltDB.class.getName());
private static final VoltLogger hostLog = new VoltLogger("HOST");
private static final VoltLogger recoveryLog = new VoltLogger("RECOVERY");
private class VoltDBNodeFailureFaultHandler implements FaultHandler
{
@Override
public void faultOccured(Set<VoltFault> faults)
{
for (VoltFault fault : faults) {
if (fault instanceof NodeFailureFault)
{
NodeFailureFault node_fault = (NodeFailureFault) fault;
handleNodeFailureFault(node_fault);
}
VoltDB.instance().getFaultDistributor().reportFaultHandled(this, fault);
}
}
private void handleNodeFailureFault(NodeFailureFault node_fault) {
ArrayList<Integer> dead_sites =
VoltDB.instance().getCatalogContext().
siteTracker.getAllSitesForHost(node_fault.getHostId());
Collections.sort(dead_sites);
hostLog.error("Host failed, host id: " + node_fault.getHostId() +
" hostname: " + node_fault.getHostname());
hostLog.error(" Removing sites from cluster: " + dead_sites);
StringBuilder sb = new StringBuilder();
for (int site_id : dead_sites)
{
sb.append("set ");
String site_path = VoltDB.instance().getCatalogContext().catalog.
getClusters().get("cluster").getSites().
get(Integer.toString(site_id)).getPath();
sb.append(site_path).append(" ").append("isUp false");
sb.append("\n");
}
VoltDB.instance().clusterUpdate(sb.toString());
if (m_catalogContext.siteTracker.getFailedPartitions().size() != 0)
{
hostLog.fatal("Failure of host " + node_fault.getHostId() +
" has rendered the cluster unviable. Shutting down...");
VoltDB.crashVoltDB();
}
m_waitForFaultReported.release();
/*
* Use a new thread since this is a asynchronous (and infrequent)
* task and locks are being held by the fault distributor.
*/
new Thread() {
@Override
public void run() {
//Notify the export manager the cluster topology has changed
ExportManager.instance().notifyOfClusterTopologyChange();
}
}.start();
}
@Override
public void faultCleared(Set<VoltFault> faults) {
for (VoltFault fault : faults) {
if (fault instanceof NodeFailureFault) {
m_waitForFaultClear.release();
}
}
}
/**
* When clearing a fault, specifically a rejoining node, wait to make sure it is cleared
* before proceeding because proceeding might generate new faults that should
* be deduped by the FaultManager.
*/
private final Semaphore m_waitForFaultClear = new Semaphore(0);
/**
* When starting up as a rejoining node a fault is reported
* for every currently down node. Once this fault is handled
* here by RealVoltDB's handler the catalog will be updated.
* Then the rest of the system can init with the updated catalog.
*/
private final Semaphore m_waitForFaultReported = new Semaphore(0);
}
static class RejoinCallback implements ProcedureCallback {
ClientResponse response;
@Override
public synchronized void clientCallback(ClientResponse clientResponse)
throws Exception {
response = clientResponse;
if (response.getStatus() != ClientResponse.SUCCESS) {
hostLog.fatal(response.getStatusString());
VoltDB.crashVoltDB();
}
VoltTable results[] = clientResponse.getResults();
if (results.length > 0) {
VoltTable errors = results[0];
while (errors.advanceRow()) {
hostLog.fatal("Host " + errors.getLong(0) + " error: " + errors.getString(1));
}
VoltDB.crashVoltDB();
}
this.notify();
}
public synchronized ClientResponse waitForResponse(int timeout) throws InterruptedException {
final long start = System.currentTimeMillis();
while (response == null) {
this.wait(timeout);
long finish = System.currentTimeMillis();
if (finish - start >= timeout) {
return null;
}
}
return response;
}
}
/**
* A class that instantiates an ExecutionSite and then waits for notification before
* running the execution site. Would it be better if this extended Thread
* so we don't have to have m_runners and m_siteThreads?
*/
private static class ExecutionSiteRunner implements Runnable {
private volatile boolean m_isSiteCreated = false;
private final int m_siteId;
private final String m_serializedCatalog;
private volatile ExecutionSite m_siteObj;
private final boolean m_recovering;
private final HashSet<Integer> m_failedHostIds;
private final long m_txnId;
public ExecutionSiteRunner(
final int siteId,
final CatalogContext context,
final String serializedCatalog,
boolean recovering,
HashSet<Integer> failedHostIds) {
m_siteId = siteId;
m_serializedCatalog = serializedCatalog;
m_recovering = recovering;
m_failedHostIds = failedHostIds;
m_txnId = context.m_transactionId;
}
@Override
public void run() {
Mailbox mailbox = VoltDB.instance().getMessenger()
.createMailbox(m_siteId, VoltDB.DTXN_MAILBOX_ID);
m_siteObj =
new ExecutionSite(VoltDB.instance(),
mailbox,
m_siteId,
m_serializedCatalog,
null,
m_recovering,
m_failedHostIds,
m_txnId);
synchronized (this) {
m_isSiteCreated = true;
this.notifyAll();
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
try
{
m_siteObj.run();
}
catch (OutOfMemoryError e)
{
// Even though OOM should be caught by the Throwable section below,
// it sadly needs to be handled seperately. The goal here is to make
// sure VoltDB crashes.
String errmsg = "ExecutionSite: " + m_siteId + " ran out of Java memory. " +
"This node will shut down.";
hostLog.fatal(errmsg, e);
VoltDB.crashVoltDB();
}
catch (Throwable t)
{
String errmsg = "ExecutionSite: " + m_siteId + " encountered an " +
"unexpected error and will die, taking this VoltDB node down.";
System.err.println(errmsg);
t.printStackTrace();
hostLog.fatal(errmsg, t);
VoltDB.crashVoltDB();
}
}
}
public VoltDB.Configuration m_config = new VoltDB.Configuration();
private CatalogContext m_catalogContext;
private String m_buildString;
private static final String m_defaultVersionString = "1.3.2.trunk";
private String m_versionString = m_defaultVersionString;
// fields accessed via the singleton
private HostMessenger m_messenger = null;
private final ArrayList<ClientInterface> m_clientInterfaces =
new ArrayList<ClientInterface>();
private Map<Integer, ExecutionSite> m_localSites;
private VoltNetwork m_network = null;
private HTTPAdminListener m_adminListener;
private Map<Integer, Thread> m_siteThreads;
private ArrayList<ExecutionSiteRunner> m_runners;
private ExecutionSite m_currentThreadSite;
private StatsAgent m_statsAgent = new StatsAgent();
private FaultDistributor m_faultManager;
private Object m_instanceId[];
private PartitionCountStats m_partitionCountStats = null;
private IOStats m_ioStats = null;
private MemoryStats m_memoryStats = null;
private StatsManager m_statsManager = null;
// Should the execution sites be started in recovery mode
// (used for joining a node to an existing cluster)
private volatile boolean m_recovering = false;
// Synchronize initialize and shutdown.
private final Object m_startAndStopLock = new Object();
// Synchronize updates of catalog contexts with context accessors.
private final Object m_catalogUpdateLock = new Object();
// add a random number to the sampler output to make it likely to be unique for this process.
private final VoltSampler m_sampler = new VoltSampler(10, "sample" + String.valueOf(new Random().nextInt() % 10000) + ".txt");
private final AtomicBoolean m_hasStartedSampler = new AtomicBoolean(false);
private final VoltDBNodeFailureFaultHandler m_faultHandler = new VoltDBNodeFailureFaultHandler();
private RestoreAgent m_restoreAgent = null;
private volatile boolean m_isRunning = false;
@Override
public boolean recovering() { return m_recovering; }
private long m_recoveryStartTime = System.currentTimeMillis();
private CommandLog m_commandLog = new CommandLog() {
@Override
public void init(CatalogContext context) {}
@Override
public void log(InitiateTaskMessage message) {}
@Override
public void shutdown() throws InterruptedException {}
@Override
public Semaphore logFault(Set<Integer> failedSites,
Set<Long> faultedTxns) {
return new Semaphore(1);
}
@Override
public void logHeartbeat(final long txnId) {
// TODO Auto-generated method stub
}
@Override
public void setFaultSequenceNumber(long sequenceNumber,
Set<Integer> failedSites) {
// TODO Auto-generated method stub
}
};
private CommandLogReinitiator m_commandLogReplay = new CommandLogReinitiator() {
private Callback m_callback = null;
@Override
public void skipPartitions(Set<Integer> partitions) {}
@Override
public void skipMultiPartitionTxns(boolean val) {}
@Override
public void replay() {
// Shortcut to enable the cluster for normal operation
if (m_callback != null) {
m_callback.onReplayCompletion();
}
}
@Override
public void join() throws InterruptedException {}
@Override
public void setCallback(Callback callback) {
m_callback = callback;
}
@Override
public boolean hasReplayed() {
return false;
}
@Override
public long getMinLastSeenTxn() {
return 0;
}
};
private volatile OperationMode m_mode = OperationMode.RUNNING;
private OperationMode m_startMode = null;
// metadata is currently of the format:
// IP:CIENTPORT:ADMINPORT:HTTPPORT
private volatile String m_localMetadata = "0.0.0.0:0:0:0";
private final Map<Integer, String> m_clusterMetadata = Collections.synchronizedMap(new HashMap<Integer, String>());
// methods accessed via the singleton
@Override
public void startSampler() {
if (m_hasStartedSampler.compareAndSet(false, true)) {
m_sampler.start();
}
}
PeriodicWorkTimerThread fivems;
private static File m_pidFile = null;
/**
* Initialize all the global components, then initialize all the m_sites.
*/
@Override
public void initialize(VoltDB.Configuration config) {
synchronized(m_startAndStopLock) {
// start (asynchronously) getting platform info
// this will start a thread that should die in less
// than a second
PlatformProperties.fetchPlatformProperties();
if (m_pidFile == null) {
String name = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
String pidString = name.substring(0, name.indexOf('@'));
m_pidFile = new java.io.File("/var/tmp/voltpid." + pidString);
try {
boolean success = m_pidFile.createNewFile();
if (!success) {
hostLog.error("Could not create PID file " + m_pidFile + " because it already exists");
}
m_pidFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(m_pidFile);
fos.write(pidString.getBytes("UTF-8"));
fos.close();
} catch (IOException e) {
hostLog.error("Error creating PID file " + m_pidFile, e);
}
}
// useful for debugging, but doesn't do anything unless VLog is enabled
if (config.m_port != VoltDB.DEFAULT_PORT) {
VLog.setPortNo(config.m_port);
}
VLog.log("\n### RealVoltDB.initialize() for port %d ###", config.m_port);
hostLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_StartupString.name(), null);
// Set std-out/err to use the UTF-8 encoding and fail if UTF-8 isn't supported
try {
System.setOut(new PrintStream(System.out, true, "UTF-8"));
System.setErr(new PrintStream(System.err, true, "UTF-8"));
} catch (UnsupportedEncodingException e) {
hostLog.fatal("Support for the UTF-8 encoding is required for VoltDB. This means you are likely running an unsupported JVM. Exiting.");
System.exit(-1);
}
// check that this is a 64 bit VM
if (System.getProperty("java.vm.name").contains("64") == false) {
hostLog.fatal("You are running on an unsupported (probably 32 bit) JVM. Exiting.");
System.exit(-1);
}
// start the dumper thread
if (config.listenForDumpRequests)
DumpManager.init();
readBuildInfo();
m_config = config;
// Initialize the catalog and some common shortcuts
if (m_config.m_pathToCatalog.startsWith("http")) {
hostLog.info("Loading application catalog jarfile from " + m_config.m_pathToCatalog);
}
else {
File f = new File(m_config.m_pathToCatalog);
hostLog.info("Loading application catalog jarfile from " + f.getAbsolutePath());
}
String serializedCatalog = CatalogUtil.loadCatalogFromJar(m_config.m_pathToCatalog, hostLog);
if ((serializedCatalog == null) || (serializedCatalog.length() == 0))
VoltDB.crashVoltDB();
/* N.B. node recovery requires discovering the current catalog version. */
final int catalogVersion = 0;
Catalog catalog = new Catalog();
catalog.execute(serializedCatalog);
// note if this fails it will print an error first
long depCRC = -1;
try {
depCRC = CatalogUtil.compileDeploymentAndGetCRC(catalog, m_config.m_pathToDeployment, true);
if (depCRC < 0)
System.exit(-1);
} catch (Exception e) {
hostLog.fatal("Error parsing deployment file", e);
System.exit(-1);
}
serializedCatalog = catalog.serialize();
m_catalogContext = new CatalogContext(
0,
catalog, m_config.m_pathToCatalog, depCRC, catalogVersion, -1);
if (m_catalogContext.cluster.getLogconfig().get("log").getEnabled()) {
try {
@SuppressWarnings("rawtypes")
Class loggerClass = loadProClass("org.voltdb.CommandLogImpl",
"Command logging", false);
if (loggerClass != null) {
m_commandLog = (CommandLog)loggerClass.newInstance();
}
} catch (InstantiationException e) {
hostLog.fatal("Unable to instantiate command log", e);
VoltDB.crashVoltDB();
} catch (IllegalAccessException e) {
hostLog.fatal("Unable to instantiate command log", e);
VoltDB.crashVoltDB();
}
} else {
hostLog.info("Command logging is disabled");
}
// See if we should bring the server up in admin mode
if (m_catalogContext.cluster.getAdminstartup())
{
m_startMode = OperationMode.PAUSED;
}
/*
* Set the server in replay mode now, it will be set to the proper
* mode when replay finishes
*/
m_mode = OperationMode.INITIALIZING;
// set the adminPort from the deployment file
int adminPort = m_catalogContext.cluster.getAdminport();
// but allow command line override
if (config.m_adminPort > 0)
adminPort = config.m_adminPort;
// other places might use config to figure out the port
config.m_adminPort = adminPort;
// requires a catalog context.
m_faultManager = new FaultDistributor(this);
// Install a handler for NODE_FAILURE faults to update the catalog
// This should be the first handler to run when a node fails
m_faultManager.registerFaultHandler(NodeFailureFault.NODE_FAILURE_CATALOG,
m_faultHandler,
FaultType.NODE_FAILURE);
if (!m_faultManager.testPartitionDetectionDirectory(m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"))) {
VoltDB.crashVoltDB();
}
// Initialize the complex partitioning scheme
TheHashinator.initialize(catalog);
// start the httpd dashboard/jsonapi. A port value of -1 means disabled
// by the deployment.xml configuration.
int httpPort = m_catalogContext.cluster.getHttpdportno();
boolean jsonEnabled = m_catalogContext.cluster.getJsonapi();
String httpPortExtraLogMessage = null;
// if not set by the user, just find a free port
if (httpPort == 0) {
// if not set by the user, start at 8080
httpPort = 8080;
for (; true; httpPort++) {
try {
m_adminListener = new HTTPAdminListener(jsonEnabled, httpPort);
break;
} catch (Exception e1) {}
}
if (httpPort == 8081)
httpPortExtraLogMessage = "HTTP admin console unable to bind to port 8080";
else if (httpPort > 8081)
httpPortExtraLogMessage = "HTTP admin console unable to bind to ports 8080 through " + String.valueOf(httpPort - 1);
}
else if (httpPort != -1) {
try {
m_adminListener = new HTTPAdminListener(jsonEnabled, httpPort);
} catch (Exception e1) {
hostLog.info("HTTP admin console unable to bind to port " + httpPort + ". Exiting.");
System.exit(-1);
}
}
// create the string that describes the public interface
// format "XXX.XXX.XXX.XXX:clientport:adminport:httpport"
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e1) {
- hostLog.fatal("Unable to discover local IP address. Usually a java permissions failure.");
+ hostLog.fatal("Unable to discover local IP address by invoking Java's InetAddress.getLocalHost() method. Usually this is because the hostname of this node fails to resolve (for example \"ping `hostname`\" would fail). VoltDB requires that the hostname of every node resolves correctly at that node as well as every other node.");
VoltDB.crashVoltDB();
}
String localMetadata = addr.getHostAddress();
localMetadata += ":" + Integer.valueOf(config.m_port);
localMetadata += ":" + Integer.valueOf(adminPort);
localMetadata += ":" + Integer.valueOf(httpPort); // json
// possibly atomic swap from null to realz
m_localMetadata = localMetadata;
// Prepare the network socket manager for work
m_network = new VoltNetwork();
final HashSet<Integer> downHosts = new HashSet<Integer>();
boolean isRejoin = config.m_rejoinToHostAndPort != null;
if (!isRejoin) {
// Create the intra-cluster mesh
InetAddress leader = null;
try {
leader = InetAddress.getByName(m_catalogContext.cluster.getLeaderaddress());
} catch (UnknownHostException ex) {
hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_CouldNotRetrieveLeaderAddress.name(), new Object[] { m_catalogContext.cluster.getLeaderaddress() }, null);
VoltDB.crashVoltDB();
}
// ensure at least one host (catalog compiler should check this too
if (m_catalogContext.numberOfNodes <= 0) {
hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_InvalidHostCount.name(), new Object[] { m_catalogContext.numberOfNodes }, null);
VoltDB.crashVoltDB();
}
hostLog.l7dlog( Level.TRACE, LogKeys.host_VoltDB_CreatingVoltDB.name(), new Object[] { m_catalogContext.numberOfNodes, leader }, null);
hostLog.info(String.format("Beginning inter-node communication on port %d.", config.m_internalPort));
m_messenger = new HostMessenger(m_network, leader, m_catalogContext.numberOfNodes, m_catalogContext.catalogCRC, depCRC, hostLog);
Object retval[] = m_messenger.waitForGroupJoin();
m_instanceId = new Object[] { retval[0], retval[1] };
}
else {
downHosts.addAll(initializeForRejoin(config, m_catalogContext.catalogCRC, depCRC));
/**
* Whatever hosts were reported as being down on rejoin should
* be reported to the fault manager so that the fault can be distributed.
* The execution sites were informed on construction so they don't have
* to go through the agreement process.
*/
for (Integer downHost : downHosts) {
m_faultManager.reportFault(new NodeFailureFault( downHost, "UNKNOWN"));
}
try {
m_faultHandler.m_waitForFaultReported.acquire(downHosts.size());
} catch (InterruptedException e) {
VoltDB.crashVoltDB();
}
ExecutionSite.recoveringSiteCount.set(
m_catalogContext.siteTracker.getLiveExecutionSitesForHost(m_messenger.getHostId()).size());
}
m_catalogContext.m_transactionId = m_messenger.getDiscoveredCatalogTxnId();
assert(m_messenger.getDiscoveredCatalogTxnId() != 0);
// Use the host messenger's hostId.
int myHostId = m_messenger.getHostId();
// make sure the local entry for metadata is current
// it's possible it could get overwritten in a rejoin scenario
m_clusterMetadata.put(myHostId, m_localMetadata);
// Let the Export system read its configuration from the catalog.
try {
ExportManager.initialize(myHostId, m_catalogContext, isRejoin);
} catch (ExportManager.SetupException e) {
hostLog.l7dlog(Level.FATAL, LogKeys.host_VoltDB_ExportInitFailure.name(), e);
System.exit(-1);
}
// set up site structure
m_localSites = Collections.synchronizedMap(new HashMap<Integer, ExecutionSite>());
m_siteThreads = Collections.synchronizedMap(new HashMap<Integer, Thread>());
m_runners = new ArrayList<ExecutionSiteRunner>();
if (config.m_backend.isIPC) {
int eeCount = 0;
for (Site site : m_catalogContext.siteTracker.getUpSites()) {
if (site.getIsexec() &&
myHostId == Integer.parseInt(site.getHost().getTypeName())) {
eeCount++;
}
}
if (config.m_ipcPorts.size() != eeCount) {
hostLog.fatal("Specified an IPC backend but only supplied " + config.m_ipcPorts.size() +
" backend ports when " + eeCount + " are required");
System.exit(-1);
}
}
/*
* Create execution sites runners (and threads) for all exec sites except the first one.
* This allows the sites to be set up in the thread that will end up running them.
* Cache the first Site from the catalog and only do the setup once the other threads have been started.
*/
Site siteForThisThread = null;
m_currentThreadSite = null;
for (Site site : m_catalogContext.siteTracker.getUpSites()) {
int sitesHostId = Integer.parseInt(site.getHost().getTypeName());
int siteId = Integer.parseInt(site.getTypeName());
// start a local site
if (sitesHostId == myHostId) {
log.l7dlog( Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingLocalSite.name(), new Object[] { siteId }, null);
m_messenger.createLocalSite(siteId);
if (site.getIsexec()) {
if (siteForThisThread == null) {
siteForThisThread = site;
} else {
ExecutionSiteRunner runner =
new ExecutionSiteRunner(
siteId,
m_catalogContext,
serializedCatalog,
m_recovering,
downHosts);
m_runners.add(runner);
Thread runnerThread = new Thread(runner, "Site " + siteId);
runnerThread.start();
log.l7dlog(Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingThreadForSite.name(), new Object[] { siteId }, null);
m_siteThreads.put(siteId, runnerThread);
}
}
}
}
/*
* Now that the runners have been started and are doing setup of the other sites in parallel
* this thread can set up its own execution site.
*/
int siteId = Integer.parseInt(siteForThisThread.getTypeName());
ExecutionSite siteObj =
new ExecutionSite(VoltDB.instance(),
VoltDB.instance().getMessenger().createMailbox(
siteId,
VoltDB.DTXN_MAILBOX_ID),
siteId,
serializedCatalog,
null,
m_recovering,
downHosts,
m_catalogContext.m_transactionId);
m_localSites.put(Integer.parseInt(siteForThisThread.getTypeName()), siteObj);
m_currentThreadSite = siteObj;
/*
* Stop and wait for the runners to finish setting up and then put
* the constructed ExecutionSites in the local site map.
*/
for (ExecutionSiteRunner runner : m_runners) {
synchronized (runner) {
if (!runner.m_isSiteCreated) {
try {
runner.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
m_localSites.put(runner.m_siteId, runner.m_siteObj);
}
}
// set up profiling and tracing
// hack to prevent profiling on multiple machines
if (m_config.m_profilingLevel != ProcedureProfiler.Level.DISABLED) {
if (m_localSites.size() == 1) {
hostLog.l7dlog(Level.INFO,
LogKeys.host_VoltDB_ProfileLevelIs.name(),
new Object[] { m_config.m_profilingLevel },
null);
ProcedureProfiler.profilingLevel = m_config.m_profilingLevel;
}
else {
hostLog.l7dlog(
Level.INFO,
LogKeys.host_VoltDB_InternalProfilingDisabledOnMultipartitionHosts.name(),
null);
}
}
// if a workload tracer is specified, start her up!
ProcedureProfiler.initializeWorkloadTrace(catalog);
// Create the client interfaces and associated dtxn initiators
int portOffset = 0;
for (Site site : m_catalogContext.siteTracker.getUpSites()) {
int sitesHostId = Integer.parseInt(site.getHost().getTypeName());
int currSiteId = Integer.parseInt(site.getTypeName());
// create CI for each local non-EE site
if ((sitesHostId == myHostId) && (site.getIsexec() == false)) {
ClientInterface ci =
ClientInterface.create(m_network,
m_messenger,
m_catalogContext,
m_catalogContext.numberOfNodes,
currSiteId,
site.getInitiatorid(),
config.m_port + portOffset,
adminPort + portOffset,
m_config.m_timestampTestingSalt);
portOffset++;
m_clientInterfaces.add(ci);
try {
ci.startAcceptingConnections();
} catch (IOException e) {
hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_ErrorStartAcceptingConnections.name(), e);
VoltDB.crashVoltDB();
}
}
}
m_partitionCountStats = new PartitionCountStats("Partition Count Stats",
m_catalogContext.numberOfPartitions);
m_statsAgent.registerStatsSource(SysProcSelector.PARTITIONCOUNT,
0, m_partitionCountStats);
m_ioStats = new IOStats("IO Stats");
m_statsAgent.registerStatsSource(SysProcSelector.IOSTATS,
0, m_ioStats);
m_memoryStats = new MemoryStats("Memory Stats");
m_statsAgent.registerStatsSource(SysProcSelector.MEMORY,
0, m_memoryStats);
// Create the statistics manager and register it to JMX registry
m_statsManager = null;
try {
final Class<?> statsManagerClass =
Class.forName("org.voltdb.management.JMXStatsManager");
m_statsManager = (StatsManager)statsManagerClass.newInstance();
m_statsManager.initialize(new ArrayList<Integer>(m_localSites.keySet()));
} catch (Exception e) {}
// Start running the socket handlers
hostLog.l7dlog(Level.INFO,
LogKeys.host_VoltDB_StartingNetwork.name(),
new Object[] { m_network.threadPoolSize },
null);
m_network.start();
// tell other booting nodes that this node is ready. Primary purpose is to publish a hostname
m_messenger.sendReadyMessage();
// only needs to be done if this is an initial cluster startup, not a rejoin
if (config.m_rejoinToHostAndPort == null) {
// wait for all nodes to be ready
m_messenger.waitForAllHostsToBeReady();
}
fivems = new PeriodicWorkTimerThread(m_clientInterfaces,
m_statsManager);
fivems.start();
// print out a bunch of useful system info
logDebuggingInfo(adminPort, httpPort, httpPortExtraLogMessage, jsonEnabled);
int k = m_catalogContext.numberOfExecSites / m_catalogContext.numberOfPartitions;
if (k == 1) {
hostLog.warn("Running without redundancy (k=0) is not recommended for production use.");
}
assert(m_clientInterfaces.size() > 0);
ClientInterface ci = m_clientInterfaces.get(0);
TransactionInitiator initiator = ci.getInitiator();
// TODO: disable replay until the UI is in place
boolean replay = false;
if (!isRejoin && replay) {
// Load command log reader
LogReader reader = null;
try {
String logpath = m_catalogContext.cluster.getLogconfig().get("log").getLogpath();
File path = new File(logpath);
Class<?> readerClass = loadProClass("org.voltdb.utils.LogReaderImpl",
null, true);
if (readerClass != null) {
Constructor<?> constructor = readerClass.getConstructor(File.class);
reader = (LogReader) constructor.newInstance(path);
}
} catch (InvocationTargetException e) {
hostLog.info("Unable to instantiate command log reader: " +
e.getTargetException().getMessage());
} catch (Exception e) {
hostLog.fatal("Unable to instantiate command log reader", e);
VoltDB.crashVoltDB();
}
// Load command log reinitiator
try {
Class<?> replayClass = loadProClass("org.voltdb.CommandLogReinitiatorImpl",
"Command log replay", false);
if (replayClass != null) {
Constructor<?> constructor =
replayClass.getConstructor(LogReader.class,
long.class,
TransactionInitiator.class,
CatalogContext.class);
if (reader != null && !reader.isEmpty()) {
m_commandLogReplay =
(CommandLogReinitiator) constructor.newInstance(reader,
0,
initiator,
m_catalogContext);
} else {
hostLog.info("No command log to replay");
}
}
} catch (Exception e) {
hostLog.fatal("Unable to instantiate command log reinitiator", e);
VoltDB.crashVoltDB();
}
}
m_restoreAgent = new RestoreAgent(m_catalogContext, initiator,
m_commandLogReplay);
}
}
/**
* Try to load a PRO class. If it's running the community edition, an error
* message will be logged and null will be returned.
*
* @param classname The class name of the PRO class
* @param feature The name of the feature
* @param suppress true to suppress the log message
* @return null if running the community edition
*/
private static Class<?> loadProClass(String classname, String feature, boolean suppress) {
try {
Class<?> klass = Class.forName(classname);
return klass;
} catch (ClassNotFoundException e) {
if (!suppress) {
hostLog.warn("Cannot load " + classname + " in VoltDB community edition. " +
feature + " will be disabled.");
}
return null;
}
}
public HashSet<Integer> initializeForRejoin(VoltDB.Configuration config, long catalogCRC, long deploymentCRC) {
// sensible defaults (sorta)
String rejoinHostCredentialString = null;
String rejoinHostAddressString = null;
//Client interface port of node that will receive @Rejoin invocation
int rejoinPort = config.m_port;
String rejoinHost = null;
String rejoinUser = null;
String rejoinPass = null;
// this will cause the ExecutionSites to start in recovering mode
m_recovering = true;
// split a "user:pass@host:port" string into "user:pass" and "host:port"
int atSignIndex = config.m_rejoinToHostAndPort.indexOf('@');
if (atSignIndex == -1) {
rejoinHostAddressString = config.m_rejoinToHostAndPort;
}
else {
rejoinHostCredentialString = config.m_rejoinToHostAndPort.substring(0, atSignIndex).trim();
rejoinHostAddressString = config.m_rejoinToHostAndPort.substring(atSignIndex + 1).trim();
}
int colonIndex = -1;
// split a "user:pass" string into "user" and "pass"
if (rejoinHostCredentialString != null) {
colonIndex = rejoinHostCredentialString.indexOf(':');
if (colonIndex == -1) {
rejoinUser = rejoinHostCredentialString.trim();
System.out.print("password: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
rejoinPass = br.readLine();
} catch (IOException e) {
hostLog.error("Unable to read passord for rejoining credentials from console.");
System.exit(-1);
}
}
else {
rejoinUser = rejoinHostCredentialString.substring(0, colonIndex).trim();
rejoinPass = rejoinHostCredentialString.substring(colonIndex + 1).trim();
}
}
// split a "host:port" string into "host" and "port"
colonIndex = rejoinHostAddressString.indexOf(':');
if (colonIndex == -1) {
rejoinHost = rejoinHostAddressString.trim();
// note rejoinPort has a default
}
else {
rejoinHost = rejoinHostAddressString.substring(0, colonIndex).trim();
rejoinPort = Integer.parseInt(rejoinHostAddressString.substring(colonIndex + 1).trim());
}
hostLog.info(String.format("Inter-node communication will use port %d.", config.m_internalPort));
ServerSocketChannel listener = null;
try {
listener = ServerSocketChannel.open();
listener.socket().bind(new InetSocketAddress(config.m_internalPort));
} catch (IOException e) {
hostLog.error("Problem opening listening rejoin socket: " + e.getMessage());
System.exit(-1);
}
m_messenger = new HostMessenger(m_network, listener, m_catalogContext.numberOfNodes, catalogCRC, deploymentCRC, hostLog);
// make empty strings null
if ((rejoinUser != null) && (rejoinUser.length() == 0)) rejoinUser = null;
if ((rejoinPass != null) && (rejoinPass.length() == 0)) rejoinPass = null;
// URL Decode so usernames/passwords can contain weird stuff
try {
if (rejoinUser != null) rejoinUser = URLDecoder.decode(rejoinUser, "UTF-8");
if (rejoinPass != null) rejoinPass = URLDecoder.decode(rejoinPass, "UTF-8");
} catch (UnsupportedEncodingException e) {
hostLog.error("Problem URL-decoding credentials for rejoin authentication: " + e.getMessage());
System.exit(-1);
}
ClientConfig clientConfig = new ClientConfig(rejoinUser, rejoinPass);
Client client = ClientFactory.createClient(clientConfig);
ClientResponse response = null;
RejoinCallback rcb = new RejoinCallback() {
};
try {
client.createConnection(rejoinHost, rejoinPort);
InetSocketAddress inetsockaddr = new InetSocketAddress(rejoinHost, rejoinPort);
SocketChannel socket = SocketChannel.open(inetsockaddr);
String ip_addr = socket.socket().getLocalAddress().getHostAddress();
socket.close();
config.m_selectedRejoinInterface =
config.m_internalInterface.isEmpty() ? ip_addr : config.m_internalInterface;
client.callProcedure(
rcb,
"@Rejoin",
config.m_selectedRejoinInterface,
config.m_internalPort);
}
catch (Exception e) {
recoveryLog.fatal("Problem connecting client: " + e.getMessage());
VoltDB.crashVoltDB();
}
Object retval[] = m_messenger.waitForGroupJoin(60 * 1000);
m_catalogContext = new CatalogContext(
TransactionIdManager.makeIdFromComponents(System.currentTimeMillis(), 0, 0),
m_catalogContext.catalog,
m_catalogContext.pathToCatalogJar,
deploymentCRC,
m_messenger.getDiscoveredCatalogVersion(),
0);
m_instanceId = new Object[] { retval[0], retval[1] };
@SuppressWarnings("unchecked")
HashSet<Integer> downHosts = (HashSet<Integer>)retval[2];
recoveryLog.info("Down hosts are " + downHosts.toString());
try {
//Callback validates response asynchronously. Just wait for the response before continuing.
//Timeout because a failure might result in the response not coming.
response = rcb.waitForResponse(3000);
if (response == null) {
recoveryLog.fatal("Recovering node timed out rejoining");
VoltDB.crashVoltDB();
}
}
catch (InterruptedException e) {
recoveryLog.fatal("Interrupted while attempting to rejoin cluster");
VoltDB.crashVoltDB();
}
return downHosts;
}
void logDebuggingInfo(int adminPort, int httpPort, String httpPortExtraLogMessage, boolean jsonEnabled) {
// print out awesome network stuff
hostLog.info(String.format("Listening for native wire protocol clients on port %d.", m_config.m_port));
hostLog.info(String.format("Listening for admin wire protocol clients on port %d.", adminPort));
if (m_startMode == OperationMode.PAUSED) {
hostLog.info(String.format("Started in admin mode. Clients on port %d will be rejected in admin mode.", m_config.m_port));
}
if (httpPortExtraLogMessage != null)
hostLog.info(httpPortExtraLogMessage);
if (httpPort != -1) {
hostLog.info(String.format("Local machine HTTP monitoring is listening on port %d.", httpPort));
}
else {
hostLog.info(String.format("Local machine HTTP monitoring is disabled."));
}
if (jsonEnabled) {
hostLog.info(String.format("Json API over HTTP enabled at path /api/1.0/, listening on port %d.", httpPort));
}
else {
hostLog.info("Json API disabled.");
}
// replay command line args that we can see
List<String> iargs = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuilder sb = new StringBuilder("Available JVM arguments:");
for (String iarg : iargs)
sb.append(" ").append(iarg);
if (iargs.size() > 0) hostLog.info(sb.toString());
else hostLog.info("No JVM command line args known.");
// java heap size
long javamaxheapmem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax();
javamaxheapmem /= (1024 * 1024);
hostLog.info(String.format("Maximum usable Java heap set to %d mb.", javamaxheapmem));
m_catalogContext.logDebuggingInfoFromCatalog();
// print out a bunch of useful system info
PlatformProperties pp = PlatformProperties.getPlatformProperties();
String[] lines = pp.toLogLines().split("\n");
for (String line : lines) {
hostLog.info(line.trim());
}
// print out cluster membership
hostLog.info("About to list cluster interfaces for all nodes with format ip:client-port:admin-port:http-port");
for (int hostId : m_catalogContext.siteTracker.getAllLiveHosts()) {
if (hostId == m_messenger.getHostId()) {
hostLog.info(String.format(" Host id: %d with interfaces: %s [SELF]", hostId, getLocalMetadata()));
}
else {
String hostMeta = m_clusterMetadata.get(hostId);
hostLog.info(String.format(" Host id: %d with interfaces: %s [PEER]", hostId, hostMeta));
}
}
}
public static String[] extractBuildInfo() {
StringBuilder sb = new StringBuilder(64);
String buildString = "VoltDB";
String versionString = m_defaultVersionString;
byte b = -1;
try {
InputStream buildstringStream =
ClassLoader.getSystemResourceAsStream("buildstring.txt");
while ((b = (byte) buildstringStream.read()) != -1) {
sb.append((char)b);
}
sb.append("\n");
String parts[] = sb.toString().split(" ", 2);
if (parts.length != 2) {
throw new RuntimeException("Invalid buildstring.txt file.");
}
versionString = parts[0].trim();
buildString = parts[1].trim();
} catch (Exception ignored) {
try {
InputStream buildstringStream = new FileInputStream("version.txt");
while ((b = (byte) buildstringStream.read()) != -1) {
sb.append((char)b);
}
versionString = sb.toString().trim();
}
catch (Exception ignored2) {
log.l7dlog( Level.ERROR, LogKeys.org_voltdb_VoltDB_FailedToRetrieveBuildString.name(), ignored);
}
}
return new String[] { versionString, buildString };
}
@Override
public void readBuildInfo() {
String buildInfo[] = extractBuildInfo();
m_versionString = buildInfo[0];
m_buildString = buildInfo[1];
hostLog.info("Build: " + m_versionString + " " + m_buildString);
}
/**
* Start all the site's event loops. That's it.
*/
@Override
public void run() {
// start the separate EE threads
for (ExecutionSiteRunner r : m_runners) {
synchronized (r) {
assert(r.m_isSiteCreated) : "Site should already have been created by ExecutionSiteRunner";
r.notifyAll();
}
}
// start restore process
m_restoreAgent.restore();
// start one site in the current thread
Thread.currentThread().setName("ExecutionSiteAndVoltDB");
m_isRunning = true;
try
{
m_currentThreadSite.run();
}
catch (Throwable t)
{
String errmsg = "ExecutionSite: " + m_currentThreadSite.m_siteId +
" encountered an " +
"unexpected error and will die, taking this VoltDB node down.";
System.err.println(errmsg);
t.printStackTrace();
hostLog.fatal(errmsg, t);
VoltDB.crashVoltDB();
}
}
/**
* Try to shut everything down so they system is ready to call
* initialize again.
* @param mainSiteThread The thread that m_inititalized the VoltDB or
* null if called from that thread.
*/
@Override
public void shutdown(Thread mainSiteThread) throws InterruptedException {
synchronized(m_startAndStopLock) {
fivems.interrupt();
fivems.join();
// Things are going pear-shaped, tell the fault distributor to
// shut its fat mouth
m_faultManager.shutDown();
if (m_hasStartedSampler.get()) {
m_sampler.setShouldStop();
m_sampler.join();
}
// shutdown the web monitoring / json
if (m_adminListener != null)
m_adminListener.stop();
// shut down the client interface
for (ClientInterface ci : m_clientInterfaces) {
ci.shutdown();
}
// shut down Export and its connectors.
ExportManager.instance().shutdown();
// tell all m_sites to stop their runloops
if (m_localSites != null) {
for (ExecutionSite site : m_localSites.values())
site.startShutdown();
}
// try to join all threads but the main one
// probably want to check if one of these is the current thread
if (m_siteThreads != null) {
for (Thread siteThread : m_siteThreads.values()) {
if (Thread.currentThread().equals(siteThread) == false) {
// don't interrupt here. the site will start shutdown when
// it sees the shutdown flag set.
siteThread.join();
}
}
}
// try to join the main thread (possibly this one)
if (mainSiteThread != null) {
if (Thread.currentThread().equals(mainSiteThread) == false) {
// don't interrupt here. the site will start shutdown when
// it sees the shutdown flag set.
mainSiteThread.join();
}
}
// help the gc along
m_localSites = null;
m_currentThreadSite = null;
m_siteThreads = null;
m_runners = null;
// shut down the network/messaging stuff
// Close the host messenger first, which should close down all of
// the ForeignHost sockets cleanly
if (m_messenger != null)
{
m_messenger.shutdown();
}
if (m_network != null) {
//Synchronized so the interruption won't interrupt the network thread
//while it is waiting for the executor service to shutdown
m_network.shutdown();
}
m_messenger = null;
m_network = null;
//Also for test code that expects a fresh stats agent
m_statsAgent = new StatsAgent();
// The network iterates this list. Clear it after network's done.
m_clientInterfaces.clear();
ExportManager.instance().shutdown();
// probably unnecessary
System.gc();
m_isRunning = false;
}
}
/** Last transaction ID at which the rejoin commit took place.
* Also, use the intrinsic lock to safeguard access from multiple
* execution site threads */
private static Long lastNodeRejoinPrepare_txnId = 0L;
@Override
public synchronized String doRejoinPrepare(
long currentTxnId,
int rejoinHostId,
String rejoiningHostname,
int portToConnect,
Set<Integer> liveHosts)
{
// another site already did this work.
if (currentTxnId == lastNodeRejoinPrepare_txnId) {
return null;
}
else if (currentTxnId < lastNodeRejoinPrepare_txnId) {
throw new RuntimeException("Trying to rejoin (prepare) with an old transaction.");
}
// connect to the joining node, build a foreign host
InetSocketAddress addr = new InetSocketAddress(rejoiningHostname, portToConnect);
String ipAddr = addr.getAddress().toString();
recoveryLog.info("Rejoining node with host id: " + rejoinHostId +
", hostname: " + ipAddr +
" at txnid: " + currentTxnId);
lastNodeRejoinPrepare_txnId = currentTxnId;
HostMessenger messenger = getHostMessenger();
// connect to the joining node, build a foreign host
try {
messenger.rejoinForeignHostPrepare(rejoinHostId, addr, m_catalogContext.catalogCRC,
m_catalogContext.deploymentCRC, liveHosts,
m_catalogContext.catalogVersion, m_catalogContext.m_transactionId);
return null;
} catch (Exception e) {
//e.printStackTrace();
return e.getMessage() == null ? e.getClass().getName() : e.getMessage();
}
}
/** Last transaction ID at which the rejoin commit took place.
* Also, use the intrinsic lock to safeguard access from multiple
* execution site threads */
private static Long lastNodeRejoinFinish_txnId = 0L;
@Override
public synchronized String doRejoinCommitOrRollback(long currentTxnId, boolean commit) {
// another site already did this work.
if (currentTxnId == lastNodeRejoinFinish_txnId) {
return null;
}
else if (currentTxnId < lastNodeRejoinFinish_txnId) {
throw new RuntimeException("Trying to rejoin (commit/rollback) with an old transaction.");
}
recoveryLog.info("Rejoining commit node with txnid: " + currentTxnId +
" lastNodeRejoinFinish_txnId: " + lastNodeRejoinFinish_txnId);
HostMessenger messenger = getHostMessenger();
if (commit) {
// put the foreign host into the set of active ones
HostMessenger.JoiningNodeInfo joinNodeInfo = messenger.rejoinForeignHostCommit();
m_faultManager.reportFaultCleared(new NodeFailureFault(joinNodeInfo.hostId, joinNodeInfo.hostName));
try {
m_faultHandler.m_waitForFaultClear.acquire();
} catch (InterruptedException e) {
VoltDB.crashVoltDB();//shouldn't happen
}
ArrayList<Integer> rejoiningSiteIds = new ArrayList<Integer>();
ArrayList<Integer> rejoiningExecSiteIds = new ArrayList<Integer>();
Cluster cluster = m_catalogContext.catalog.getClusters().get("cluster");
for (Site site : cluster.getSites()) {
int siteId = Integer.parseInt(site.getTypeName());
int hostId = Integer.parseInt(site.getHost().getTypeName());
if (hostId == joinNodeInfo.hostId) {
assert(site.getIsup() == false);
rejoiningSiteIds.add(siteId);
if (site.getIsexec() == true) {
rejoiningExecSiteIds.add(siteId);
}
}
}
assert(rejoiningSiteIds.size() > 0);
// get a string list of all the new sites
StringBuilder newIds = new StringBuilder();
for (int siteId : rejoiningSiteIds) {
newIds.append(siteId).append(",");
}
// trim the last comma
newIds.setLength(newIds.length() - 1);
// change the catalog to reflect this change
hostLog.info("Host joined, host id: " + joinNodeInfo.hostId + " hostname: " + joinNodeInfo.hostName);
hostLog.info(" Adding sites to cluster: " + newIds);
StringBuilder sb = new StringBuilder();
for (int siteId : rejoiningSiteIds)
{
sb.append("set ");
String site_path = VoltDB.instance().getCatalogContext().catalog.
getClusters().get("cluster").getSites().
get(Integer.toString(siteId)).getPath();
sb.append(site_path).append(" ").append("isUp true");
sb.append("\n");
}
String catalogDiffCommands = sb.toString();
clusterUpdate(catalogDiffCommands);
// update the SafteyState in the initiators
for (ClientInterface ci : m_clientInterfaces) {
TransactionInitiator initiator = ci.getInitiator();
initiator.notifyExecutionSiteRejoin(rejoiningExecSiteIds);
}
//Notify the export manager the cluster topology has changed
ExportManager.instance().notifyOfClusterTopologyChange();
}
else {
// clean up any connections made
messenger.rejoinForeignHostRollback();
}
recoveryLog.info("Setting lastNodeRejoinFinish_txnId to: " + currentTxnId);
lastNodeRejoinFinish_txnId = currentTxnId;
return null;
}
/** Last transaction ID at which the logging config updated.
* Also, use the intrinsic lock to safeguard access from multiple
* execution site threads */
private static Long lastLogUpdate_txnId = 0L;
@Override
public void logUpdate(String xmlConfig, long currentTxnId)
{
synchronized(lastLogUpdate_txnId)
{
// another site already did this work.
if (currentTxnId == lastLogUpdate_txnId) {
return;
}
else if (currentTxnId < lastLogUpdate_txnId) {
throw new RuntimeException("Trying to update logging config with an old transaction.");
}
System.out.println("Updating RealVoltDB logging config from txnid: " +
lastLogUpdate_txnId + " to " + currentTxnId);
lastLogUpdate_txnId = currentTxnId;
VoltLogger.configure(xmlConfig);
}
}
/** Struct to associate a context with a counter of served sites */
private static class ContextTracker {
ContextTracker(CatalogContext context) {
m_dispensedSites = 1;
m_context = context;
}
long m_dispensedSites;
CatalogContext m_context;
}
/** Associate transaction ids to contexts */
private HashMap<Long, ContextTracker>m_txnIdToContextTracker =
new HashMap<Long, ContextTracker>();
@Override
public CatalogContext catalogUpdate(
String diffCommands,
String newCatalogURL,
int expectedCatalogVersion,
long currentTxnId,
long deploymentCRC)
{
synchronized(m_catalogUpdateLock) {
// A site is catching up with catalog updates
if (currentTxnId <= m_catalogContext.m_transactionId) {
ContextTracker contextTracker = m_txnIdToContextTracker.get(currentTxnId);
// This 'dispensed' concept is a little crazy fragile. Maybe it would be better
// to keep a rolling N catalogs? Or perhaps to keep catalogs for N minutes? Open
// to opinions here.
contextTracker.m_dispensedSites++;
int ttlsites = m_catalogContext.siteTracker.getLiveExecutionSitesForHost(m_messenger.getHostId()).size();
if (contextTracker.m_dispensedSites == ttlsites) {
m_txnIdToContextTracker.remove(currentTxnId);
}
return contextTracker.m_context;
}
else if (m_catalogContext.catalogVersion != expectedCatalogVersion) {
throw new RuntimeException("Trying to update main catalog context with diff " +
"commands generated for an out-of date catalog. Expected catalog version: " +
expectedCatalogVersion + " does not match actual version: " + m_catalogContext.catalogVersion);
}
// 0. A new catalog! Update the global context and the context tracker
m_catalogContext =
m_catalogContext.update(currentTxnId, newCatalogURL, diffCommands, true, deploymentCRC);
m_txnIdToContextTracker.put(currentTxnId, new ContextTracker(m_catalogContext));
m_catalogContext.logDebuggingInfoFromCatalog();
// 1. update the export manager.
ExportManager.instance().updateCatalog(m_catalogContext);
// 2. update client interface (asynchronously)
// CI in turn updates the planner thread.
for (ClientInterface ci : m_clientInterfaces) {
ci.notifyOfCatalogUpdate();
}
// 3. update HTTPClientInterface (asynchronously)
// This purges cached connection state so that access with
// stale auth info is prevented.
if (m_adminListener != null)
{
m_adminListener.notifyOfCatalogUpdate();
}
return m_catalogContext;
}
}
@Override
public void clusterUpdate(String diffCommands)
{
synchronized(m_catalogUpdateLock)
{
//Reuse the txn id since this doesn't change schema/procs/export
m_catalogContext = m_catalogContext.update( m_catalogContext.m_transactionId, CatalogContext.NO_PATH,
diffCommands, false, -1);
}
for (ClientInterface ci : m_clientInterfaces)
{
ci.notifyOfCatalogUpdate();
}
}
@Override
public VoltDB.Configuration getConfig()
{
return m_config;
}
@Override
public String getBuildString() {
return m_buildString;
}
@Override
public String getVersionString() {
return m_versionString;
}
@Override
public Messenger getMessenger() {
return m_messenger;
}
@Override
public HostMessenger getHostMessenger() {
return m_messenger;
}
@Override
public ArrayList<ClientInterface> getClientInterfaces() {
return m_clientInterfaces;
}
@Override
public Map<Integer, ExecutionSite> getLocalSites() {
return m_localSites;
}
@Override
public VoltNetwork getNetwork() {
return m_network;
}
@Override
public StatsAgent getStatsAgent() {
return m_statsAgent;
}
@Override
public MemoryStats getMemoryStatsSource() {
return m_memoryStats;
}
@Override
public FaultDistributorInterface getFaultDistributor()
{
return m_faultManager;
}
@Override
public CatalogContext getCatalogContext() {
synchronized(m_catalogUpdateLock) {
return m_catalogContext;
}
}
/**
* Tells if the VoltDB is running. m_isRunning needs to be set to true
* when the run() method is called, and set to false when shutting down.
*
* @return true if the VoltDB is running.
*/
@Override
public boolean isRunning() {
return m_isRunning;
}
/**
* Debugging function - creates a record of the current state of the system.
* @param out PrintStream to write report to.
*/
public void createRuntimeReport(PrintStream out) {
// This function may be running in its own thread.
out.print("MIME-Version: 1.0\n");
out.print("Content-type: multipart/mixed; boundary=\"reportsection\"");
out.print("\n\n--reportsection\nContent-Type: text/plain\n\nClientInterface Report\n");
for (ClientInterface ci : getClientInterfaces()) {
out.print(ci.toString() + "\n");
}
out.print("\n\n--reportsection\nContent-Type: text/plain\n\nLocalSite Report\n");
for(ExecutionSite es : getLocalSites().values()) {
out.print(es.toString() + "\n");
}
out.print("\n\n--reportsection--");
}
@Override
public boolean ignoreCrash() {
return false;
}
@Override
public Object[] getInstanceId() {
return m_instanceId;
}
@Override
public BackendTarget getBackendTargetType() {
return m_config.m_backend;
}
@Override
public void onRecoveryCompletion(long transferred) {
final long now = System.currentTimeMillis();
final long delta = ((now - m_recoveryStartTime) / 1000);
final long megabytes = transferred / (1024 * 1024);
final double megabytesPerSecond = megabytes / ((now - m_recoveryStartTime) / 1000.0);
m_recovering = false;
for (ClientInterface intf : getClientInterfaces()) {
intf.mayActivateSnapshotDaemon();
}
hostLog.info(
"Node recovery completed after " + delta + " seconds with " + megabytes +
" megabytes transferred at a rate of " +
megabytesPerSecond + " megabytes/sec");
}
@Override
public CommandLog getCommandLog() {
return m_commandLog;
}
@Override
public OperationMode getMode()
{
return m_mode;
}
@Override
public void setMode(OperationMode mode)
{
if (m_mode != mode)
{
if (mode == OperationMode.PAUSED)
{
hostLog.info("Server is entering admin mode and pausing.");
}
else if (m_mode == OperationMode.PAUSED)
{
hostLog.info("Server is exiting admin mode and resuming operation.");
}
}
m_mode = mode;
}
@Override
public void setStartMode(OperationMode mode) {
m_startMode = mode;
}
/**
* Get the metadata map for the wholes cluster.
* Note: this may include failed nodes so check for live ones
* and filter this if needed.
*
* Metadata is currently of the format:
* IP:CIENTPORT:ADMINPORT:HTTPPORT]
*/
@Override
public Map<Integer, String> getClusterMetadataMap() {
return m_clusterMetadata;
}
/**
* Metadata is currently of the format:
* IP:CIENTPORT:ADMINPORT:HTTPPORT]
*/
@Override
public String getLocalMetadata() {
return m_localMetadata;
}
@Override
public void onRestoreCompletion() {
// Enable the initiator to send normal heartbeats
for (ClientInterface ci : m_clientInterfaces) {
ci.getInitiator().setSendHeartbeats(true);
}
// Initialize command logger
m_commandLog.init(m_catalogContext);
if (m_startMode != null) {
m_mode = m_startMode;
} else {
// Shouldn't be here, but to be safe
m_mode = OperationMode.RUNNING;
}
hostLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_ServerCompletedInitialization.name(), null);
}
}
| true | true | public void initialize(VoltDB.Configuration config) {
synchronized(m_startAndStopLock) {
// start (asynchronously) getting platform info
// this will start a thread that should die in less
// than a second
PlatformProperties.fetchPlatformProperties();
if (m_pidFile == null) {
String name = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
String pidString = name.substring(0, name.indexOf('@'));
m_pidFile = new java.io.File("/var/tmp/voltpid." + pidString);
try {
boolean success = m_pidFile.createNewFile();
if (!success) {
hostLog.error("Could not create PID file " + m_pidFile + " because it already exists");
}
m_pidFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(m_pidFile);
fos.write(pidString.getBytes("UTF-8"));
fos.close();
} catch (IOException e) {
hostLog.error("Error creating PID file " + m_pidFile, e);
}
}
// useful for debugging, but doesn't do anything unless VLog is enabled
if (config.m_port != VoltDB.DEFAULT_PORT) {
VLog.setPortNo(config.m_port);
}
VLog.log("\n### RealVoltDB.initialize() for port %d ###", config.m_port);
hostLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_StartupString.name(), null);
// Set std-out/err to use the UTF-8 encoding and fail if UTF-8 isn't supported
try {
System.setOut(new PrintStream(System.out, true, "UTF-8"));
System.setErr(new PrintStream(System.err, true, "UTF-8"));
} catch (UnsupportedEncodingException e) {
hostLog.fatal("Support for the UTF-8 encoding is required for VoltDB. This means you are likely running an unsupported JVM. Exiting.");
System.exit(-1);
}
// check that this is a 64 bit VM
if (System.getProperty("java.vm.name").contains("64") == false) {
hostLog.fatal("You are running on an unsupported (probably 32 bit) JVM. Exiting.");
System.exit(-1);
}
// start the dumper thread
if (config.listenForDumpRequests)
DumpManager.init();
readBuildInfo();
m_config = config;
// Initialize the catalog and some common shortcuts
if (m_config.m_pathToCatalog.startsWith("http")) {
hostLog.info("Loading application catalog jarfile from " + m_config.m_pathToCatalog);
}
else {
File f = new File(m_config.m_pathToCatalog);
hostLog.info("Loading application catalog jarfile from " + f.getAbsolutePath());
}
String serializedCatalog = CatalogUtil.loadCatalogFromJar(m_config.m_pathToCatalog, hostLog);
if ((serializedCatalog == null) || (serializedCatalog.length() == 0))
VoltDB.crashVoltDB();
/* N.B. node recovery requires discovering the current catalog version. */
final int catalogVersion = 0;
Catalog catalog = new Catalog();
catalog.execute(serializedCatalog);
// note if this fails it will print an error first
long depCRC = -1;
try {
depCRC = CatalogUtil.compileDeploymentAndGetCRC(catalog, m_config.m_pathToDeployment, true);
if (depCRC < 0)
System.exit(-1);
} catch (Exception e) {
hostLog.fatal("Error parsing deployment file", e);
System.exit(-1);
}
serializedCatalog = catalog.serialize();
m_catalogContext = new CatalogContext(
0,
catalog, m_config.m_pathToCatalog, depCRC, catalogVersion, -1);
if (m_catalogContext.cluster.getLogconfig().get("log").getEnabled()) {
try {
@SuppressWarnings("rawtypes")
Class loggerClass = loadProClass("org.voltdb.CommandLogImpl",
"Command logging", false);
if (loggerClass != null) {
m_commandLog = (CommandLog)loggerClass.newInstance();
}
} catch (InstantiationException e) {
hostLog.fatal("Unable to instantiate command log", e);
VoltDB.crashVoltDB();
} catch (IllegalAccessException e) {
hostLog.fatal("Unable to instantiate command log", e);
VoltDB.crashVoltDB();
}
} else {
hostLog.info("Command logging is disabled");
}
// See if we should bring the server up in admin mode
if (m_catalogContext.cluster.getAdminstartup())
{
m_startMode = OperationMode.PAUSED;
}
/*
* Set the server in replay mode now, it will be set to the proper
* mode when replay finishes
*/
m_mode = OperationMode.INITIALIZING;
// set the adminPort from the deployment file
int adminPort = m_catalogContext.cluster.getAdminport();
// but allow command line override
if (config.m_adminPort > 0)
adminPort = config.m_adminPort;
// other places might use config to figure out the port
config.m_adminPort = adminPort;
// requires a catalog context.
m_faultManager = new FaultDistributor(this);
// Install a handler for NODE_FAILURE faults to update the catalog
// This should be the first handler to run when a node fails
m_faultManager.registerFaultHandler(NodeFailureFault.NODE_FAILURE_CATALOG,
m_faultHandler,
FaultType.NODE_FAILURE);
if (!m_faultManager.testPartitionDetectionDirectory(m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"))) {
VoltDB.crashVoltDB();
}
// Initialize the complex partitioning scheme
TheHashinator.initialize(catalog);
// start the httpd dashboard/jsonapi. A port value of -1 means disabled
// by the deployment.xml configuration.
int httpPort = m_catalogContext.cluster.getHttpdportno();
boolean jsonEnabled = m_catalogContext.cluster.getJsonapi();
String httpPortExtraLogMessage = null;
// if not set by the user, just find a free port
if (httpPort == 0) {
// if not set by the user, start at 8080
httpPort = 8080;
for (; true; httpPort++) {
try {
m_adminListener = new HTTPAdminListener(jsonEnabled, httpPort);
break;
} catch (Exception e1) {}
}
if (httpPort == 8081)
httpPortExtraLogMessage = "HTTP admin console unable to bind to port 8080";
else if (httpPort > 8081)
httpPortExtraLogMessage = "HTTP admin console unable to bind to ports 8080 through " + String.valueOf(httpPort - 1);
}
else if (httpPort != -1) {
try {
m_adminListener = new HTTPAdminListener(jsonEnabled, httpPort);
} catch (Exception e1) {
hostLog.info("HTTP admin console unable to bind to port " + httpPort + ". Exiting.");
System.exit(-1);
}
}
// create the string that describes the public interface
// format "XXX.XXX.XXX.XXX:clientport:adminport:httpport"
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e1) {
hostLog.fatal("Unable to discover local IP address. Usually a java permissions failure.");
VoltDB.crashVoltDB();
}
String localMetadata = addr.getHostAddress();
localMetadata += ":" + Integer.valueOf(config.m_port);
localMetadata += ":" + Integer.valueOf(adminPort);
localMetadata += ":" + Integer.valueOf(httpPort); // json
// possibly atomic swap from null to realz
m_localMetadata = localMetadata;
// Prepare the network socket manager for work
m_network = new VoltNetwork();
final HashSet<Integer> downHosts = new HashSet<Integer>();
boolean isRejoin = config.m_rejoinToHostAndPort != null;
if (!isRejoin) {
// Create the intra-cluster mesh
InetAddress leader = null;
try {
leader = InetAddress.getByName(m_catalogContext.cluster.getLeaderaddress());
} catch (UnknownHostException ex) {
hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_CouldNotRetrieveLeaderAddress.name(), new Object[] { m_catalogContext.cluster.getLeaderaddress() }, null);
VoltDB.crashVoltDB();
}
// ensure at least one host (catalog compiler should check this too
if (m_catalogContext.numberOfNodes <= 0) {
hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_InvalidHostCount.name(), new Object[] { m_catalogContext.numberOfNodes }, null);
VoltDB.crashVoltDB();
}
hostLog.l7dlog( Level.TRACE, LogKeys.host_VoltDB_CreatingVoltDB.name(), new Object[] { m_catalogContext.numberOfNodes, leader }, null);
hostLog.info(String.format("Beginning inter-node communication on port %d.", config.m_internalPort));
m_messenger = new HostMessenger(m_network, leader, m_catalogContext.numberOfNodes, m_catalogContext.catalogCRC, depCRC, hostLog);
Object retval[] = m_messenger.waitForGroupJoin();
m_instanceId = new Object[] { retval[0], retval[1] };
}
else {
downHosts.addAll(initializeForRejoin(config, m_catalogContext.catalogCRC, depCRC));
/**
* Whatever hosts were reported as being down on rejoin should
* be reported to the fault manager so that the fault can be distributed.
* The execution sites were informed on construction so they don't have
* to go through the agreement process.
*/
for (Integer downHost : downHosts) {
m_faultManager.reportFault(new NodeFailureFault( downHost, "UNKNOWN"));
}
try {
m_faultHandler.m_waitForFaultReported.acquire(downHosts.size());
} catch (InterruptedException e) {
VoltDB.crashVoltDB();
}
ExecutionSite.recoveringSiteCount.set(
m_catalogContext.siteTracker.getLiveExecutionSitesForHost(m_messenger.getHostId()).size());
}
m_catalogContext.m_transactionId = m_messenger.getDiscoveredCatalogTxnId();
assert(m_messenger.getDiscoveredCatalogTxnId() != 0);
// Use the host messenger's hostId.
int myHostId = m_messenger.getHostId();
// make sure the local entry for metadata is current
// it's possible it could get overwritten in a rejoin scenario
m_clusterMetadata.put(myHostId, m_localMetadata);
// Let the Export system read its configuration from the catalog.
try {
ExportManager.initialize(myHostId, m_catalogContext, isRejoin);
} catch (ExportManager.SetupException e) {
hostLog.l7dlog(Level.FATAL, LogKeys.host_VoltDB_ExportInitFailure.name(), e);
System.exit(-1);
}
// set up site structure
m_localSites = Collections.synchronizedMap(new HashMap<Integer, ExecutionSite>());
m_siteThreads = Collections.synchronizedMap(new HashMap<Integer, Thread>());
m_runners = new ArrayList<ExecutionSiteRunner>();
if (config.m_backend.isIPC) {
int eeCount = 0;
for (Site site : m_catalogContext.siteTracker.getUpSites()) {
if (site.getIsexec() &&
myHostId == Integer.parseInt(site.getHost().getTypeName())) {
eeCount++;
}
}
if (config.m_ipcPorts.size() != eeCount) {
hostLog.fatal("Specified an IPC backend but only supplied " + config.m_ipcPorts.size() +
" backend ports when " + eeCount + " are required");
System.exit(-1);
}
}
/*
* Create execution sites runners (and threads) for all exec sites except the first one.
* This allows the sites to be set up in the thread that will end up running them.
* Cache the first Site from the catalog and only do the setup once the other threads have been started.
*/
Site siteForThisThread = null;
m_currentThreadSite = null;
for (Site site : m_catalogContext.siteTracker.getUpSites()) {
int sitesHostId = Integer.parseInt(site.getHost().getTypeName());
int siteId = Integer.parseInt(site.getTypeName());
// start a local site
if (sitesHostId == myHostId) {
log.l7dlog( Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingLocalSite.name(), new Object[] { siteId }, null);
m_messenger.createLocalSite(siteId);
if (site.getIsexec()) {
if (siteForThisThread == null) {
siteForThisThread = site;
} else {
ExecutionSiteRunner runner =
new ExecutionSiteRunner(
siteId,
m_catalogContext,
serializedCatalog,
m_recovering,
downHosts);
m_runners.add(runner);
Thread runnerThread = new Thread(runner, "Site " + siteId);
runnerThread.start();
log.l7dlog(Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingThreadForSite.name(), new Object[] { siteId }, null);
m_siteThreads.put(siteId, runnerThread);
}
}
}
}
/*
* Now that the runners have been started and are doing setup of the other sites in parallel
* this thread can set up its own execution site.
*/
int siteId = Integer.parseInt(siteForThisThread.getTypeName());
ExecutionSite siteObj =
new ExecutionSite(VoltDB.instance(),
VoltDB.instance().getMessenger().createMailbox(
siteId,
VoltDB.DTXN_MAILBOX_ID),
siteId,
serializedCatalog,
null,
m_recovering,
downHosts,
m_catalogContext.m_transactionId);
m_localSites.put(Integer.parseInt(siteForThisThread.getTypeName()), siteObj);
m_currentThreadSite = siteObj;
/*
* Stop and wait for the runners to finish setting up and then put
* the constructed ExecutionSites in the local site map.
*/
for (ExecutionSiteRunner runner : m_runners) {
synchronized (runner) {
if (!runner.m_isSiteCreated) {
try {
runner.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
m_localSites.put(runner.m_siteId, runner.m_siteObj);
}
}
// set up profiling and tracing
// hack to prevent profiling on multiple machines
if (m_config.m_profilingLevel != ProcedureProfiler.Level.DISABLED) {
if (m_localSites.size() == 1) {
hostLog.l7dlog(Level.INFO,
LogKeys.host_VoltDB_ProfileLevelIs.name(),
new Object[] { m_config.m_profilingLevel },
null);
ProcedureProfiler.profilingLevel = m_config.m_profilingLevel;
}
else {
hostLog.l7dlog(
Level.INFO,
LogKeys.host_VoltDB_InternalProfilingDisabledOnMultipartitionHosts.name(),
null);
}
}
// if a workload tracer is specified, start her up!
ProcedureProfiler.initializeWorkloadTrace(catalog);
// Create the client interfaces and associated dtxn initiators
int portOffset = 0;
for (Site site : m_catalogContext.siteTracker.getUpSites()) {
int sitesHostId = Integer.parseInt(site.getHost().getTypeName());
int currSiteId = Integer.parseInt(site.getTypeName());
// create CI for each local non-EE site
if ((sitesHostId == myHostId) && (site.getIsexec() == false)) {
ClientInterface ci =
ClientInterface.create(m_network,
m_messenger,
m_catalogContext,
m_catalogContext.numberOfNodes,
currSiteId,
site.getInitiatorid(),
config.m_port + portOffset,
adminPort + portOffset,
m_config.m_timestampTestingSalt);
portOffset++;
m_clientInterfaces.add(ci);
try {
ci.startAcceptingConnections();
} catch (IOException e) {
hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_ErrorStartAcceptingConnections.name(), e);
VoltDB.crashVoltDB();
}
}
}
m_partitionCountStats = new PartitionCountStats("Partition Count Stats",
m_catalogContext.numberOfPartitions);
m_statsAgent.registerStatsSource(SysProcSelector.PARTITIONCOUNT,
0, m_partitionCountStats);
m_ioStats = new IOStats("IO Stats");
m_statsAgent.registerStatsSource(SysProcSelector.IOSTATS,
0, m_ioStats);
m_memoryStats = new MemoryStats("Memory Stats");
m_statsAgent.registerStatsSource(SysProcSelector.MEMORY,
0, m_memoryStats);
// Create the statistics manager and register it to JMX registry
m_statsManager = null;
try {
final Class<?> statsManagerClass =
Class.forName("org.voltdb.management.JMXStatsManager");
m_statsManager = (StatsManager)statsManagerClass.newInstance();
m_statsManager.initialize(new ArrayList<Integer>(m_localSites.keySet()));
} catch (Exception e) {}
// Start running the socket handlers
hostLog.l7dlog(Level.INFO,
LogKeys.host_VoltDB_StartingNetwork.name(),
new Object[] { m_network.threadPoolSize },
null);
m_network.start();
// tell other booting nodes that this node is ready. Primary purpose is to publish a hostname
m_messenger.sendReadyMessage();
// only needs to be done if this is an initial cluster startup, not a rejoin
if (config.m_rejoinToHostAndPort == null) {
// wait for all nodes to be ready
m_messenger.waitForAllHostsToBeReady();
}
fivems = new PeriodicWorkTimerThread(m_clientInterfaces,
m_statsManager);
fivems.start();
// print out a bunch of useful system info
logDebuggingInfo(adminPort, httpPort, httpPortExtraLogMessage, jsonEnabled);
int k = m_catalogContext.numberOfExecSites / m_catalogContext.numberOfPartitions;
if (k == 1) {
hostLog.warn("Running without redundancy (k=0) is not recommended for production use.");
}
assert(m_clientInterfaces.size() > 0);
ClientInterface ci = m_clientInterfaces.get(0);
TransactionInitiator initiator = ci.getInitiator();
// TODO: disable replay until the UI is in place
boolean replay = false;
if (!isRejoin && replay) {
// Load command log reader
LogReader reader = null;
try {
String logpath = m_catalogContext.cluster.getLogconfig().get("log").getLogpath();
File path = new File(logpath);
Class<?> readerClass = loadProClass("org.voltdb.utils.LogReaderImpl",
null, true);
if (readerClass != null) {
Constructor<?> constructor = readerClass.getConstructor(File.class);
reader = (LogReader) constructor.newInstance(path);
}
} catch (InvocationTargetException e) {
hostLog.info("Unable to instantiate command log reader: " +
e.getTargetException().getMessage());
} catch (Exception e) {
hostLog.fatal("Unable to instantiate command log reader", e);
VoltDB.crashVoltDB();
}
// Load command log reinitiator
try {
Class<?> replayClass = loadProClass("org.voltdb.CommandLogReinitiatorImpl",
"Command log replay", false);
if (replayClass != null) {
Constructor<?> constructor =
replayClass.getConstructor(LogReader.class,
long.class,
TransactionInitiator.class,
CatalogContext.class);
if (reader != null && !reader.isEmpty()) {
m_commandLogReplay =
(CommandLogReinitiator) constructor.newInstance(reader,
0,
initiator,
m_catalogContext);
} else {
hostLog.info("No command log to replay");
}
}
} catch (Exception e) {
hostLog.fatal("Unable to instantiate command log reinitiator", e);
VoltDB.crashVoltDB();
}
}
m_restoreAgent = new RestoreAgent(m_catalogContext, initiator,
m_commandLogReplay);
}
}
| public void initialize(VoltDB.Configuration config) {
synchronized(m_startAndStopLock) {
// start (asynchronously) getting platform info
// this will start a thread that should die in less
// than a second
PlatformProperties.fetchPlatformProperties();
if (m_pidFile == null) {
String name = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
String pidString = name.substring(0, name.indexOf('@'));
m_pidFile = new java.io.File("/var/tmp/voltpid." + pidString);
try {
boolean success = m_pidFile.createNewFile();
if (!success) {
hostLog.error("Could not create PID file " + m_pidFile + " because it already exists");
}
m_pidFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(m_pidFile);
fos.write(pidString.getBytes("UTF-8"));
fos.close();
} catch (IOException e) {
hostLog.error("Error creating PID file " + m_pidFile, e);
}
}
// useful for debugging, but doesn't do anything unless VLog is enabled
if (config.m_port != VoltDB.DEFAULT_PORT) {
VLog.setPortNo(config.m_port);
}
VLog.log("\n### RealVoltDB.initialize() for port %d ###", config.m_port);
hostLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_StartupString.name(), null);
// Set std-out/err to use the UTF-8 encoding and fail if UTF-8 isn't supported
try {
System.setOut(new PrintStream(System.out, true, "UTF-8"));
System.setErr(new PrintStream(System.err, true, "UTF-8"));
} catch (UnsupportedEncodingException e) {
hostLog.fatal("Support for the UTF-8 encoding is required for VoltDB. This means you are likely running an unsupported JVM. Exiting.");
System.exit(-1);
}
// check that this is a 64 bit VM
if (System.getProperty("java.vm.name").contains("64") == false) {
hostLog.fatal("You are running on an unsupported (probably 32 bit) JVM. Exiting.");
System.exit(-1);
}
// start the dumper thread
if (config.listenForDumpRequests)
DumpManager.init();
readBuildInfo();
m_config = config;
// Initialize the catalog and some common shortcuts
if (m_config.m_pathToCatalog.startsWith("http")) {
hostLog.info("Loading application catalog jarfile from " + m_config.m_pathToCatalog);
}
else {
File f = new File(m_config.m_pathToCatalog);
hostLog.info("Loading application catalog jarfile from " + f.getAbsolutePath());
}
String serializedCatalog = CatalogUtil.loadCatalogFromJar(m_config.m_pathToCatalog, hostLog);
if ((serializedCatalog == null) || (serializedCatalog.length() == 0))
VoltDB.crashVoltDB();
/* N.B. node recovery requires discovering the current catalog version. */
final int catalogVersion = 0;
Catalog catalog = new Catalog();
catalog.execute(serializedCatalog);
// note if this fails it will print an error first
long depCRC = -1;
try {
depCRC = CatalogUtil.compileDeploymentAndGetCRC(catalog, m_config.m_pathToDeployment, true);
if (depCRC < 0)
System.exit(-1);
} catch (Exception e) {
hostLog.fatal("Error parsing deployment file", e);
System.exit(-1);
}
serializedCatalog = catalog.serialize();
m_catalogContext = new CatalogContext(
0,
catalog, m_config.m_pathToCatalog, depCRC, catalogVersion, -1);
if (m_catalogContext.cluster.getLogconfig().get("log").getEnabled()) {
try {
@SuppressWarnings("rawtypes")
Class loggerClass = loadProClass("org.voltdb.CommandLogImpl",
"Command logging", false);
if (loggerClass != null) {
m_commandLog = (CommandLog)loggerClass.newInstance();
}
} catch (InstantiationException e) {
hostLog.fatal("Unable to instantiate command log", e);
VoltDB.crashVoltDB();
} catch (IllegalAccessException e) {
hostLog.fatal("Unable to instantiate command log", e);
VoltDB.crashVoltDB();
}
} else {
hostLog.info("Command logging is disabled");
}
// See if we should bring the server up in admin mode
if (m_catalogContext.cluster.getAdminstartup())
{
m_startMode = OperationMode.PAUSED;
}
/*
* Set the server in replay mode now, it will be set to the proper
* mode when replay finishes
*/
m_mode = OperationMode.INITIALIZING;
// set the adminPort from the deployment file
int adminPort = m_catalogContext.cluster.getAdminport();
// but allow command line override
if (config.m_adminPort > 0)
adminPort = config.m_adminPort;
// other places might use config to figure out the port
config.m_adminPort = adminPort;
// requires a catalog context.
m_faultManager = new FaultDistributor(this);
// Install a handler for NODE_FAILURE faults to update the catalog
// This should be the first handler to run when a node fails
m_faultManager.registerFaultHandler(NodeFailureFault.NODE_FAILURE_CATALOG,
m_faultHandler,
FaultType.NODE_FAILURE);
if (!m_faultManager.testPartitionDetectionDirectory(m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"))) {
VoltDB.crashVoltDB();
}
// Initialize the complex partitioning scheme
TheHashinator.initialize(catalog);
// start the httpd dashboard/jsonapi. A port value of -1 means disabled
// by the deployment.xml configuration.
int httpPort = m_catalogContext.cluster.getHttpdportno();
boolean jsonEnabled = m_catalogContext.cluster.getJsonapi();
String httpPortExtraLogMessage = null;
// if not set by the user, just find a free port
if (httpPort == 0) {
// if not set by the user, start at 8080
httpPort = 8080;
for (; true; httpPort++) {
try {
m_adminListener = new HTTPAdminListener(jsonEnabled, httpPort);
break;
} catch (Exception e1) {}
}
if (httpPort == 8081)
httpPortExtraLogMessage = "HTTP admin console unable to bind to port 8080";
else if (httpPort > 8081)
httpPortExtraLogMessage = "HTTP admin console unable to bind to ports 8080 through " + String.valueOf(httpPort - 1);
}
else if (httpPort != -1) {
try {
m_adminListener = new HTTPAdminListener(jsonEnabled, httpPort);
} catch (Exception e1) {
hostLog.info("HTTP admin console unable to bind to port " + httpPort + ". Exiting.");
System.exit(-1);
}
}
// create the string that describes the public interface
// format "XXX.XXX.XXX.XXX:clientport:adminport:httpport"
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e1) {
hostLog.fatal("Unable to discover local IP address by invoking Java's InetAddress.getLocalHost() method. Usually this is because the hostname of this node fails to resolve (for example \"ping `hostname`\" would fail). VoltDB requires that the hostname of every node resolves correctly at that node as well as every other node.");
VoltDB.crashVoltDB();
}
String localMetadata = addr.getHostAddress();
localMetadata += ":" + Integer.valueOf(config.m_port);
localMetadata += ":" + Integer.valueOf(adminPort);
localMetadata += ":" + Integer.valueOf(httpPort); // json
// possibly atomic swap from null to realz
m_localMetadata = localMetadata;
// Prepare the network socket manager for work
m_network = new VoltNetwork();
final HashSet<Integer> downHosts = new HashSet<Integer>();
boolean isRejoin = config.m_rejoinToHostAndPort != null;
if (!isRejoin) {
// Create the intra-cluster mesh
InetAddress leader = null;
try {
leader = InetAddress.getByName(m_catalogContext.cluster.getLeaderaddress());
} catch (UnknownHostException ex) {
hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_CouldNotRetrieveLeaderAddress.name(), new Object[] { m_catalogContext.cluster.getLeaderaddress() }, null);
VoltDB.crashVoltDB();
}
// ensure at least one host (catalog compiler should check this too
if (m_catalogContext.numberOfNodes <= 0) {
hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_InvalidHostCount.name(), new Object[] { m_catalogContext.numberOfNodes }, null);
VoltDB.crashVoltDB();
}
hostLog.l7dlog( Level.TRACE, LogKeys.host_VoltDB_CreatingVoltDB.name(), new Object[] { m_catalogContext.numberOfNodes, leader }, null);
hostLog.info(String.format("Beginning inter-node communication on port %d.", config.m_internalPort));
m_messenger = new HostMessenger(m_network, leader, m_catalogContext.numberOfNodes, m_catalogContext.catalogCRC, depCRC, hostLog);
Object retval[] = m_messenger.waitForGroupJoin();
m_instanceId = new Object[] { retval[0], retval[1] };
}
else {
downHosts.addAll(initializeForRejoin(config, m_catalogContext.catalogCRC, depCRC));
/**
* Whatever hosts were reported as being down on rejoin should
* be reported to the fault manager so that the fault can be distributed.
* The execution sites were informed on construction so they don't have
* to go through the agreement process.
*/
for (Integer downHost : downHosts) {
m_faultManager.reportFault(new NodeFailureFault( downHost, "UNKNOWN"));
}
try {
m_faultHandler.m_waitForFaultReported.acquire(downHosts.size());
} catch (InterruptedException e) {
VoltDB.crashVoltDB();
}
ExecutionSite.recoveringSiteCount.set(
m_catalogContext.siteTracker.getLiveExecutionSitesForHost(m_messenger.getHostId()).size());
}
m_catalogContext.m_transactionId = m_messenger.getDiscoveredCatalogTxnId();
assert(m_messenger.getDiscoveredCatalogTxnId() != 0);
// Use the host messenger's hostId.
int myHostId = m_messenger.getHostId();
// make sure the local entry for metadata is current
// it's possible it could get overwritten in a rejoin scenario
m_clusterMetadata.put(myHostId, m_localMetadata);
// Let the Export system read its configuration from the catalog.
try {
ExportManager.initialize(myHostId, m_catalogContext, isRejoin);
} catch (ExportManager.SetupException e) {
hostLog.l7dlog(Level.FATAL, LogKeys.host_VoltDB_ExportInitFailure.name(), e);
System.exit(-1);
}
// set up site structure
m_localSites = Collections.synchronizedMap(new HashMap<Integer, ExecutionSite>());
m_siteThreads = Collections.synchronizedMap(new HashMap<Integer, Thread>());
m_runners = new ArrayList<ExecutionSiteRunner>();
if (config.m_backend.isIPC) {
int eeCount = 0;
for (Site site : m_catalogContext.siteTracker.getUpSites()) {
if (site.getIsexec() &&
myHostId == Integer.parseInt(site.getHost().getTypeName())) {
eeCount++;
}
}
if (config.m_ipcPorts.size() != eeCount) {
hostLog.fatal("Specified an IPC backend but only supplied " + config.m_ipcPorts.size() +
" backend ports when " + eeCount + " are required");
System.exit(-1);
}
}
/*
* Create execution sites runners (and threads) for all exec sites except the first one.
* This allows the sites to be set up in the thread that will end up running them.
* Cache the first Site from the catalog and only do the setup once the other threads have been started.
*/
Site siteForThisThread = null;
m_currentThreadSite = null;
for (Site site : m_catalogContext.siteTracker.getUpSites()) {
int sitesHostId = Integer.parseInt(site.getHost().getTypeName());
int siteId = Integer.parseInt(site.getTypeName());
// start a local site
if (sitesHostId == myHostId) {
log.l7dlog( Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingLocalSite.name(), new Object[] { siteId }, null);
m_messenger.createLocalSite(siteId);
if (site.getIsexec()) {
if (siteForThisThread == null) {
siteForThisThread = site;
} else {
ExecutionSiteRunner runner =
new ExecutionSiteRunner(
siteId,
m_catalogContext,
serializedCatalog,
m_recovering,
downHosts);
m_runners.add(runner);
Thread runnerThread = new Thread(runner, "Site " + siteId);
runnerThread.start();
log.l7dlog(Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingThreadForSite.name(), new Object[] { siteId }, null);
m_siteThreads.put(siteId, runnerThread);
}
}
}
}
/*
* Now that the runners have been started and are doing setup of the other sites in parallel
* this thread can set up its own execution site.
*/
int siteId = Integer.parseInt(siteForThisThread.getTypeName());
ExecutionSite siteObj =
new ExecutionSite(VoltDB.instance(),
VoltDB.instance().getMessenger().createMailbox(
siteId,
VoltDB.DTXN_MAILBOX_ID),
siteId,
serializedCatalog,
null,
m_recovering,
downHosts,
m_catalogContext.m_transactionId);
m_localSites.put(Integer.parseInt(siteForThisThread.getTypeName()), siteObj);
m_currentThreadSite = siteObj;
/*
* Stop and wait for the runners to finish setting up and then put
* the constructed ExecutionSites in the local site map.
*/
for (ExecutionSiteRunner runner : m_runners) {
synchronized (runner) {
if (!runner.m_isSiteCreated) {
try {
runner.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
m_localSites.put(runner.m_siteId, runner.m_siteObj);
}
}
// set up profiling and tracing
// hack to prevent profiling on multiple machines
if (m_config.m_profilingLevel != ProcedureProfiler.Level.DISABLED) {
if (m_localSites.size() == 1) {
hostLog.l7dlog(Level.INFO,
LogKeys.host_VoltDB_ProfileLevelIs.name(),
new Object[] { m_config.m_profilingLevel },
null);
ProcedureProfiler.profilingLevel = m_config.m_profilingLevel;
}
else {
hostLog.l7dlog(
Level.INFO,
LogKeys.host_VoltDB_InternalProfilingDisabledOnMultipartitionHosts.name(),
null);
}
}
// if a workload tracer is specified, start her up!
ProcedureProfiler.initializeWorkloadTrace(catalog);
// Create the client interfaces and associated dtxn initiators
int portOffset = 0;
for (Site site : m_catalogContext.siteTracker.getUpSites()) {
int sitesHostId = Integer.parseInt(site.getHost().getTypeName());
int currSiteId = Integer.parseInt(site.getTypeName());
// create CI for each local non-EE site
if ((sitesHostId == myHostId) && (site.getIsexec() == false)) {
ClientInterface ci =
ClientInterface.create(m_network,
m_messenger,
m_catalogContext,
m_catalogContext.numberOfNodes,
currSiteId,
site.getInitiatorid(),
config.m_port + portOffset,
adminPort + portOffset,
m_config.m_timestampTestingSalt);
portOffset++;
m_clientInterfaces.add(ci);
try {
ci.startAcceptingConnections();
} catch (IOException e) {
hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_ErrorStartAcceptingConnections.name(), e);
VoltDB.crashVoltDB();
}
}
}
m_partitionCountStats = new PartitionCountStats("Partition Count Stats",
m_catalogContext.numberOfPartitions);
m_statsAgent.registerStatsSource(SysProcSelector.PARTITIONCOUNT,
0, m_partitionCountStats);
m_ioStats = new IOStats("IO Stats");
m_statsAgent.registerStatsSource(SysProcSelector.IOSTATS,
0, m_ioStats);
m_memoryStats = new MemoryStats("Memory Stats");
m_statsAgent.registerStatsSource(SysProcSelector.MEMORY,
0, m_memoryStats);
// Create the statistics manager and register it to JMX registry
m_statsManager = null;
try {
final Class<?> statsManagerClass =
Class.forName("org.voltdb.management.JMXStatsManager");
m_statsManager = (StatsManager)statsManagerClass.newInstance();
m_statsManager.initialize(new ArrayList<Integer>(m_localSites.keySet()));
} catch (Exception e) {}
// Start running the socket handlers
hostLog.l7dlog(Level.INFO,
LogKeys.host_VoltDB_StartingNetwork.name(),
new Object[] { m_network.threadPoolSize },
null);
m_network.start();
// tell other booting nodes that this node is ready. Primary purpose is to publish a hostname
m_messenger.sendReadyMessage();
// only needs to be done if this is an initial cluster startup, not a rejoin
if (config.m_rejoinToHostAndPort == null) {
// wait for all nodes to be ready
m_messenger.waitForAllHostsToBeReady();
}
fivems = new PeriodicWorkTimerThread(m_clientInterfaces,
m_statsManager);
fivems.start();
// print out a bunch of useful system info
logDebuggingInfo(adminPort, httpPort, httpPortExtraLogMessage, jsonEnabled);
int k = m_catalogContext.numberOfExecSites / m_catalogContext.numberOfPartitions;
if (k == 1) {
hostLog.warn("Running without redundancy (k=0) is not recommended for production use.");
}
assert(m_clientInterfaces.size() > 0);
ClientInterface ci = m_clientInterfaces.get(0);
TransactionInitiator initiator = ci.getInitiator();
// TODO: disable replay until the UI is in place
boolean replay = false;
if (!isRejoin && replay) {
// Load command log reader
LogReader reader = null;
try {
String logpath = m_catalogContext.cluster.getLogconfig().get("log").getLogpath();
File path = new File(logpath);
Class<?> readerClass = loadProClass("org.voltdb.utils.LogReaderImpl",
null, true);
if (readerClass != null) {
Constructor<?> constructor = readerClass.getConstructor(File.class);
reader = (LogReader) constructor.newInstance(path);
}
} catch (InvocationTargetException e) {
hostLog.info("Unable to instantiate command log reader: " +
e.getTargetException().getMessage());
} catch (Exception e) {
hostLog.fatal("Unable to instantiate command log reader", e);
VoltDB.crashVoltDB();
}
// Load command log reinitiator
try {
Class<?> replayClass = loadProClass("org.voltdb.CommandLogReinitiatorImpl",
"Command log replay", false);
if (replayClass != null) {
Constructor<?> constructor =
replayClass.getConstructor(LogReader.class,
long.class,
TransactionInitiator.class,
CatalogContext.class);
if (reader != null && !reader.isEmpty()) {
m_commandLogReplay =
(CommandLogReinitiator) constructor.newInstance(reader,
0,
initiator,
m_catalogContext);
} else {
hostLog.info("No command log to replay");
}
}
} catch (Exception e) {
hostLog.fatal("Unable to instantiate command log reinitiator", e);
VoltDB.crashVoltDB();
}
}
m_restoreAgent = new RestoreAgent(m_catalogContext, initiator,
m_commandLogReplay);
}
}
|
diff --git a/bbb-android/src/org/sipdroid/media/RtpStreamSender.java b/bbb-android/src/org/sipdroid/media/RtpStreamSender.java
index ef3e7aa..a7d7d72 100644
--- a/bbb-android/src/org/sipdroid/media/RtpStreamSender.java
+++ b/bbb-android/src/org/sipdroid/media/RtpStreamSender.java
@@ -1,522 +1,524 @@
/*
* Copyright (C) 2009 The Sipdroid Open Source Project
* Copyright (C) 2005 Luca Veltri - University of Parma - Italy
*
* This file is part of Sipdroid (http://www.sipdroid.org)
*
* Sipdroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.sipdroid.media;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Random;
import org.sipdroid.net.RtpPacket;
import org.sipdroid.net.RtpSocket;
import org.sipdroid.net.SipdroidSocket;
import org.sipdroid.sipua.UserAgent;
import org.sipdroid.sipua.ui.Receiver;
import org.sipdroid.sipua.ui.Settings;
import org.sipdroid.sipua.ui.Sipdroid;
import org.sipdroid.codecs.Codecs;
import org.sipdroid.codecs.G711;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.SystemClock;
import android.preference.PreferenceManager;
/**
* RtpStreamSender is a generic stream sender. It takes an InputStream and sends
* it through RTP.
*/
public class RtpStreamSender extends Thread {
/** Whether working in debug mode. */
public static boolean DEBUG = true;
/** The RtpSocket */
RtpSocket rtp_socket = null;
/** Payload type */
Codecs.Map p_type;
/** Number of frame per second */
int frame_rate;
/** Number of bytes per frame */
int frame_size;
/**
* Whether it works synchronously with a local clock, or it it acts as slave
* of the InputStream
*/
boolean do_sync = true;
/**
* Synchronization correction value, in milliseconds. It accellarates the
* sending rate respect to the nominal value, in order to compensate program
* latencies.
*/
int sync_adj = 0;
/** Whether it is running */
boolean running = false;
boolean muted = false;
//DTMF change
String dtmf = "";
int dtmf_payload_type = 101;
private static HashMap<Character, Byte> rtpEventMap = new HashMap<Character,Byte>(){{
put('0',(byte)0);
put('1',(byte)1);
put('2',(byte)2);
put('3',(byte)3);
put('4',(byte)4);
put('5',(byte)5);
put('6',(byte)6);
put('7',(byte)7);
put('8',(byte)8);
put('9',(byte)9);
put('*',(byte)10);
put('#',(byte)11);
put('A',(byte)12);
put('B',(byte)13);
put('C',(byte)14);
put('D',(byte)15);
}};
//DTMF change
/**
* Constructs a RtpStreamSender.
*
* @param input_stream
* the stream to be sent
* @param do_sync
* whether time synchronization must be performed by the
* RtpStreamSender, or it is performed by the InputStream (e.g.
* the system audio input)
* @param payload_type
* the payload type
* @param frame_rate
* the frame rate, i.e. the number of frames that should be sent
* per second; it is used to calculate the nominal packet time
* and,in case of do_sync==true, the next departure time
* @param frame_size
* the size of the payload
* @param src_socket
* the socket used to send the RTP packet
* @param dest_addr
* the destination address
* @param dest_port
* the destination port
*/
public RtpStreamSender(boolean do_sync, Codecs.Map payload_type,
long frame_rate, int frame_size,
SipdroidSocket src_socket, String dest_addr,
int dest_port) {
init(do_sync, payload_type, frame_rate, frame_size,
src_socket, dest_addr, dest_port);
}
/** Inits the RtpStreamSender */
private void init(boolean do_sync, Codecs.Map payload_type,
long frame_rate, int frame_size,
SipdroidSocket src_socket, String dest_addr,
int dest_port) {
this.p_type = payload_type;
this.frame_rate = (int)frame_rate;
if (PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).getString(Settings.PREF_SERVER, "").equals(Settings.DEFAULT_SERVER))
switch (payload_type.codec.number()) {
case 0:
case 8:
this.frame_size = 1024;
break;
case 9:
this.frame_size = 960;
break;
default:
this.frame_size = frame_size;
break;
}
else
this.frame_size = frame_size;
this.do_sync = do_sync;
try {
rtp_socket = new RtpSocket(src_socket, InetAddress
.getByName(dest_addr), dest_port);
} catch (Exception e) {
if (!Sipdroid.release) e.printStackTrace();
}
}
/** Sets the synchronization adjustment time (in milliseconds). */
public void setSyncAdj(int millisecs) {
sync_adj = millisecs;
}
/** Whether is running */
public boolean isRunning() {
return running;
}
public boolean mute() {
return muted = !muted;
}
public static int delay = 0;
public static boolean changed;
/** Stops running */
public void halt() {
running = false;
}
Random random;
double smin = 200,s;
int nearend;
void calc(short[] lin,int off,int len) {
int i,j;
double sm = 30000,r;
for (i = 0; i < len; i += 5) {
j = lin[i+off];
s = 0.03*Math.abs(j) + 0.97*s;
if (s < sm) sm = s;
if (s > smin) nearend = 3000*mu/5;
else if (nearend > 0) nearend--;
}
r = (double)len/(100000*mu);
if (sm > 2*smin || sm < smin/2)
smin = sm*r + smin*(1-r);
}
void calc1(short[] lin,int off,int len) {
int i,j;
for (i = 0; i < len; i++) {
j = lin[i+off];
lin[i+off] = (short)(j>>2);
}
}
void calc2(short[] lin,int off,int len) {
int i,j;
for (i = 0; i < len; i++) {
j = lin[i+off];
lin[i+off] = (short)(j>>1);
}
}
void calc10(short[] lin,int off,int len) {
int i,j;
for (i = 0; i < len; i++) {
j = lin[i+off];
if (j > 16350)
lin[i+off] = 16350<<1;
else if (j < -16350)
lin[i+off] = -16350<<1;
else
lin[i+off] = (short)(j<<1);
}
}
void noise(short[] lin,int off,int len,double power) {
int i,r = (int)(power*2);
short ran;
if (r == 0) r = 1;
for (i = 0; i < len; i += 4) {
ran = (short)(random.nextInt(r*2)-r);
lin[i+off] = ran;
lin[i+off+1] = ran;
lin[i+off+2] = ran;
lin[i+off+3] = ran;
}
}
public static int m;
int mu;
/** Runs it in a new Thread. */
public void run() {
WifiManager wm = (WifiManager) Receiver.mContext.getSystemService(Context.WIFI_SERVICE);
long lastscan = 0;
if (rtp_socket == null)
return;
int seqn = 0;
long time = 0;
double p = 0;
boolean improve = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).getBoolean(Settings.PREF_IMPROVE, Settings.DEFAULT_IMPROVE);
boolean selectWifi = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).getBoolean(org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI);
int micgain = 0;
long last_tx_time = 0;
long next_tx_delay;
long now;
running = true;
m = 1;
int dtframesize = 4;
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
mu = p_type.codec.samp_rate()/8000;
int min = AudioRecord.getMinBufferSize(p_type.codec.samp_rate(),
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
if (min == 640) {
if (frame_size == 960) frame_size = 320;
if (frame_size == 1024) frame_size = 160;
min = 4096*3/2;
} else if (min < 4096) {
if (min <= 2048 && frame_size == 1024) frame_size /= 2;
min = 4096*3/2;
} else if (min == 4096) {
min *= 3/2;
if (frame_size == 960) frame_size = 320;
} else {
if (frame_size == 960) frame_size = 320;
if (frame_size == 1024) frame_size *= 2;
min *= 2;
}
frame_rate = p_type.codec.samp_rate()/frame_size;
long frame_period = 1000 / frame_rate;
frame_rate *= 1.5;
byte[] buffer = new byte[frame_size + 12];
RtpPacket rtp_packet = new RtpPacket(buffer, 0);
rtp_packet.setPayloadType(p_type.number);
if (DEBUG)
println("Reading blocks of " + buffer.length + " bytes");
println("Sample rate = " + p_type.codec.samp_rate());
println("Buffer size = " + min);
AudioRecord record = null;
short[] lin = new short[frame_size*(frame_rate+1)];
int num,ring = 0,pos;
random = new Random();
InputStream alerting = null;
try {
alerting = Receiver.mContext.getAssets().open("alerting");
} catch (IOException e2) {
if (!Sipdroid.release) e2.printStackTrace();
}
p_type.codec.init();
while (running) {
if (changed || record == null) {
if (record != null) {
record.stop();
record.release();
if (RtpStreamReceiver.samsung) {
AudioManager am = (AudioManager) Receiver.mContext.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
am.setMode(AudioManager.MODE_NORMAL);
}
}
changed = false;
record = new AudioRecord(MediaRecorder.AudioSource.MIC, p_type.codec.samp_rate(), AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
min);
if (record.getState() != AudioRecord.STATE_INITIALIZED) {
Receiver.engine(Receiver.mContext).rejectcall();
record = null;
break;
}
record.startRecording();
micgain = (int)(Settings.getMicGain()*10);
}
if (muted || Receiver.call_state == UserAgent.UA_STATE_HOLD) {
if (Receiver.call_state == UserAgent.UA_STATE_HOLD)
RtpStreamReceiver.restoreMode();
record.stop();
+ record.release();
+ record = null;
while (running && (muted || Receiver.call_state == UserAgent.UA_STATE_HOLD)) {
try {
sleep(1000);
} catch (InterruptedException e1) {
}
}
- record.startRecording();
+ continue;
}
//DTMF change start
if (dtmf.length() != 0) {
byte[] dtmfbuf = new byte[dtframesize + 12];
RtpPacket dt_packet = new RtpPacket(dtmfbuf, 0);
dt_packet.setPayloadType(dtmf_payload_type);
dt_packet.setPayloadLength(dtframesize);
dt_packet.setSscr(rtp_packet.getSscr());
long dttime = time;
int duration;
for (int i = 0; i < 6; i++) {
time += 160;
duration = (int)(time - dttime);
dt_packet.setSequenceNumber(seqn++);
dt_packet.setTimestamp(dttime);
dtmfbuf[12] = rtpEventMap.get(dtmf.charAt(0));
dtmfbuf[13] = (byte)0x0a;
dtmfbuf[14] = (byte)(duration >> 8);
dtmfbuf[15] = (byte)duration;
try {
rtp_socket.send(dt_packet);
sleep(20);
} catch (IOException e1) {
} catch (InterruptedException e1) {
}
}
for (int i = 0; i < 3; i++) {
duration = (int)(time - dttime);
dt_packet.setSequenceNumber(seqn);
dt_packet.setTimestamp(dttime);
dtmfbuf[12] = rtpEventMap.get(dtmf.charAt(0));
dtmfbuf[13] = (byte)0x8a;
dtmfbuf[14] = (byte)(duration >> 8);
dtmfbuf[15] = (byte)duration;
try {
rtp_socket.send(dt_packet);
} catch (IOException e1) {
}
}
time += 160; seqn++;
dtmf=dtmf.substring(1);
}
//DTMF change end
if (frame_size < 480) {
now = System.currentTimeMillis();
next_tx_delay = frame_period - (now - last_tx_time);
last_tx_time = now;
if (next_tx_delay > 0) {
try {
sleep(next_tx_delay);
} catch (InterruptedException e1) {
}
last_tx_time += next_tx_delay-sync_adj;
}
}
pos = (ring+delay*frame_rate*frame_size)%(frame_size*(frame_rate+1));
num = record.read(lin,pos,frame_size);
if (num <= 0)
continue;
if (!p_type.codec.isValid())
continue;
if (RtpStreamReceiver.speakermode == AudioManager.MODE_NORMAL) {
calc(lin,pos,num);
if (RtpStreamReceiver.nearend != 0 && RtpStreamReceiver.down_time == 0)
noise(lin,pos,num,p/2);
else if (nearend == 0)
p = 0.9*p + 0.1*s;
} else switch (micgain) {
case 1:
calc1(lin,pos,num);
break;
case 2:
calc2(lin,pos,num);
break;
case 10:
calc10(lin,pos,num);
break;
}
if (Receiver.call_state != UserAgent.UA_STATE_INCALL &&
Receiver.call_state != UserAgent.UA_STATE_OUTGOING_CALL && alerting != null) {
try {
if (alerting.available() < num/mu)
alerting.reset();
alerting.read(buffer,12,num/mu);
} catch (IOException e) {
if (!Sipdroid.release) e.printStackTrace();
}
if (p_type.codec.number() != 8) {
G711.alaw2linear(buffer, lin, num, mu);
num = p_type.codec.encode(lin, 0, buffer, num);
}
} else {
num = p_type.codec.encode(lin, ring%(frame_size*(frame_rate+1)), buffer, num);
}
ring += frame_size;
rtp_packet.setSequenceNumber(seqn++);
rtp_packet.setTimestamp(time);
rtp_packet.setPayloadLength(num);
try {
rtp_socket.send(rtp_packet);
if (m == 2)
rtp_socket.send(rtp_packet);
} catch (IOException e) {
}
if (p_type.codec.number() == 9)
time += frame_size/2;
else
time += frame_size;
if (RtpStreamReceiver.good != 0 &&
RtpStreamReceiver.loss/RtpStreamReceiver.good > 0.01) {
if (selectWifi && Receiver.on_wlan && SystemClock.elapsedRealtime()-lastscan > 10000) {
wm.startScan();
lastscan = SystemClock.elapsedRealtime();
}
if (improve && delay == 0 &&
(p_type.codec.number() == 0 || p_type.codec.number() == 8 || p_type.codec.number() == 9))
m = 2;
else
m = 1;
} else
m = 1;
}
if (Integer.parseInt(Build.VERSION.SDK) < 5)
while (RtpStreamReceiver.getMode() == AudioManager.MODE_IN_CALL)
try {
sleep(1000);
} catch (InterruptedException e) {
}
if (record != null) {
record.stop();
record.release();
}
m = 0;
p_type.codec.close();
rtp_socket.close();
rtp_socket = null;
if (DEBUG)
println("rtp sender terminated");
}
/** Debug output */
private static void println(String str) {
if (!Sipdroid.release) System.out.println("RtpStreamSender: " + str);
}
/** Set RTP payload type of outband DTMF packets. **/
public void setDTMFpayloadType(int payload_type){
dtmf_payload_type = payload_type;
}
/** Send outband DTMF packets */
public void sendDTMF(char c) {
dtmf = dtmf+c; // will be set to 0 after sending tones
}
//DTMF change
}
| false | true | public void run() {
WifiManager wm = (WifiManager) Receiver.mContext.getSystemService(Context.WIFI_SERVICE);
long lastscan = 0;
if (rtp_socket == null)
return;
int seqn = 0;
long time = 0;
double p = 0;
boolean improve = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).getBoolean(Settings.PREF_IMPROVE, Settings.DEFAULT_IMPROVE);
boolean selectWifi = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).getBoolean(org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI);
int micgain = 0;
long last_tx_time = 0;
long next_tx_delay;
long now;
running = true;
m = 1;
int dtframesize = 4;
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
mu = p_type.codec.samp_rate()/8000;
int min = AudioRecord.getMinBufferSize(p_type.codec.samp_rate(),
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
if (min == 640) {
if (frame_size == 960) frame_size = 320;
if (frame_size == 1024) frame_size = 160;
min = 4096*3/2;
} else if (min < 4096) {
if (min <= 2048 && frame_size == 1024) frame_size /= 2;
min = 4096*3/2;
} else if (min == 4096) {
min *= 3/2;
if (frame_size == 960) frame_size = 320;
} else {
if (frame_size == 960) frame_size = 320;
if (frame_size == 1024) frame_size *= 2;
min *= 2;
}
frame_rate = p_type.codec.samp_rate()/frame_size;
long frame_period = 1000 / frame_rate;
frame_rate *= 1.5;
byte[] buffer = new byte[frame_size + 12];
RtpPacket rtp_packet = new RtpPacket(buffer, 0);
rtp_packet.setPayloadType(p_type.number);
if (DEBUG)
println("Reading blocks of " + buffer.length + " bytes");
println("Sample rate = " + p_type.codec.samp_rate());
println("Buffer size = " + min);
AudioRecord record = null;
short[] lin = new short[frame_size*(frame_rate+1)];
int num,ring = 0,pos;
random = new Random();
InputStream alerting = null;
try {
alerting = Receiver.mContext.getAssets().open("alerting");
} catch (IOException e2) {
if (!Sipdroid.release) e2.printStackTrace();
}
p_type.codec.init();
while (running) {
if (changed || record == null) {
if (record != null) {
record.stop();
record.release();
if (RtpStreamReceiver.samsung) {
AudioManager am = (AudioManager) Receiver.mContext.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
am.setMode(AudioManager.MODE_NORMAL);
}
}
changed = false;
record = new AudioRecord(MediaRecorder.AudioSource.MIC, p_type.codec.samp_rate(), AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
min);
if (record.getState() != AudioRecord.STATE_INITIALIZED) {
Receiver.engine(Receiver.mContext).rejectcall();
record = null;
break;
}
record.startRecording();
micgain = (int)(Settings.getMicGain()*10);
}
if (muted || Receiver.call_state == UserAgent.UA_STATE_HOLD) {
if (Receiver.call_state == UserAgent.UA_STATE_HOLD)
RtpStreamReceiver.restoreMode();
record.stop();
while (running && (muted || Receiver.call_state == UserAgent.UA_STATE_HOLD)) {
try {
sleep(1000);
} catch (InterruptedException e1) {
}
}
record.startRecording();
}
//DTMF change start
if (dtmf.length() != 0) {
byte[] dtmfbuf = new byte[dtframesize + 12];
RtpPacket dt_packet = new RtpPacket(dtmfbuf, 0);
dt_packet.setPayloadType(dtmf_payload_type);
dt_packet.setPayloadLength(dtframesize);
dt_packet.setSscr(rtp_packet.getSscr());
long dttime = time;
int duration;
for (int i = 0; i < 6; i++) {
time += 160;
duration = (int)(time - dttime);
dt_packet.setSequenceNumber(seqn++);
dt_packet.setTimestamp(dttime);
dtmfbuf[12] = rtpEventMap.get(dtmf.charAt(0));
dtmfbuf[13] = (byte)0x0a;
dtmfbuf[14] = (byte)(duration >> 8);
dtmfbuf[15] = (byte)duration;
try {
rtp_socket.send(dt_packet);
sleep(20);
} catch (IOException e1) {
} catch (InterruptedException e1) {
}
}
for (int i = 0; i < 3; i++) {
duration = (int)(time - dttime);
dt_packet.setSequenceNumber(seqn);
dt_packet.setTimestamp(dttime);
dtmfbuf[12] = rtpEventMap.get(dtmf.charAt(0));
dtmfbuf[13] = (byte)0x8a;
dtmfbuf[14] = (byte)(duration >> 8);
dtmfbuf[15] = (byte)duration;
try {
rtp_socket.send(dt_packet);
} catch (IOException e1) {
}
}
time += 160; seqn++;
dtmf=dtmf.substring(1);
}
//DTMF change end
if (frame_size < 480) {
now = System.currentTimeMillis();
next_tx_delay = frame_period - (now - last_tx_time);
last_tx_time = now;
if (next_tx_delay > 0) {
try {
sleep(next_tx_delay);
} catch (InterruptedException e1) {
}
last_tx_time += next_tx_delay-sync_adj;
}
}
pos = (ring+delay*frame_rate*frame_size)%(frame_size*(frame_rate+1));
num = record.read(lin,pos,frame_size);
if (num <= 0)
continue;
if (!p_type.codec.isValid())
continue;
if (RtpStreamReceiver.speakermode == AudioManager.MODE_NORMAL) {
calc(lin,pos,num);
if (RtpStreamReceiver.nearend != 0 && RtpStreamReceiver.down_time == 0)
noise(lin,pos,num,p/2);
else if (nearend == 0)
p = 0.9*p + 0.1*s;
} else switch (micgain) {
case 1:
calc1(lin,pos,num);
break;
case 2:
calc2(lin,pos,num);
break;
case 10:
calc10(lin,pos,num);
break;
}
if (Receiver.call_state != UserAgent.UA_STATE_INCALL &&
Receiver.call_state != UserAgent.UA_STATE_OUTGOING_CALL && alerting != null) {
try {
if (alerting.available() < num/mu)
alerting.reset();
alerting.read(buffer,12,num/mu);
} catch (IOException e) {
if (!Sipdroid.release) e.printStackTrace();
}
if (p_type.codec.number() != 8) {
G711.alaw2linear(buffer, lin, num, mu);
num = p_type.codec.encode(lin, 0, buffer, num);
}
} else {
num = p_type.codec.encode(lin, ring%(frame_size*(frame_rate+1)), buffer, num);
}
ring += frame_size;
rtp_packet.setSequenceNumber(seqn++);
rtp_packet.setTimestamp(time);
rtp_packet.setPayloadLength(num);
try {
rtp_socket.send(rtp_packet);
if (m == 2)
rtp_socket.send(rtp_packet);
} catch (IOException e) {
}
if (p_type.codec.number() == 9)
time += frame_size/2;
else
time += frame_size;
if (RtpStreamReceiver.good != 0 &&
RtpStreamReceiver.loss/RtpStreamReceiver.good > 0.01) {
if (selectWifi && Receiver.on_wlan && SystemClock.elapsedRealtime()-lastscan > 10000) {
wm.startScan();
lastscan = SystemClock.elapsedRealtime();
}
if (improve && delay == 0 &&
(p_type.codec.number() == 0 || p_type.codec.number() == 8 || p_type.codec.number() == 9))
m = 2;
else
m = 1;
} else
m = 1;
}
if (Integer.parseInt(Build.VERSION.SDK) < 5)
while (RtpStreamReceiver.getMode() == AudioManager.MODE_IN_CALL)
try {
sleep(1000);
} catch (InterruptedException e) {
}
if (record != null) {
record.stop();
record.release();
}
m = 0;
p_type.codec.close();
rtp_socket.close();
rtp_socket = null;
if (DEBUG)
println("rtp sender terminated");
}
| public void run() {
WifiManager wm = (WifiManager) Receiver.mContext.getSystemService(Context.WIFI_SERVICE);
long lastscan = 0;
if (rtp_socket == null)
return;
int seqn = 0;
long time = 0;
double p = 0;
boolean improve = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).getBoolean(Settings.PREF_IMPROVE, Settings.DEFAULT_IMPROVE);
boolean selectWifi = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).getBoolean(org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI);
int micgain = 0;
long last_tx_time = 0;
long next_tx_delay;
long now;
running = true;
m = 1;
int dtframesize = 4;
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
mu = p_type.codec.samp_rate()/8000;
int min = AudioRecord.getMinBufferSize(p_type.codec.samp_rate(),
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
if (min == 640) {
if (frame_size == 960) frame_size = 320;
if (frame_size == 1024) frame_size = 160;
min = 4096*3/2;
} else if (min < 4096) {
if (min <= 2048 && frame_size == 1024) frame_size /= 2;
min = 4096*3/2;
} else if (min == 4096) {
min *= 3/2;
if (frame_size == 960) frame_size = 320;
} else {
if (frame_size == 960) frame_size = 320;
if (frame_size == 1024) frame_size *= 2;
min *= 2;
}
frame_rate = p_type.codec.samp_rate()/frame_size;
long frame_period = 1000 / frame_rate;
frame_rate *= 1.5;
byte[] buffer = new byte[frame_size + 12];
RtpPacket rtp_packet = new RtpPacket(buffer, 0);
rtp_packet.setPayloadType(p_type.number);
if (DEBUG)
println("Reading blocks of " + buffer.length + " bytes");
println("Sample rate = " + p_type.codec.samp_rate());
println("Buffer size = " + min);
AudioRecord record = null;
short[] lin = new short[frame_size*(frame_rate+1)];
int num,ring = 0,pos;
random = new Random();
InputStream alerting = null;
try {
alerting = Receiver.mContext.getAssets().open("alerting");
} catch (IOException e2) {
if (!Sipdroid.release) e2.printStackTrace();
}
p_type.codec.init();
while (running) {
if (changed || record == null) {
if (record != null) {
record.stop();
record.release();
if (RtpStreamReceiver.samsung) {
AudioManager am = (AudioManager) Receiver.mContext.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
am.setMode(AudioManager.MODE_NORMAL);
}
}
changed = false;
record = new AudioRecord(MediaRecorder.AudioSource.MIC, p_type.codec.samp_rate(), AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
min);
if (record.getState() != AudioRecord.STATE_INITIALIZED) {
Receiver.engine(Receiver.mContext).rejectcall();
record = null;
break;
}
record.startRecording();
micgain = (int)(Settings.getMicGain()*10);
}
if (muted || Receiver.call_state == UserAgent.UA_STATE_HOLD) {
if (Receiver.call_state == UserAgent.UA_STATE_HOLD)
RtpStreamReceiver.restoreMode();
record.stop();
record.release();
record = null;
while (running && (muted || Receiver.call_state == UserAgent.UA_STATE_HOLD)) {
try {
sleep(1000);
} catch (InterruptedException e1) {
}
}
continue;
}
//DTMF change start
if (dtmf.length() != 0) {
byte[] dtmfbuf = new byte[dtframesize + 12];
RtpPacket dt_packet = new RtpPacket(dtmfbuf, 0);
dt_packet.setPayloadType(dtmf_payload_type);
dt_packet.setPayloadLength(dtframesize);
dt_packet.setSscr(rtp_packet.getSscr());
long dttime = time;
int duration;
for (int i = 0; i < 6; i++) {
time += 160;
duration = (int)(time - dttime);
dt_packet.setSequenceNumber(seqn++);
dt_packet.setTimestamp(dttime);
dtmfbuf[12] = rtpEventMap.get(dtmf.charAt(0));
dtmfbuf[13] = (byte)0x0a;
dtmfbuf[14] = (byte)(duration >> 8);
dtmfbuf[15] = (byte)duration;
try {
rtp_socket.send(dt_packet);
sleep(20);
} catch (IOException e1) {
} catch (InterruptedException e1) {
}
}
for (int i = 0; i < 3; i++) {
duration = (int)(time - dttime);
dt_packet.setSequenceNumber(seqn);
dt_packet.setTimestamp(dttime);
dtmfbuf[12] = rtpEventMap.get(dtmf.charAt(0));
dtmfbuf[13] = (byte)0x8a;
dtmfbuf[14] = (byte)(duration >> 8);
dtmfbuf[15] = (byte)duration;
try {
rtp_socket.send(dt_packet);
} catch (IOException e1) {
}
}
time += 160; seqn++;
dtmf=dtmf.substring(1);
}
//DTMF change end
if (frame_size < 480) {
now = System.currentTimeMillis();
next_tx_delay = frame_period - (now - last_tx_time);
last_tx_time = now;
if (next_tx_delay > 0) {
try {
sleep(next_tx_delay);
} catch (InterruptedException e1) {
}
last_tx_time += next_tx_delay-sync_adj;
}
}
pos = (ring+delay*frame_rate*frame_size)%(frame_size*(frame_rate+1));
num = record.read(lin,pos,frame_size);
if (num <= 0)
continue;
if (!p_type.codec.isValid())
continue;
if (RtpStreamReceiver.speakermode == AudioManager.MODE_NORMAL) {
calc(lin,pos,num);
if (RtpStreamReceiver.nearend != 0 && RtpStreamReceiver.down_time == 0)
noise(lin,pos,num,p/2);
else if (nearend == 0)
p = 0.9*p + 0.1*s;
} else switch (micgain) {
case 1:
calc1(lin,pos,num);
break;
case 2:
calc2(lin,pos,num);
break;
case 10:
calc10(lin,pos,num);
break;
}
if (Receiver.call_state != UserAgent.UA_STATE_INCALL &&
Receiver.call_state != UserAgent.UA_STATE_OUTGOING_CALL && alerting != null) {
try {
if (alerting.available() < num/mu)
alerting.reset();
alerting.read(buffer,12,num/mu);
} catch (IOException e) {
if (!Sipdroid.release) e.printStackTrace();
}
if (p_type.codec.number() != 8) {
G711.alaw2linear(buffer, lin, num, mu);
num = p_type.codec.encode(lin, 0, buffer, num);
}
} else {
num = p_type.codec.encode(lin, ring%(frame_size*(frame_rate+1)), buffer, num);
}
ring += frame_size;
rtp_packet.setSequenceNumber(seqn++);
rtp_packet.setTimestamp(time);
rtp_packet.setPayloadLength(num);
try {
rtp_socket.send(rtp_packet);
if (m == 2)
rtp_socket.send(rtp_packet);
} catch (IOException e) {
}
if (p_type.codec.number() == 9)
time += frame_size/2;
else
time += frame_size;
if (RtpStreamReceiver.good != 0 &&
RtpStreamReceiver.loss/RtpStreamReceiver.good > 0.01) {
if (selectWifi && Receiver.on_wlan && SystemClock.elapsedRealtime()-lastscan > 10000) {
wm.startScan();
lastscan = SystemClock.elapsedRealtime();
}
if (improve && delay == 0 &&
(p_type.codec.number() == 0 || p_type.codec.number() == 8 || p_type.codec.number() == 9))
m = 2;
else
m = 1;
} else
m = 1;
}
if (Integer.parseInt(Build.VERSION.SDK) < 5)
while (RtpStreamReceiver.getMode() == AudioManager.MODE_IN_CALL)
try {
sleep(1000);
} catch (InterruptedException e) {
}
if (record != null) {
record.stop();
record.release();
}
m = 0;
p_type.codec.close();
rtp_socket.close();
rtp_socket = null;
if (DEBUG)
println("rtp sender terminated");
}
|
diff --git a/android/TubeChaser/src/com/andybotting/tubechaser/activity/StationMap.java b/android/TubeChaser/src/com/andybotting/tubechaser/activity/StationMap.java
index 2532671..dd12fc2 100644
--- a/android/TubeChaser/src/com/andybotting/tubechaser/activity/StationMap.java
+++ b/android/TubeChaser/src/com/andybotting/tubechaser/activity/StationMap.java
@@ -1,183 +1,189 @@
/*
* Copyright 2010 Andy Botting <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2010 Google 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.andybotting.tubechaser.activity;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.andybotting.tubechaser.R;
import com.andybotting.tubechaser.objects.Station;
import com.andybotting.tubechaser.provider.TubeChaserProvider;
import com.andybotting.tubechaser.ui.BalloonItemizedOverlay;
import com.andybotting.tubechaser.utils.UIUtils;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class StationMap extends MapActivity {
public static final String EXTRA_STATION = "com.andybotting.tubechaser.extra.STATION";
private List<Overlay> mMapOverlays;
private MapController mMapController;
private MapView mMapView;
private MyLocationOverlay mMyLocationOverlay;
Station mStation;
Context mContext;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_station_map);
final Uri stationUri = getIntent().getParcelableExtra(EXTRA_STATION);
mContext = this.getBaseContext();
TubeChaserProvider provider = new TubeChaserProvider();
mStation = provider.getStation(mContext, stationUri);
((TextView) findViewById(R.id.title_text)).setText(mStation.getName());
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMapOverlays = mMapView.getOverlays();
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMapOverlays.add(mMyLocationOverlay);
mMapView.setClickable(true);
mMapView.setEnabled(true);
// Home button
findViewById(R.id.btn_title_home).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
UIUtils.goHome(StationMap.this);
}
});
// My Location button
findViewById(R.id.btn_title_myloc).setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation());
+ public void onClick(View v) {
+ GeoPoint myLoc = mMyLocationOverlay.getMyLocation();
+ if (myLoc != null) {
+ mMapView.getController().animateTo(myLoc);
+ }
+ else {
+ UIUtils.popToast(getApplicationContext(), "Unable to find your location");
+ }
}
});
displayStation(mStation);
}
public class MyItemizedOverlay extends BalloonItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> m_overlays = new ArrayList<OverlayItem>();
public MyItemizedOverlay(Drawable defaultMarker, MapView mapView) {
super(boundCenter(defaultMarker), mapView);
}
public void addOverlay(OverlayItem overlay) {
m_overlays.add(overlay);
populate();
}
@Override
protected OverlayItem createItem(int i) {
return m_overlays.get(i);
}
@Override
public int size() {
return m_overlays.size();
}
@Override
protected boolean onBalloonTap(int index) {
return true;
}
}
private void displayStation(Station mStation) {
Drawable drawable = this.getResources().getDrawable(R.drawable.map_marker);
MyItemizedOverlay itemizedOverlay = new MyItemizedOverlay(drawable, mMapView);
mMapOverlays.add(itemizedOverlay);
GeoPoint point = mStation.getGeoPoint();
String title = mStation.getName();
String snippet = mStation.getLinesString();
OverlayItem overlayitem = new OverlayItem(point, title, snippet);
itemizedOverlay.addOverlay(overlayitem);
mMapController.setZoom(17);
mMapController.setCenter(point);
}
@Override
protected void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
}
@Override
protected void onStop() {
mMyLocationOverlay.disableMyLocation();
super.onStop();
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_station_map);
final Uri stationUri = getIntent().getParcelableExtra(EXTRA_STATION);
mContext = this.getBaseContext();
TubeChaserProvider provider = new TubeChaserProvider();
mStation = provider.getStation(mContext, stationUri);
((TextView) findViewById(R.id.title_text)).setText(mStation.getName());
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMapOverlays = mMapView.getOverlays();
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMapOverlays.add(mMyLocationOverlay);
mMapView.setClickable(true);
mMapView.setEnabled(true);
// Home button
findViewById(R.id.btn_title_home).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
UIUtils.goHome(StationMap.this);
}
});
// My Location button
findViewById(R.id.btn_title_myloc).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation());
}
});
displayStation(mStation);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_station_map);
final Uri stationUri = getIntent().getParcelableExtra(EXTRA_STATION);
mContext = this.getBaseContext();
TubeChaserProvider provider = new TubeChaserProvider();
mStation = provider.getStation(mContext, stationUri);
((TextView) findViewById(R.id.title_text)).setText(mStation.getName());
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMapOverlays = mMapView.getOverlays();
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMapOverlays.add(mMyLocationOverlay);
mMapView.setClickable(true);
mMapView.setEnabled(true);
// Home button
findViewById(R.id.btn_title_home).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
UIUtils.goHome(StationMap.this);
}
});
// My Location button
findViewById(R.id.btn_title_myloc).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GeoPoint myLoc = mMyLocationOverlay.getMyLocation();
if (myLoc != null) {
mMapView.getController().animateTo(myLoc);
}
else {
UIUtils.popToast(getApplicationContext(), "Unable to find your location");
}
}
});
displayStation(mStation);
}
|
diff --git a/org.eclipse.stem.ui.populationmodels/src/org/eclipse/stem/ui/populationmodels/standard/wizards/PopulationInitializerDefinitionControl.java b/org.eclipse.stem.ui.populationmodels/src/org/eclipse/stem/ui/populationmodels/standard/wizards/PopulationInitializerDefinitionControl.java
index 2c6ec585..abbbbe6a 100644
--- a/org.eclipse.stem.ui.populationmodels/src/org/eclipse/stem/ui/populationmodels/standard/wizards/PopulationInitializerDefinitionControl.java
+++ b/org.eclipse.stem.ui.populationmodels/src/org/eclipse/stem/ui/populationmodels/standard/wizards/PopulationInitializerDefinitionControl.java
@@ -1,229 +1,229 @@
package org.eclipse.stem.ui.populationmodels.standard.wizards;
/*******************************************************************************
* Copyright (c) 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.stem.populationmodels.standard.PopulationInitializer;
import org.eclipse.stem.populationmodels.standard.PopulationModel;
import org.eclipse.stem.ui.Activator;
import org.eclipse.stem.ui.widgets.LocationPickerDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
/**
* This class represents the SWT control for defining a disease.
*/
public class PopulationInitializerDefinitionControl extends Composite {
private static PopulationInitializer[] populationInitializers = null;
private final Combo combo;
private final PopulationInitializerPropertyComposite populationInitializerPropertyComposite;
private String isoKey="";
/**
* Create the composite
*
* @param parent
* @param style
* @param projectValidator
*/
public PopulationInitializerDefinitionControl(final Composite parent, final int style,
ModifyListener projectValidator) {
super(parent, style);
final GridLayout gridLayout = new GridLayout();
gridLayout.marginWidth = 0;
gridLayout.numColumns = 2;
setLayout(gridLayout);
- final Label populationModelLabel = new Label(this, SWT.NONE);
- final GridData gd_populationModelLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
- gd_populationModelLabel.widthHint = 100;
- populationModelLabel.setLayoutData(gd_populationModelLabel);
- populationModelLabel.setText(PopulationModelWizardMessages.getString("DDC.0")); //$NON-NLS-1$
+ final Label populationInitializerLabel = new Label(this, SWT.NONE);
+ final GridData gd_populationInitializerLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
+ gd_populationInitializerLabel.widthHint = 100;
+ populationInitializerLabel.setLayoutData(gd_populationInitializerLabel);
+ populationInitializerLabel.setText(PopulationModelWizardMessages.getString("DDC.5")); //$NON-NLS-1$
combo = new Combo(this, SWT.READ_ONLY);
combo.setTextLimit(30);
final GridData gd_combo = new GridData(SWT.FILL, SWT.CENTER, true,
false);
gd_combo.widthHint = 303;
combo.setLayoutData(gd_combo);
combo.setToolTipText(PopulationModelWizardMessages.getString("DDC.1")); //$NON-NLS-1$
// Initialize the list of disease models available
combo.setItems(getPopulationInitializerNames(getPopulationInitializers()));
combo.select(0);
combo.addModifyListener(projectValidator);
populationInitializerPropertyComposite = new PopulationInitializerPropertyComposite(this,
SWT.NONE, getPopulationInitializers(), projectValidator);
final GridData gd_populationInitializerPropertyControl = new GridData(SWT.FILL,
SWT.CENTER, true, false, 2, 1);
populationInitializerPropertyComposite
.setLayoutData(gd_populationInitializerPropertyControl);
combo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
populationInitializerPropertyComposite
.displayPopulationInitializer(getPopulationInitializers()[combo
.getSelectionIndex()]);
// layout();
} // widgetSelected
});
final PopulationInitializerDefinitionControl self = this;
// Location picker
// ISO Key
final Label isoKeyLabel = new Label(this, SWT.NONE);
isoKeyLabel.setText(PopulationModelWizardMessages.getString("NPopWizISOK")); //$NON-NLS-1$
final GridData gd_isoKeyLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
isoKeyLabel.setLayoutData(gd_isoKeyLabel);
final Label isokeyValueLabel = new Label(this, SWT.NONE);
isokeyValueLabel.setText(isoKey);
final GridData gd_isoKeyLabelValue = new GridData(SWT.FILL, SWT.CENTER, true, false);
isokeyValueLabel.setLayoutData(gd_isoKeyLabelValue);
final Button locationButton = new Button(this, SWT.NONE);
locationButton.setText(PopulationModelWizardMessages.getString("NPopWizPickLoc"));
final GridData lb_isoKeyLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
locationButton.setLayoutData(lb_isoKeyLabel);
locationButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
LocationPickerDialog lpDialog = new LocationPickerDialog(PopulationInitializerDefinitionControl.this.getShell(), SWT.NONE, PopulationModelWizardMessages.getString("NPopWizPickLocTitle"), PopulationInitializerDefinitionControl.this.isoKey);
isoKey = lpDialog.open();
isokeyValueLabel.setText(isoKey);
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
} // DiseaseDefinitionControl
/**
* @return an array of the {@link DiseaseModels}s defined in the system.
*/
private PopulationInitializer[] getPopulationInitializers() {
if (populationInitializers == null) {
final IExtensionRegistry registry = Platform.getExtensionRegistry();
final IConfigurationElement[] populationInitializerConfigElements = registry
.getConfigurationElementsFor(org.eclipse.stem.populationmodels.Constants.ID_POPULATION_INITIALIZER_EXTENSION_POINT);
final List<PopulationInitializer> temp = new ArrayList<PopulationInitializer>();
populationInitializers = new PopulationInitializer[populationInitializerConfigElements.length];
for (int i = 0; i < populationInitializerConfigElements.length; i++) {
final IConfigurationElement element = populationInitializerConfigElements[i];
// Does the element specify the class of the population model?
if (element.getName().equals(org.eclipse.stem.populationmodels.Constants.POPULATION_INITIALIZER_ELEMENT)) {
// Yes
try {
temp.add((PopulationInitializer) element
.createExecutableExtension(PopulationModelWizardMessages.getString("DDC.2"))); //$NON-NLS-1$
} catch (final CoreException e) {
Activator.logError(
PopulationModelWizardMessages.getString("DDC.4"), e); //$NON-NLS-1$
}
} // if
} // for each configuration element
populationInitializers = temp.toArray(new PopulationInitializer[] {});
} // if populationModels not created
return populationInitializers;
} // getPopulationModels
/**
* @return the names of the disease models
*/
private String[] getPopulationInitializerNames(final PopulationInitializer[] populationModels) {
final String[] retValue = new String[populationInitializers.length];
for (int i = 0; i < populationInitializers.length; i++) {
String name = populationInitializers[i].getDublinCore().getTitle();
// Was a name specified?
if ((name == null) || name.equals("")) { //$NON-NLS-1$
// No
name = populationInitializers[i].getClass().getSimpleName();
} // if
retValue[i] = name;
} // for i
return retValue;
} // getPopulationModelNames
PopulationInitializer getSelectedPopulationInitializer() {
final PopulationInitializer retValue = (PopulationInitializer)EcoreUtil
.copy(getPopulationInitializers()[combo.getSelectionIndex()]);
populationInitializerPropertyComposite.populatePopulationInitializer(retValue);
retValue.setTargetISOKey(this.getIsoKey());
return retValue;
} // getSelectedPopulationModel
@Override
public void dispose() {
super.dispose();
}
@Override
protected void checkSubclass() {
// Disable the check that prevents sub-classing of SWT components
}
/**
* @return <code>true</code> if the contents of the control are valid,
* <code>false</code> otherwise.
*/
public boolean validate() {
return populationInitializerPropertyComposite.validate();
} // validate
/**
* @return the error message set by {@link #validate()}
*/
public String getErrorMessage() {
return populationInitializerPropertyComposite.getErrorMessage();
}
public String getIsoKey() {
return isoKey;
}
}
| true | true | public PopulationInitializerDefinitionControl(final Composite parent, final int style,
ModifyListener projectValidator) {
super(parent, style);
final GridLayout gridLayout = new GridLayout();
gridLayout.marginWidth = 0;
gridLayout.numColumns = 2;
setLayout(gridLayout);
final Label populationModelLabel = new Label(this, SWT.NONE);
final GridData gd_populationModelLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd_populationModelLabel.widthHint = 100;
populationModelLabel.setLayoutData(gd_populationModelLabel);
populationModelLabel.setText(PopulationModelWizardMessages.getString("DDC.0")); //$NON-NLS-1$
combo = new Combo(this, SWT.READ_ONLY);
combo.setTextLimit(30);
final GridData gd_combo = new GridData(SWT.FILL, SWT.CENTER, true,
false);
gd_combo.widthHint = 303;
combo.setLayoutData(gd_combo);
combo.setToolTipText(PopulationModelWizardMessages.getString("DDC.1")); //$NON-NLS-1$
// Initialize the list of disease models available
combo.setItems(getPopulationInitializerNames(getPopulationInitializers()));
combo.select(0);
combo.addModifyListener(projectValidator);
populationInitializerPropertyComposite = new PopulationInitializerPropertyComposite(this,
SWT.NONE, getPopulationInitializers(), projectValidator);
final GridData gd_populationInitializerPropertyControl = new GridData(SWT.FILL,
SWT.CENTER, true, false, 2, 1);
populationInitializerPropertyComposite
.setLayoutData(gd_populationInitializerPropertyControl);
combo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
populationInitializerPropertyComposite
.displayPopulationInitializer(getPopulationInitializers()[combo
.getSelectionIndex()]);
// layout();
} // widgetSelected
});
final PopulationInitializerDefinitionControl self = this;
// Location picker
// ISO Key
final Label isoKeyLabel = new Label(this, SWT.NONE);
isoKeyLabel.setText(PopulationModelWizardMessages.getString("NPopWizISOK")); //$NON-NLS-1$
final GridData gd_isoKeyLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
isoKeyLabel.setLayoutData(gd_isoKeyLabel);
final Label isokeyValueLabel = new Label(this, SWT.NONE);
isokeyValueLabel.setText(isoKey);
final GridData gd_isoKeyLabelValue = new GridData(SWT.FILL, SWT.CENTER, true, false);
isokeyValueLabel.setLayoutData(gd_isoKeyLabelValue);
final Button locationButton = new Button(this, SWT.NONE);
locationButton.setText(PopulationModelWizardMessages.getString("NPopWizPickLoc"));
final GridData lb_isoKeyLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
locationButton.setLayoutData(lb_isoKeyLabel);
locationButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
LocationPickerDialog lpDialog = new LocationPickerDialog(PopulationInitializerDefinitionControl.this.getShell(), SWT.NONE, PopulationModelWizardMessages.getString("NPopWizPickLocTitle"), PopulationInitializerDefinitionControl.this.isoKey);
isoKey = lpDialog.open();
isokeyValueLabel.setText(isoKey);
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
} // DiseaseDefinitionControl
| public PopulationInitializerDefinitionControl(final Composite parent, final int style,
ModifyListener projectValidator) {
super(parent, style);
final GridLayout gridLayout = new GridLayout();
gridLayout.marginWidth = 0;
gridLayout.numColumns = 2;
setLayout(gridLayout);
final Label populationInitializerLabel = new Label(this, SWT.NONE);
final GridData gd_populationInitializerLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd_populationInitializerLabel.widthHint = 100;
populationInitializerLabel.setLayoutData(gd_populationInitializerLabel);
populationInitializerLabel.setText(PopulationModelWizardMessages.getString("DDC.5")); //$NON-NLS-1$
combo = new Combo(this, SWT.READ_ONLY);
combo.setTextLimit(30);
final GridData gd_combo = new GridData(SWT.FILL, SWT.CENTER, true,
false);
gd_combo.widthHint = 303;
combo.setLayoutData(gd_combo);
combo.setToolTipText(PopulationModelWizardMessages.getString("DDC.1")); //$NON-NLS-1$
// Initialize the list of disease models available
combo.setItems(getPopulationInitializerNames(getPopulationInitializers()));
combo.select(0);
combo.addModifyListener(projectValidator);
populationInitializerPropertyComposite = new PopulationInitializerPropertyComposite(this,
SWT.NONE, getPopulationInitializers(), projectValidator);
final GridData gd_populationInitializerPropertyControl = new GridData(SWT.FILL,
SWT.CENTER, true, false, 2, 1);
populationInitializerPropertyComposite
.setLayoutData(gd_populationInitializerPropertyControl);
combo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
populationInitializerPropertyComposite
.displayPopulationInitializer(getPopulationInitializers()[combo
.getSelectionIndex()]);
// layout();
} // widgetSelected
});
final PopulationInitializerDefinitionControl self = this;
// Location picker
// ISO Key
final Label isoKeyLabel = new Label(this, SWT.NONE);
isoKeyLabel.setText(PopulationModelWizardMessages.getString("NPopWizISOK")); //$NON-NLS-1$
final GridData gd_isoKeyLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
isoKeyLabel.setLayoutData(gd_isoKeyLabel);
final Label isokeyValueLabel = new Label(this, SWT.NONE);
isokeyValueLabel.setText(isoKey);
final GridData gd_isoKeyLabelValue = new GridData(SWT.FILL, SWT.CENTER, true, false);
isokeyValueLabel.setLayoutData(gd_isoKeyLabelValue);
final Button locationButton = new Button(this, SWT.NONE);
locationButton.setText(PopulationModelWizardMessages.getString("NPopWizPickLoc"));
final GridData lb_isoKeyLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
locationButton.setLayoutData(lb_isoKeyLabel);
locationButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
LocationPickerDialog lpDialog = new LocationPickerDialog(PopulationInitializerDefinitionControl.this.getShell(), SWT.NONE, PopulationModelWizardMessages.getString("NPopWizPickLocTitle"), PopulationInitializerDefinitionControl.this.isoKey);
isoKey = lpDialog.open();
isokeyValueLabel.setText(isoKey);
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
} // DiseaseDefinitionControl
|
diff --git a/src/main/java/com/aes/HashPassword.java b/src/main/java/com/aes/HashPassword.java
index 818b37b..c12e115 100644
--- a/src/main/java/com/aes/HashPassword.java
+++ b/src/main/java/com/aes/HashPassword.java
@@ -1,78 +1,77 @@
package com.aes;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* User: sergey.vyatkin
* Date: 12/4/13
* Time: 9:37 AM
*/
public class HashPassword {
/**
* Password hash.
*
* @param password the password to hash.
* @param salt the salt
* @param iterations the iteration count (slowness factor)
* @param lengthInBytes the length of the hash to compute in bytes
* @param algorithm the algorithm
* @return the PBDKF2 hash of the password
*/
private static byte[] getHashPassword(final char[] password,
final byte[] salt,
final int iterations,
final int lengthInBytes,
final String algorithm)
throws NoSuchAlgorithmException, InvalidKeySpecException {
/**
* PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength)
* Constructor that takes a password, salt, iteration count,
* and to-be-derived key length for generating PBEKey of variable-key-size PBE ciphers.
*/
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, lengthInBytes);
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
return skf.generateSecret(spec).getEncoded();
}
/**
* Simple test to hash password.
*
* @param args
*/
public static void main(final String[] args) throws DecoderException, UnsupportedEncodingException {
String[] algorithms = {"PBKDF2WithHmacSHA1"};
// Generate a random salt
- SecureRandom random = new SecureRandom();
byte[] salt = new byte[24]; // SALT_LENGTH = 24
- random.nextBytes(salt);
+ new SecureRandom().nextBytes(salt);
for (String algorithm : algorithms) {
// Hash the password
try {
byte[] hash = getHashPassword("password".toCharArray(), salt, 100, 24 * 8, algorithm);
// encode hash to hexadecimal string
String hexStr = Hex.encodeHexString(hash);
System.out.println(algorithm + ":salt:" + salt + ":hash:"
+ Arrays.toString(hash) + ":hex:" + hexStr);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
}
}
| false | true | public static void main(final String[] args) throws DecoderException, UnsupportedEncodingException {
String[] algorithms = {"PBKDF2WithHmacSHA1"};
// Generate a random salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[24]; // SALT_LENGTH = 24
random.nextBytes(salt);
for (String algorithm : algorithms) {
// Hash the password
try {
byte[] hash = getHashPassword("password".toCharArray(), salt, 100, 24 * 8, algorithm);
// encode hash to hexadecimal string
String hexStr = Hex.encodeHexString(hash);
System.out.println(algorithm + ":salt:" + salt + ":hash:"
+ Arrays.toString(hash) + ":hex:" + hexStr);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
}
| public static void main(final String[] args) throws DecoderException, UnsupportedEncodingException {
String[] algorithms = {"PBKDF2WithHmacSHA1"};
// Generate a random salt
byte[] salt = new byte[24]; // SALT_LENGTH = 24
new SecureRandom().nextBytes(salt);
for (String algorithm : algorithms) {
// Hash the password
try {
byte[] hash = getHashPassword("password".toCharArray(), salt, 100, 24 * 8, algorithm);
// encode hash to hexadecimal string
String hexStr = Hex.encodeHexString(hash);
System.out.println(algorithm + ":salt:" + salt + ":hash:"
+ Arrays.toString(hash) + ":hex:" + hexStr);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
}
|
diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ReductionUtils.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ReductionUtils.java
index 0275f738..75f6402c 100644
--- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ReductionUtils.java
+++ b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ReductionUtils.java
@@ -1,210 +1,213 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.nativelibs4java.opencl.util;
import com.nativelibs4java.opencl.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.Buffer;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.nativelibs4java.util.IOUtils;
import com.nativelibs4java.util.NIOUtils;
import com.ochafik.util.listenable.Pair;
/**
*
* @author Olivier
*/
public class ReductionUtils {
static String source;
static final String sourcePath = ReductionUtils.class.getPackage().getName().replace('.', '/') + "/" + "Reduction.c";
static synchronized String getSource() throws IOException {
InputStream in = ReductionUtils.class.getClassLoader().getResourceAsStream(sourcePath);
if (in == null)
throw new FileNotFoundException(sourcePath);
return source = IOUtils.readText(in);
}
public enum Operation {
Add,
Multiply,
Min,
Max;
}
public static Pair<String, Map<String, Object>> getReductionCodeAndMacros(Operation op, OpenCLType valueType, int channels) throws IOException {
Map<String, Object> macros = new LinkedHashMap<String, Object>();
String cType = valueType.toCType() + (channels == 1 ? "" : channels);
macros.put("OPERAND_TYPE", cType);
String operation, seed;
switch (op) {
case Add:
operation = "_add_";
seed = "0";
break;
case Multiply:
operation = "_mul_";
seed = "1";
break;
case Min:
operation = "_min_";
switch (valueType) {
case Int:
seed = Integer.MAX_VALUE + "";
break;
case Long:
seed = Long.MAX_VALUE + "LL";
break;
case Short:
seed = Short.MAX_VALUE + "";
break;
case Float:
seed = "MAXFLOAT";
break;
case Double:
seed = "MAXDOUBLE";
break;
default:
throw new IllegalArgumentException("Unhandled seed type: " + valueType);
}
break;
case Max:
operation = "_max_";
switch (valueType) {
case Int:
seed = Integer.MIN_VALUE + "";
break;
case Long:
seed = Long.MIN_VALUE + "LL";
break;
case Short:
seed = Short.MIN_VALUE + "";
break;
case Float:
seed = "-MAXFLOAT";
break;
case Double:
seed = "-MAXDOUBLE";
break;
default:
throw new IllegalArgumentException("Unhandled seed type: " + valueType);
}
break;
default:
throw new IllegalArgumentException("Unhandled operation: " + op);
}
macros.put("OPERATION", operation);
macros.put("SEED", seed);
return new Pair<String, Map<String, Object>>(getSource(), macros);
}
public interface Reductor<B extends Buffer> {
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor);
public B reduce(CLQueue queue, CLBuffer<B> input, long inputLength, int maxReductionSize, CLEvent... eventsToWaitFor);
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, CLBuffer<B> output, int maxReductionSize, CLEvent... eventsToWaitFor);
}
/*public interface WeightedReductor<B extends Buffer, W extends Buffer> {
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, CLBuffer<W> weights, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor);
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, CLBuffer<W> weights, long inputLength, CLBuffer<B> output, int maxReductionSize, CLEvent... eventsToWaitFor);
}*/
static int getNextPowerOfTwo(int i) {
int shifted = 0;
boolean lost = false;
for (;;) {
int next = i >> 1;
if (next == 0) {
if (lost)
return 1 << (shifted + 1);
else
return 1 << shifted;
}
lost = lost || (next << 1 != i);
shifted++;
i = next;
}
}
public static <B extends Buffer> Reductor<B> createReductor(final CLContext context, Operation op, OpenCLType valueType, final int valueChannels) throws CLBuildException {
try {
Pair<String, Map<String, Object>> codeAndMacros = getReductionCodeAndMacros(op, valueType, valueChannels);
CLProgram program = context.createProgram(codeAndMacros.getFirst());
program.defineMacros(codeAndMacros.getValue());
program.build();
CLKernel[] kernels = program.createKernels();
if (kernels.length != 1)
throw new RuntimeException("Expected 1 kernel, found : " + kernels.length);
final CLKernel kernel = kernels[0];
return new Reductor<B>() {
@SuppressWarnings("unchecked")
@Override
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor) {
Pair<CLBuffer<B>, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, (Class<B>)output.getClass(), maxReductionSize, eventsToWaitFor);
return outAndEvts.getFirst().read(queue, 0, valueChannels, output, false, outAndEvts.getSecond());
}
@Override
public B reduce(CLQueue queue, CLBuffer<B> input, long inputLength, int maxReductionSize, CLEvent... eventsToWaitFor) {
B output = NIOUtils.directBuffer((int)inputLength, context.getByteOrder(), input.typedBufferClass());
CLEvent evt = reduce(queue, input, inputLength, output, maxReductionSize, eventsToWaitFor);
//queue.finish();
//TODO
evt.waitFor();
return output;
}
@Override
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, CLBuffer<B> output, int maxReductionSize, CLEvent... eventsToWaitFor) {
Pair<CLBuffer<B>, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, output.typedBufferClass(), maxReductionSize, eventsToWaitFor);
return outAndEvts.getFirst().copyTo(queue, 0, valueChannels, output, 0, outAndEvts.getSecond());
}
@SuppressWarnings("unchecked")
public Pair<CLBuffer<B>, CLEvent[]> reduceHelper(CLQueue queue, CLBuffer<B> input, int inputLength, Class<B> outputClass, int maxReductionSize, CLEvent... eventsToWaitFor) {
+ if (inputLength == 1) {
+ return new Pair<CLBuffer<B>, CLEvent[]>(input, new CLEvent[0]);
+ }
CLBuffer<?>[] tempBuffers = new CLBuffer<?>[2];
int depth = 0;
CLBuffer<B> currentOutput = null;
CLEvent[] eventsArr = new CLEvent[1];
int[] blockCountArr = new int[1];
int maxWIS = (int)queue.getDevice().getMaxWorkItemSizes()[0];
while (inputLength > 1) {
int blocksInCurrentDepth = inputLength / maxReductionSize;
if (inputLength > blocksInCurrentDepth * maxReductionSize)
blocksInCurrentDepth++;
int iOutput = depth & 1;
CLBuffer<? extends Buffer> currentInput = depth == 0 ? input : tempBuffers[iOutput ^ 1];
currentOutput = (CLBuffer<B>)tempBuffers[iOutput];
if (currentOutput == null)
currentOutput = (CLBuffer<B>)(tempBuffers[iOutput] = context.createBuffer(CLMem.Usage.InputOutput, blocksInCurrentDepth * valueChannels, outputClass));
synchronized (kernel) {
kernel.setArgs(currentInput, (long)blocksInCurrentDepth, (long)inputLength, (long)maxReductionSize, currentOutput);
int workgroupSize = blocksInCurrentDepth;
if (workgroupSize == 1)
workgroupSize = 2;
blockCountArr[0] = workgroupSize;
eventsArr[0] = kernel.enqueueNDRange(queue, blockCountArr, null, eventsToWaitFor);
}
eventsToWaitFor = eventsArr;
inputLength = blocksInCurrentDepth;
depth++;
}
return new Pair<CLBuffer<B>, CLEvent[]>(currentOutput, eventsToWaitFor);
}
};
} catch (IOException ex) {
Logger.getLogger(ReductionUtils.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException("Failed to create a " + op + " reductor for type " + valueType + valueChannels, ex);
}
}
}
| true | true | public static <B extends Buffer> Reductor<B> createReductor(final CLContext context, Operation op, OpenCLType valueType, final int valueChannels) throws CLBuildException {
try {
Pair<String, Map<String, Object>> codeAndMacros = getReductionCodeAndMacros(op, valueType, valueChannels);
CLProgram program = context.createProgram(codeAndMacros.getFirst());
program.defineMacros(codeAndMacros.getValue());
program.build();
CLKernel[] kernels = program.createKernels();
if (kernels.length != 1)
throw new RuntimeException("Expected 1 kernel, found : " + kernels.length);
final CLKernel kernel = kernels[0];
return new Reductor<B>() {
@SuppressWarnings("unchecked")
@Override
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor) {
Pair<CLBuffer<B>, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, (Class<B>)output.getClass(), maxReductionSize, eventsToWaitFor);
return outAndEvts.getFirst().read(queue, 0, valueChannels, output, false, outAndEvts.getSecond());
}
@Override
public B reduce(CLQueue queue, CLBuffer<B> input, long inputLength, int maxReductionSize, CLEvent... eventsToWaitFor) {
B output = NIOUtils.directBuffer((int)inputLength, context.getByteOrder(), input.typedBufferClass());
CLEvent evt = reduce(queue, input, inputLength, output, maxReductionSize, eventsToWaitFor);
//queue.finish();
//TODO
evt.waitFor();
return output;
}
@Override
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, CLBuffer<B> output, int maxReductionSize, CLEvent... eventsToWaitFor) {
Pair<CLBuffer<B>, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, output.typedBufferClass(), maxReductionSize, eventsToWaitFor);
return outAndEvts.getFirst().copyTo(queue, 0, valueChannels, output, 0, outAndEvts.getSecond());
}
@SuppressWarnings("unchecked")
public Pair<CLBuffer<B>, CLEvent[]> reduceHelper(CLQueue queue, CLBuffer<B> input, int inputLength, Class<B> outputClass, int maxReductionSize, CLEvent... eventsToWaitFor) {
CLBuffer<?>[] tempBuffers = new CLBuffer<?>[2];
int depth = 0;
CLBuffer<B> currentOutput = null;
CLEvent[] eventsArr = new CLEvent[1];
int[] blockCountArr = new int[1];
int maxWIS = (int)queue.getDevice().getMaxWorkItemSizes()[0];
while (inputLength > 1) {
int blocksInCurrentDepth = inputLength / maxReductionSize;
if (inputLength > blocksInCurrentDepth * maxReductionSize)
blocksInCurrentDepth++;
int iOutput = depth & 1;
CLBuffer<? extends Buffer> currentInput = depth == 0 ? input : tempBuffers[iOutput ^ 1];
currentOutput = (CLBuffer<B>)tempBuffers[iOutput];
if (currentOutput == null)
currentOutput = (CLBuffer<B>)(tempBuffers[iOutput] = context.createBuffer(CLMem.Usage.InputOutput, blocksInCurrentDepth * valueChannels, outputClass));
synchronized (kernel) {
kernel.setArgs(currentInput, (long)blocksInCurrentDepth, (long)inputLength, (long)maxReductionSize, currentOutput);
int workgroupSize = blocksInCurrentDepth;
if (workgroupSize == 1)
workgroupSize = 2;
blockCountArr[0] = workgroupSize;
eventsArr[0] = kernel.enqueueNDRange(queue, blockCountArr, null, eventsToWaitFor);
}
eventsToWaitFor = eventsArr;
inputLength = blocksInCurrentDepth;
depth++;
}
return new Pair<CLBuffer<B>, CLEvent[]>(currentOutput, eventsToWaitFor);
}
};
} catch (IOException ex) {
Logger.getLogger(ReductionUtils.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException("Failed to create a " + op + " reductor for type " + valueType + valueChannels, ex);
}
}
| public static <B extends Buffer> Reductor<B> createReductor(final CLContext context, Operation op, OpenCLType valueType, final int valueChannels) throws CLBuildException {
try {
Pair<String, Map<String, Object>> codeAndMacros = getReductionCodeAndMacros(op, valueType, valueChannels);
CLProgram program = context.createProgram(codeAndMacros.getFirst());
program.defineMacros(codeAndMacros.getValue());
program.build();
CLKernel[] kernels = program.createKernels();
if (kernels.length != 1)
throw new RuntimeException("Expected 1 kernel, found : " + kernels.length);
final CLKernel kernel = kernels[0];
return new Reductor<B>() {
@SuppressWarnings("unchecked")
@Override
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor) {
Pair<CLBuffer<B>, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, (Class<B>)output.getClass(), maxReductionSize, eventsToWaitFor);
return outAndEvts.getFirst().read(queue, 0, valueChannels, output, false, outAndEvts.getSecond());
}
@Override
public B reduce(CLQueue queue, CLBuffer<B> input, long inputLength, int maxReductionSize, CLEvent... eventsToWaitFor) {
B output = NIOUtils.directBuffer((int)inputLength, context.getByteOrder(), input.typedBufferClass());
CLEvent evt = reduce(queue, input, inputLength, output, maxReductionSize, eventsToWaitFor);
//queue.finish();
//TODO
evt.waitFor();
return output;
}
@Override
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, CLBuffer<B> output, int maxReductionSize, CLEvent... eventsToWaitFor) {
Pair<CLBuffer<B>, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, output.typedBufferClass(), maxReductionSize, eventsToWaitFor);
return outAndEvts.getFirst().copyTo(queue, 0, valueChannels, output, 0, outAndEvts.getSecond());
}
@SuppressWarnings("unchecked")
public Pair<CLBuffer<B>, CLEvent[]> reduceHelper(CLQueue queue, CLBuffer<B> input, int inputLength, Class<B> outputClass, int maxReductionSize, CLEvent... eventsToWaitFor) {
if (inputLength == 1) {
return new Pair<CLBuffer<B>, CLEvent[]>(input, new CLEvent[0]);
}
CLBuffer<?>[] tempBuffers = new CLBuffer<?>[2];
int depth = 0;
CLBuffer<B> currentOutput = null;
CLEvent[] eventsArr = new CLEvent[1];
int[] blockCountArr = new int[1];
int maxWIS = (int)queue.getDevice().getMaxWorkItemSizes()[0];
while (inputLength > 1) {
int blocksInCurrentDepth = inputLength / maxReductionSize;
if (inputLength > blocksInCurrentDepth * maxReductionSize)
blocksInCurrentDepth++;
int iOutput = depth & 1;
CLBuffer<? extends Buffer> currentInput = depth == 0 ? input : tempBuffers[iOutput ^ 1];
currentOutput = (CLBuffer<B>)tempBuffers[iOutput];
if (currentOutput == null)
currentOutput = (CLBuffer<B>)(tempBuffers[iOutput] = context.createBuffer(CLMem.Usage.InputOutput, blocksInCurrentDepth * valueChannels, outputClass));
synchronized (kernel) {
kernel.setArgs(currentInput, (long)blocksInCurrentDepth, (long)inputLength, (long)maxReductionSize, currentOutput);
int workgroupSize = blocksInCurrentDepth;
if (workgroupSize == 1)
workgroupSize = 2;
blockCountArr[0] = workgroupSize;
eventsArr[0] = kernel.enqueueNDRange(queue, blockCountArr, null, eventsToWaitFor);
}
eventsToWaitFor = eventsArr;
inputLength = blocksInCurrentDepth;
depth++;
}
return new Pair<CLBuffer<B>, CLEvent[]>(currentOutput, eventsToWaitFor);
}
};
} catch (IOException ex) {
Logger.getLogger(ReductionUtils.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException("Failed to create a " + op + " reductor for type " + valueType + valueChannels, ex);
}
}
|
diff --git a/components/bio-formats/src/loci/formats/tiff/TiffParser.java b/components/bio-formats/src/loci/formats/tiff/TiffParser.java
index f8acdb9fc..a3653bc25 100644
--- a/components/bio-formats/src/loci/formats/tiff/TiffParser.java
+++ b/components/bio-formats/src/loci/formats/tiff/TiffParser.java
@@ -1,909 +1,908 @@
//
// TiffParser.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.tiff;
import java.io.IOException;
import loci.common.DataTools;
import loci.common.LogTools;
import loci.common.RandomAccessInputStream;
import loci.common.Region;
import loci.formats.FormatException;
import loci.formats.codec.BitBuffer;
import loci.formats.codec.CodecOptions;
/**
* Parses TIFF data from an input source.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/tiff/TiffParser.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/tiff/TiffParser.java">SVN</a></dd></dl>
*
* @author Curtis Rueden ctrueden at wisc.edu
* @author Eric Kjellman egkjellman at wisc.edu
* @author Melissa Linkert linkert at wisc.edu
* @author Chris Allan callan at blackcat.ca
*/
public class TiffParser {
// -- Fields --
/** Input source from which to parse TIFF data. */
protected RandomAccessInputStream in;
/** Cached tile buffer to avoid re-allocations when reading tiles. */
private byte[] cachedTileBuffer;
// -- Constructors --
/** Constructs a new TIFF parser from the given input source. */
public TiffParser(RandomAccessInputStream in) {
this.in = in;
}
// -- TiffParser methods --
/** Gets the stream from which TIFF data is being parsed. */
public RandomAccessInputStream getStream() {
return in;
}
/** Tests this stream to see if it represents a TIFF file. */
public boolean isValidHeader() {
try {
return checkHeader() != null;
}
catch (IOException e) {
return false;
}
}
/**
* Checks the TIFF header.
*
* @return true if little-endian,
* false if big-endian,
* or null if not a TIFF.
*/
public Boolean checkHeader() throws IOException {
if (in.length() < 4) return null;
// byte order must be II or MM
in.seek(0);
int endianOne = in.read();
int endianTwo = in.read();
boolean littleEndian = endianOne == TiffConstants.LITTLE &&
endianTwo == TiffConstants.LITTLE; // II
boolean bigEndian = endianOne == TiffConstants.BIG &&
endianTwo == TiffConstants.BIG; // MM
if (!littleEndian && !bigEndian) return null;
// check magic number (42)
in.order(littleEndian);
short magic = in.readShort();
if (magic != TiffConstants.MAGIC_NUMBER &&
magic != TiffConstants.BIG_TIFF_MAGIC_NUMBER)
{
return null;
}
return new Boolean(littleEndian);
}
// -- TiffParser methods - IFD parsing --
/**
* Gets all IFDs within the TIFF file, or null
* if the input source is not a valid TIFF file.
*/
public IFDList getIFDs() throws IOException {
return getIFDs(false);
}
/**
* Gets all IFDs within the TIFF file, or null
* if the input source is not a valid TIFF file.
* If 'skipThumbnails' is set to true, thumbnail IFDs will not be returned.
*/
public IFDList getIFDs(boolean skipThumbnails) throws IOException {
// check TIFF header
Boolean result = checkHeader();
if (result == null) return null;
in.seek(2);
boolean bigTiff = in.readShort() == TiffConstants.BIG_TIFF_MAGIC_NUMBER;
long offset = getFirstOffset(bigTiff);
// compute maximum possible number of IFDs, for loop safety
// each IFD must have at least one directory entry, which means that
// each IFD must be at least 2 + 12 + 4 = 18 bytes in length
long ifdMax = (in.length() - 8) / (bigTiff ? 22 : 18);
// read in IFDs
IFDList ifds = new IFDList();
for (long ifdNum=0; ifdNum<ifdMax; ifdNum++) {
IFD ifd = getIFD(ifdNum, offset, bigTiff);
if (ifd == null || ifd.size() <= 2) break;
Number subfile = (Number) ifd.getIFDValue(IFD.NEW_SUBFILE_TYPE);
int subfileType = subfile == null ? 0 : subfile.intValue();
if (!skipThumbnails || subfileType == 0) {
ifds.add(ifd);
}
else ifd = null;
offset = getNextOffset(bigTiff, offset);
if (offset <= 0 || offset >= in.length()) {
if (offset != 0) {
LogTools.debug("getIFDs: invalid IFD offset: " + offset);
}
break;
}
}
return ifds;
}
/**
* Gets the first IFD within the TIFF file, or null
* if the input source is not a valid TIFF file.
*/
public IFD getFirstIFD() throws IOException {
// check TIFF header
Boolean result = checkHeader();
if (result == null) return null;
in.seek(2);
boolean bigTiff = in.readShort() == TiffConstants.BIG_TIFF_MAGIC_NUMBER;
long offset = getFirstOffset(bigTiff);
IFD ifd = getIFD(0, offset, bigTiff);
if (ifd != null) {
ifd.put(new Integer(IFD.BIG_TIFF), new Boolean(bigTiff));
}
return ifd;
}
/**
* Retrieve a given entry from the first IFD in the stream.
*
* @param tag the tag of the entry to be retrieved.
* @return an object representing the entry's fields.
* @throws IOException when there is an error accessing the stream.
* @throws IllegalArgumentException when the tag number is unknown.
*/
public TiffIFDEntry getFirstIFDEntry(int tag) throws IOException {
// First lets re-position the file pointer by checking the TIFF header
Boolean result = checkHeader();
if (result == null) return null;
in.seek(2);
boolean bigTiff = in.readShort() == TiffConstants.BIG_TIFF_MAGIC_NUMBER;
// Get the offset of the first IFD
long offset = getFirstOffset(bigTiff);
// The following loosely resembles the logic of getIFD()...
in.seek(offset);
long numEntries = bigTiff ? in.readLong() : in.readShort() & 0xffff;
for (int i = 0; i < numEntries; i++) {
in.seek(offset + // The beginning of the IFD
2 + // The width of the initial numEntries field
(bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY :
TiffConstants.BYTES_PER_ENTRY) * i);
int entryTag = in.readShort() & 0xffff;
// Skip this tag unless it matches the one we want
if (entryTag != tag) continue;
// Parse the entry's "Type"
int entryType = in.readShort() & 0xffff;
// Parse the entry's "ValueCount"
int valueCount =
bigTiff ? (int) (in.readLong() & 0xffffffff) : in.readInt();
if (valueCount < 0) {
throw new RuntimeException("Count of '" + valueCount + "' unexpected.");
}
// Parse the entry's "ValueOffset"
long valueOffset = getNextOffset(bigTiff, offset);
return new TiffIFDEntry(entryTag, entryType, valueCount, valueOffset);
}
throw new IllegalArgumentException("Unknown tag: " + tag);
}
/**
* Gets offset to the first IFD, or -1 if stream is not TIFF.
* Assumes the stream is positioned properly (checkHeader just called).
*/
public long getFirstOffset() throws IOException {
return getFirstOffset(false);
}
/**
* Gets offset to the first IFD, or -1 if stream is not TIFF.
* Assumes the stream is positioned properly (checkHeader just called).
*
* @param bigTiff true if this is a BigTIFF file (8 byte pointers).
*/
public long getFirstOffset(boolean bigTiff) throws IOException {
if (bigTiff) in.skipBytes(4);
return bigTiff ? in.readLong() : in.readInt();
}
/** Gets the IFD stored at the given offset. */
public IFD getIFD(long ifdNum, long offset) throws IOException {
return getIFD(ifdNum, offset, false);
}
/** Gets the IFD stored at the given offset. */
public IFD getIFD(long ifdNum, long offset, boolean bigTiff)
throws IOException
{
IFD ifd = new IFD();
// save little-endian flag to internal LITTLE_ENDIAN tag
ifd.put(new Integer(IFD.LITTLE_ENDIAN), new Boolean(in.isLittleEndian()));
ifd.put(new Integer(IFD.BIG_TIFF), new Boolean(bigTiff));
// read in directory entries for this IFD
LogTools.debug("getIFDs: seeking IFD #" + ifdNum + " at " + offset);
in.seek(offset);
long numEntries = bigTiff ? in.readLong() : in.readShort() & 0xffff;
LogTools.debug("getIFDs: " + numEntries + " directory entries to read");
if (numEntries == 0 || numEntries == 1) return ifd;
int bytesPerEntry = bigTiff ?
TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY;
int baseOffset = bigTiff ? 8 : 2;
int threshhold = bigTiff ? 8 : 4;
for (int i=0; i<numEntries; i++) {
in.seek(offset + baseOffset + bytesPerEntry * i);
int tag = in.readShort() & 0xffff;
int type = in.readShort() & 0xffff;
// BigTIFF case is a slight hack
int count = bigTiff ? (int) (in.readLong() & 0xffffffff) : in.readInt();
LogTools.debug("getIFDs: read " + IFD.getIFDTagName(tag) +
" (type=" + IFD.getIFDTypeName(type) + "; count=" + count + ")");
if (count < 0) return null; // invalid data
Object value = null;
int bpe = IFD.getIFDTypeLength(type);
if (bpe <= 0) return null; // invalid data
if (count > threshhold / bpe) {
- long pointer = getNextOffset(bigTiff,
- offset + baseOffset + bytesPerEntry * i);
+ long pointer = getNextOffset(bigTiff, 0);
LogTools.debug("getIFDs: seeking to offset: " + pointer);
in.seek(pointer);
}
long inputLen = in.length();
long inputPointer = in.getFilePointer();
if (count * bpe + inputPointer > inputLen) {
int oldCount = count;
count = (int) ((inputLen - inputPointer) / bpe);
LogTools.debug("getIFDs: truncated " + (oldCount - count) +
" array elements for tag " + tag);
}
if (type == IFD.BYTE) {
// 8-bit unsigned integer
if (count == 1) value = new Short(in.readByte());
else {
byte[] bytes = new byte[count];
in.readFully(bytes);
// bytes are unsigned, so use shorts
short[] shorts = new short[count];
for (int j=0; j<count; j++) shorts[j] = (short) (bytes[j] & 0xff);
value = shorts;
}
}
else if (type == IFD.ASCII) {
// 8-bit byte that contain a 7-bit ASCII code;
// the last byte must be NUL (binary zero)
byte[] ascii = new byte[count];
in.read(ascii);
// count number of null terminators
int nullCount = 0;
for (int j=0; j<count; j++) {
if (ascii[j] == 0 || j == count - 1) nullCount++;
}
// convert character array to array of strings
String[] strings = nullCount == 1 ? null : new String[nullCount];
String s = null;
int c = 0, ndx = -1;
for (int j=0; j<count; j++) {
if (ascii[j] == 0) {
s = new String(ascii, ndx + 1, j - ndx - 1);
ndx = j;
}
else if (j == count - 1) {
// handle non-null-terminated strings
s = new String(ascii, ndx + 1, j - ndx);
}
else s = null;
if (strings != null && s != null) strings[c++] = s;
}
value = strings == null ? (Object) s : strings;
}
else if (type == IFD.SHORT) {
// 16-bit (2-byte) unsigned integer
if (count == 1) value = new Integer(in.readShort() & 0xffff);
else {
int[] shorts = new int[count];
for (int j=0; j<count; j++) {
shorts[j] = in.readShort() & 0xffff;
}
value = shorts;
}
}
else if (type == IFD.LONG || type == IFD.IFD) {
// 32-bit (4-byte) unsigned integer
if (count == 1) value = new Long(in.readInt());
else {
long[] longs = new long[count];
for (int j=0; j<count; j++) longs[j] = in.readInt();
value = longs;
}
}
else if (type == IFD.LONG8 || type == IFD.SLONG8 || type == IFD.IFD8) {
if (count == 1) value = new Long(in.readLong());
else {
long[] longs = new long[count];
for (int j=0; j<count; j++) longs[j] = in.readLong();
value = longs;
}
}
else if (type == IFD.RATIONAL || type == IFD.SRATIONAL) {
// Two LONGs or SLONGs: the first represents the numerator
// of a fraction; the second, the denominator
if (count == 1) value = new TiffRational(in.readInt(), in.readInt());
else {
TiffRational[] rationals = new TiffRational[count];
for (int j=0; j<count; j++) {
rationals[j] = new TiffRational(in.readInt(), in.readInt());
}
value = rationals;
}
}
else if (type == IFD.SBYTE || type == IFD.UNDEFINED) {
// SBYTE: An 8-bit signed (twos-complement) integer
// UNDEFINED: An 8-bit byte that may contain anything,
// depending on the definition of the field
if (count == 1) value = new Byte(in.readByte());
else {
byte[] sbytes = new byte[count];
in.read(sbytes);
value = sbytes;
}
}
else if (type == IFD.SSHORT) {
// A 16-bit (2-byte) signed (twos-complement) integer
if (count == 1) value = new Short(in.readShort());
else {
short[] sshorts = new short[count];
for (int j=0; j<count; j++) sshorts[j] = in.readShort();
value = sshorts;
}
}
else if (type == IFD.SLONG) {
// A 32-bit (4-byte) signed (twos-complement) integer
if (count == 1) value = new Integer(in.readInt());
else {
int[] slongs = new int[count];
for (int j=0; j<count; j++) slongs[j] = in.readInt();
value = slongs;
}
}
else if (type == IFD.FLOAT) {
// Single precision (4-byte) IEEE format
if (count == 1) value = new Float(in.readFloat());
else {
float[] floats = new float[count];
for (int j=0; j<count; j++) floats[j] = in.readFloat();
value = floats;
}
}
else if (type == IFD.DOUBLE) {
// Double precision (8-byte) IEEE format
if (count == 1) value = new Double(in.readDouble());
else {
double[] doubles = new double[count];
for (int j=0; j<count; j++) {
doubles[j] = in.readDouble();
}
value = doubles;
}
}
if (value != null) ifd.put(new Integer(tag), value);
}
in.seek(offset + baseOffset + bytesPerEntry * numEntries);
return ifd;
}
/** Convenience method for obtaining a stream's first ImageDescription. */
public String getComment() throws IOException {
IFD firstIFD = getFirstIFD();
return firstIFD == null ? null : firstIFD.getComment();
}
// -- TiffParser methods - image reading --
public byte[] getTile(IFD ifd, int row, int col)
throws FormatException, IOException
{
int samplesPerPixel = ifd.getSamplesPerPixel();
if (ifd.getPlanarConfiguration() == 2) samplesPerPixel = 1;
int bpp = ifd.getBytesPerSample()[0];
int width = (int) ifd.getTileWidth();
int height = (int) ifd.getTileLength();
byte[] buf = new byte[width * height * samplesPerPixel * bpp];
return getTile(ifd, buf, row, col);
}
public byte[] getTile(IFD ifd, byte[] buf, int row, int col)
throws FormatException, IOException
{
byte[] jpegTable = (byte[]) ifd.getIFDValue(IFD.JPEG_TABLES, false, null);
CodecOptions options = new CodecOptions();
options.interleaved = true;
options.littleEndian = ifd.isLittleEndian();
long tileWidth = ifd.getTileWidth();
long tileLength = ifd.getTileLength();
int samplesPerPixel = ifd.getSamplesPerPixel();
int planarConfig = ifd.getPlanarConfiguration();
int compression = ifd.getCompression();
long numTileCols = ifd.getTilesPerRow();
int pixel = ifd.getBytesPerSample()[0];
int effectiveChannels = planarConfig == 2 ? 1 : samplesPerPixel;
long[] stripOffsets = ifd.getStripOffsets();
long[] stripByteCounts = ifd.getStripByteCounts();
int tileNumber = (int) (row * numTileCols + col);
byte[] tile = new byte[(int) stripByteCounts[tileNumber]];
in.seek(stripOffsets[tileNumber]);
in.read(tile);
int size = (int) (tileWidth * tileLength * pixel * effectiveChannels);
options.maxBytes = size;
if (jpegTable != null) {
byte[] q = new byte[jpegTable.length + tile.length - 4];
System.arraycopy(jpegTable, 0, q, 0, jpegTable.length - 2);
System.arraycopy(tile, 2, q, jpegTable.length - 2, tile.length - 2);
tile = TiffCompression.uncompress(q, compression, options);
}
else tile = TiffCompression.uncompress(tile, compression, options);
TiffCompression.undifference(tile, ifd);
unpackBytes(buf, 0, tile, ifd);
return buf;
}
/** Reads the image defined in the given IFD from the input source. */
public byte[][] getSamples(IFD ifd) throws FormatException, IOException {
return getSamples(ifd, 0, 0, (int) ifd.getImageWidth(),
(int) ifd.getImageLength());
}
/** Reads the image defined in the given IFD from the input source. */
public byte[][] getSamples(IFD ifd, int x, int y, int w, int h)
throws FormatException, IOException
{
int samplesPerPixel = ifd.getSamplesPerPixel();
int bpp = ifd.getBytesPerSample()[0];
long width = ifd.getImageWidth();
long length = ifd.getImageLength();
byte[] b = new byte[(int) (w * h * samplesPerPixel * bpp)];
getSamples(ifd, b, x, y, w, h);
byte[][] samples = new byte[samplesPerPixel][(int) (w * h * bpp)];
for (int i=0; i<samplesPerPixel; i++) {
System.arraycopy(b, (int) (i*w*h*bpp), samples[i], 0, samples[i].length);
}
b = null;
return samples;
}
public byte[] getSamples(IFD ifd, byte[] buf)
throws FormatException, IOException
{
long width = ifd.getImageWidth();
long length = ifd.getImageLength();
return getSamples(ifd, buf, 0, 0, width, length);
}
public byte[] getSamples(IFD ifd, byte[] buf, int x, int y,
long width, long height) throws FormatException, IOException
{
LogTools.debug("parsing IFD entries");
// get internal non-IFD entries
boolean littleEndian = ifd.isLittleEndian();
in.order(littleEndian);
// get relevant IFD entries
int samplesPerPixel = ifd.getSamplesPerPixel();
long tileWidth = ifd.getTileWidth();
long tileLength = ifd.getTileLength();
long numTileRows = ifd.getTilesPerColumn();
long numTileCols = ifd.getTilesPerRow();
int planarConfig = ifd.getPlanarConfiguration();
int pixel = ifd.getBytesPerSample()[0];
int effectiveChannels = planarConfig == 2 ? 1 : samplesPerPixel;
ifd.printIFD();
if (width * height > Integer.MAX_VALUE) {
throw new FormatException("Sorry, ImageWidth x ImageLength > " +
Integer.MAX_VALUE + " is not supported (" +
width + " x " + height + ")");
}
if (width * height * effectiveChannels * pixel > Integer.MAX_VALUE) {
throw new FormatException("Sorry, ImageWidth x ImageLength x " +
"SamplesPerPixel x BitsPerSample > " + Integer.MAX_VALUE +
" is not supported (" + width + " x " + height + " x " +
samplesPerPixel + " x " + (pixel * 8) + ")");
}
// casting to int is safe because we have already determined that
// width * height is less than Integer.MAX_VALUE
int numSamples = (int) (width * height);
// read in image strips
LogTools.debug("reading image data (samplesPerPixel=" +
samplesPerPixel + "; numSamples=" + numSamples + ")");
long nrows = numTileRows;
if (planarConfig == 2) numTileRows *= samplesPerPixel;
Region imageBounds = new Region(x, y, (int) width,
(int) (height * (samplesPerPixel / effectiveChannels)));
int endX = (int) width + x;
int endY = (int) height + y;
int rowLen = pixel * (int) tileWidth;
int tileSize = (int) (rowLen * tileLength);
int planeSize = (int) (width * height * pixel);
int outputRowLen = (int) (pixel * width);
int bufferSizeSamplesPerPixel = samplesPerPixel;
if (ifd.getPlanarConfiguration() == 2) bufferSizeSamplesPerPixel = 1;
int bpp = ifd.getBytesPerSample()[0];
int bufferSize = (int) tileWidth * (int) tileLength *
bufferSizeSamplesPerPixel * bpp;
if (cachedTileBuffer == null || cachedTileBuffer.length != bufferSize) {
cachedTileBuffer = new byte[bufferSize];
}
for (int row=0; row<numTileRows; row++) {
for (int col=0; col<numTileCols; col++) {
Region tileBounds = new Region(col * (int) tileWidth,
(int) (row * tileLength), (int) tileWidth, (int) tileLength);
if (!imageBounds.intersects(tileBounds)) continue;
if (planarConfig == 2) {
tileBounds.y = (int) ((row % nrows) * tileLength);
}
getTile(ifd, cachedTileBuffer, row, col);
// adjust tile bounds, if necessary
int tileX = (int) Math.max(tileBounds.x, x);
int tileY = (int) Math.max(tileBounds.y, y);
int realX = tileX % (int) tileWidth;
int realY = tileY % (int) tileLength;
int twidth = (int) Math.min(endX - tileX, tileWidth - realX);
int theight = (int) Math.min(endY - tileY, tileLength - realY);
// copy appropriate portion of the tile to the output buffer
int copy = pixel * twidth;
realX *= pixel;
realY *= rowLen;
for (int q=0; q<effectiveChannels; q++) {
int src = (int) (q * tileSize) + realX + realY;
int dest = (int) (q * planeSize) + pixel * (tileX - x) +
outputRowLen * (tileY - y);
if (planarConfig == 2) dest += (planeSize * (row / nrows));
for (int tileRow=0; tileRow<theight; tileRow++) {
System.arraycopy(cachedTileBuffer, src, buf, dest, copy);
src += rowLen;
dest += outputRowLen;
}
}
}
}
return buf;
}
// -- Utility methods - byte stream decoding --
/**
* Extracts pixel information from the given byte array according to the
* bits per sample, photometric interpretation, and the specified byte
* ordering.
* No error checking is performed.
* This method is tailored specifically for planar (separated) images.
*/
public static void planarUnpack(byte[] samples, int startIndex, byte[] bytes,
IFD ifd) throws FormatException
{
BitBuffer bb = new BitBuffer(bytes);
int numBytes = ifd.getBytesPerSample()[0];
int realBytes = numBytes;
if (numBytes == 3) numBytes++;
int bitsPerSample = ifd.getBitsPerSample()[0];
boolean littleEndian = ifd.isLittleEndian();
int photoInterp = ifd.getPhotometricInterpretation();
for (int j=0; j<bytes.length / realBytes; j++) {
int value = bb.getBits(bitsPerSample);
if (littleEndian) value = DataTools.swap(value) >> (32 - bitsPerSample);
if (photoInterp == PhotoInterp.WHITE_IS_ZERO) {
value = (int) (Math.pow(2, bitsPerSample) - 1 - value);
}
else if (photoInterp == PhotoInterp.CMYK) {
value = Integer.MAX_VALUE - value;
}
if (numBytes*(startIndex + j) < samples.length) {
DataTools.unpackBytes(value, samples, numBytes*(startIndex + j),
numBytes, littleEndian);
}
}
}
/**
* Extracts pixel information from the given byte array according to the
* bits per sample, photometric interpretation and color map IFD directory
* entry values, and the specified byte ordering.
* No error checking is performed.
*/
public static void unpackBytes(byte[] samples, int startIndex, byte[] bytes,
IFD ifd) throws FormatException
{
if (ifd.getPlanarConfiguration() == 2) {
planarUnpack(samples, startIndex, bytes, ifd);
return;
}
int compression = ifd.getCompression();
int photoInterp = ifd.getPhotometricInterpretation();
if (compression == TiffCompression.JPEG) photoInterp = PhotoInterp.RGB;
int[] bitsPerSample = ifd.getBitsPerSample();
int nChannels = bitsPerSample.length;
int nSamples = samples.length / nChannels;
int totalBits = 0;
for (int i=0; i<nChannels; i++) totalBits += bitsPerSample[i];
int sampleCount = 8 * bytes.length / totalBits;
if (photoInterp == PhotoInterp.Y_CB_CR) sampleCount *= 3;
LogTools.debug("unpacking " + sampleCount + " samples (startIndex=" +
startIndex + "; totalBits=" + totalBits +
"; numBytes=" + bytes.length + ")");
long imageWidth = ifd.getImageWidth();
int bps0 = bitsPerSample[0];
int numBytes = ifd.getBytesPerSample()[0];
boolean noDiv8 = bps0 % 8 != 0;
boolean bps8 = bps0 == 8;
boolean bps16 = bps0 == 16;
int row = startIndex / (int) imageWidth;
int col = 0;
int cw = 0, ch = 0;
boolean littleEndian = ifd.isLittleEndian();
int[] reference = ifd.getIFDIntArray(IFD.REFERENCE_BLACK_WHITE, false);
int[] subsampling = ifd.getIFDIntArray(IFD.Y_CB_CR_SUB_SAMPLING, false);
TiffRational[] coefficients = (TiffRational[])
ifd.getIFDValue(IFD.Y_CB_CR_COEFFICIENTS);
int count = 0;
BitBuffer bb = new BitBuffer(bytes);
// Hyper optimisation that takes any 8-bit or 16-bit data, where there is
// only one channel, the source byte buffer's size is less than or equal to
// that of the destination buffer and for which no special unpacking is
// required and performs a simple array copy. Over the course of reading
// semi-large datasets this can save **billions** of method calls.
// Wed Aug 5 19:04:59 BST 2009
// Chris Allan <[email protected]>
if ((bps8 || bps16) && bytes.length <= samples.length && nChannels == 1
&& photoInterp != PhotoInterp.WHITE_IS_ZERO
&& photoInterp != PhotoInterp.CMYK
&& photoInterp != PhotoInterp.Y_CB_CR) {
System.arraycopy(bytes, 0, samples, 0, bytes.length);
return;
}
for (int j=0; j<sampleCount; j++) {
for (int i=0; i<nChannels; i++) {
int index = numBytes * (j * nChannels + i);
int ndx = startIndex + j;
if (ndx >= nSamples) {
break;
}
int outputIndex = i * nSamples + ndx * numBytes;
if (noDiv8) {
// bits per sample is not a multiple of 8
short s = 0;
if ((i == 0 && photoInterp == PhotoInterp.RGB_PALETTE) ||
(photoInterp != PhotoInterp.CFA_ARRAY &&
photoInterp != PhotoInterp.RGB_PALETTE))
{
s = (short) (bb.getBits(bps0) & 0xffff);
if ((ndx % imageWidth) == imageWidth - 1 && bps0 < 8) {
bb.skipBits((imageWidth * bps0 * sampleCount) % 8);
}
}
if (photoInterp == PhotoInterp.WHITE_IS_ZERO ||
photoInterp == PhotoInterp.CMYK)
{
// invert colors
s = (short) (Math.pow(2, bitsPerSample[0]) - 1 - s);
}
if (outputIndex + numBytes <= samples.length) {
DataTools.unpackBytes(s, samples, outputIndex, numBytes,
littleEndian);
}
}
else if (bps8) {
// special case handles 8-bit data more quickly
if (outputIndex >= samples.length) break;
if (photoInterp != PhotoInterp.Y_CB_CR) {
samples[outputIndex] = (byte) (bytes[index] & 0xff);
}
if (photoInterp == PhotoInterp.WHITE_IS_ZERO) { // invert color value
samples[outputIndex] = (byte) (255 - samples[outputIndex]);
}
else if (photoInterp == PhotoInterp.CMYK) {
samples[outputIndex] =
(byte) (Integer.MAX_VALUE - samples[outputIndex]);
}
else if (photoInterp == PhotoInterp.Y_CB_CR) {
if (i == bitsPerSample.length - 1) {
float lumaRed = 0.299f;
float lumaGreen = 0.587f;
float lumaBlue = 0.114f;
if (coefficients != null) {
lumaRed = coefficients[0].floatValue();
lumaGreen = coefficients[1].floatValue();
lumaBlue = coefficients[2].floatValue();
}
int subX = subsampling == null ? 2 : subsampling[0];
int subY = subsampling == null ? 2 : subsampling[1];
int block = subX * subY;
int lumaIndex = j + (2 * (j / block));
int chromaIndex = (j / block) * (block + 2) + block;
if (chromaIndex + 1 >= bytes.length) break;
int tile = ndx / block;
int pixel = ndx % block;
int nTiles = (int) (imageWidth / subX);
long r = subY * (tile / nTiles) + (pixel / subX);
long c = subX * (tile % nTiles) + (pixel % subX);
int idx = (int) (r * imageWidth + c);
if (idx < nSamples) {
int y = (bytes[lumaIndex] & 0xff) - reference[0];
int cb = (bytes[chromaIndex] & 0xff) - reference[2];
int cr = (bytes[chromaIndex + 1] & 0xff) - reference[4];
int red = (int) (cr * (2 - 2 * lumaRed) + y);
int blue = (int) (cb * (2 - 2 * lumaBlue) + y);
int green = (int)
((y - lumaBlue * blue - lumaRed * red) / lumaGreen);
samples[idx] = (byte) red;
samples[nSamples + idx] = (byte) green;
samples[2*nSamples + idx] = (byte) blue;
}
}
}
} // end if (bps8)
else {
int offset = numBytes + index < bytes.length ?
index : bytes.length - numBytes;
long v = DataTools.bytesToLong(bytes, offset, numBytes, littleEndian);
if (photoInterp == PhotoInterp.WHITE_IS_ZERO) { // invert color value
long max = (long) Math.pow(2, numBytes * 8) - 1;
v = max - v;
}
else if (photoInterp == PhotoInterp.CMYK) {
v = Integer.MAX_VALUE - v;
}
if (ndx*numBytes >= nSamples) break;
DataTools.unpackBytes(v, samples, i*nSamples + ndx*numBytes,
numBytes, littleEndian);
} // end else
}
}
}
/**
* Read a file offset.
* For bigTiff, a 64-bit number is read. For other Tiffs, a 32-bit number
* is read and possibly adjusted for a possible carry-over from the previous
* offset.
*/
long getNextOffset(boolean bigTiff, long previous) throws IOException {
if (bigTiff) {
return in.readLong();
}
long offset = (previous & ~0xffffffffL) | (in.readInt() & 0xffffffffL);
if (offset < previous) {
offset += 0x100000000L;
}
return offset;
}
}
| true | true | public IFD getIFD(long ifdNum, long offset, boolean bigTiff)
throws IOException
{
IFD ifd = new IFD();
// save little-endian flag to internal LITTLE_ENDIAN tag
ifd.put(new Integer(IFD.LITTLE_ENDIAN), new Boolean(in.isLittleEndian()));
ifd.put(new Integer(IFD.BIG_TIFF), new Boolean(bigTiff));
// read in directory entries for this IFD
LogTools.debug("getIFDs: seeking IFD #" + ifdNum + " at " + offset);
in.seek(offset);
long numEntries = bigTiff ? in.readLong() : in.readShort() & 0xffff;
LogTools.debug("getIFDs: " + numEntries + " directory entries to read");
if (numEntries == 0 || numEntries == 1) return ifd;
int bytesPerEntry = bigTiff ?
TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY;
int baseOffset = bigTiff ? 8 : 2;
int threshhold = bigTiff ? 8 : 4;
for (int i=0; i<numEntries; i++) {
in.seek(offset + baseOffset + bytesPerEntry * i);
int tag = in.readShort() & 0xffff;
int type = in.readShort() & 0xffff;
// BigTIFF case is a slight hack
int count = bigTiff ? (int) (in.readLong() & 0xffffffff) : in.readInt();
LogTools.debug("getIFDs: read " + IFD.getIFDTagName(tag) +
" (type=" + IFD.getIFDTypeName(type) + "; count=" + count + ")");
if (count < 0) return null; // invalid data
Object value = null;
int bpe = IFD.getIFDTypeLength(type);
if (bpe <= 0) return null; // invalid data
if (count > threshhold / bpe) {
long pointer = getNextOffset(bigTiff,
offset + baseOffset + bytesPerEntry * i);
LogTools.debug("getIFDs: seeking to offset: " + pointer);
in.seek(pointer);
}
long inputLen = in.length();
long inputPointer = in.getFilePointer();
if (count * bpe + inputPointer > inputLen) {
int oldCount = count;
count = (int) ((inputLen - inputPointer) / bpe);
LogTools.debug("getIFDs: truncated " + (oldCount - count) +
" array elements for tag " + tag);
}
if (type == IFD.BYTE) {
// 8-bit unsigned integer
if (count == 1) value = new Short(in.readByte());
else {
byte[] bytes = new byte[count];
in.readFully(bytes);
// bytes are unsigned, so use shorts
short[] shorts = new short[count];
for (int j=0; j<count; j++) shorts[j] = (short) (bytes[j] & 0xff);
value = shorts;
}
}
else if (type == IFD.ASCII) {
// 8-bit byte that contain a 7-bit ASCII code;
// the last byte must be NUL (binary zero)
byte[] ascii = new byte[count];
in.read(ascii);
// count number of null terminators
int nullCount = 0;
for (int j=0; j<count; j++) {
if (ascii[j] == 0 || j == count - 1) nullCount++;
}
// convert character array to array of strings
String[] strings = nullCount == 1 ? null : new String[nullCount];
String s = null;
int c = 0, ndx = -1;
for (int j=0; j<count; j++) {
if (ascii[j] == 0) {
s = new String(ascii, ndx + 1, j - ndx - 1);
ndx = j;
}
else if (j == count - 1) {
// handle non-null-terminated strings
s = new String(ascii, ndx + 1, j - ndx);
}
else s = null;
if (strings != null && s != null) strings[c++] = s;
}
value = strings == null ? (Object) s : strings;
}
else if (type == IFD.SHORT) {
// 16-bit (2-byte) unsigned integer
if (count == 1) value = new Integer(in.readShort() & 0xffff);
else {
int[] shorts = new int[count];
for (int j=0; j<count; j++) {
shorts[j] = in.readShort() & 0xffff;
}
value = shorts;
}
}
else if (type == IFD.LONG || type == IFD.IFD) {
// 32-bit (4-byte) unsigned integer
if (count == 1) value = new Long(in.readInt());
else {
long[] longs = new long[count];
for (int j=0; j<count; j++) longs[j] = in.readInt();
value = longs;
}
}
else if (type == IFD.LONG8 || type == IFD.SLONG8 || type == IFD.IFD8) {
if (count == 1) value = new Long(in.readLong());
else {
long[] longs = new long[count];
for (int j=0; j<count; j++) longs[j] = in.readLong();
value = longs;
}
}
else if (type == IFD.RATIONAL || type == IFD.SRATIONAL) {
// Two LONGs or SLONGs: the first represents the numerator
// of a fraction; the second, the denominator
if (count == 1) value = new TiffRational(in.readInt(), in.readInt());
else {
TiffRational[] rationals = new TiffRational[count];
for (int j=0; j<count; j++) {
rationals[j] = new TiffRational(in.readInt(), in.readInt());
}
value = rationals;
}
}
else if (type == IFD.SBYTE || type == IFD.UNDEFINED) {
// SBYTE: An 8-bit signed (twos-complement) integer
// UNDEFINED: An 8-bit byte that may contain anything,
// depending on the definition of the field
if (count == 1) value = new Byte(in.readByte());
else {
byte[] sbytes = new byte[count];
in.read(sbytes);
value = sbytes;
}
}
else if (type == IFD.SSHORT) {
// A 16-bit (2-byte) signed (twos-complement) integer
if (count == 1) value = new Short(in.readShort());
else {
short[] sshorts = new short[count];
for (int j=0; j<count; j++) sshorts[j] = in.readShort();
value = sshorts;
}
}
else if (type == IFD.SLONG) {
// A 32-bit (4-byte) signed (twos-complement) integer
if (count == 1) value = new Integer(in.readInt());
else {
int[] slongs = new int[count];
for (int j=0; j<count; j++) slongs[j] = in.readInt();
value = slongs;
}
}
else if (type == IFD.FLOAT) {
// Single precision (4-byte) IEEE format
if (count == 1) value = new Float(in.readFloat());
else {
float[] floats = new float[count];
for (int j=0; j<count; j++) floats[j] = in.readFloat();
value = floats;
}
}
else if (type == IFD.DOUBLE) {
// Double precision (8-byte) IEEE format
if (count == 1) value = new Double(in.readDouble());
else {
double[] doubles = new double[count];
for (int j=0; j<count; j++) {
doubles[j] = in.readDouble();
}
value = doubles;
}
}
if (value != null) ifd.put(new Integer(tag), value);
}
in.seek(offset + baseOffset + bytesPerEntry * numEntries);
return ifd;
}
| public IFD getIFD(long ifdNum, long offset, boolean bigTiff)
throws IOException
{
IFD ifd = new IFD();
// save little-endian flag to internal LITTLE_ENDIAN tag
ifd.put(new Integer(IFD.LITTLE_ENDIAN), new Boolean(in.isLittleEndian()));
ifd.put(new Integer(IFD.BIG_TIFF), new Boolean(bigTiff));
// read in directory entries for this IFD
LogTools.debug("getIFDs: seeking IFD #" + ifdNum + " at " + offset);
in.seek(offset);
long numEntries = bigTiff ? in.readLong() : in.readShort() & 0xffff;
LogTools.debug("getIFDs: " + numEntries + " directory entries to read");
if (numEntries == 0 || numEntries == 1) return ifd;
int bytesPerEntry = bigTiff ?
TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY;
int baseOffset = bigTiff ? 8 : 2;
int threshhold = bigTiff ? 8 : 4;
for (int i=0; i<numEntries; i++) {
in.seek(offset + baseOffset + bytesPerEntry * i);
int tag = in.readShort() & 0xffff;
int type = in.readShort() & 0xffff;
// BigTIFF case is a slight hack
int count = bigTiff ? (int) (in.readLong() & 0xffffffff) : in.readInt();
LogTools.debug("getIFDs: read " + IFD.getIFDTagName(tag) +
" (type=" + IFD.getIFDTypeName(type) + "; count=" + count + ")");
if (count < 0) return null; // invalid data
Object value = null;
int bpe = IFD.getIFDTypeLength(type);
if (bpe <= 0) return null; // invalid data
if (count > threshhold / bpe) {
long pointer = getNextOffset(bigTiff, 0);
LogTools.debug("getIFDs: seeking to offset: " + pointer);
in.seek(pointer);
}
long inputLen = in.length();
long inputPointer = in.getFilePointer();
if (count * bpe + inputPointer > inputLen) {
int oldCount = count;
count = (int) ((inputLen - inputPointer) / bpe);
LogTools.debug("getIFDs: truncated " + (oldCount - count) +
" array elements for tag " + tag);
}
if (type == IFD.BYTE) {
// 8-bit unsigned integer
if (count == 1) value = new Short(in.readByte());
else {
byte[] bytes = new byte[count];
in.readFully(bytes);
// bytes are unsigned, so use shorts
short[] shorts = new short[count];
for (int j=0; j<count; j++) shorts[j] = (short) (bytes[j] & 0xff);
value = shorts;
}
}
else if (type == IFD.ASCII) {
// 8-bit byte that contain a 7-bit ASCII code;
// the last byte must be NUL (binary zero)
byte[] ascii = new byte[count];
in.read(ascii);
// count number of null terminators
int nullCount = 0;
for (int j=0; j<count; j++) {
if (ascii[j] == 0 || j == count - 1) nullCount++;
}
// convert character array to array of strings
String[] strings = nullCount == 1 ? null : new String[nullCount];
String s = null;
int c = 0, ndx = -1;
for (int j=0; j<count; j++) {
if (ascii[j] == 0) {
s = new String(ascii, ndx + 1, j - ndx - 1);
ndx = j;
}
else if (j == count - 1) {
// handle non-null-terminated strings
s = new String(ascii, ndx + 1, j - ndx);
}
else s = null;
if (strings != null && s != null) strings[c++] = s;
}
value = strings == null ? (Object) s : strings;
}
else if (type == IFD.SHORT) {
// 16-bit (2-byte) unsigned integer
if (count == 1) value = new Integer(in.readShort() & 0xffff);
else {
int[] shorts = new int[count];
for (int j=0; j<count; j++) {
shorts[j] = in.readShort() & 0xffff;
}
value = shorts;
}
}
else if (type == IFD.LONG || type == IFD.IFD) {
// 32-bit (4-byte) unsigned integer
if (count == 1) value = new Long(in.readInt());
else {
long[] longs = new long[count];
for (int j=0; j<count; j++) longs[j] = in.readInt();
value = longs;
}
}
else if (type == IFD.LONG8 || type == IFD.SLONG8 || type == IFD.IFD8) {
if (count == 1) value = new Long(in.readLong());
else {
long[] longs = new long[count];
for (int j=0; j<count; j++) longs[j] = in.readLong();
value = longs;
}
}
else if (type == IFD.RATIONAL || type == IFD.SRATIONAL) {
// Two LONGs or SLONGs: the first represents the numerator
// of a fraction; the second, the denominator
if (count == 1) value = new TiffRational(in.readInt(), in.readInt());
else {
TiffRational[] rationals = new TiffRational[count];
for (int j=0; j<count; j++) {
rationals[j] = new TiffRational(in.readInt(), in.readInt());
}
value = rationals;
}
}
else if (type == IFD.SBYTE || type == IFD.UNDEFINED) {
// SBYTE: An 8-bit signed (twos-complement) integer
// UNDEFINED: An 8-bit byte that may contain anything,
// depending on the definition of the field
if (count == 1) value = new Byte(in.readByte());
else {
byte[] sbytes = new byte[count];
in.read(sbytes);
value = sbytes;
}
}
else if (type == IFD.SSHORT) {
// A 16-bit (2-byte) signed (twos-complement) integer
if (count == 1) value = new Short(in.readShort());
else {
short[] sshorts = new short[count];
for (int j=0; j<count; j++) sshorts[j] = in.readShort();
value = sshorts;
}
}
else if (type == IFD.SLONG) {
// A 32-bit (4-byte) signed (twos-complement) integer
if (count == 1) value = new Integer(in.readInt());
else {
int[] slongs = new int[count];
for (int j=0; j<count; j++) slongs[j] = in.readInt();
value = slongs;
}
}
else if (type == IFD.FLOAT) {
// Single precision (4-byte) IEEE format
if (count == 1) value = new Float(in.readFloat());
else {
float[] floats = new float[count];
for (int j=0; j<count; j++) floats[j] = in.readFloat();
value = floats;
}
}
else if (type == IFD.DOUBLE) {
// Double precision (8-byte) IEEE format
if (count == 1) value = new Double(in.readDouble());
else {
double[] doubles = new double[count];
for (int j=0; j<count; j++) {
doubles[j] = in.readDouble();
}
value = doubles;
}
}
if (value != null) ifd.put(new Integer(tag), value);
}
in.seek(offset + baseOffset + bytesPerEntry * numEntries);
return ifd;
}
|
diff --git a/src/main/java/com/bia/monitor/service/Scheduler.java b/src/main/java/com/bia/monitor/service/Scheduler.java
index 13a9e06..b5ca98f 100644
--- a/src/main/java/com/bia/monitor/service/Scheduler.java
+++ b/src/main/java/com/bia/monitor/service/Scheduler.java
@@ -1,109 +1,111 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bia.monitor.service;
import com.bia.monitor.dao.GenericDao;
import com.bia.monitor.data.Job;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import org.springframework.stereotype.Component;
/**
* Schedular creates jobs which runs on given time intervals
* @author Intesar Mohammed
*/
@Component
public class Scheduler {
protected static final Logger logger = Logger.getLogger(Scheduler.class);
static final int UP_CHECK_INTERVAL = 15;
static final int DOWN_CHECK_INTERVAL = 1;
protected GenericDao generciDao;
private ScheduledThreadPoolExecutor executor;
@Autowired
public Scheduler(GenericDao generciDao) {
this.generciDao = generciDao;
}
@PostConstruct
protected void setUpExecutor() {
executor = new ScheduledThreadPoolExecutor(10);
// prod
// 15 minutes check for up sites
executor.scheduleAtFixedRate(new VerifyMethod(generciDao, false), 0, UP_CHECK_INTERVAL, TimeUnit.MINUTES);
// one minute check for only down sites
executor.scheduleAtFixedRate(new VerifyMethod(generciDao, true), 0, DOWN_CHECK_INTERVAL, TimeUnit.MINUTES);
// dev env
//executor.scheduleAtFixedRate(new VerifyMethod(generciDao, false), 0, 2, TimeUnit.MINUTES);
logger.info("setting up executor!");
}
private class VerifyMethod implements Runnable {
protected final Logger logger_ = Logger.getLogger(VerifyMethod.class);
private boolean checkDown;
private GenericDao genericDao_;
VerifyMethod(GenericDao genericDao_, boolean checkDown) {
this.checkDown = checkDown;
this.genericDao_ = genericDao_;
logger_.info(" checker added for site-up=" + checkDown + " genericDao=" + genericDao_);
}
@Override
public void run() {
List<Job> list;
try {
if (checkDown) {
list = genericDao_.getMongoTemplate().find(query(where("lastUp").is(Boolean.FALSE)), Job.class);
logger_.info("checking " + (list != null ? list.size() : 0 ) + " down sites!");
//list = mongoOps.findAll(Job.class);
} else {
list = genericDao_.getMongoTemplate().find(query(where("lastUp").is(Boolean.TRUE)), Job.class);
logger_.info("checking " + (list != null ? list.size() : 0 ) + " up sites!");
}
for (Job job : list) {
- Runnable job_ = new JobCheck(genericDao_.getMongoTemplate(), job);
- executor.schedule(job_, 10, TimeUnit.MILLISECONDS);
+ if ( job.getEmail() != null && !job.getEmail().isEmpty() ) {
+ Runnable job_ = new JobCheck(genericDao_.getMongoTemplate(), job);
+ executor.schedule(job_, 10, TimeUnit.MILLISECONDS);
+ }
}
} catch (Exception e) {
logger_.error(e.getMessage(), e);
}
}
}
@PreDestroy
public void shutdown() {
this.executor.shutdown();
}
}
| true | true | public void run() {
List<Job> list;
try {
if (checkDown) {
list = genericDao_.getMongoTemplate().find(query(where("lastUp").is(Boolean.FALSE)), Job.class);
logger_.info("checking " + (list != null ? list.size() : 0 ) + " down sites!");
//list = mongoOps.findAll(Job.class);
} else {
list = genericDao_.getMongoTemplate().find(query(where("lastUp").is(Boolean.TRUE)), Job.class);
logger_.info("checking " + (list != null ? list.size() : 0 ) + " up sites!");
}
for (Job job : list) {
Runnable job_ = new JobCheck(genericDao_.getMongoTemplate(), job);
executor.schedule(job_, 10, TimeUnit.MILLISECONDS);
}
} catch (Exception e) {
logger_.error(e.getMessage(), e);
}
}
| public void run() {
List<Job> list;
try {
if (checkDown) {
list = genericDao_.getMongoTemplate().find(query(where("lastUp").is(Boolean.FALSE)), Job.class);
logger_.info("checking " + (list != null ? list.size() : 0 ) + " down sites!");
//list = mongoOps.findAll(Job.class);
} else {
list = genericDao_.getMongoTemplate().find(query(where("lastUp").is(Boolean.TRUE)), Job.class);
logger_.info("checking " + (list != null ? list.size() : 0 ) + " up sites!");
}
for (Job job : list) {
if ( job.getEmail() != null && !job.getEmail().isEmpty() ) {
Runnable job_ = new JobCheck(genericDao_.getMongoTemplate(), job);
executor.schedule(job_, 10, TimeUnit.MILLISECONDS);
}
}
} catch (Exception e) {
logger_.error(e.getMessage(), e);
}
}
|
diff --git a/ebms-as4/src/main/java/org/jentrata/ebms/internal/messaging/PartPropertiesPayloadProcessor.java b/ebms-as4/src/main/java/org/jentrata/ebms/internal/messaging/PartPropertiesPayloadProcessor.java
index a9b4c23..7565e99 100644
--- a/ebms-as4/src/main/java/org/jentrata/ebms/internal/messaging/PartPropertiesPayloadProcessor.java
+++ b/ebms-as4/src/main/java/org/jentrata/ebms/internal/messaging/PartPropertiesPayloadProcessor.java
@@ -1,64 +1,64 @@
package org.jentrata.ebms.internal.messaging;
import org.apache.camel.Exchange;
import org.apache.camel.builder.xml.XPathBuilder;
import org.jentrata.ebms.EbmsConstants;
import org.jentrata.ebms.soap.SoapPayloadProcessor;
import org.jentrata.ebms.utils.EbmsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Adds the PartProperties for the matching PartInfo from the ebms User Message
* as message headers on the payload message
*
* @author aaronwalker
*/
public class PartPropertiesPayloadProcessor implements SoapPayloadProcessor {
private static final Logger LOG = LoggerFactory.getLogger(PartPropertiesPayloadProcessor.class);
private String partPropertyXpath = "//*[local-name()='PartInfo' and @href[.='cid:%s']]";
private String soapPartPropertyXpath = "//*[local-name()='PartInfo' and (not(@href) or string-length(@href)=0)]";
@Override
public void process(String soapMessage, String payloadId, Exchange exchange) {
try {
Node partInfo;
if(payloadId.equals(EbmsConstants.SOAP_BODY_PAYLOAD_ID)) {
partInfo = EbmsUtils.ebmsXpathNode(soapMessage,String.format(soapPartPropertyXpath,payloadId));
}
else {
partInfo = EbmsUtils.ebmsXpathNode(soapMessage,String.format(partPropertyXpath,payloadId));
}
- NodeList partProperties = EbmsUtils.ebmsXpathNodeList(partInfo,"//*[local-name()='Property']");
+ NodeList partProperties = EbmsUtils.ebmsXpathNodeList(partInfo,".//*[local-name()='Property']");
for (int i = 0; i < partProperties.getLength(); i++) {
Node property = partProperties.item(i);
String name = property.getAttributes().getNamedItem("name").getTextContent();
String value = property.getTextContent();
exchange.getIn().setHeader(name, value);
}
} catch (Exception ex) {
LOG.warn("unable to extract PartProperties for payload " + payloadId + ":" + ex);
LOG.debug("",ex);
}
}
public String getPartPropertyXpath() {
return partPropertyXpath;
}
public void setPartPropertyXpath(String partPropertyXpath) {
this.partPropertyXpath = partPropertyXpath;
}
public String getSoapPartPropertyXpath() {
return soapPartPropertyXpath;
}
public void setSoapPartPropertyXpath(String soapPartPropertyXpath) {
this.soapPartPropertyXpath = soapPartPropertyXpath;
}
}
| true | true | public void process(String soapMessage, String payloadId, Exchange exchange) {
try {
Node partInfo;
if(payloadId.equals(EbmsConstants.SOAP_BODY_PAYLOAD_ID)) {
partInfo = EbmsUtils.ebmsXpathNode(soapMessage,String.format(soapPartPropertyXpath,payloadId));
}
else {
partInfo = EbmsUtils.ebmsXpathNode(soapMessage,String.format(partPropertyXpath,payloadId));
}
NodeList partProperties = EbmsUtils.ebmsXpathNodeList(partInfo,"//*[local-name()='Property']");
for (int i = 0; i < partProperties.getLength(); i++) {
Node property = partProperties.item(i);
String name = property.getAttributes().getNamedItem("name").getTextContent();
String value = property.getTextContent();
exchange.getIn().setHeader(name, value);
}
} catch (Exception ex) {
LOG.warn("unable to extract PartProperties for payload " + payloadId + ":" + ex);
LOG.debug("",ex);
}
}
| public void process(String soapMessage, String payloadId, Exchange exchange) {
try {
Node partInfo;
if(payloadId.equals(EbmsConstants.SOAP_BODY_PAYLOAD_ID)) {
partInfo = EbmsUtils.ebmsXpathNode(soapMessage,String.format(soapPartPropertyXpath,payloadId));
}
else {
partInfo = EbmsUtils.ebmsXpathNode(soapMessage,String.format(partPropertyXpath,payloadId));
}
NodeList partProperties = EbmsUtils.ebmsXpathNodeList(partInfo,".//*[local-name()='Property']");
for (int i = 0; i < partProperties.getLength(); i++) {
Node property = partProperties.item(i);
String name = property.getAttributes().getNamedItem("name").getTextContent();
String value = property.getTextContent();
exchange.getIn().setHeader(name, value);
}
} catch (Exception ex) {
LOG.warn("unable to extract PartProperties for payload " + payloadId + ":" + ex);
LOG.debug("",ex);
}
}
|
diff --git a/seqware-pipeline/src/main/java/net/sourceforge/seqware/pipeline/workflowV2/engine/pegasus/object/Adag.java b/seqware-pipeline/src/main/java/net/sourceforge/seqware/pipeline/workflowV2/engine/pegasus/object/Adag.java
index e44009f5..2cbddaf4 100644
--- a/seqware-pipeline/src/main/java/net/sourceforge/seqware/pipeline/workflowV2/engine/pegasus/object/Adag.java
+++ b/seqware-pipeline/src/main/java/net/sourceforge/seqware/pipeline/workflowV2/engine/pegasus/object/Adag.java
@@ -1,310 +1,311 @@
/*
* Copyright (C) 2012 SeqWare
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sourceforge.seqware.pipeline.workflowV2.engine.pegasus.object;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.seqware.pipeline.workflowV2.AbstractWorkflowDataModel;
import net.sourceforge.seqware.pipeline.workflowV2.model.AbstractJob;
import net.sourceforge.seqware.pipeline.workflowV2.model.BashJob;
import net.sourceforge.seqware.pipeline.workflowV2.model.JavaJob;
import net.sourceforge.seqware.pipeline.workflowV2.model.JavaSeqwareModuleJob;
import net.sourceforge.seqware.pipeline.workflowV2.model.Job;
import net.sourceforge.seqware.pipeline.workflowV2.model.PerlJob;
import net.sourceforge.seqware.pipeline.workflowV2.model.SqwFile;
import net.sourceforge.seqware.pipeline.workflowV2.model.Workflow;
import net.sourceforge.seqware.pipeline.workflowV2.engine.pegasus.WorkflowExecutableUtils;
import org.jdom.Element;
import org.jdom.Namespace;
/**
*
* @author yongliang
*/
public class Adag {
private Collection<WorkflowExecutable> executables;
private List<PegasusJob> jobs;
private String schemaLocation = "http://pegasus.isi.edu/schema/DAX http://pegasus.isi.edu/schema/dax-3.2.xsd";
public static Namespace NAMESPACE = Namespace.getNamespace("http://pegasus.isi.edu/schema/DAX");
public static Namespace XSI = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
//FIXME should be passed in from maven
public static String PIPELINE = "seqware-pipeline-0.13.3-SNAPSHOT-full.jar";
private String version = "3.2";
private String count = "1";
private String index = "0";
private Workflow wf;
private AbstractWorkflowDataModel wfdm;
private Map<SqwFile, PegasusJob> fileJobMap;
public Adag(AbstractWorkflowDataModel wfdm) {
this.wfdm = wfdm;
this.jobs = new ArrayList<PegasusJob>();
this.fileJobMap = new HashMap<SqwFile, PegasusJob>();
//this.parseWorkflow(wf);
this.parseWorkflow(wfdm);
this.setDefaultExcutables();
}
private void setDefaultExcutables() {
executables = new ArrayList<WorkflowExecutable>();
executables.add(WorkflowExecutableUtils.getDefaultJavaExcutable(this.wfdm));
executables.add(WorkflowExecutableUtils.getDefaultPerlExcutable(this.wfdm));
executables.add(WorkflowExecutableUtils.getDefaultDirManagerExcutable(this.wfdm));
}
public Element serializeXML() {
Element adag = new Element("adag", NAMESPACE);
adag.addNamespaceDeclaration(XSI);
adag.setAttribute("schemaLocation", schemaLocation, XSI);
adag.setAttribute("version", version);
adag.setAttribute("count", count);
adag.setAttribute("index", index);
adag.setAttribute("name", this.wfdm.getName());
for (WorkflowExecutable ex : executables) {
adag.addContent(ex.serializeXML());
}
for (PegasusJob pjob : this.jobs) {
adag.addContent(pjob.serializeXML());
}
// dependencies
for (PegasusJob pjob : this.jobs) {
for (PegasusJob parent : pjob.getParents()) {
adag.addContent(pjob.getDependentElement(parent));
}
}
return adag;
}
public Workflow getWorkflow() {
return wf;
}
public void setWorkflow(Workflow wf) {
this.wf = wf;
}
private void parseWorkflow(AbstractWorkflowDataModel wfdm) {
boolean metadatawriteback = Boolean.parseBoolean(wfdm.getConfigs().get("metadata"));
List<PegasusJob> parents = new ArrayList<PegasusJob>();
int provisionFileCount = 0;
//mkdir data job
AbstractJob job0 = new BashJob("createdirs");
job0.getCommand().addArgument("mkdir -p provisionfiles; ");
//check if there are user defined directory
if(!wfdm.getDirectories().isEmpty()) {
for(String dir: wfdm.getDirectories()) {
job0.getCommand().addArgument("mkdir -p " + dir + "; ");
}
}
PegasusJob pjob0 = new PegasusJob(job0, wfdm.getConfigs().get("basedir"));
pjob0.setId(this.jobs.size());
pjob0.setMetadataWriteback(metadatawriteback);
//if has parent-accessions, assign it to first job
String parentAccession = wfdm.getConfigs().get("parent-accessions");
if(parentAccession!=null && !parentAccession.isEmpty()) {
pjob0.setParentAccession(parentAccession);
}
String workflowRunAccession = wfdm.getConfigs().get("workflow-run-accession");
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
pjob0.setWorkflowRunAccession(workflowRunAccession);
pjob0.setWorkflowRunAncesstor(true);
}
this.jobs.add(pjob0);
parents.add(pjob0);
//sqwfiles
if(!wfdm.getFiles().isEmpty()) {
Collection<PegasusJob> newParents = new ArrayList<PegasusJob>();
for(Map.Entry<String,SqwFile> entry: wfdm.getFiles().entrySet()) {
AbstractJob job = new BashJob("provisionFile_"+entry.getKey());
job.addFile(entry.getValue());
ProvisionFilesJob pjob = new ProvisionFilesJob(job,wfdm.getConfigs().get("basedir"), entry.getValue());
pjob.setId(this.jobs.size());
pjob.setMetadataWriteback(metadatawriteback);
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
pjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(pjob);
this.fileJobMap.put(entry.getValue(), pjob);
//handle in
if(entry.getValue().isInput()) {
newParents.add(pjob);
for(PegasusJob parent: parents) {
pjob.addParent(parent);
}
//add mkdir to the first job, then set the file path
String outputDir = "provisionfiles/" + provisionFileCount ;
job0.getCommand().addArgument("mkdir -p " + outputDir + "; ");
pjob.setOutputDir(outputDir);
provisionFileCount ++;
} else {
pjob.setMetadataOutputPrefix(wfdm.getConfigs().get("metadata-output-file-prefix"));
pjob.setOutputDir(wfdm.getConfigs().get("metadata-output-dir"));
//set the filepath
}
}
//reset parents
parents.clear();
parents.addAll(newParents);
}
int idCount = this.jobs.size();
//need to remember the provisionOut and reset the job's children to provisionout's children
Map<PegasusJob, PegasusJob> hasProvisionOut = new HashMap<PegasusJob, PegasusJob>();
for(AbstractJob job: wfdm.getWorkflow().getJobs()) {
PegasusJob pjob = this.createPegasusJobObject(job, wfdm);
pjob.setId(idCount);
pjob.setMetadataWriteback(metadatawriteback);
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
pjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(pjob);
idCount++;
for(Job parent: job.getParents()) {
pjob.addParent(this.getPegasusJobObject((AbstractJob)parent));
}
//has provisionfiles dependency?
// this based on the assumption that the provisionFiles job is always in the beginning or the end.
if(job.getFiles().isEmpty() == false) {
for(SqwFile file: job.getFiles()) {
//create a provisionfile job\
if(file.isInput()) {
//create a provisionFileJob;
AbstractJob pfjob = new BashJob("provisionFile_in");
pfjob.addFile(file);
- PegasusJob parentPfjob = new ProvisionFilesJob(pfjob,wfdm.getConfigs().get("basedir"), file);
+ ProvisionFilesJob parentPfjob = new ProvisionFilesJob(pfjob,wfdm.getConfigs().get("basedir"), file);
parentPfjob.setId(this.jobs.size());
parentPfjob.addParent(pjob0);
parentPfjob.setMetadataWriteback(metadatawriteback);
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
parentPfjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(parentPfjob);
+ parentPfjob.setOutputDir("provisionfiles/" + provisionFileCount) ;
pjob.addParent(parentPfjob);
//add mkdir to the first job, then set the file path
job0.getCommand().addArgument("mkdir -p provisionfiles/" + provisionFileCount + "; ");
provisionFileCount ++;
} else {
//create a provisionFileJob;
AbstractJob pfjob = new BashJob("provisionFile_in");
pfjob.addFile(file);
ProvisionFilesJob parentPfjob = new ProvisionFilesJob(pfjob,wfdm.getConfigs().get("basedir"), file);
parentPfjob.setId(this.jobs.size());
parentPfjob.addParent(pjob);
parentPfjob.setMetadataWriteback(metadatawriteback);
parentPfjob.setMetadataOutputPrefix(wfdm.getConfigs().get("metadata-output-file-prefix"));
parentPfjob.setOutputDir(wfdm.getConfigs().get("metadata-output-dir"));
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
parentPfjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(parentPfjob);
hasProvisionOut.put(pjob, parentPfjob);
}
}
}
//if no parent, set parents after provisionfiles
if(pjob.getParents().isEmpty()) {
for(PegasusJob parent: parents) {
pjob.addParent(parent);
}
}
}
if(!hasProvisionOut.isEmpty()) {
for(Map.Entry<PegasusJob, PegasusJob> entry: hasProvisionOut.entrySet()) {
//get all children
Collection<PegasusJob> children = entry.getKey().getChildren();
if(children.size()<=1)
continue;
// and set other's parent as the value
for(PegasusJob child: children ) {
if(child == entry.getValue())
continue;
child.addParent(entry.getValue());
}
}
}
//add all provision out job
//get all the leaf job
List<PegasusJob> leaves = new ArrayList<PegasusJob>();
for(PegasusJob _job: this.jobs) {
if(_job.getChildren().isEmpty()) {
leaves.add(_job);
}
}
for(Map.Entry<SqwFile, PegasusJob> entry: fileJobMap.entrySet()) {
if(entry.getKey().isOutput()) {
//set parents to all leaf jobs
for(PegasusJob leaf: leaves) {
if(leaf!=entry.getValue())
entry.getValue().addParent(leaf);
}
}
}
//set accessionFile relations
this.setAccessionFileRelations(pjob0);
}
private PegasusJob getPegasusJobObject(AbstractJob job) {
for(PegasusJob pjob: this.jobs) {
if(job.equals(pjob.getJobObject()))
return pjob;
}
return null;
}
private PegasusJob createPegasusJobObject(AbstractJob job, AbstractWorkflowDataModel wfdm) {
PegasusJob ret = null;
if(job instanceof JavaJob) {
ret = new PegasusJavaJob(job,wfdm.getConfigs().get("basedir"));
} else if(job instanceof PerlJob) {
ret = new PegasusPerlJob(job, wfdm.getConfigs().get("basedir"));
} else if (job instanceof JavaSeqwareModuleJob){
ret = new PegasusJavaSeqwareModuleJob(job, wfdm.getConfigs().get("basedir"));
} else {
ret = new PegasusJob(job, wfdm.getConfigs().get("basedir"));
}
return ret;
}
private void setAccessionFileRelations(PegasusJob parent) {
for(PegasusJob pjob: parent.getChildren()) {
pjob.addParentAccessionFile(parent.getAccessionFile());
setAccessionFileRelations(pjob);
}
}
}
| false | true | private void parseWorkflow(AbstractWorkflowDataModel wfdm) {
boolean metadatawriteback = Boolean.parseBoolean(wfdm.getConfigs().get("metadata"));
List<PegasusJob> parents = new ArrayList<PegasusJob>();
int provisionFileCount = 0;
//mkdir data job
AbstractJob job0 = new BashJob("createdirs");
job0.getCommand().addArgument("mkdir -p provisionfiles; ");
//check if there are user defined directory
if(!wfdm.getDirectories().isEmpty()) {
for(String dir: wfdm.getDirectories()) {
job0.getCommand().addArgument("mkdir -p " + dir + "; ");
}
}
PegasusJob pjob0 = new PegasusJob(job0, wfdm.getConfigs().get("basedir"));
pjob0.setId(this.jobs.size());
pjob0.setMetadataWriteback(metadatawriteback);
//if has parent-accessions, assign it to first job
String parentAccession = wfdm.getConfigs().get("parent-accessions");
if(parentAccession!=null && !parentAccession.isEmpty()) {
pjob0.setParentAccession(parentAccession);
}
String workflowRunAccession = wfdm.getConfigs().get("workflow-run-accession");
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
pjob0.setWorkflowRunAccession(workflowRunAccession);
pjob0.setWorkflowRunAncesstor(true);
}
this.jobs.add(pjob0);
parents.add(pjob0);
//sqwfiles
if(!wfdm.getFiles().isEmpty()) {
Collection<PegasusJob> newParents = new ArrayList<PegasusJob>();
for(Map.Entry<String,SqwFile> entry: wfdm.getFiles().entrySet()) {
AbstractJob job = new BashJob("provisionFile_"+entry.getKey());
job.addFile(entry.getValue());
ProvisionFilesJob pjob = new ProvisionFilesJob(job,wfdm.getConfigs().get("basedir"), entry.getValue());
pjob.setId(this.jobs.size());
pjob.setMetadataWriteback(metadatawriteback);
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
pjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(pjob);
this.fileJobMap.put(entry.getValue(), pjob);
//handle in
if(entry.getValue().isInput()) {
newParents.add(pjob);
for(PegasusJob parent: parents) {
pjob.addParent(parent);
}
//add mkdir to the first job, then set the file path
String outputDir = "provisionfiles/" + provisionFileCount ;
job0.getCommand().addArgument("mkdir -p " + outputDir + "; ");
pjob.setOutputDir(outputDir);
provisionFileCount ++;
} else {
pjob.setMetadataOutputPrefix(wfdm.getConfigs().get("metadata-output-file-prefix"));
pjob.setOutputDir(wfdm.getConfigs().get("metadata-output-dir"));
//set the filepath
}
}
//reset parents
parents.clear();
parents.addAll(newParents);
}
int idCount = this.jobs.size();
//need to remember the provisionOut and reset the job's children to provisionout's children
Map<PegasusJob, PegasusJob> hasProvisionOut = new HashMap<PegasusJob, PegasusJob>();
for(AbstractJob job: wfdm.getWorkflow().getJobs()) {
PegasusJob pjob = this.createPegasusJobObject(job, wfdm);
pjob.setId(idCount);
pjob.setMetadataWriteback(metadatawriteback);
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
pjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(pjob);
idCount++;
for(Job parent: job.getParents()) {
pjob.addParent(this.getPegasusJobObject((AbstractJob)parent));
}
//has provisionfiles dependency?
// this based on the assumption that the provisionFiles job is always in the beginning or the end.
if(job.getFiles().isEmpty() == false) {
for(SqwFile file: job.getFiles()) {
//create a provisionfile job\
if(file.isInput()) {
//create a provisionFileJob;
AbstractJob pfjob = new BashJob("provisionFile_in");
pfjob.addFile(file);
PegasusJob parentPfjob = new ProvisionFilesJob(pfjob,wfdm.getConfigs().get("basedir"), file);
parentPfjob.setId(this.jobs.size());
parentPfjob.addParent(pjob0);
parentPfjob.setMetadataWriteback(metadatawriteback);
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
parentPfjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(parentPfjob);
pjob.addParent(parentPfjob);
//add mkdir to the first job, then set the file path
job0.getCommand().addArgument("mkdir -p provisionfiles/" + provisionFileCount + "; ");
provisionFileCount ++;
} else {
//create a provisionFileJob;
AbstractJob pfjob = new BashJob("provisionFile_in");
pfjob.addFile(file);
ProvisionFilesJob parentPfjob = new ProvisionFilesJob(pfjob,wfdm.getConfigs().get("basedir"), file);
parentPfjob.setId(this.jobs.size());
parentPfjob.addParent(pjob);
parentPfjob.setMetadataWriteback(metadatawriteback);
parentPfjob.setMetadataOutputPrefix(wfdm.getConfigs().get("metadata-output-file-prefix"));
parentPfjob.setOutputDir(wfdm.getConfigs().get("metadata-output-dir"));
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
parentPfjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(parentPfjob);
hasProvisionOut.put(pjob, parentPfjob);
}
}
}
//if no parent, set parents after provisionfiles
if(pjob.getParents().isEmpty()) {
for(PegasusJob parent: parents) {
pjob.addParent(parent);
}
}
}
if(!hasProvisionOut.isEmpty()) {
for(Map.Entry<PegasusJob, PegasusJob> entry: hasProvisionOut.entrySet()) {
//get all children
Collection<PegasusJob> children = entry.getKey().getChildren();
if(children.size()<=1)
continue;
// and set other's parent as the value
for(PegasusJob child: children ) {
if(child == entry.getValue())
continue;
child.addParent(entry.getValue());
}
}
}
//add all provision out job
//get all the leaf job
List<PegasusJob> leaves = new ArrayList<PegasusJob>();
for(PegasusJob _job: this.jobs) {
if(_job.getChildren().isEmpty()) {
leaves.add(_job);
}
}
for(Map.Entry<SqwFile, PegasusJob> entry: fileJobMap.entrySet()) {
if(entry.getKey().isOutput()) {
//set parents to all leaf jobs
for(PegasusJob leaf: leaves) {
if(leaf!=entry.getValue())
entry.getValue().addParent(leaf);
}
}
}
//set accessionFile relations
this.setAccessionFileRelations(pjob0);
}
| private void parseWorkflow(AbstractWorkflowDataModel wfdm) {
boolean metadatawriteback = Boolean.parseBoolean(wfdm.getConfigs().get("metadata"));
List<PegasusJob> parents = new ArrayList<PegasusJob>();
int provisionFileCount = 0;
//mkdir data job
AbstractJob job0 = new BashJob("createdirs");
job0.getCommand().addArgument("mkdir -p provisionfiles; ");
//check if there are user defined directory
if(!wfdm.getDirectories().isEmpty()) {
for(String dir: wfdm.getDirectories()) {
job0.getCommand().addArgument("mkdir -p " + dir + "; ");
}
}
PegasusJob pjob0 = new PegasusJob(job0, wfdm.getConfigs().get("basedir"));
pjob0.setId(this.jobs.size());
pjob0.setMetadataWriteback(metadatawriteback);
//if has parent-accessions, assign it to first job
String parentAccession = wfdm.getConfigs().get("parent-accessions");
if(parentAccession!=null && !parentAccession.isEmpty()) {
pjob0.setParentAccession(parentAccession);
}
String workflowRunAccession = wfdm.getConfigs().get("workflow-run-accession");
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
pjob0.setWorkflowRunAccession(workflowRunAccession);
pjob0.setWorkflowRunAncesstor(true);
}
this.jobs.add(pjob0);
parents.add(pjob0);
//sqwfiles
if(!wfdm.getFiles().isEmpty()) {
Collection<PegasusJob> newParents = new ArrayList<PegasusJob>();
for(Map.Entry<String,SqwFile> entry: wfdm.getFiles().entrySet()) {
AbstractJob job = new BashJob("provisionFile_"+entry.getKey());
job.addFile(entry.getValue());
ProvisionFilesJob pjob = new ProvisionFilesJob(job,wfdm.getConfigs().get("basedir"), entry.getValue());
pjob.setId(this.jobs.size());
pjob.setMetadataWriteback(metadatawriteback);
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
pjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(pjob);
this.fileJobMap.put(entry.getValue(), pjob);
//handle in
if(entry.getValue().isInput()) {
newParents.add(pjob);
for(PegasusJob parent: parents) {
pjob.addParent(parent);
}
//add mkdir to the first job, then set the file path
String outputDir = "provisionfiles/" + provisionFileCount ;
job0.getCommand().addArgument("mkdir -p " + outputDir + "; ");
pjob.setOutputDir(outputDir);
provisionFileCount ++;
} else {
pjob.setMetadataOutputPrefix(wfdm.getConfigs().get("metadata-output-file-prefix"));
pjob.setOutputDir(wfdm.getConfigs().get("metadata-output-dir"));
//set the filepath
}
}
//reset parents
parents.clear();
parents.addAll(newParents);
}
int idCount = this.jobs.size();
//need to remember the provisionOut and reset the job's children to provisionout's children
Map<PegasusJob, PegasusJob> hasProvisionOut = new HashMap<PegasusJob, PegasusJob>();
for(AbstractJob job: wfdm.getWorkflow().getJobs()) {
PegasusJob pjob = this.createPegasusJobObject(job, wfdm);
pjob.setId(idCount);
pjob.setMetadataWriteback(metadatawriteback);
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
pjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(pjob);
idCount++;
for(Job parent: job.getParents()) {
pjob.addParent(this.getPegasusJobObject((AbstractJob)parent));
}
//has provisionfiles dependency?
// this based on the assumption that the provisionFiles job is always in the beginning or the end.
if(job.getFiles().isEmpty() == false) {
for(SqwFile file: job.getFiles()) {
//create a provisionfile job\
if(file.isInput()) {
//create a provisionFileJob;
AbstractJob pfjob = new BashJob("provisionFile_in");
pfjob.addFile(file);
ProvisionFilesJob parentPfjob = new ProvisionFilesJob(pfjob,wfdm.getConfigs().get("basedir"), file);
parentPfjob.setId(this.jobs.size());
parentPfjob.addParent(pjob0);
parentPfjob.setMetadataWriteback(metadatawriteback);
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
parentPfjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(parentPfjob);
parentPfjob.setOutputDir("provisionfiles/" + provisionFileCount) ;
pjob.addParent(parentPfjob);
//add mkdir to the first job, then set the file path
job0.getCommand().addArgument("mkdir -p provisionfiles/" + provisionFileCount + "; ");
provisionFileCount ++;
} else {
//create a provisionFileJob;
AbstractJob pfjob = new BashJob("provisionFile_in");
pfjob.addFile(file);
ProvisionFilesJob parentPfjob = new ProvisionFilesJob(pfjob,wfdm.getConfigs().get("basedir"), file);
parentPfjob.setId(this.jobs.size());
parentPfjob.addParent(pjob);
parentPfjob.setMetadataWriteback(metadatawriteback);
parentPfjob.setMetadataOutputPrefix(wfdm.getConfigs().get("metadata-output-file-prefix"));
parentPfjob.setOutputDir(wfdm.getConfigs().get("metadata-output-dir"));
if(workflowRunAccession!=null && !workflowRunAccession.isEmpty()) {
parentPfjob.setWorkflowRunAccession(workflowRunAccession);
}
this.jobs.add(parentPfjob);
hasProvisionOut.put(pjob, parentPfjob);
}
}
}
//if no parent, set parents after provisionfiles
if(pjob.getParents().isEmpty()) {
for(PegasusJob parent: parents) {
pjob.addParent(parent);
}
}
}
if(!hasProvisionOut.isEmpty()) {
for(Map.Entry<PegasusJob, PegasusJob> entry: hasProvisionOut.entrySet()) {
//get all children
Collection<PegasusJob> children = entry.getKey().getChildren();
if(children.size()<=1)
continue;
// and set other's parent as the value
for(PegasusJob child: children ) {
if(child == entry.getValue())
continue;
child.addParent(entry.getValue());
}
}
}
//add all provision out job
//get all the leaf job
List<PegasusJob> leaves = new ArrayList<PegasusJob>();
for(PegasusJob _job: this.jobs) {
if(_job.getChildren().isEmpty()) {
leaves.add(_job);
}
}
for(Map.Entry<SqwFile, PegasusJob> entry: fileJobMap.entrySet()) {
if(entry.getKey().isOutput()) {
//set parents to all leaf jobs
for(PegasusJob leaf: leaves) {
if(leaf!=entry.getValue())
entry.getValue().addParent(leaf);
}
}
}
//set accessionFile relations
this.setAccessionFileRelations(pjob0);
}
|
diff --git a/java/src/test/java/euler/java/Problem1Test.java b/java/src/test/java/euler/java/Problem1Test.java
index ba881fa..1054473 100644
--- a/java/src/test/java/euler/java/Problem1Test.java
+++ b/java/src/test/java/euler/java/Problem1Test.java
@@ -1,29 +1,29 @@
package euler.java;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/**
* Test class for {@link Problem1}.
*
* @author Ryo TANAKA
* @since 1.0
*/
public class Problem1Test {
private final Problem1 testee = new Problem1();
/**
* Test for {@link Problem1#fizzBuzzSum(int)}.
*
* @throws Exception Unexpected exception.
*/
@Test
public void testFizzBussSum() throws Exception {
assertEquals("fizz buzz summation below 10 is 23", testee.fizzBuzzSum(10), 23L);
- assertThat("fizz buzz summation below 13 is 35", testee.fizzBuzzSum(13), is(45L));
+ assertThat("fizz buzz summation below 13 is 45", testee.fizzBuzzSum(13), is(45L));
assertThat("fizz buzz summation below 1000 is ??", testee.fizzBuzzSum(1000), is(233168L));
}
}
| true | true | public void testFizzBussSum() throws Exception {
assertEquals("fizz buzz summation below 10 is 23", testee.fizzBuzzSum(10), 23L);
assertThat("fizz buzz summation below 13 is 35", testee.fizzBuzzSum(13), is(45L));
assertThat("fizz buzz summation below 1000 is ??", testee.fizzBuzzSum(1000), is(233168L));
}
| public void testFizzBussSum() throws Exception {
assertEquals("fizz buzz summation below 10 is 23", testee.fizzBuzzSum(10), 23L);
assertThat("fizz buzz summation below 13 is 45", testee.fizzBuzzSum(13), is(45L));
assertThat("fizz buzz summation below 1000 is ??", testee.fizzBuzzSum(1000), is(233168L));
}
|
diff --git a/src/test/java/com/bdt/kiradb/CACMDocTest.java b/src/test/java/com/bdt/kiradb/CACMDocTest.java
index 138eb04..5389884 100644
--- a/src/test/java/com/bdt/kiradb/CACMDocTest.java
+++ b/src/test/java/com/bdt/kiradb/CACMDocTest.java
@@ -1,102 +1,101 @@
package com.bdt.kiradb;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.bdt.kiradb.mykdbapp.TextDocument;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
public class CACMDocTest {
Core db;
// Gets run before each method annotated with @Test
@Before
public void setup() throws KiraCorruptIndexException, IOException {
db = new Core("KiraDBIndex");
System.out.println("Creating Index...");
db.createIndex();
}
// Gets run after any method annotated with @Test
@After
public void teardown() throws IOException {
db.deleteIndex();
}
@Test
public void testCACMAllDocs() throws IOException, InterruptedException, KiraException, ClassNotFoundException {
File dir = new File("testdocs");
if (!dir.isDirectory()) {
System.out.println("testdocs is not a directory, skipping test");
return;
}
String[] exts = {"txt"};
Collection<File> files = FileUtils.listFiles(dir, exts, false);
System.out.println("Indexing " + files.size() + " documents...");
int nDocs = 0;
for (File f : files) {
- nDocs++;
//System.out.println("Found document: " + f.getName());
String baseName = f.getName();
final int lastPeriodPos = baseName.lastIndexOf('.');
if (lastPeriodPos > 0) {
// Remove the last period and everything after it
baseName = baseName.substring(0, lastPeriodPos);
}
//System.out.println("docId: " + baseName);
String fData = FileUtils.readFileToString(f);
int n = fData.length();
int i = 0;
for ( ; i < n; i++) {
char c = fData.charAt(i);
if (!Character.isWhitespace(c))
break;
}
// Beginning of title
int beg = i++;
while (i < n) {
char c = fData.charAt(i);
if (c < ' ')
break;
i++;
}
String title = fData.substring(beg, i).trim();
//System.out.println("title: " + title);
TextDocument doc = new TextDocument();
doc.setDocId(baseName);
doc.setTitle(title);
doc.setBody(fData);
db.storeObject(doc);
nDocs++;
}
System.out.println("Indexed docs: " + nDocs);
List<Object> qResults = db.executeQuery(new TextDocument(), TextDocument.BODY, "system", Integer.MAX_VALUE, 0, null, true);
assertNotNull("The CACM query result should not be null", qResults);
System.out.println("Matched docs: " + qResults.size());
assertTrue("The query should have matched exactly 719 documents", qResults.size() == 719);
}
}
| true | true | public void testCACMAllDocs() throws IOException, InterruptedException, KiraException, ClassNotFoundException {
File dir = new File("testdocs");
if (!dir.isDirectory()) {
System.out.println("testdocs is not a directory, skipping test");
return;
}
String[] exts = {"txt"};
Collection<File> files = FileUtils.listFiles(dir, exts, false);
System.out.println("Indexing " + files.size() + " documents...");
int nDocs = 0;
for (File f : files) {
nDocs++;
//System.out.println("Found document: " + f.getName());
String baseName = f.getName();
final int lastPeriodPos = baseName.lastIndexOf('.');
if (lastPeriodPos > 0) {
// Remove the last period and everything after it
baseName = baseName.substring(0, lastPeriodPos);
}
//System.out.println("docId: " + baseName);
String fData = FileUtils.readFileToString(f);
int n = fData.length();
int i = 0;
for ( ; i < n; i++) {
char c = fData.charAt(i);
if (!Character.isWhitespace(c))
break;
}
// Beginning of title
int beg = i++;
while (i < n) {
char c = fData.charAt(i);
if (c < ' ')
break;
i++;
}
String title = fData.substring(beg, i).trim();
//System.out.println("title: " + title);
TextDocument doc = new TextDocument();
doc.setDocId(baseName);
doc.setTitle(title);
doc.setBody(fData);
db.storeObject(doc);
nDocs++;
}
System.out.println("Indexed docs: " + nDocs);
List<Object> qResults = db.executeQuery(new TextDocument(), TextDocument.BODY, "system", Integer.MAX_VALUE, 0, null, true);
assertNotNull("The CACM query result should not be null", qResults);
System.out.println("Matched docs: " + qResults.size());
assertTrue("The query should have matched exactly 719 documents", qResults.size() == 719);
}
| public void testCACMAllDocs() throws IOException, InterruptedException, KiraException, ClassNotFoundException {
File dir = new File("testdocs");
if (!dir.isDirectory()) {
System.out.println("testdocs is not a directory, skipping test");
return;
}
String[] exts = {"txt"};
Collection<File> files = FileUtils.listFiles(dir, exts, false);
System.out.println("Indexing " + files.size() + " documents...");
int nDocs = 0;
for (File f : files) {
//System.out.println("Found document: " + f.getName());
String baseName = f.getName();
final int lastPeriodPos = baseName.lastIndexOf('.');
if (lastPeriodPos > 0) {
// Remove the last period and everything after it
baseName = baseName.substring(0, lastPeriodPos);
}
//System.out.println("docId: " + baseName);
String fData = FileUtils.readFileToString(f);
int n = fData.length();
int i = 0;
for ( ; i < n; i++) {
char c = fData.charAt(i);
if (!Character.isWhitespace(c))
break;
}
// Beginning of title
int beg = i++;
while (i < n) {
char c = fData.charAt(i);
if (c < ' ')
break;
i++;
}
String title = fData.substring(beg, i).trim();
//System.out.println("title: " + title);
TextDocument doc = new TextDocument();
doc.setDocId(baseName);
doc.setTitle(title);
doc.setBody(fData);
db.storeObject(doc);
nDocs++;
}
System.out.println("Indexed docs: " + nDocs);
List<Object> qResults = db.executeQuery(new TextDocument(), TextDocument.BODY, "system", Integer.MAX_VALUE, 0, null, true);
assertNotNull("The CACM query result should not be null", qResults);
System.out.println("Matched docs: " + qResults.size());
assertTrue("The query should have matched exactly 719 documents", qResults.size() == 719);
}
|
diff --git a/src/biz/bokhorst/xprivacy/PrivacyService.java b/src/biz/bokhorst/xprivacy/PrivacyService.java
index a545920e..a5f7d0e8 100644
--- a/src/biz/bokhorst/xprivacy/PrivacyService.java
+++ b/src/biz/bokhorst/xprivacy/PrivacyService.java
@@ -1,627 +1,632 @@
package biz.bokhorst.xprivacy;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDoneException;
import android.database.sqlite.SQLiteStatement;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.util.Log;
public class PrivacyService {
private static int mXPrivacyUid = 0;
private static IPrivacyService mClient = null;
private static SQLiteDatabase mDatabase = null;
private static ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private static SQLiteStatement stmtGetRestriction = null;
private static SQLiteStatement stmtGetSetting = null;
private static SQLiteStatement stmtGetUsageRestriction = null;
private static SQLiteStatement stmtGetUsageMethod = null;
private static int cCurrentVersion = 1;
private static String cServiceName = "xprivacy237";
private static String cTableRestriction = "restriction";
private static String cTableUsage = "usage";
private static String cTableSetting = "setting";
// TODO: define column names
public static void register() {
try {
// public static void addService(String name, IBinder service)
Class<?> cServiceManager = Class.forName("android.os.ServiceManager");
Method mAddService = cServiceManager.getDeclaredMethod("addService", String.class, IBinder.class);
mAddService.invoke(null, cServiceName, mPrivacyService);
Util.log(null, Log.WARN, "Privacy service registered name=" + cServiceName);
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
public static IPrivacyService getClient() {
if (mClient == null)
try {
// TODO: retries to get privacy client?
// public static IBinder getService(String name)
Class<?> cServiceManager = Class.forName("android.os.ServiceManager");
Method mGetService = cServiceManager.getDeclaredMethod("getService", String.class);
mClient = IPrivacyService.Stub.asInterface((IBinder) mGetService.invoke(null, cServiceName));
if (mClient != null)
if (PrivacyService.getClient().getVersion() != cCurrentVersion)
mClient = null;
} catch (Throwable ex) {
mClient = null;
Util.bug(null, ex);
}
// Disable disk strict mode
ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
ThreadPolicy newpolicy = new ThreadPolicy.Builder(oldPolicy).permitDiskReads().permitDiskWrites().build();
StrictMode.setThreadPolicy(newpolicy);
return mClient;
}
private static final IPrivacyService.Stub mPrivacyService = new IPrivacyService.Stub() {
// Management
@Override
public int getVersion() throws RemoteException {
return cCurrentVersion;
}
@Override
public void migrated() throws RemoteException {
SQLiteDatabase db = getDatabase();
if (db.getVersion() < 2)
db.setVersion(2);
}
@Override
public void check() throws RemoteException {
enforcePermission();
}
// Restrictions
@Override
public void setRestriction(int uid, String restrictionName, String methodName, boolean restricted)
throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
// Create category record
if (methodName == null || restricted) {
ContentValues cvalues = new ContentValues();
cvalues.put("uid", uid);
cvalues.put("restriction", restrictionName);
cvalues.put("method", "");
cvalues.put("restricted", restricted);
db.insertWithOnConflict(cTableRestriction, null, cvalues, SQLiteDatabase.CONFLICT_REPLACE);
}
// Create method record
if (methodName != null) {
ContentValues mvalues = new ContentValues();
mvalues.put("uid", uid);
mvalues.put("restriction", restrictionName);
mvalues.put("method", methodName);
mvalues.put("restricted", !restricted);
db.insertWithOnConflict(cTableRestriction, null, mvalues, SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
public boolean getRestriction(final int uid, final String restrictionName, final String methodName,
final boolean usage) throws RemoteException {
boolean restricted = false;
try {
// No persmissions required
final SQLiteDatabase db = getDatabase();
// Precompile statement when needed
if (stmtGetRestriction == null) {
String sql = "SELECT restricted FROM " + cTableRestriction
+ " WHERE uid=? AND restriction=? AND method=?";
stmtGetRestriction = db.compileStatement(sql);
}
// Execute statement
db.beginTransaction();
try {
try {
synchronized (stmtGetRestriction) {
stmtGetRestriction.clearBindings();
stmtGetRestriction.bindLong(1, uid);
stmtGetRestriction.bindString(2, restrictionName);
stmtGetRestriction.bindString(3, "");
restricted = (stmtGetRestriction.simpleQueryForLong() > 0);
}
} catch (SQLiteDoneException ignored) {
restricted = false;
}
if (restricted && methodName != null)
try {
synchronized (stmtGetRestriction) {
stmtGetRestriction.clearBindings();
stmtGetRestriction.bindLong(1, uid);
stmtGetRestriction.bindString(2, restrictionName);
stmtGetRestriction.bindString(3, methodName);
if (stmtGetRestriction.simpleQueryForLong() > 0)
restricted = false;
}
} catch (SQLiteDoneException ignored) {
// no change
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Fallback
if (restricted == false && db.getVersion() == 1)
restricted = PrivacyProvider.getRestrictedFallback(null, uid, restrictionName, methodName);
// Log usage
if (usage) {
final boolean sRestricted = restricted;
mExecutor.execute(new Runnable() {
public void run() {
try {
db.beginTransaction();
try {
// Category
ContentValues cvalues = new ContentValues();
cvalues.put("uid", uid);
cvalues.put("restriction", restrictionName);
cvalues.put("method", "");
cvalues.put("restricted", sRestricted);
cvalues.put("time", new Date().getTime());
db.insertWithOnConflict(cTableUsage, null, cvalues, SQLiteDatabase.CONFLICT_REPLACE);
// Method
if (methodName != null) {
ContentValues mvalues = new ContentValues();
mvalues.put("uid", uid);
mvalues.put("restriction", restrictionName);
mvalues.put("method", methodName);
mvalues.put("restricted", sRestricted);
mvalues.put("time", new Date().getTime());
db.insertWithOnConflict(cTableUsage, null, mvalues,
SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
});
}
} catch (Throwable ex) {
Util.bug(null, ex);
return false;
}
return restricted;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public List getRestrictionList(int uid, String restrictionName) throws RemoteException {
List result = new ArrayList();
try {
enforcePermission();
if (restrictionName == null)
for (String sRestrictionName : PrivacyManager.getRestrictions())
result.add(getRestriction(uid, sRestrictionName, null, false));
else
for (PrivacyManager.Hook md : PrivacyManager.getHooks(restrictionName))
result.add(getRestriction(uid, restrictionName, md.getName(), false));
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteRestrictions(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
db.delete(cTableRestriction, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Restrictions deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
// Usage
@Override
@SuppressWarnings("rawtypes")
public long getUsage(int uid, List restrictionNames, String methodName) throws RemoteException {
long lastUsage = 0;
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
// Precompile statement when needed
if (stmtGetUsageRestriction == null) {
String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=?";
stmtGetUsageRestriction = db.compileStatement(sql);
}
if (stmtGetUsageMethod == null) {
String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=? AND method=?";
stmtGetUsageMethod = db.compileStatement(sql);
}
db.beginTransaction();
try {
for (Object restrictionName : restrictionNames) {
if (methodName == null)
try {
synchronized (stmtGetUsageRestriction) {
stmtGetUsageRestriction.clearBindings();
stmtGetUsageRestriction.bindLong(1, uid);
stmtGetUsageRestriction.bindString(2, (String) restrictionName);
lastUsage = Math.max(lastUsage, stmtGetUsageRestriction.simpleQueryForLong());
}
} catch (SQLiteDoneException ignored) {
}
else
try {
synchronized (stmtGetUsageMethod) {
stmtGetUsageMethod.clearBindings();
stmtGetUsageMethod.bindLong(1, uid);
stmtGetUsageMethod.bindString(2, (String) restrictionName);
stmtGetUsageMethod.bindString(3, methodName);
lastUsage = Math.max(lastUsage, stmtGetUsageMethod.simpleQueryForLong());
}
} catch (SQLiteDoneException ignored) {
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return lastUsage;
}
@Override
public List<ParcelableUsageData> getUsageList(int uid) throws RemoteException {
List<ParcelableUsageData> result = new ArrayList<ParcelableUsageData>();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor;
if (uid == 0)
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, null, new String[] {}, null, null, null);
else
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (usage data)");
else
try {
while (cursor.moveToNext()) {
ParcelableUsageData data = new ParcelableUsageData();
data.uid = cursor.getInt(0);
data.restrictionName = cursor.getString(1);
data.methodName = cursor.getString(2);
data.restricted = (cursor.getInt(3) > 0);
data.time = cursor.getLong(4);
result.add(data);
}
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteUsage(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
if (uid == 0)
db.delete(cTableUsage, null, new String[] {});
else
db.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Usage data deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
// Settings
@Override
public void setSetting(int uid, String name, String value) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
// Create record
ContentValues values = new ContentValues();
values.put("uid", uid);
values.put("name", name);
values.put("value", value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
@SuppressLint("DefaultLocale")
public String getSetting(int uid, String name, String defaultValue) throws RemoteException {
String value = null;
try {
// No persmissions required
SQLiteDatabase db = getDatabase();
// Fallback
if (db.getVersion() == 1) {
if (uid == 0)
value = PrivacyProvider.getSettingFallback(name, null, false);
if (value == null)
return PrivacyProvider.getSettingFallback(String.format("%s.%d", name, uid), defaultValue,
false);
}
// Precompile statement when needed
if (stmtGetSetting == null) {
String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND name=?";
stmtGetSetting = db.compileStatement(sql);
}
// Execute statement
db.beginTransaction();
try {
try {
synchronized (stmtGetSetting) {
stmtGetSetting.clearBindings();
stmtGetSetting.bindLong(1, uid);
stmtGetSetting.bindString(2, name);
value = stmtGetSetting.simpleQueryForString();
}
} catch (SQLiteDoneException ignored) {
value = defaultValue;
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
return defaultValue;
}
return value;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Map getSettings(int uid) throws RemoteException {
Map mapName = new HashMap();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor = db.query(cTableSetting, new String[] { "name", "value" }, "uid=?",
new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (settings)");
else
try {
while (cursor.moveToNext())
mapName.put(cursor.getString(0), cursor.getString(1));
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return mapName;
}
@Override
public void deleteSettings(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Settings deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
};
private static void enforcePermission() {
int uid = Util.getAppId(Binder.getCallingUid());
if (mXPrivacyUid == 0) {
Context context = getContext();
if (context == null)
throw new SecurityException("Context is null");
String[] packages = context.getPackageManager().getPackagesForUid(uid);
String self = PrivacyService.class.getPackage().getName();
String calling = (packages.length > 0 ? packages[0] : null);
if (self.equals(calling))
mXPrivacyUid = uid;
else
throw new SecurityException("self=" + self + " calling=" + calling);
} else if (uid != mXPrivacyUid)
throw new SecurityException("uid=" + mXPrivacyUid + " calling=" + Binder.getCallingUid());
}
private static Context getContext() {
// public static ActivityManagerService self()
// frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
try {
Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService");
Object am = cam.getMethod("self").invoke(null);
return (Context) cam.getDeclaredField("mContext").get(am);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
private static File getDbFile() {
return new File(Environment.getDataDirectory() + File.separator + "data" + File.separator
+ PrivacyService.class.getPackage().getName() + File.separator + "xprivacy.db");
}
public static void setupDatebase() {
try {
- // Set folder permission
+ // Set file permission
Util.setPermission(getDbFile().getParentFile().getAbsolutePath(), 0775, -1, PrivacyManager.cAndroidUid);
+ if (getDbFile().exists())
+ Util.setPermission(getDbFile().getAbsolutePath(), 0775, -1, PrivacyManager.cAndroidUid);
+ File journal = new File(getDbFile() + "-journal");
+ if (journal.exists())
+ Util.setPermission(journal.getAbsolutePath(), 0775, -1, PrivacyManager.cAndroidUid);
// Move database from experimental location
File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy");
if (folder.exists()) {
File[] files = folder.listFiles();
if (files != null)
for (File file : files) {
File target = new File(getDbFile().getParentFile() + File.separator + file.getName());
Util.log(null, Log.WARN, "Moving " + file + " to " + target);
file.renameTo(target);
}
folder.delete();
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private static SQLiteDatabase getDatabase() {
if (mDatabase == null) {
File dbFile = getDbFile();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
if (db.needUpgrade(1)) {
db.beginTransaction();
try {
// http://www.sqlite.org/lang_createtable.html
db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)");
db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)");
db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)");
db.setVersion(1);
db.setTransactionSuccessful();
Util.log(null, Log.WARN, "Privacy database created");
} finally {
db.endTransaction();
}
}
Util.log(null, Log.WARN, "Privacy database version=" + db.getVersion());
mDatabase = db;
}
return mDatabase;
}
}
| false | true | public List<ParcelableUsageData> getUsageList(int uid) throws RemoteException {
List<ParcelableUsageData> result = new ArrayList<ParcelableUsageData>();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor;
if (uid == 0)
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, null, new String[] {}, null, null, null);
else
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (usage data)");
else
try {
while (cursor.moveToNext()) {
ParcelableUsageData data = new ParcelableUsageData();
data.uid = cursor.getInt(0);
data.restrictionName = cursor.getString(1);
data.methodName = cursor.getString(2);
data.restricted = (cursor.getInt(3) > 0);
data.time = cursor.getLong(4);
result.add(data);
}
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteUsage(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
if (uid == 0)
db.delete(cTableUsage, null, new String[] {});
else
db.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Usage data deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
// Settings
@Override
public void setSetting(int uid, String name, String value) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
// Create record
ContentValues values = new ContentValues();
values.put("uid", uid);
values.put("name", name);
values.put("value", value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
@SuppressLint("DefaultLocale")
public String getSetting(int uid, String name, String defaultValue) throws RemoteException {
String value = null;
try {
// No persmissions required
SQLiteDatabase db = getDatabase();
// Fallback
if (db.getVersion() == 1) {
if (uid == 0)
value = PrivacyProvider.getSettingFallback(name, null, false);
if (value == null)
return PrivacyProvider.getSettingFallback(String.format("%s.%d", name, uid), defaultValue,
false);
}
// Precompile statement when needed
if (stmtGetSetting == null) {
String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND name=?";
stmtGetSetting = db.compileStatement(sql);
}
// Execute statement
db.beginTransaction();
try {
try {
synchronized (stmtGetSetting) {
stmtGetSetting.clearBindings();
stmtGetSetting.bindLong(1, uid);
stmtGetSetting.bindString(2, name);
value = stmtGetSetting.simpleQueryForString();
}
} catch (SQLiteDoneException ignored) {
value = defaultValue;
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
return defaultValue;
}
return value;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Map getSettings(int uid) throws RemoteException {
Map mapName = new HashMap();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor = db.query(cTableSetting, new String[] { "name", "value" }, "uid=?",
new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (settings)");
else
try {
while (cursor.moveToNext())
mapName.put(cursor.getString(0), cursor.getString(1));
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return mapName;
}
@Override
public void deleteSettings(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Settings deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
};
private static void enforcePermission() {
int uid = Util.getAppId(Binder.getCallingUid());
if (mXPrivacyUid == 0) {
Context context = getContext();
if (context == null)
throw new SecurityException("Context is null");
String[] packages = context.getPackageManager().getPackagesForUid(uid);
String self = PrivacyService.class.getPackage().getName();
String calling = (packages.length > 0 ? packages[0] : null);
if (self.equals(calling))
mXPrivacyUid = uid;
else
throw new SecurityException("self=" + self + " calling=" + calling);
} else if (uid != mXPrivacyUid)
throw new SecurityException("uid=" + mXPrivacyUid + " calling=" + Binder.getCallingUid());
}
private static Context getContext() {
// public static ActivityManagerService self()
// frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
try {
Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService");
Object am = cam.getMethod("self").invoke(null);
return (Context) cam.getDeclaredField("mContext").get(am);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
private static File getDbFile() {
return new File(Environment.getDataDirectory() + File.separator + "data" + File.separator
+ PrivacyService.class.getPackage().getName() + File.separator + "xprivacy.db");
}
public static void setupDatebase() {
try {
// Set folder permission
Util.setPermission(getDbFile().getParentFile().getAbsolutePath(), 0775, -1, PrivacyManager.cAndroidUid);
// Move database from experimental location
File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy");
if (folder.exists()) {
File[] files = folder.listFiles();
if (files != null)
for (File file : files) {
File target = new File(getDbFile().getParentFile() + File.separator + file.getName());
Util.log(null, Log.WARN, "Moving " + file + " to " + target);
file.renameTo(target);
}
folder.delete();
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private static SQLiteDatabase getDatabase() {
if (mDatabase == null) {
File dbFile = getDbFile();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
if (db.needUpgrade(1)) {
db.beginTransaction();
try {
// http://www.sqlite.org/lang_createtable.html
db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)");
db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)");
db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)");
db.setVersion(1);
db.setTransactionSuccessful();
Util.log(null, Log.WARN, "Privacy database created");
} finally {
db.endTransaction();
}
}
Util.log(null, Log.WARN, "Privacy database version=" + db.getVersion());
mDatabase = db;
}
return mDatabase;
}
}
| public List<ParcelableUsageData> getUsageList(int uid) throws RemoteException {
List<ParcelableUsageData> result = new ArrayList<ParcelableUsageData>();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor;
if (uid == 0)
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, null, new String[] {}, null, null, null);
else
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (usage data)");
else
try {
while (cursor.moveToNext()) {
ParcelableUsageData data = new ParcelableUsageData();
data.uid = cursor.getInt(0);
data.restrictionName = cursor.getString(1);
data.methodName = cursor.getString(2);
data.restricted = (cursor.getInt(3) > 0);
data.time = cursor.getLong(4);
result.add(data);
}
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteUsage(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
if (uid == 0)
db.delete(cTableUsage, null, new String[] {});
else
db.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Usage data deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
// Settings
@Override
public void setSetting(int uid, String name, String value) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
// Create record
ContentValues values = new ContentValues();
values.put("uid", uid);
values.put("name", name);
values.put("value", value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
@SuppressLint("DefaultLocale")
public String getSetting(int uid, String name, String defaultValue) throws RemoteException {
String value = null;
try {
// No persmissions required
SQLiteDatabase db = getDatabase();
// Fallback
if (db.getVersion() == 1) {
if (uid == 0)
value = PrivacyProvider.getSettingFallback(name, null, false);
if (value == null)
return PrivacyProvider.getSettingFallback(String.format("%s.%d", name, uid), defaultValue,
false);
}
// Precompile statement when needed
if (stmtGetSetting == null) {
String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND name=?";
stmtGetSetting = db.compileStatement(sql);
}
// Execute statement
db.beginTransaction();
try {
try {
synchronized (stmtGetSetting) {
stmtGetSetting.clearBindings();
stmtGetSetting.bindLong(1, uid);
stmtGetSetting.bindString(2, name);
value = stmtGetSetting.simpleQueryForString();
}
} catch (SQLiteDoneException ignored) {
value = defaultValue;
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
return defaultValue;
}
return value;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Map getSettings(int uid) throws RemoteException {
Map mapName = new HashMap();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor = db.query(cTableSetting, new String[] { "name", "value" }, "uid=?",
new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (settings)");
else
try {
while (cursor.moveToNext())
mapName.put(cursor.getString(0), cursor.getString(1));
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return mapName;
}
@Override
public void deleteSettings(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Settings deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
};
private static void enforcePermission() {
int uid = Util.getAppId(Binder.getCallingUid());
if (mXPrivacyUid == 0) {
Context context = getContext();
if (context == null)
throw new SecurityException("Context is null");
String[] packages = context.getPackageManager().getPackagesForUid(uid);
String self = PrivacyService.class.getPackage().getName();
String calling = (packages.length > 0 ? packages[0] : null);
if (self.equals(calling))
mXPrivacyUid = uid;
else
throw new SecurityException("self=" + self + " calling=" + calling);
} else if (uid != mXPrivacyUid)
throw new SecurityException("uid=" + mXPrivacyUid + " calling=" + Binder.getCallingUid());
}
private static Context getContext() {
// public static ActivityManagerService self()
// frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
try {
Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService");
Object am = cam.getMethod("self").invoke(null);
return (Context) cam.getDeclaredField("mContext").get(am);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
private static File getDbFile() {
return new File(Environment.getDataDirectory() + File.separator + "data" + File.separator
+ PrivacyService.class.getPackage().getName() + File.separator + "xprivacy.db");
}
public static void setupDatebase() {
try {
// Set file permission
Util.setPermission(getDbFile().getParentFile().getAbsolutePath(), 0775, -1, PrivacyManager.cAndroidUid);
if (getDbFile().exists())
Util.setPermission(getDbFile().getAbsolutePath(), 0775, -1, PrivacyManager.cAndroidUid);
File journal = new File(getDbFile() + "-journal");
if (journal.exists())
Util.setPermission(journal.getAbsolutePath(), 0775, -1, PrivacyManager.cAndroidUid);
// Move database from experimental location
File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy");
if (folder.exists()) {
File[] files = folder.listFiles();
if (files != null)
for (File file : files) {
File target = new File(getDbFile().getParentFile() + File.separator + file.getName());
Util.log(null, Log.WARN, "Moving " + file + " to " + target);
file.renameTo(target);
}
folder.delete();
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private static SQLiteDatabase getDatabase() {
if (mDatabase == null) {
File dbFile = getDbFile();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
if (db.needUpgrade(1)) {
db.beginTransaction();
try {
// http://www.sqlite.org/lang_createtable.html
db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)");
db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)");
db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)");
db.setVersion(1);
db.setTransactionSuccessful();
Util.log(null, Log.WARN, "Privacy database created");
} finally {
db.endTransaction();
}
}
Util.log(null, Log.WARN, "Privacy database version=" + db.getVersion());
mDatabase = db;
}
return mDatabase;
}
}
|
diff --git a/jbpm-flow-builder/src/test/java/org/jbpm/integrationtests/ExecutionFlowControlTest.java b/jbpm-flow-builder/src/test/java/org/jbpm/integrationtests/ExecutionFlowControlTest.java
index dc112ecff..765713868 100644
--- a/jbpm-flow-builder/src/test/java/org/jbpm/integrationtests/ExecutionFlowControlTest.java
+++ b/jbpm-flow-builder/src/test/java/org/jbpm/integrationtests/ExecutionFlowControlTest.java
@@ -1,50 +1,48 @@
package org.jbpm.integrationtests;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.kie.api.io.ResourceType;
import org.kie.internal.runtime.StatefulKnowledgeSession;
import org.kie.api.runtime.process.ProcessInstance;
public class ExecutionFlowControlTest extends TestCase {
public void testRuleFlowUpgrade() throws Exception {
final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
// Set the system property so that automatic conversion can happen
System.setProperty( "drools.ruleflow.port", "true" );
kbuilder.add( ResourceFactory.newClassPathResource("ruleflow.drl", ExecutionFlowControlTest.class), ResourceType.DRL);
kbuilder.add( ResourceFactory.newClassPathResource("ruleflow40.rfm", ExecutionFlowControlTest.class), ResourceType.DRF);
KnowledgeBase kbase = kbuilder.newKnowledgeBase();
final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
final List list = new ArrayList();
ksession.setGlobal("list", list);
ksession.fireAllRules();
assertEquals(0, list.size());
final ProcessInstance processInstance = ksession.startProcess("0");
assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
ksession.fireAllRules();
assertEquals( 4,
list.size() );
assertEquals( "Rule1",
list.get( 0 ) );
- assertEquals( "Rule3",
- list.get( 1 ) );
- assertEquals( "Rule2",
- list.get( 2 ) );
+ list.subList(1,2).contains( "Rule2" );
+ list.subList(1,2).contains( "Rule3" );
assertEquals( "Rule4",
list.get( 3 ) );
assertEquals( ProcessInstance.STATE_COMPLETED,
processInstance.getState() );
// Reset the system property so that automatic conversion should not happen
System.setProperty("drools.ruleflow.port", "false");
}
}
| true | true | public void testRuleFlowUpgrade() throws Exception {
final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
// Set the system property so that automatic conversion can happen
System.setProperty( "drools.ruleflow.port", "true" );
kbuilder.add( ResourceFactory.newClassPathResource("ruleflow.drl", ExecutionFlowControlTest.class), ResourceType.DRL);
kbuilder.add( ResourceFactory.newClassPathResource("ruleflow40.rfm", ExecutionFlowControlTest.class), ResourceType.DRF);
KnowledgeBase kbase = kbuilder.newKnowledgeBase();
final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
final List list = new ArrayList();
ksession.setGlobal("list", list);
ksession.fireAllRules();
assertEquals(0, list.size());
final ProcessInstance processInstance = ksession.startProcess("0");
assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
ksession.fireAllRules();
assertEquals( 4,
list.size() );
assertEquals( "Rule1",
list.get( 0 ) );
assertEquals( "Rule3",
list.get( 1 ) );
assertEquals( "Rule2",
list.get( 2 ) );
assertEquals( "Rule4",
list.get( 3 ) );
assertEquals( ProcessInstance.STATE_COMPLETED,
processInstance.getState() );
// Reset the system property so that automatic conversion should not happen
System.setProperty("drools.ruleflow.port", "false");
}
| public void testRuleFlowUpgrade() throws Exception {
final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
// Set the system property so that automatic conversion can happen
System.setProperty( "drools.ruleflow.port", "true" );
kbuilder.add( ResourceFactory.newClassPathResource("ruleflow.drl", ExecutionFlowControlTest.class), ResourceType.DRL);
kbuilder.add( ResourceFactory.newClassPathResource("ruleflow40.rfm", ExecutionFlowControlTest.class), ResourceType.DRF);
KnowledgeBase kbase = kbuilder.newKnowledgeBase();
final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
final List list = new ArrayList();
ksession.setGlobal("list", list);
ksession.fireAllRules();
assertEquals(0, list.size());
final ProcessInstance processInstance = ksession.startProcess("0");
assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
ksession.fireAllRules();
assertEquals( 4,
list.size() );
assertEquals( "Rule1",
list.get( 0 ) );
list.subList(1,2).contains( "Rule2" );
list.subList(1,2).contains( "Rule3" );
assertEquals( "Rule4",
list.get( 3 ) );
assertEquals( ProcessInstance.STATE_COMPLETED,
processInstance.getState() );
// Reset the system property so that automatic conversion should not happen
System.setProperty("drools.ruleflow.port", "false");
}
|
diff --git a/tests/org.jboss.ide.eclipse.freemarker.test/src/org/jboss/ide/eclipse/freemarker/test/FreemarkerAllTests.java b/tests/org.jboss.ide.eclipse.freemarker.test/src/org/jboss/ide/eclipse/freemarker/test/FreemarkerAllTests.java
index 072d795..b60d424 100644
--- a/tests/org.jboss.ide.eclipse.freemarker.test/src/org/jboss/ide/eclipse/freemarker/test/FreemarkerAllTests.java
+++ b/tests/org.jboss.ide.eclipse.freemarker.test/src/org/jboss/ide/eclipse/freemarker/test/FreemarkerAllTests.java
@@ -1,31 +1,30 @@
package org.jboss.ide.eclipse.freemarker.test;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jboss.ide.eclipse.freemarker.editor.test.FreemarkerEditorTest;
import org.jboss.ide.eclipse.freemarker.preferences.test.FreemarkerPreferencePageTest;
import org.jboss.tools.tests.AbstractPluginsLoadTest;
public class FreemarkerAllTests extends TestCase {
public static Test suite ()
{
TestSuite suite = new TestSuite(FreemarkerAllTests.class.getName());
- suite.addTestSuite(FreemarkerPluginsLoadTest.class);
suite.addTestSuite(FreemarkerPreferencePageTest.class);
suite.addTestSuite(FreemarkerEditorTest.class);
return suite;
}
static public class FreemarkerPluginsLoadTest extends AbstractPluginsLoadTest {
public FreemarkerPluginsLoadTest() {}
public void testFreemarkerPluginsAreResolvedAndActivated() {
testBundlesAreLoadedFor("org.jboss.ide.eclipse.freemarker.feature");
}
}
}
| true | true | public static Test suite ()
{
TestSuite suite = new TestSuite(FreemarkerAllTests.class.getName());
suite.addTestSuite(FreemarkerPluginsLoadTest.class);
suite.addTestSuite(FreemarkerPreferencePageTest.class);
suite.addTestSuite(FreemarkerEditorTest.class);
return suite;
}
| public static Test suite ()
{
TestSuite suite = new TestSuite(FreemarkerAllTests.class.getName());
suite.addTestSuite(FreemarkerPreferencePageTest.class);
suite.addTestSuite(FreemarkerEditorTest.class);
return suite;
}
|
diff --git a/seadas-app/src/main/java/gov/nasa/gsfc/seadas/SeadasMain.java b/seadas-app/src/main/java/gov/nasa/gsfc/seadas/SeadasMain.java
index 35cb0b08..402eb49b 100644
--- a/seadas-app/src/main/java/gov/nasa/gsfc/seadas/SeadasMain.java
+++ b/seadas-app/src/main/java/gov/nasa/gsfc/seadas/SeadasMain.java
@@ -1,203 +1,205 @@
/*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.core.runtime.RuntimeContext;
import com.bc.ceres.core.runtime.RuntimeRunnable;
import com.jidesoft.utils.Lm;
import com.jidesoft.utils.SystemInfo;
import org.esa.beam.BeamUiActivator;
import org.esa.beam.framework.dataio.ProductIO;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.ui.BasicApp;
import org.esa.beam.framework.ui.UIUtils;
import org.esa.beam.framework.ui.application.ApplicationDescriptor;
import org.esa.beam.framework.ui.command.Command;
import org.esa.beam.framework.ui.command.CommandManager;
import org.esa.beam.util.Debug;
import org.esa.beam.visat.actions.session.OpenSessionAction;
import javax.media.jai.JAI;
import javax.media.jai.util.ImagingListener;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Locale;
/**
* The startup class for VISAT. It provides the <code>main</code> method for the application.
* <p/>
* <p>The VISAT application accepts the following command line options: <ld> <li> <code>-d</code> or
* <code>--debug</code> sets VISAT into debugging mode <li> <code>-l <i>file</i></code> or <code>--logfile
* <i>file</i></code> sets the logfile for VISAT to <i>file</i> </ld>
*
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public class SeadasMain implements RuntimeRunnable {
/**
* Entry point for the VISAT application called by the Ceres runtime.
*
* @param argument a {@code String[]} containing the command line arguments
* @param progressMonitor a progress monitor
* @throws Exception if an error occurs
*/
@Override
public void run(Object argument, ProgressMonitor progressMonitor) throws Exception {
String[] args = new String[0];
if (argument instanceof String[]) {
args = (String[]) argument;
}
Locale.setDefault(Locale.UK); // Force usage of British English locale
Lm.verifyLicense("NASA GSFC", "SeaDAS", "HYG8VYydWJkjk8XvjVYl9n0UaYy61tb2");
if (SystemInfo.isMacOSX()) {
if (System.getProperty("com.apple.macos.useScreenMenuBar") == null) {
System.setProperty("com.apple.macos.useScreenMenuBar", "true");
}
if (System.getProperty("apple.laf.useScreenMenuBar") == null) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
}
if (System.getProperty("apple.awt.brushMetalLook") == null) {
System.setProperty("apple.awt.brushMetalLook", "true");
}
}
final ApplicationDescriptor applicationDescriptor = BeamUiActivator.getInstance().getApplicationDescriptor();
if (applicationDescriptor == null) {
throw new IllegalStateException(String.format("Application descriptor not found for applicationId='%s'.",
BeamUiActivator.getInstance().getApplicationId()));
}
boolean debugEnabled = false;
ArrayList<String> productFilepathList = new ArrayList<String>();
String sessionFile = null;
for (String arg : args) {
if (arg.startsWith("-")) {
if (arg.equals("-d") || arg.equals("--debug")) {
debugEnabled = true;
} else {
System.err.printf("%s error: illegal option '" + arg + "'", applicationDescriptor.getDisplayName());
return;
}
} else if (arg.endsWith(OpenSessionAction.getSessionFileFilter().getDefaultExtension())) {
sessionFile = arg;
} else {
productFilepathList.add(arg);
}
}
Debug.setEnabled(debugEnabled);
if (debugEnabled) {
JAI.getDefaultInstance().setImagingListener(new ImagingListener() {
@Override
public boolean errorOccurred(String message, Throwable thrown, Object where, boolean isRetryable) throws RuntimeException {
Debug.trace("JAI Error: " + message);
Debug.trace(thrown);
return false;
}
});
}
SeadasApp app = createApplication(applicationDescriptor);
app.startUp(progressMonitor);
openSession(app, sessionFile);
openProducts(app, productFilepathList);
CommandManager commandManager = app.getApplicationPage().getCommandManager();
Command c = commandManager.getCommand("install_ocssw.py");
- if (isOCSSWExist()) {
- c.setText("Update Processors");
- } else {
- c.setText("Install Processors");
+ if (c != null) {
+ if (isOCSSWExist()) {
+ c.setText("Update Processors");
+ } else {
+ c.setText("Install Processors");
+ }
}
}
private boolean isOCSSWExist() {
String dirPath = RuntimeContext.getConfig().getContextProperty("ocssw.root", System.getenv("OCSSWROOT"));
if (dirPath == null) {
dirPath = RuntimeContext.getConfig().getContextProperty("home", System.getProperty("user.home") + System.getProperty("file.separator") + "ocssw");
}
if (dirPath != null) {
final File dir = new File(dirPath + System.getProperty("file.separator") + "run" + System.getProperty("file.separator") + "scripts");
if (dir.isDirectory()) {
return true;
}
}
return false;
}
protected SeadasApp createApplication(ApplicationDescriptor applicationDescriptor) {
return new SeadasApp(applicationDescriptor);
}
private void openSession(SeadasApp app, String sessionFile) {
if (sessionFile != null && !(sessionFile.trim().isEmpty())) {
final OpenSessionAction action = (OpenSessionAction) app.getCommandManager().getCommand(OpenSessionAction.ID);
action.openSession(app, new File(sessionFile));
}
}
private static void openProducts(SeadasApp app, ArrayList<String> productFilepathList) {
for (String productFilepath : productFilepathList) {
openProduct(app, productFilepath);
}
}
private static void openProduct(final SeadasApp app, final String productFilepath) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
UIUtils.setRootFrameWaitCursor(app.getMainFrame());
try {
openProductImpl(app, productFilepath);
} finally {
UIUtils.setRootFrameDefaultCursor(app.getMainFrame());
}
}
});
}
private static void openProductImpl(SeadasApp app, final String productFilepath) {
final File productFile = new File(productFilepath);
final Product product;
try {
product = ProductIO.readProduct(productFile);
if (product == null) {
final MessageFormat mf = new MessageFormat("No reader found for data product\n''{0}''."); /*I18N*/
final Object[] args = new Object[]{productFile.getPath()};
showError(app, mf.format(args));
return;
}
} catch (IOException e) {
final MessageFormat mf = new MessageFormat("I/O error while opening file\n{0}:\n{1}"); /*I18N*/
final Object[] args = new Object[]{productFile.getPath(), e.getMessage()};
showError(app, mf.format(args));
return;
}
app.addProduct(product);
}
private static void showError(BasicApp app, final String message) {
JOptionPane.showMessageDialog(null,
message,
app.getAppName(),
JOptionPane.ERROR_MESSAGE);
}
}
| true | true | public void run(Object argument, ProgressMonitor progressMonitor) throws Exception {
String[] args = new String[0];
if (argument instanceof String[]) {
args = (String[]) argument;
}
Locale.setDefault(Locale.UK); // Force usage of British English locale
Lm.verifyLicense("NASA GSFC", "SeaDAS", "HYG8VYydWJkjk8XvjVYl9n0UaYy61tb2");
if (SystemInfo.isMacOSX()) {
if (System.getProperty("com.apple.macos.useScreenMenuBar") == null) {
System.setProperty("com.apple.macos.useScreenMenuBar", "true");
}
if (System.getProperty("apple.laf.useScreenMenuBar") == null) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
}
if (System.getProperty("apple.awt.brushMetalLook") == null) {
System.setProperty("apple.awt.brushMetalLook", "true");
}
}
final ApplicationDescriptor applicationDescriptor = BeamUiActivator.getInstance().getApplicationDescriptor();
if (applicationDescriptor == null) {
throw new IllegalStateException(String.format("Application descriptor not found for applicationId='%s'.",
BeamUiActivator.getInstance().getApplicationId()));
}
boolean debugEnabled = false;
ArrayList<String> productFilepathList = new ArrayList<String>();
String sessionFile = null;
for (String arg : args) {
if (arg.startsWith("-")) {
if (arg.equals("-d") || arg.equals("--debug")) {
debugEnabled = true;
} else {
System.err.printf("%s error: illegal option '" + arg + "'", applicationDescriptor.getDisplayName());
return;
}
} else if (arg.endsWith(OpenSessionAction.getSessionFileFilter().getDefaultExtension())) {
sessionFile = arg;
} else {
productFilepathList.add(arg);
}
}
Debug.setEnabled(debugEnabled);
if (debugEnabled) {
JAI.getDefaultInstance().setImagingListener(new ImagingListener() {
@Override
public boolean errorOccurred(String message, Throwable thrown, Object where, boolean isRetryable) throws RuntimeException {
Debug.trace("JAI Error: " + message);
Debug.trace(thrown);
return false;
}
});
}
SeadasApp app = createApplication(applicationDescriptor);
app.startUp(progressMonitor);
openSession(app, sessionFile);
openProducts(app, productFilepathList);
CommandManager commandManager = app.getApplicationPage().getCommandManager();
Command c = commandManager.getCommand("install_ocssw.py");
if (isOCSSWExist()) {
c.setText("Update Processors");
} else {
c.setText("Install Processors");
}
}
| public void run(Object argument, ProgressMonitor progressMonitor) throws Exception {
String[] args = new String[0];
if (argument instanceof String[]) {
args = (String[]) argument;
}
Locale.setDefault(Locale.UK); // Force usage of British English locale
Lm.verifyLicense("NASA GSFC", "SeaDAS", "HYG8VYydWJkjk8XvjVYl9n0UaYy61tb2");
if (SystemInfo.isMacOSX()) {
if (System.getProperty("com.apple.macos.useScreenMenuBar") == null) {
System.setProperty("com.apple.macos.useScreenMenuBar", "true");
}
if (System.getProperty("apple.laf.useScreenMenuBar") == null) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
}
if (System.getProperty("apple.awt.brushMetalLook") == null) {
System.setProperty("apple.awt.brushMetalLook", "true");
}
}
final ApplicationDescriptor applicationDescriptor = BeamUiActivator.getInstance().getApplicationDescriptor();
if (applicationDescriptor == null) {
throw new IllegalStateException(String.format("Application descriptor not found for applicationId='%s'.",
BeamUiActivator.getInstance().getApplicationId()));
}
boolean debugEnabled = false;
ArrayList<String> productFilepathList = new ArrayList<String>();
String sessionFile = null;
for (String arg : args) {
if (arg.startsWith("-")) {
if (arg.equals("-d") || arg.equals("--debug")) {
debugEnabled = true;
} else {
System.err.printf("%s error: illegal option '" + arg + "'", applicationDescriptor.getDisplayName());
return;
}
} else if (arg.endsWith(OpenSessionAction.getSessionFileFilter().getDefaultExtension())) {
sessionFile = arg;
} else {
productFilepathList.add(arg);
}
}
Debug.setEnabled(debugEnabled);
if (debugEnabled) {
JAI.getDefaultInstance().setImagingListener(new ImagingListener() {
@Override
public boolean errorOccurred(String message, Throwable thrown, Object where, boolean isRetryable) throws RuntimeException {
Debug.trace("JAI Error: " + message);
Debug.trace(thrown);
return false;
}
});
}
SeadasApp app = createApplication(applicationDescriptor);
app.startUp(progressMonitor);
openSession(app, sessionFile);
openProducts(app, productFilepathList);
CommandManager commandManager = app.getApplicationPage().getCommandManager();
Command c = commandManager.getCommand("install_ocssw.py");
if (c != null) {
if (isOCSSWExist()) {
c.setText("Update Processors");
} else {
c.setText("Install Processors");
}
}
}
|
diff --git a/services/movement/client/src/test/java/org/collectionspace/services/client/test/MovementSortByTest.java b/services/movement/client/src/test/java/org/collectionspace/services/client/test/MovementSortByTest.java
index 7ccb94382..5e844ec3b 100644
--- a/services/movement/client/src/test/java/org/collectionspace/services/client/test/MovementSortByTest.java
+++ b/services/movement/client/src/test/java/org/collectionspace/services/client/test/MovementSortByTest.java
@@ -1,796 +1,796 @@
/**
* This document is a part of the source code and related artifacts
* for CollectionSpace, an open source collections management system
* for museums and related institutions:
*
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
* Copyright © 2009 Regents of the University of California
*
* Licensed under the Educational Community License (ECL), Version 2.0.
* You may not use this file except in compliance with this License.
*
* You may obtain a copy of the ECL 2.0 License at
* https://source.collectionspace.org/collection-space/LICENSE.txt
*
* 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.collectionspace.services.client.test;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.collectionspace.services.MovementJAXBSchema;
import org.collectionspace.services.client.CollectionSpaceClient;
import org.collectionspace.services.client.MovementClient;
import org.collectionspace.services.movement.MovementsCommon;
import org.collectionspace.services.movement.MovementsCommonList;
import org.collectionspace.services.jaxb.AbstractCommonList;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* MovementSortByTest, tests sorting of summary lists by fields
* of various datatypes.
*
* $LastChangedRevision: 2562 $
* $LastChangedDate: 2010-06-22 23:26:51 -0700 (Tue, 22 Jun 2010) $
*/
public class MovementSortByTest extends BaseServiceTest {
private final String CLASS_NAME = MovementSortByTest.class.getName();
private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
// Instance variables specific to this test.
private final String DELIMITER_SCHEMA_AND_FIELD = ":";
private final String KEYWORD_DESCENDING_SEARCH = "DESC";
private final String SERVICE_PATH_COMPONENT = "movements";
private final String TEST_SPECIFIC_KEYWORD = "msotebstpfscn";
private List<String> movementIdsCreated = new ArrayList<String>();
private final String SORT_FIELD_SEPARATOR = ", ";
/* (non-Javadoc)
* @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
*/
@Override
protected CollectionSpaceClient getClientInstance() {
throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
}
/* (non-Javadoc)
* @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
*/
@Override
protected AbstractCommonList getAbstractCommonList(
ClientResponse<AbstractCommonList> response) {
throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
}
// ---------------------------------------------------------------
// Sort tests
// ---------------------------------------------------------------
// Success outcomes
/*
* Tests whether a list of records, sorted by a String field in
* ascending order, is returned in the expected order.
*/
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
dependsOnMethods = {"createList"})
public void sortByStringFieldAscending(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
String sortFieldName = qualifySortFieldName(MovementJAXBSchema.MOVEMENT_NOTE);
if (logger.isDebugEnabled()) {
logger.debug("Sorting on field name=" + sortFieldName);
}
MovementsCommonList list = readSortedList(sortFieldName);
List<MovementsCommonList.MovementListItem> items =
list.getMovementListItem();
ArrayList<String> values = new ArrayList<String>();
Collator usEnglishCollator = Collator.getInstance(Locale.US);
int i = 0;
for (MovementsCommonList.MovementListItem item : items) {
// Because movementNote is not currently a summary field
// (returned in summary list items), we will need to verify
// sort order by retrieving full records, using the
// IDs provided in the summary list items. amd then retriving
// the value of that field from each of those records.
MovementsCommon movement = read(item.getCsid());
values.add(i, movement.getMovementNote());
if (logger.isDebugEnabled()) {
logger.debug("list-item[" + i + "] movementNote=" + values.get(i));
}
// Verify that the value of the specified field in the current record
// is equal to or greater than its value in the previous record,
// using a locale-specific collator.
//
// (Note: when used with certain text, this test case could potentially
// reflect inconsistencies, if any, between Java's collator and the
// collator used for ordering by the database. To help avoid this,
// it might be useful to keep test strings fairly generic.)
if (i > 0 && values.get(i) != null && values.get(i - 1) != null) {
Assert.assertTrue(usEnglishCollator.compare(values.get(i), values.get(i - 1)) >= 0);
}
i++;
}
}
/*
* Tests whether a list of records, obtained by a keyword search, and
* sorted by a String field in ascending order, is returned in the expected order.
*
* This verifies that summary list results from keyword searches, in
* addition to 'read list' requests, can be returned in sorted order.
*/
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
dependsOnMethods = {"createList"})
public void sortKeywordSearchResultsByStringFieldAscending(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
String sortFieldName = qualifySortFieldName(MovementJAXBSchema.MOVEMENT_NOTE);
if (logger.isDebugEnabled()) {
logger.debug("Sorting on field name=" + sortFieldName);
}
MovementsCommonList list = keywordSearchSortedBy(TEST_SPECIFIC_KEYWORD, sortFieldName);
List<MovementsCommonList.MovementListItem> items =
list.getMovementListItem();
ArrayList<String> values = new ArrayList<String>();
Collator usEnglishCollator = Collator.getInstance(Locale.US);
int i = 0;
for (MovementsCommonList.MovementListItem item : items) {
// Because movementNote is not currently a summary field
// (returned in summary list items), we will need to verify
// sort order by retrieving full records, using the
// IDs provided in the summary list items. amd then retriving
// the value of that field from each of those records.
MovementsCommon movement = read(item.getCsid());
values.add(i, movement.getMovementNote());
if (logger.isDebugEnabled()) {
logger.debug("list-item[" + i + "] movementNote=" + values.get(i));
}
// Verify that the value of the specified field in the current record
// is equal to or greater than its value in the previous record,
// using a locale-specific collator.
//
// (Note: when used with certain text, this test case could potentially
// reflect inconsistencies, if any, between Java's collator and the
// collator used for ordering by the database. To help avoid this,
// it might be useful to keep test strings fairly generic.)
if (i > 0 && values.get(i) != null && values.get(i - 1) != null) {
Assert.assertTrue(usEnglishCollator.compare(values.get(i), values.get(i - 1)) >= 0);
}
i++;
}
}
/*
* Tests whether a list of records, sorted by a String field in
* descending order, is returned in the expected order.
*/
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
dependsOnMethods = {"createList"})
public void sortByStringFieldDescending(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
String sortFieldName =
asDescendingSort(qualifySortFieldName(MovementJAXBSchema.MOVEMENT_NOTE));
if (logger.isDebugEnabled()) {
logger.debug("Sorting on field name=" + sortFieldName);
}
MovementsCommonList list = readSortedList(sortFieldName);
List<MovementsCommonList.MovementListItem> items =
list.getMovementListItem();
ArrayList<String> values = new ArrayList<String>();
Collator usEnglishCollator = Collator.getInstance(Locale.US);
int i = 0;
for (MovementsCommonList.MovementListItem item : items) {
// Because movementNote is not currently a summary field
// (returned in summary list items), we will need to verify
// sort order by retrieving full records, using the
// IDs provided in the summary list items. amd then retriving
// the value of that field from each of those records.
MovementsCommon movement = read(item.getCsid());
values.add(i, movement.getMovementNote());
if (logger.isDebugEnabled()) {
logger.debug("list-item[" + i + "] movementNote=" + values.get(i));
}
// Verify that the value of the specified field in the current record
// is less than or equal to than its value in the previous record,
// using a locale-specific collator.
//
// (Note: when used with certain text, this test case could potentially
// reflect inconsistencies, if any, between Java's collator and the
// collator used for ordering by the database. To help avoid this,
// it might be useful to keep test strings fairly generic.)
if (i > 0 && values.get(i) != null && values.get(i - 1) != null) {
Assert.assertTrue(usEnglishCollator.compare(values.get(i), values.get(i - 1)) <= 0);
}
i++;
}
}
/*
* Tests whether a list of records, sorted by a dateTime field in
* ascending order, is returned in the expected order.
*/
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
dependsOnMethods = {"createList"})
public void sortByDateTimeFieldAscending(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
String sortFieldName = qualifySortFieldName(MovementJAXBSchema.LOCATION_DATE);
if (logger.isDebugEnabled()) {
logger.debug("Sorting on field name=" + sortFieldName);
}
MovementsCommonList list = readSortedList(sortFieldName);
List<MovementsCommonList.MovementListItem> items =
list.getMovementListItem();
ArrayList<String> values = new ArrayList<String>();
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
int i = 0;
for (MovementsCommonList.MovementListItem item : items) {
values.add(i, item.getLocationDate());
if (logger.isDebugEnabled()) {
logger.debug("list-item[" + i + "] locationDate=" + values.get(i));
}
// Verify that the value of the specified field in the current record
// is equal to or greater than its value in the previous record.
if (i > 0 && values.get(i) != null && values.get(i - 1) != null) {
Assert.assertTrue(comparator.compare(values.get(i), values.get(i - 1)) >= 0);
}
i++;
}
}
/*
* Tests whether a list of records, sorted by a dateTime field in
* descending order, is returned in the expected order.
*/
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
dependsOnMethods = {"createList"})
public void sortByDateTimeFieldDescending(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
String sortFieldName =
asDescendingSort(qualifySortFieldName(MovementJAXBSchema.LOCATION_DATE));
if (logger.isDebugEnabled()) {
logger.debug("Sorting on field name=" + sortFieldName);
}
MovementsCommonList list = readSortedList(sortFieldName);
List<MovementsCommonList.MovementListItem> items =
list.getMovementListItem();
ArrayList<String> values = new ArrayList<String>();
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
int i = 0;
for (MovementsCommonList.MovementListItem item : items) {
values.add(i, item.getLocationDate());
if (logger.isDebugEnabled()) {
logger.debug("list-item[" + i + "] locationDate=" + values.get(i));
}
// Verify that the value of the specified field in the current record
// is less than or equal to its value in the previous record.
if (i > 0 && values.get(i) != null && values.get(i - 1) != null) {
Assert.assertTrue(comparator.compare(values.get(i), values.get(i - 1)) <= 0);
}
i++;
}
}
/*
* Tests whether a list of records, sorted by two different fields in
* ascending order, is returned in the expected order.
*/
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
dependsOnMethods = {"createList"})
public void sortByTwoFieldsAscending(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
String firstSortFieldName = qualifySortFieldName(MovementJAXBSchema.MOVEMENT_NOTE);
String secondSortFieldName = qualifySortFieldName(MovementJAXBSchema.LOCATION_DATE);
if (logger.isDebugEnabled()) {
logger.debug("Sorting on field names=" + firstSortFieldName + " and " + secondSortFieldName);
}
String sortExpression = firstSortFieldName + SORT_FIELD_SEPARATOR + secondSortFieldName;
MovementsCommonList list = readSortedList(sortExpression);
List<MovementsCommonList.MovementListItem> items =
list.getMovementListItem();
ArrayList<String> firstFieldValues = new ArrayList<String>();
ArrayList<String> secondFieldValues = new ArrayList<String>();
Collator usEnglishCollator = Collator.getInstance(Locale.US);
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
int i = 0;
for (MovementsCommonList.MovementListItem item : items) {
// Because movementNote is not currently a summary field
// (returned in summary list items), we will need to verify
// sort order by retrieving full records, using the
// IDs provided in the summary list items. amd then retriving
// the value of that field from each of those records.
MovementsCommon movement = read(item.getCsid());
firstFieldValues.add(i, movement.getMovementNote());
secondFieldValues.add(i, movement.getLocationDate());
if (logger.isDebugEnabled()) {
logger.debug("list-item[" + i + "] movementNote=" + firstFieldValues.get(i));
logger.debug("list-item[" + i + "] locationDate=" + secondFieldValues.get(i));
}
// Verify that the value of the specified field in the current record
// is less than or greater than its value in the previous record.
if (i > 0 && firstFieldValues.get(i) != null && firstFieldValues.get(i - 1) != null) {
Assert.assertTrue(usEnglishCollator.compare(firstFieldValues.get(i), firstFieldValues.get(i - 1)) >= 0);
// If the value of the first sort field in the current record is identical to
// its value in the previous record, verify that the value of the second sort
// field is equal to or greater than its value in the previous record,
// using a locale-specific collator.
if (usEnglishCollator.compare(firstFieldValues.get(i), firstFieldValues.get(i - 1)) == 0) {
if (i > 0 && secondFieldValues.get(i) != null && secondFieldValues.get(i - 1) != null) {
Assert.assertTrue(comparator.compare(secondFieldValues.get(i), secondFieldValues.get(i - 1)) >= 0);
}
}
}
i++;
}
}
/*
* Tests whether a list of records, sorted by one different fields in
* descending order and a second field in ascending order, is returned in the expected order.
*/
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
dependsOnMethods = {"createList"})
public void sortByOneFieldAscendingOneFieldsDescending(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
String firstSortFieldName =
asDescendingSort(qualifySortFieldName(MovementJAXBSchema.LOCATION_DATE));
String secondSortFieldName = qualifySortFieldName(MovementJAXBSchema.MOVEMENT_NOTE);
if (logger.isDebugEnabled()) {
logger.debug("Sorting on field names=" + firstSortFieldName + " and " + secondSortFieldName);
}
String sortExpression = firstSortFieldName + SORT_FIELD_SEPARATOR + secondSortFieldName;
MovementsCommonList list = readSortedList(sortExpression);
List<MovementsCommonList.MovementListItem> items =
list.getMovementListItem();
ArrayList<String> firstFieldValues = new ArrayList<String>();
ArrayList<String> secondFieldValues = new ArrayList<String>();
Collator usEnglishCollator = Collator.getInstance(Locale.US);
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
int i = 0;
for (MovementsCommonList.MovementListItem item : items) {
// Because movementNote is not currently a summary field
// (returned in summary list items), we will need to verify
// sort order by retrieving full records, using the
// IDs provided in the summary list items. amd then retriving
// the value of that field from each of those records.
MovementsCommon movement = read(item.getCsid());
firstFieldValues.add(i, movement.getLocationDate());
secondFieldValues.add(i, movement.getMovementNote());
if (logger.isDebugEnabled()) {
logger.debug("list-item[" + i + "] locationDate=" + firstFieldValues.get(i));
logger.debug("list-item[" + i + "] movementNote=" + secondFieldValues.get(i));
}
// Verify that the value of the specified field in the current record
- // is less than or greater than its value in the previous record.
+ // is less than or equal to than its value in the previous record.
if (i > 0 && firstFieldValues.get(i) != null && firstFieldValues.get(i - 1) != null) {
Assert.assertTrue(comparator.compare(firstFieldValues.get(i), firstFieldValues.get(i - 1)) <= 0);
// If the value of the first sort field in the current record is identical to
// its value in the previous record, verify that the value of the second sort
// field is equal to or greater than its value in the previous record,
// using a locale-specific collator.
if (comparator.compare(firstFieldValues.get(i), firstFieldValues.get(i - 1)) == 0) {
if (i > 0 && secondFieldValues.get(i) != null && secondFieldValues.get(i - 1) != null) {
Assert.assertTrue(usEnglishCollator.compare(secondFieldValues.get(i), secondFieldValues.get(i - 1)) >= 0);
}
}
}
i++;
}
}
/*
* Tests whether a request to sort by an empty field name is handled
* as expected: the query parameter is simply ignored, and a list
* of records is returned, unsorted, with a success result.
*/
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
public void sortWithEmptySortFieldName(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
testSetup(STATUS_OK, ServiceRequestType.READ);
// Submit the request to the service and store the response.
MovementClient client = new MovementClient();
final String EMPTY_SORT_FIELD_NAME = "";
ClientResponse<MovementsCommonList> res =
client.readListSortedBy(EMPTY_SORT_FIELD_NAME);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if (logger.isDebugEnabled()) {
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// Failure outcomes
/*
* Tests whether a request to sort by an unqualified field name is
* handled as expected. The field name provided in this test is valid,
* but has not been qualified by being prefixed by a schema name and delimiter.
*/
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
public void sortWithUnqualifiedFieldName(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
// FIXME: Ultimately, this should return a BAD_REQUEST status.
testSetup(STATUS_INTERNAL_SERVER_ERROR, ServiceRequestType.READ);
// Submit the request to the service and store the response.
MovementClient client = new MovementClient();
ClientResponse<MovementsCommonList> res =
client.readListSortedBy(MovementJAXBSchema.LOCATION_DATE);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if (logger.isDebugEnabled()) {
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
/*
* Tests whether a request to sort by an invalid identifier for the
* sort order (ascending or descending) is handled as expected.
*/
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
public void sortWithInvalidSortOrderIdentifier(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
// FIXME: Ultimately, this should return a BAD_REQUEST status.
testSetup(STATUS_INTERNAL_SERVER_ERROR, ServiceRequestType.READ);
// Submit the request to the service and store the response.
MovementClient client = new MovementClient();
final String INVALID_SORT_ORDER_IDENTIFIER = "NO_DIRECTION";
ClientResponse<MovementsCommonList> res =
client.readListSortedBy(MovementJAXBSchema.LOCATION_DATE
+ " " + INVALID_SORT_ORDER_IDENTIFIER);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if (logger.isDebugEnabled()) {
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
/*
* Tests whether a request to sort by a malformed field name is
* handled as expected.
*/
/*
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
public void sortWithMalformedFieldName(String testName) throws Exception {
// FIXME: Implement this stub method.
// FIXME: Consider splitting this test into various tests, with
// different malformed field name formats that might confuse parsers
// and/or validation code.
// FIXME: Consider fixing DocumentFilter.setSortOrder() to return
// an error response to this test case, then revise this test case
// to expect that response.
}
*/
// ---------------------------------------------------------------
// Cleanup of resources created during testing
// ---------------------------------------------------------------
/**
* Deletes all resources created by tests, after all tests have been run.
*
* This cleanup method will always be run, even if one or more tests fail.
* For this reason, it attempts to remove all resources created
* at any point during testing, even if some of those resources
* may be expected to be deleted by certain tests.
*/
@AfterClass(alwaysRun = true)
public void cleanUp() {
String noTest = System.getProperty("noTestCleanup");
if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping Cleanup phase ...");
}
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Cleaning up temporary resources created for testing ...");
}
// Delete all Movement resource(s) created during this test.
MovementClient movementClient = new MovementClient();
for (String resourceId : movementIdsCreated) {
// Note: Any non-success responses are ignored and not reported.
movementClient.delete(resourceId);
}
}
// ---------------------------------------------------------------
// Utility methods used by tests above
// ---------------------------------------------------------------
@Override
public String getServicePathComponent() {
return SERVICE_PATH_COMPONENT;
}
private String getCommonSchemaName() {
// FIXME: While this convention - appending a suffix to the name of
// the service's first unique URL path component - works, it would
// be preferable to get the common schema name from configuration.
//
// Such configuration is provided for example, on the services side, in
// org.collectionspace.services.common.context.AbstractServiceContextImpl
return getServicePathComponent() + "_" + "common";
}
public String qualifySortFieldName(String fieldName) {
return getCommonSchemaName() + DELIMITER_SCHEMA_AND_FIELD + fieldName;
}
public String asDescendingSort(String qualifiedFieldName) {
return qualifiedFieldName + " " + KEYWORD_DESCENDING_SEARCH;
}
/*
* A data provider that provides a set of unsorted values, which are
* to be used in populating (seeding) values in test records.
*
* Data elements provided for each test record consist of:
* * An integer, reflecting expected sort order.
* * US English text, to populate the value of a free text (String) field.
* * An ISO 8601 timestamp, to populate the value of a calendar date (dateTime) field.
*/
@DataProvider(name = "unsortedValues")
public Object[][] unsortedValues() {
// Add a test record-specific string so we have the option of
// constraining tests to only test records, in list or search results.
final String TEST_RECORD_SPECIFIC_STRING = CLASS_NAME + " " + TEST_SPECIFIC_KEYWORD;
return new Object[][]{
{1, "Aardvark and plumeria. " + TEST_RECORD_SPECIFIC_STRING, "2009-01-29T00:00:05Z"},
{10, "Zounds! " + TEST_RECORD_SPECIFIC_STRING, "2010-08-31T00:00:00Z"},
{3, "Aardvark and plumeria. " + TEST_RECORD_SPECIFIC_STRING, "2010-08-30T00:00:00Z"},
{7, "Bat fling off wall. " + TEST_RECORD_SPECIFIC_STRING, "2010-08-30T00:00:00Z"},
{4, "Aardvarks and plumeria. " + TEST_RECORD_SPECIFIC_STRING, "2009-01-29T08:00:00Z"},
{5, "Aardvarks and plumeria. " + TEST_RECORD_SPECIFIC_STRING, "2009-05-29T00:00:00Z"},
{2, "Aardvark and plumeria. " + TEST_RECORD_SPECIFIC_STRING, "2009-05-29T00:00:00Z"},
{9, "Zounds! " + TEST_RECORD_SPECIFIC_STRING, "2009-05-29T00:00:00Z"}, // Identical to next record
{8, "Zounds! " + TEST_RECORD_SPECIFIC_STRING, "2009-05-29T00:00:00Z"},
{6, "Bat flies off ball. " + TEST_RECORD_SPECIFIC_STRING, "2009-05-29T00:00:00Z"}
};
}
/*
* Create multiple test records, initially in unsorted order,
* using values for various fields obtained from the data provider.
*/
@Test(dataProvider = "unsortedValues")
public void createList(int expectedSortOrder, String movementNote,
String locationDate) throws Exception {
String testName = "createList";
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
// Iterates through the sets of values returned by the data provider,
// and creates a corresponding test record for each set of values.
create(movementNote, locationDate);
}
private void create(String movementNote, String locationDate) throws Exception {
String testName = "create";
testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
// Submit the request to the service and store the response.
MovementClient client = new MovementClient();
MultipartOutput multipart = createMovementInstance(createIdentifier(),
movementNote, locationDate);
ClientResponse<Response> res = client.create(multipart);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
//
// Specifically:
// Does it fall within the set of valid status codes?
// Does it exactly match the expected status code?
if (logger.isDebugEnabled()) {
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
// Store the IDs from every resource created by tests,
// so they can be deleted after tests have been run.
movementIdsCreated.add(extractId(res));
}
private MovementsCommon read(String csid) throws Exception {
String testName = "read";
testSetup(STATUS_OK, ServiceRequestType.READ);
// Submit the request to the service and store the response.
MovementClient client = new MovementClient();
ClientResponse<MultipartInput> res = client.read(csid);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if (logger.isDebugEnabled()) {
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
// Extract and return the common part of the record.
MultipartInput input = (MultipartInput) res.getEntity();
MovementsCommon movement = (MovementsCommon) extractPart(input,
client.getCommonPartName(), MovementsCommon.class);
return movement;
}
private MultipartOutput createMovementInstance(
String movementReferenceNumber,
String movementNote,
String locationDate) {
MovementsCommon movement = new MovementsCommon();
movement.setMovementReferenceNumber(movementReferenceNumber);
movement.setMovementNote(movementNote);
movement.setLocationDate(locationDate);
MultipartOutput multipart = new MultipartOutput();
OutputPart commonPart =
multipart.addPart(movement, MediaType.APPLICATION_XML_TYPE);
commonPart.getHeaders().add("label", new MovementClient().getCommonPartName());
if (logger.isDebugEnabled()) {
logger.debug("to be created, movement common");
logger.debug(objectAsXmlString(movement, MovementsCommon.class));
}
return multipart;
}
private MovementsCommonList readSortedList(String sortFieldName) throws Exception {
String testName = "readSortedList";
testSetup(STATUS_OK, ServiceRequestType.READ);
// Submit the request to the service and store the response.
MovementClient client = new MovementClient();
ClientResponse<MovementsCommonList> res =
client.readListSortedBy(sortFieldName);
MovementsCommonList list = res.getEntity();
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if (logger.isDebugEnabled()) {
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
return list;
}
private MovementsCommonList keywordSearchSortedBy(String keywords,
String sortFieldName) throws Exception {
String testName = "keywordSearchSortedBy";
testSetup(STATUS_OK, ServiceRequestType.READ);
// Submit the request to the service and store the response.
MovementClient client = new MovementClient();
ClientResponse<MovementsCommonList> res =
client.keywordSearchSortedBy(keywords, sortFieldName);
MovementsCommonList list = res.getEntity();
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if (logger.isDebugEnabled()) {
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
return list;
}
}
| true | true | public void sortByOneFieldAscendingOneFieldsDescending(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
String firstSortFieldName =
asDescendingSort(qualifySortFieldName(MovementJAXBSchema.LOCATION_DATE));
String secondSortFieldName = qualifySortFieldName(MovementJAXBSchema.MOVEMENT_NOTE);
if (logger.isDebugEnabled()) {
logger.debug("Sorting on field names=" + firstSortFieldName + " and " + secondSortFieldName);
}
String sortExpression = firstSortFieldName + SORT_FIELD_SEPARATOR + secondSortFieldName;
MovementsCommonList list = readSortedList(sortExpression);
List<MovementsCommonList.MovementListItem> items =
list.getMovementListItem();
ArrayList<String> firstFieldValues = new ArrayList<String>();
ArrayList<String> secondFieldValues = new ArrayList<String>();
Collator usEnglishCollator = Collator.getInstance(Locale.US);
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
int i = 0;
for (MovementsCommonList.MovementListItem item : items) {
// Because movementNote is not currently a summary field
// (returned in summary list items), we will need to verify
// sort order by retrieving full records, using the
// IDs provided in the summary list items. amd then retriving
// the value of that field from each of those records.
MovementsCommon movement = read(item.getCsid());
firstFieldValues.add(i, movement.getLocationDate());
secondFieldValues.add(i, movement.getMovementNote());
if (logger.isDebugEnabled()) {
logger.debug("list-item[" + i + "] locationDate=" + firstFieldValues.get(i));
logger.debug("list-item[" + i + "] movementNote=" + secondFieldValues.get(i));
}
// Verify that the value of the specified field in the current record
// is less than or greater than its value in the previous record.
if (i > 0 && firstFieldValues.get(i) != null && firstFieldValues.get(i - 1) != null) {
Assert.assertTrue(comparator.compare(firstFieldValues.get(i), firstFieldValues.get(i - 1)) <= 0);
// If the value of the first sort field in the current record is identical to
// its value in the previous record, verify that the value of the second sort
// field is equal to or greater than its value in the previous record,
// using a locale-specific collator.
if (comparator.compare(firstFieldValues.get(i), firstFieldValues.get(i - 1)) == 0) {
if (i > 0 && secondFieldValues.get(i) != null && secondFieldValues.get(i - 1) != null) {
Assert.assertTrue(usEnglishCollator.compare(secondFieldValues.get(i), secondFieldValues.get(i - 1)) >= 0);
}
}
}
i++;
}
}
| public void sortByOneFieldAscendingOneFieldsDescending(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
String firstSortFieldName =
asDescendingSort(qualifySortFieldName(MovementJAXBSchema.LOCATION_DATE));
String secondSortFieldName = qualifySortFieldName(MovementJAXBSchema.MOVEMENT_NOTE);
if (logger.isDebugEnabled()) {
logger.debug("Sorting on field names=" + firstSortFieldName + " and " + secondSortFieldName);
}
String sortExpression = firstSortFieldName + SORT_FIELD_SEPARATOR + secondSortFieldName;
MovementsCommonList list = readSortedList(sortExpression);
List<MovementsCommonList.MovementListItem> items =
list.getMovementListItem();
ArrayList<String> firstFieldValues = new ArrayList<String>();
ArrayList<String> secondFieldValues = new ArrayList<String>();
Collator usEnglishCollator = Collator.getInstance(Locale.US);
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
int i = 0;
for (MovementsCommonList.MovementListItem item : items) {
// Because movementNote is not currently a summary field
// (returned in summary list items), we will need to verify
// sort order by retrieving full records, using the
// IDs provided in the summary list items. amd then retriving
// the value of that field from each of those records.
MovementsCommon movement = read(item.getCsid());
firstFieldValues.add(i, movement.getLocationDate());
secondFieldValues.add(i, movement.getMovementNote());
if (logger.isDebugEnabled()) {
logger.debug("list-item[" + i + "] locationDate=" + firstFieldValues.get(i));
logger.debug("list-item[" + i + "] movementNote=" + secondFieldValues.get(i));
}
// Verify that the value of the specified field in the current record
// is less than or equal to than its value in the previous record.
if (i > 0 && firstFieldValues.get(i) != null && firstFieldValues.get(i - 1) != null) {
Assert.assertTrue(comparator.compare(firstFieldValues.get(i), firstFieldValues.get(i - 1)) <= 0);
// If the value of the first sort field in the current record is identical to
// its value in the previous record, verify that the value of the second sort
// field is equal to or greater than its value in the previous record,
// using a locale-specific collator.
if (comparator.compare(firstFieldValues.get(i), firstFieldValues.get(i - 1)) == 0) {
if (i > 0 && secondFieldValues.get(i) != null && secondFieldValues.get(i - 1) != null) {
Assert.assertTrue(usEnglishCollator.compare(secondFieldValues.get(i), secondFieldValues.get(i - 1)) >= 0);
}
}
}
i++;
}
}
|
diff --git a/DistributedInvoke/src/main/java/com/joelj/distributedinvoke/RemoteMachineListener.java b/DistributedInvoke/src/main/java/com/joelj/distributedinvoke/RemoteMachineListener.java
index 92955e5..eb65bc0 100644
--- a/DistributedInvoke/src/main/java/com/joelj/distributedinvoke/RemoteMachineListener.java
+++ b/DistributedInvoke/src/main/java/com/joelj/distributedinvoke/RemoteMachineListener.java
@@ -1,155 +1,156 @@
package com.joelj.distributedinvoke;
import com.joelj.distributedinvoke.channels.ServerSocketRemoteChannel;
import com.joelj.distributedinvoke.logging.Logger;
import com.joelj.ezasync.EzAsync;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.net.InetAddress;
import java.util.concurrent.Callable;
/**
* User: Joel Johnson
* Date: 3/2/13
* Time: 12:36 AM
*/
public class RemoteMachineListener implements Closeable {
private static final Logger LOGGER = Logger.forClass(RemoteMachineListener.class);
private final InetAddress bindAddress;
private final int listeningPort;
private final transient Thread thread;
private final transient EzAsync ezAsync;
/**
* Creates the listener and starts listening.
* @param bindAddress The address to bind to.
* @param listeningPort The port to listen on.
* @return The new instance of RemoteMachineListener that is actively listening for a new connection.
*/
public static RemoteMachineListener start(@NotNull InetAddress bindAddress, int listeningPort) {
return new RemoteMachineListener(bindAddress, listeningPort);
}
/**
* @param bindAddress The address to bind to.
* @param listeningPort Must be between 1 and 65535. On some operating systems, if the value is between 1 and 1024 the underlying JVM may need special privileges to open the socket.
*/
private RemoteMachineListener(@NotNull InetAddress bindAddress, int listeningPort) {
this.bindAddress = bindAddress;
this.listeningPort = listeningPort;
thread = new Thread(new ListeningThread(), this.getClass().getSimpleName());
thread.start();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
close();
}
}));
ezAsync = EzAsync.create();
}
@Override
public void close() {
thread.interrupt();
}
private class ListeningThread implements Runnable {
@Override
public void run() {
ServerSocketRemoteChannel channel;
try {
channel = ServerSocketRemoteChannel.create(listeningPort, bindAddress);
} catch (IOException e) {
throw new RuntimeException(e);
}
while(!Thread.interrupted() && !channel.isClosed()) {
ObjectInputStream inputStream;
try {
inputStream = channel.getInputStream();
} catch (InterruptedException e) {
- throw new RuntimeException(e); //TODO: handle exception
+ LOGGER.error("Thread interrupted while obtaining the input stream. Attempting clean shutdown.");
+ break;
} catch (IOException e) {
- throw new RuntimeException(e); //TODO: handle exception
+ throw new RuntimeException(e);
}
Object object;
try {
LOGGER.info("Waiting for request");
object = inputStream.readObject();
LOGGER.info("Received request");
} catch (IOException e) {
LOGGER.error(e);
continue;
} catch (ClassNotFoundException e) {
LOGGER.error("Class path is out of sync", e);
continue;
}
if(object != null && object instanceof Transport) {
Transport transport = (Transport)object;
String requestId = transport.getId();
Object requestObject = transport.getObject();
if(requestObject instanceof Callable) {
LOGGER.info("Scheduling request to be executed");
//noinspection unchecked
ezAsync.execute((Callable) requestObject, new RequestCallback(requestId, channel));
LOGGER.info("Request execution scheduled");
} else {
LOGGER.error("Unexpected object type. Expected " + Callable.class.getCanonicalName() + " but was " + (requestObject == null ? "null" : requestObject.getClass().getCanonicalName()));
}
} else {
LOGGER.error("Unexpected object type. Expected " + Transport.class.getCanonicalName() + " but was " + (object == null ? "null" : object.getClass().getCanonicalName()));
}
}
try {
channel.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
- LOGGER.info("Listener shut down.");
+ LOGGER.info("Listener cleanly shut down.");
}
}
private static class RequestCallback implements EzAsync.Callback<String> {
@NotNull
private final String id;
@NotNull
private final ServerSocketRemoteChannel channel;
public RequestCallback(@NotNull String id, @NotNull ServerSocketRemoteChannel channel) {
this.id = id;
this.channel = channel;
}
@Override
public void done(@Nullable String result) {
LOGGER.info("Done executing request and received result");
Transport<?> response = Transport.wrapWithId(result, id);
try {
ObjectOutputStream outputStream = channel.getOutputStream();
LOGGER.info("Writing response");
outputStream.writeObject(response);
} catch (IOException e) {
LOGGER.error("Couldn't write response.", e);
} catch (InterruptedException e) {
LOGGER.error("Thread interrupted. Closing channel.", e);
try {
channel.close();
} catch (IOException closeChannelException) {
LOGGER.error("Error while trying to close channel.", closeChannelException);
}
}
}
}
}
| false | true | public void run() {
ServerSocketRemoteChannel channel;
try {
channel = ServerSocketRemoteChannel.create(listeningPort, bindAddress);
} catch (IOException e) {
throw new RuntimeException(e);
}
while(!Thread.interrupted() && !channel.isClosed()) {
ObjectInputStream inputStream;
try {
inputStream = channel.getInputStream();
} catch (InterruptedException e) {
throw new RuntimeException(e); //TODO: handle exception
} catch (IOException e) {
throw new RuntimeException(e); //TODO: handle exception
}
Object object;
try {
LOGGER.info("Waiting for request");
object = inputStream.readObject();
LOGGER.info("Received request");
} catch (IOException e) {
LOGGER.error(e);
continue;
} catch (ClassNotFoundException e) {
LOGGER.error("Class path is out of sync", e);
continue;
}
if(object != null && object instanceof Transport) {
Transport transport = (Transport)object;
String requestId = transport.getId();
Object requestObject = transport.getObject();
if(requestObject instanceof Callable) {
LOGGER.info("Scheduling request to be executed");
//noinspection unchecked
ezAsync.execute((Callable) requestObject, new RequestCallback(requestId, channel));
LOGGER.info("Request execution scheduled");
} else {
LOGGER.error("Unexpected object type. Expected " + Callable.class.getCanonicalName() + " but was " + (requestObject == null ? "null" : requestObject.getClass().getCanonicalName()));
}
} else {
LOGGER.error("Unexpected object type. Expected " + Transport.class.getCanonicalName() + " but was " + (object == null ? "null" : object.getClass().getCanonicalName()));
}
}
try {
channel.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
LOGGER.info("Listener shut down.");
}
| public void run() {
ServerSocketRemoteChannel channel;
try {
channel = ServerSocketRemoteChannel.create(listeningPort, bindAddress);
} catch (IOException e) {
throw new RuntimeException(e);
}
while(!Thread.interrupted() && !channel.isClosed()) {
ObjectInputStream inputStream;
try {
inputStream = channel.getInputStream();
} catch (InterruptedException e) {
LOGGER.error("Thread interrupted while obtaining the input stream. Attempting clean shutdown.");
break;
} catch (IOException e) {
throw new RuntimeException(e);
}
Object object;
try {
LOGGER.info("Waiting for request");
object = inputStream.readObject();
LOGGER.info("Received request");
} catch (IOException e) {
LOGGER.error(e);
continue;
} catch (ClassNotFoundException e) {
LOGGER.error("Class path is out of sync", e);
continue;
}
if(object != null && object instanceof Transport) {
Transport transport = (Transport)object;
String requestId = transport.getId();
Object requestObject = transport.getObject();
if(requestObject instanceof Callable) {
LOGGER.info("Scheduling request to be executed");
//noinspection unchecked
ezAsync.execute((Callable) requestObject, new RequestCallback(requestId, channel));
LOGGER.info("Request execution scheduled");
} else {
LOGGER.error("Unexpected object type. Expected " + Callable.class.getCanonicalName() + " but was " + (requestObject == null ? "null" : requestObject.getClass().getCanonicalName()));
}
} else {
LOGGER.error("Unexpected object type. Expected " + Transport.class.getCanonicalName() + " but was " + (object == null ? "null" : object.getClass().getCanonicalName()));
}
}
try {
channel.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
LOGGER.info("Listener cleanly shut down.");
}
|
diff --git a/src/main/java/org/jboss/pressgang/ccms/server/rest/v1/CSRelatedNodeV1Factory.java b/src/main/java/org/jboss/pressgang/ccms/server/rest/v1/CSRelatedNodeV1Factory.java
index d98ccb3..a487d92 100644
--- a/src/main/java/org/jboss/pressgang/ccms/server/rest/v1/CSRelatedNodeV1Factory.java
+++ b/src/main/java/org/jboss/pressgang/ccms/server/rest/v1/CSRelatedNodeV1Factory.java
@@ -1,107 +1,108 @@
package org.jboss.pressgang.ccms.server.rest.v1;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import org.jboss.pressgang.ccms.model.contentspec.CSNodeToCSNode;
import org.jboss.pressgang.ccms.rest.v1.collections.contentspec.items.join.RESTCSRelatedNodeCollectionItemV1;
import org.jboss.pressgang.ccms.rest.v1.collections.contentspec.join.RESTCSRelatedNodeCollectionV1;
import org.jboss.pressgang.ccms.rest.v1.collections.join.RESTAssignedPropertyTagCollectionV1;
import org.jboss.pressgang.ccms.rest.v1.constants.RESTv1Constants;
import org.jboss.pressgang.ccms.rest.v1.entities.base.RESTBaseEntityV1;
import org.jboss.pressgang.ccms.rest.v1.entities.contentspec.RESTCSNodeV1;
import org.jboss.pressgang.ccms.rest.v1.entities.contentspec.enums.RESTCSNodeRelationshipTypeV1;
import org.jboss.pressgang.ccms.rest.v1.entities.contentspec.enums.RESTCSNodeTypeV1;
import org.jboss.pressgang.ccms.rest.v1.entities.contentspec.join.RESTCSRelatedNodeV1;
import org.jboss.pressgang.ccms.rest.v1.expansion.ExpandDataTrunk;
import org.jboss.pressgang.ccms.server.rest.v1.base.RESTDataObjectCollectionFactory;
import org.jboss.pressgang.ccms.server.rest.v1.base.RESTDataObjectFactory;
import org.jboss.pressgang.ccms.server.utils.EnversUtilities;
@ApplicationScoped
public class CSRelatedNodeV1Factory extends RESTDataObjectFactory<RESTCSRelatedNodeV1, CSNodeToCSNode, RESTCSRelatedNodeCollectionV1,
RESTCSRelatedNodeCollectionItemV1> {
@Inject
protected CSNodeV1Factory csNodeFactory;
@Inject
protected ContentSpecV1Factory contentSpecFactory;
@Inject
protected CSNodePropertyTagV1Factory csNodePropertyTagFactory;
@Override
public RESTCSRelatedNodeV1 createRESTEntityFromDBEntityInternal(final CSNodeToCSNode entity, final String baseUrl,
final String dataType, final ExpandDataTrunk expand, final Number revision, final boolean expandParentReferences) {
assert entity != null : "Parameter entity can not be null";
assert baseUrl != null : "Parameter baseUrl can not be null";
final RESTCSRelatedNodeV1 retValue = new RESTCSRelatedNodeV1();
final List<String> expandOptions = new ArrayList<String>();
expandOptions.add(RESTBaseEntityV1.LOG_DETAILS_NAME);
expandOptions.add(RESTCSRelatedNodeV1.PARENT_NAME);
expandOptions.add(RESTCSRelatedNodeV1.PROPERTIES_NAME);
expandOptions.add(RESTCSRelatedNodeV1.RELATED_FROM_NAME);
expandOptions.add(RESTCSRelatedNodeV1.RELATED_TO_NAME);
if (revision == null) expandOptions.add(RESTBaseEntityV1.REVISIONS_NAME);
retValue.setExpand(expandOptions);
retValue.setId(entity.getRelatedNode().getId());
retValue.setRelationshipId(entity.getId());
+ retValue.setRelationshipSort(entity.getRelationshipSort());
retValue.setTitle(entity.getRelatedNode().getCSNodeTitle());
retValue.setAdditionalText(entity.getRelatedNode().getAdditionalText());
retValue.setTargetId(entity.getRelatedNode().getCSNodeTargetId());
retValue.setRelationshipType(RESTCSNodeRelationshipTypeV1.getRelationshipType(entity.getRelationshipType()));
retValue.setCondition(entity.getRelatedNode().getCondition());
retValue.setNodeType(RESTCSNodeTypeV1.getNodeType(entity.getRelatedNode().getCSNodeType()));
retValue.setEntityId(entity.getRelatedNode().getEntityId());
retValue.setEntityRevision(entity.getRelatedNode().getEntityRevision());
// REVISIONS
if (revision == null && expand != null && expand.contains(RESTBaseEntityV1.REVISIONS_NAME)) {
retValue.setRevisions(RESTDataObjectCollectionFactory.create(RESTCSRelatedNodeCollectionV1.class, this, entity,
EnversUtilities.getRevisions(entityManager, entity), RESTBaseEntityV1.REVISIONS_NAME, dataType, expand, baseUrl,
entityManager));
}
// PARENT
if (expandParentReferences && expand != null && expand.contains(
RESTCSRelatedNodeV1.PARENT_NAME) && entity.getRelatedNode().getParent() != null) {
retValue.setParent(csNodeFactory.createRESTEntityFromDBEntity(entity.getRelatedNode().getParent(), baseUrl, dataType,
expand.get(RESTCSNodeV1.PARENT_NAME)));
}
// CONTENT SPEC
if (expand != null && expand.contains(RESTCSRelatedNodeV1.CONTENT_SPEC_NAME) && entity.getRelatedNode().getContentSpec() != null)
retValue.setContentSpec(
contentSpecFactory.createRESTEntityFromDBEntity(entity.getRelatedNode().getContentSpec(), baseUrl, dataType,
expand.get(RESTCSRelatedNodeV1.CONTENT_SPEC_NAME), revision, expandParentReferences));
// PROPERTY TAGS
if (expand != null && expand.contains(RESTCSRelatedNodeV1.PROPERTIES_NAME)) {
retValue.setProperties(
RESTDataObjectCollectionFactory.create(
RESTAssignedPropertyTagCollectionV1.class, csNodePropertyTagFactory,
entity.getRelatedNode().getPropertyTagsList(), RESTCSRelatedNodeV1.PROPERTIES_NAME, dataType, expand,
baseUrl, revision, entityManager));
}
retValue.setLinks(baseUrl, RESTv1Constants.CONTENT_SPEC_NODE_URL_NAME, dataType, retValue.getId());
return retValue;
}
@Override
public void syncDBEntityWithRESTEntityFirstPass(final CSNodeToCSNode entity, final RESTCSRelatedNodeV1 dataObject) {
if (dataObject.hasParameterSet(RESTCSRelatedNodeV1.RELATIONSHIP_TYPE_NAME))
entity.setRelationshipType(RESTCSNodeRelationshipTypeV1.getRelationshipTypeId(dataObject.getRelationshipType()));
if (dataObject.hasParameterSet(RESTCSRelatedNodeV1.RELATIONSHIP_SORT_NAME))
entity.setRelationshipSort(dataObject.getRelationshipSort());
}
@Override
protected Class<CSNodeToCSNode> getDatabaseClass() {
return CSNodeToCSNode.class;
}
}
| true | true | public RESTCSRelatedNodeV1 createRESTEntityFromDBEntityInternal(final CSNodeToCSNode entity, final String baseUrl,
final String dataType, final ExpandDataTrunk expand, final Number revision, final boolean expandParentReferences) {
assert entity != null : "Parameter entity can not be null";
assert baseUrl != null : "Parameter baseUrl can not be null";
final RESTCSRelatedNodeV1 retValue = new RESTCSRelatedNodeV1();
final List<String> expandOptions = new ArrayList<String>();
expandOptions.add(RESTBaseEntityV1.LOG_DETAILS_NAME);
expandOptions.add(RESTCSRelatedNodeV1.PARENT_NAME);
expandOptions.add(RESTCSRelatedNodeV1.PROPERTIES_NAME);
expandOptions.add(RESTCSRelatedNodeV1.RELATED_FROM_NAME);
expandOptions.add(RESTCSRelatedNodeV1.RELATED_TO_NAME);
if (revision == null) expandOptions.add(RESTBaseEntityV1.REVISIONS_NAME);
retValue.setExpand(expandOptions);
retValue.setId(entity.getRelatedNode().getId());
retValue.setRelationshipId(entity.getId());
retValue.setTitle(entity.getRelatedNode().getCSNodeTitle());
retValue.setAdditionalText(entity.getRelatedNode().getAdditionalText());
retValue.setTargetId(entity.getRelatedNode().getCSNodeTargetId());
retValue.setRelationshipType(RESTCSNodeRelationshipTypeV1.getRelationshipType(entity.getRelationshipType()));
retValue.setCondition(entity.getRelatedNode().getCondition());
retValue.setNodeType(RESTCSNodeTypeV1.getNodeType(entity.getRelatedNode().getCSNodeType()));
retValue.setEntityId(entity.getRelatedNode().getEntityId());
retValue.setEntityRevision(entity.getRelatedNode().getEntityRevision());
// REVISIONS
if (revision == null && expand != null && expand.contains(RESTBaseEntityV1.REVISIONS_NAME)) {
retValue.setRevisions(RESTDataObjectCollectionFactory.create(RESTCSRelatedNodeCollectionV1.class, this, entity,
EnversUtilities.getRevisions(entityManager, entity), RESTBaseEntityV1.REVISIONS_NAME, dataType, expand, baseUrl,
entityManager));
}
// PARENT
if (expandParentReferences && expand != null && expand.contains(
RESTCSRelatedNodeV1.PARENT_NAME) && entity.getRelatedNode().getParent() != null) {
retValue.setParent(csNodeFactory.createRESTEntityFromDBEntity(entity.getRelatedNode().getParent(), baseUrl, dataType,
expand.get(RESTCSNodeV1.PARENT_NAME)));
}
// CONTENT SPEC
if (expand != null && expand.contains(RESTCSRelatedNodeV1.CONTENT_SPEC_NAME) && entity.getRelatedNode().getContentSpec() != null)
retValue.setContentSpec(
contentSpecFactory.createRESTEntityFromDBEntity(entity.getRelatedNode().getContentSpec(), baseUrl, dataType,
expand.get(RESTCSRelatedNodeV1.CONTENT_SPEC_NAME), revision, expandParentReferences));
// PROPERTY TAGS
if (expand != null && expand.contains(RESTCSRelatedNodeV1.PROPERTIES_NAME)) {
retValue.setProperties(
RESTDataObjectCollectionFactory.create(
RESTAssignedPropertyTagCollectionV1.class, csNodePropertyTagFactory,
entity.getRelatedNode().getPropertyTagsList(), RESTCSRelatedNodeV1.PROPERTIES_NAME, dataType, expand,
baseUrl, revision, entityManager));
}
retValue.setLinks(baseUrl, RESTv1Constants.CONTENT_SPEC_NODE_URL_NAME, dataType, retValue.getId());
return retValue;
}
| public RESTCSRelatedNodeV1 createRESTEntityFromDBEntityInternal(final CSNodeToCSNode entity, final String baseUrl,
final String dataType, final ExpandDataTrunk expand, final Number revision, final boolean expandParentReferences) {
assert entity != null : "Parameter entity can not be null";
assert baseUrl != null : "Parameter baseUrl can not be null";
final RESTCSRelatedNodeV1 retValue = new RESTCSRelatedNodeV1();
final List<String> expandOptions = new ArrayList<String>();
expandOptions.add(RESTBaseEntityV1.LOG_DETAILS_NAME);
expandOptions.add(RESTCSRelatedNodeV1.PARENT_NAME);
expandOptions.add(RESTCSRelatedNodeV1.PROPERTIES_NAME);
expandOptions.add(RESTCSRelatedNodeV1.RELATED_FROM_NAME);
expandOptions.add(RESTCSRelatedNodeV1.RELATED_TO_NAME);
if (revision == null) expandOptions.add(RESTBaseEntityV1.REVISIONS_NAME);
retValue.setExpand(expandOptions);
retValue.setId(entity.getRelatedNode().getId());
retValue.setRelationshipId(entity.getId());
retValue.setRelationshipSort(entity.getRelationshipSort());
retValue.setTitle(entity.getRelatedNode().getCSNodeTitle());
retValue.setAdditionalText(entity.getRelatedNode().getAdditionalText());
retValue.setTargetId(entity.getRelatedNode().getCSNodeTargetId());
retValue.setRelationshipType(RESTCSNodeRelationshipTypeV1.getRelationshipType(entity.getRelationshipType()));
retValue.setCondition(entity.getRelatedNode().getCondition());
retValue.setNodeType(RESTCSNodeTypeV1.getNodeType(entity.getRelatedNode().getCSNodeType()));
retValue.setEntityId(entity.getRelatedNode().getEntityId());
retValue.setEntityRevision(entity.getRelatedNode().getEntityRevision());
// REVISIONS
if (revision == null && expand != null && expand.contains(RESTBaseEntityV1.REVISIONS_NAME)) {
retValue.setRevisions(RESTDataObjectCollectionFactory.create(RESTCSRelatedNodeCollectionV1.class, this, entity,
EnversUtilities.getRevisions(entityManager, entity), RESTBaseEntityV1.REVISIONS_NAME, dataType, expand, baseUrl,
entityManager));
}
// PARENT
if (expandParentReferences && expand != null && expand.contains(
RESTCSRelatedNodeV1.PARENT_NAME) && entity.getRelatedNode().getParent() != null) {
retValue.setParent(csNodeFactory.createRESTEntityFromDBEntity(entity.getRelatedNode().getParent(), baseUrl, dataType,
expand.get(RESTCSNodeV1.PARENT_NAME)));
}
// CONTENT SPEC
if (expand != null && expand.contains(RESTCSRelatedNodeV1.CONTENT_SPEC_NAME) && entity.getRelatedNode().getContentSpec() != null)
retValue.setContentSpec(
contentSpecFactory.createRESTEntityFromDBEntity(entity.getRelatedNode().getContentSpec(), baseUrl, dataType,
expand.get(RESTCSRelatedNodeV1.CONTENT_SPEC_NAME), revision, expandParentReferences));
// PROPERTY TAGS
if (expand != null && expand.contains(RESTCSRelatedNodeV1.PROPERTIES_NAME)) {
retValue.setProperties(
RESTDataObjectCollectionFactory.create(
RESTAssignedPropertyTagCollectionV1.class, csNodePropertyTagFactory,
entity.getRelatedNode().getPropertyTagsList(), RESTCSRelatedNodeV1.PROPERTIES_NAME, dataType, expand,
baseUrl, revision, entityManager));
}
retValue.setLinks(baseUrl, RESTv1Constants.CONTENT_SPEC_NODE_URL_NAME, dataType, retValue.getId());
return retValue;
}
|
diff --git a/src/test/java/jscl/math/NumeralBaseConversionTest.java b/src/test/java/jscl/math/NumeralBaseConversionTest.java
index 889e50f..3776761 100644
--- a/src/test/java/jscl/math/NumeralBaseConversionTest.java
+++ b/src/test/java/jscl/math/NumeralBaseConversionTest.java
@@ -1,134 +1,134 @@
package jscl.math;
import au.com.bytecode.opencsv.CSVReader;
import jscl.JsclMathEngine;
import jscl.MathEngine;
import jscl.text.ParseException;
import jscl.util.ExpressionGeneratorWithInput;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import org.junit.Test;
import org.solovyev.common.utils.Converter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* User: serso
* Date: 12/14/11
* Time: 4:01 PM
*/
public class NumeralBaseConversionTest {
@Test
public void testConversion() throws Exception {
CSVReader reader = null;
try {
final MathEngine me = JsclMathEngine.instance;
reader = new CSVReader(new InputStreamReader(NumeralBaseConversionTest.class.getResourceAsStream("/jscl/math/nb_table.csv")), '\t');
// skip first line
reader.readNext();
String[] line = reader.readNext();
for (; line != null; line = reader.readNext()) {
testExpression(line, new DummyExpression());
testExpression(line, new Expression1());
testExpression(line, new Expression2());
testExpression(line, new Expression3());
final String dec = line[0].toUpperCase();
final String hex = "0x:" + line[1].toUpperCase();
final String bin = "0b:" + line[2].toUpperCase();
final List<String> input = new ArrayList<String>();
input.add(dec);
input.add(hex);
input.add(bin);
- System.out.println("Dec: " + dec);
- System.out.println("Hex: " + hex);
- System.out.println("Bin: " + bin);
+ //System.out.println("Dec: " + dec);
+ //System.out.println("Hex: " + hex);
+ //System.out.println("Bin: " + bin);
final ExpressionGeneratorWithInput eg = new ExpressionGeneratorWithInput(input, 20);
final List<String> expressions = eg.generate();
final String decExpression = expressions.get(0);
final String hexExpression = expressions.get(1);
final String binExpression = expressions.get(2);
- System.out.println("Dec expression: " + decExpression);
- System.out.println("Hex expression: " + hexExpression);
- System.out.println("Bin expression: " + binExpression);
+ //System.out.println("Dec expression: " + decExpression);
+ //System.out.println("Hex expression: " + hexExpression);
+ //System.out.println("Bin expression: " + binExpression);
final String decResult = Expression.valueOf(decExpression).numeric().toString();
- System.out.println("Dec result: " + decResult);
+ //System.out.println("Dec result: " + decResult);
final String hexResult = Expression.valueOf(hexExpression).numeric().toString();
- System.out.println("Hex result: " + hexResult);
+ //System.out.println("Hex result: " + hexResult);
final String binResult = Expression.valueOf(binExpression).numeric().toString();
- System.out.println("Bin result: " + binResult);
+ //System.out.println("Bin result: " + binResult);
Assert.assertEquals("dec-hex: " + decExpression + " : " + hexExpression, decResult, hexResult);
Assert.assertEquals("dec-bin: " + decExpression + " : " + binExpression, decResult, binResult);
}
} finally {
if (reader != null) {
reader.close();
}
}
}
public static void testExpression(@NotNull String[] line, @NotNull Converter<String, String> converter) throws ParseException {
final String dec = line[0].toUpperCase();
final String hex = "0x:" + line[1].toUpperCase();
final String bin = "0b:" + line[2].toUpperCase();
final String decResult = Expression.valueOf(converter.convert(dec)).numeric().toString();
final String hexResult = Expression.valueOf(converter.convert(hex)).numeric().toString();
final String binResult = Expression.valueOf(converter.convert(bin)).numeric().toString();
Assert.assertEquals(decResult, hexResult);
Assert.assertEquals(decResult, binResult);
}
private static class DummyExpression implements Converter<String, String> {
@NotNull
@Override
public String convert(@NotNull String s) {
return s;
}
}
private static class Expression1 implements Converter<String, String> {
@NotNull
@Override
public String convert(@NotNull String s) {
return s + "*" + s;
}
}
private static class Expression2 implements Converter<String, String> {
@NotNull
@Override
public String convert(@NotNull String s) {
return s + "*" + s + " * sin(" + s + ") - 0b:1101";
}
}
private static class Expression3 implements Converter<String, String> {
@NotNull
@Override
public String convert(@NotNull String s) {
return s + "*" + s + " * sin(" + s + ") - 0b:1101 + √(" + s + ") + exp ( " + s + ")";
}
}
}
| false | true | public void testConversion() throws Exception {
CSVReader reader = null;
try {
final MathEngine me = JsclMathEngine.instance;
reader = new CSVReader(new InputStreamReader(NumeralBaseConversionTest.class.getResourceAsStream("/jscl/math/nb_table.csv")), '\t');
// skip first line
reader.readNext();
String[] line = reader.readNext();
for (; line != null; line = reader.readNext()) {
testExpression(line, new DummyExpression());
testExpression(line, new Expression1());
testExpression(line, new Expression2());
testExpression(line, new Expression3());
final String dec = line[0].toUpperCase();
final String hex = "0x:" + line[1].toUpperCase();
final String bin = "0b:" + line[2].toUpperCase();
final List<String> input = new ArrayList<String>();
input.add(dec);
input.add(hex);
input.add(bin);
System.out.println("Dec: " + dec);
System.out.println("Hex: " + hex);
System.out.println("Bin: " + bin);
final ExpressionGeneratorWithInput eg = new ExpressionGeneratorWithInput(input, 20);
final List<String> expressions = eg.generate();
final String decExpression = expressions.get(0);
final String hexExpression = expressions.get(1);
final String binExpression = expressions.get(2);
System.out.println("Dec expression: " + decExpression);
System.out.println("Hex expression: " + hexExpression);
System.out.println("Bin expression: " + binExpression);
final String decResult = Expression.valueOf(decExpression).numeric().toString();
System.out.println("Dec result: " + decResult);
final String hexResult = Expression.valueOf(hexExpression).numeric().toString();
System.out.println("Hex result: " + hexResult);
final String binResult = Expression.valueOf(binExpression).numeric().toString();
System.out.println("Bin result: " + binResult);
Assert.assertEquals("dec-hex: " + decExpression + " : " + hexExpression, decResult, hexResult);
Assert.assertEquals("dec-bin: " + decExpression + " : " + binExpression, decResult, binResult);
}
} finally {
if (reader != null) {
reader.close();
}
}
}
| public void testConversion() throws Exception {
CSVReader reader = null;
try {
final MathEngine me = JsclMathEngine.instance;
reader = new CSVReader(new InputStreamReader(NumeralBaseConversionTest.class.getResourceAsStream("/jscl/math/nb_table.csv")), '\t');
// skip first line
reader.readNext();
String[] line = reader.readNext();
for (; line != null; line = reader.readNext()) {
testExpression(line, new DummyExpression());
testExpression(line, new Expression1());
testExpression(line, new Expression2());
testExpression(line, new Expression3());
final String dec = line[0].toUpperCase();
final String hex = "0x:" + line[1].toUpperCase();
final String bin = "0b:" + line[2].toUpperCase();
final List<String> input = new ArrayList<String>();
input.add(dec);
input.add(hex);
input.add(bin);
//System.out.println("Dec: " + dec);
//System.out.println("Hex: " + hex);
//System.out.println("Bin: " + bin);
final ExpressionGeneratorWithInput eg = new ExpressionGeneratorWithInput(input, 20);
final List<String> expressions = eg.generate();
final String decExpression = expressions.get(0);
final String hexExpression = expressions.get(1);
final String binExpression = expressions.get(2);
//System.out.println("Dec expression: " + decExpression);
//System.out.println("Hex expression: " + hexExpression);
//System.out.println("Bin expression: " + binExpression);
final String decResult = Expression.valueOf(decExpression).numeric().toString();
//System.out.println("Dec result: " + decResult);
final String hexResult = Expression.valueOf(hexExpression).numeric().toString();
//System.out.println("Hex result: " + hexResult);
final String binResult = Expression.valueOf(binExpression).numeric().toString();
//System.out.println("Bin result: " + binResult);
Assert.assertEquals("dec-hex: " + decExpression + " : " + hexExpression, decResult, hexResult);
Assert.assertEquals("dec-bin: " + decExpression + " : " + binExpression, decResult, binResult);
}
} finally {
if (reader != null) {
reader.close();
}
}
}
|
diff --git a/src/main/groovy/lang/Binding.java b/src/main/groovy/lang/Binding.java
index 8af7792c1..1eee99b0b 100644
--- a/src/main/groovy/lang/Binding.java
+++ b/src/main/groovy/lang/Binding.java
@@ -1,133 +1,134 @@
/*
$Id$
Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved.
Redistribution and use of this software and associated documentation
("Software"), with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain copyright
statements and notices. Redistributions must also contain a
copy of this document.
2. Redistributions in binary form must reproduce the
above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
3. The name "groovy" must not be used to endorse or promote
products derived from this Software without prior written
permission of The Codehaus. For written permission,
please contact [email protected].
4. Products derived from this Software may not be called "groovy"
nor may "groovy" appear in their names without prior written
permission of The Codehaus. "groovy" is a registered
trademark of The Codehaus.
5. Due credit should be given to The Codehaus -
http://groovy.codehaus.org/
THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package groovy.lang;
import java.util.HashMap;
import java.util.Map;
/**
* Represents the variable bindings of a script which can be altered
* from outside the script object or created outside of a script and passed
* into it.
*
* @author <a href="mailto:[email protected]">James Strachan</a>
* @version $Revision$
*/
public class Binding extends GroovyObjectSupport {
private Map variables;
public Binding() {
variables = new HashMap();
}
public Binding(Map variables) {
this.variables = variables;
}
/**
* A helper constructor used in main(String[]) method calls
*
* @param args are the command line arguments from a main()
*/
public Binding(String[] args) {
this();
setVariable("args", args);
}
/**
* @param name the name of the variable to lookup
* @return the variable value
*/
public Object getVariable(String name) {
Object result = variables.get(name);
if (result == null && !variables.containsKey(name)) {
- throw new MissingPropertyException(name, Binding.class);
+ throw new MissingPropertyException("The property '" + name + "' is missing from the binding.",
+ name, Binding.class);
}
return result;
}
/**
* Sets the value of the given variable
* @param name the name of the variable to set
* @param value the new value for the given variable
*/
public void setVariable(String name, Object value) {
variables.put(name, value);
}
public Map getVariables() {
return variables;
}
/**
* Overloaded to make variables appear as bean properties or via the subscript operator
*/
public Object getProperty(String property) {
/** @todo we should check if we have the property with the metaClass instead of try/catch */
try {
return super.getProperty(property);
}
catch (MissingPropertyException e) {
return getVariable(property);
}
}
/**
* Overloaded to make variables appear as bean properties or via the subscript operator
*/
public void setProperty(String property, Object newValue) {
/** @todo we should check if we have the property with the metaClass instead of try/catch */
try {
super.setProperty(property, newValue);
}
catch (MissingPropertyException e) {
setVariable(property, newValue);
}
}
}
| true | true | public Object getVariable(String name) {
Object result = variables.get(name);
if (result == null && !variables.containsKey(name)) {
throw new MissingPropertyException(name, Binding.class);
}
return result;
}
| public Object getVariable(String name) {
Object result = variables.get(name);
if (result == null && !variables.containsKey(name)) {
throw new MissingPropertyException("The property '" + name + "' is missing from the binding.",
name, Binding.class);
}
return result;
}
|
diff --git a/src/main/java/by/itransition/fanfic/model/FanficModel.java b/src/main/java/by/itransition/fanfic/model/FanficModel.java
index 8363783..6daf353 100644
--- a/src/main/java/by/itransition/fanfic/model/FanficModel.java
+++ b/src/main/java/by/itransition/fanfic/model/FanficModel.java
@@ -1,175 +1,175 @@
package by.itransition.fanfic.model;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import by.itransition.fanfic.dao.ChapterDao;
import by.itransition.fanfic.dao.FanficDao;
import by.itransition.fanfic.dao.UserDao;
import by.itransition.fanfic.dao.impl.ChapterDaoImpl;
import by.itransition.fanfic.dao.impl.FanficDaoImpl;
import by.itransition.fanfic.dao.impl.UserDaoImpl;
import by.itransition.fanfic.model.bean.Chapter;
import by.itransition.fanfic.model.bean.Fanfic;
import by.itransition.fanfic.model.bean.User;
public class FanficModel {
private static FanficModel fanficModel = new FanficModel();
private UserDao userDao = new UserDaoImpl();
private FanficDao fanficDao = new FanficDaoImpl();
private ChapterDao chapterDao = new ChapterDaoImpl();
private FanficModel() {
}
public static FanficModel getInstance() {
return fanficModel;
}
public void save(User user) {
userDao.save(user);
}
public void save(Fanfic fanfic) {
fanficDao.save(fanfic);
}
public void save(Chapter chapter) {
chapterDao.save(chapter);
}
public void removeFanficById(int id) {
fanficDao.removeFanficById(id);
}
public User getUserById(int id) {
return userDao.getUserById(id);
}
public User getUserByName(String username) {
for (User user : userDao.getUsers()) {
if (user.getUsername().equals(username)) {
return user;
}
}
return null;
}
public List<Integer> getStatistic() {
List<Integer> answer = new ArrayList<Integer>();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Calendar calendar = Calendar.getInstance();
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
for (int minutesBeforeNow = 0; minutesBeforeNow < 10; ++minutesBeforeNow) {
for (User user : userDao.getUsers()) {
Date userDate = user.getDateOfRegistration();
Calendar userCalendar = Calendar.getInstance();
userCalendar.setTime(userDate);
userCalendar.clear(Calendar.SECOND);
userCalendar.clear(Calendar.MILLISECOND);
if (userCalendar.getTime().equals(calendar.getTime())) {
- if (null == map.get(10 - minutesBeforeNow)) {
+ if (null == map.get(minutesBeforeNow)) {
map.put(minutesBeforeNow, 1);
} else {
map.put(minutesBeforeNow, map.get(minutesBeforeNow) + 1);
}
}
}
calendar.add(Calendar.MINUTE, -1);
}
for (int minutesBeforeNow = 0; minutesBeforeNow < 10; ++minutesBeforeNow) {
if (null != map.get(minutesBeforeNow)) {
answer.add(map.get(minutesBeforeNow));
} else {
answer.add(0);
}
}
return answer;
}
public List<Fanfic> searchFanfics(String searchQuery) {
List<Fanfic> answer = new ArrayList<Fanfic>();
for (Fanfic fanfic : fanficDao.search(searchQuery)) {
if (!answer.contains(fanfic)) {
answer.add(fanfic);
}
}
for (Chapter chapter : chapterDao.search(searchQuery)) {
if (!answer.contains(chapter.getFanfic())) {
answer.add(chapter.getFanfic());
}
}
return answer;
}
public List<Fanfic> getFanficsByCategory(String category) {
List<Fanfic> answer = new ArrayList<Fanfic>();
for (Fanfic fanfic : fanficDao.getFanfics()) {
if (fanfic.getCategories().contains(category)) {
answer.add(fanfic);
}
}
return answer;
}
public void removeUserById(int id) {
userDao.remove(userDao.getUserById(id));
}
public void registerUser(User user) {
user.setDateOfRegistration(Calendar.getInstance().getTime());
userDao.register(user);
}
public List<Fanfic> getAllFanfics() {
return fanficDao.getFanfics();
}
public boolean isRegistered(String username, String password) {
return null != userDao.login(username, password);
}
public List<User> getAllUsers() {
return userDao.getUsers();
}
public List<Fanfic> getBestFanfics(int count) {
List<Fanfic> fanfics = fanficDao.getFanfics();
Collections.sort(fanfics, new Comparator<Fanfic>() {
@Override
public int compare(Fanfic first, Fanfic second) {
if (first.getRating() > second.getRating()) {
return 1;
} else {
if (first.getRating() < second.getRating()) {
return -1;
} else {
return 0;
}
}
}
});
if (count > fanfics.size()) {
return fanfics;
} else {
return fanfics.subList(0, count);
}
}
public Fanfic getFanficById(int id) {
return fanficDao.getFanficById(id);
}
}
| true | true | public List<Integer> getStatistic() {
List<Integer> answer = new ArrayList<Integer>();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Calendar calendar = Calendar.getInstance();
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
for (int minutesBeforeNow = 0; minutesBeforeNow < 10; ++minutesBeforeNow) {
for (User user : userDao.getUsers()) {
Date userDate = user.getDateOfRegistration();
Calendar userCalendar = Calendar.getInstance();
userCalendar.setTime(userDate);
userCalendar.clear(Calendar.SECOND);
userCalendar.clear(Calendar.MILLISECOND);
if (userCalendar.getTime().equals(calendar.getTime())) {
if (null == map.get(10 - minutesBeforeNow)) {
map.put(minutesBeforeNow, 1);
} else {
map.put(minutesBeforeNow, map.get(minutesBeforeNow) + 1);
}
}
}
calendar.add(Calendar.MINUTE, -1);
}
for (int minutesBeforeNow = 0; minutesBeforeNow < 10; ++minutesBeforeNow) {
if (null != map.get(minutesBeforeNow)) {
answer.add(map.get(minutesBeforeNow));
} else {
answer.add(0);
}
}
return answer;
}
| public List<Integer> getStatistic() {
List<Integer> answer = new ArrayList<Integer>();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Calendar calendar = Calendar.getInstance();
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
for (int minutesBeforeNow = 0; minutesBeforeNow < 10; ++minutesBeforeNow) {
for (User user : userDao.getUsers()) {
Date userDate = user.getDateOfRegistration();
Calendar userCalendar = Calendar.getInstance();
userCalendar.setTime(userDate);
userCalendar.clear(Calendar.SECOND);
userCalendar.clear(Calendar.MILLISECOND);
if (userCalendar.getTime().equals(calendar.getTime())) {
if (null == map.get(minutesBeforeNow)) {
map.put(minutesBeforeNow, 1);
} else {
map.put(minutesBeforeNow, map.get(minutesBeforeNow) + 1);
}
}
}
calendar.add(Calendar.MINUTE, -1);
}
for (int minutesBeforeNow = 0; minutesBeforeNow < 10; ++minutesBeforeNow) {
if (null != map.get(minutesBeforeNow)) {
answer.add(map.get(minutesBeforeNow));
} else {
answer.add(0);
}
}
return answer;
}
|
diff --git a/src/com/voracious/dragons/client/net/ClientTurnPacket.java b/src/com/voracious/dragons/client/net/ClientTurnPacket.java
index 5e0cdd2..cd2d89d 100644
--- a/src/com/voracious/dragons/client/net/ClientTurnPacket.java
+++ b/src/com/voracious/dragons/client/net/ClientTurnPacket.java
@@ -1,28 +1,28 @@
package com.voracious.dragons.client.net;
import com.voracious.dragons.client.Game;
import com.voracious.dragons.client.screens.PlayScreen;
import com.voracious.dragons.common.ConnectionManager;
import com.voracious.dragons.common.Message;
import com.voracious.dragons.common.Packet;
import com.voracious.dragons.common.Turn;
public class ClientTurnPacket implements Packet{
@Override
public boolean wasCalled(Message message) {
String msg = message.toString();
return msg.getBytes()[0]==7;
}
@Override
public void process(Message message, ConnectionManager cm) {
ClientConnectionManager ccm = (ClientConnectionManager) cm;
- Turn newTurn = new Turn(message.getBytes());
+ Turn newTurn = new Turn(message.getBytes(), false);
((PlayScreen) Game.getScreen(PlayScreen.ID)).onTurnCalled(newTurn);
}
@Override
public boolean isString() {
return false;
}
}
| true | true | public void process(Message message, ConnectionManager cm) {
ClientConnectionManager ccm = (ClientConnectionManager) cm;
Turn newTurn = new Turn(message.getBytes());
((PlayScreen) Game.getScreen(PlayScreen.ID)).onTurnCalled(newTurn);
}
| public void process(Message message, ConnectionManager cm) {
ClientConnectionManager ccm = (ClientConnectionManager) cm;
Turn newTurn = new Turn(message.getBytes(), false);
((PlayScreen) Game.getScreen(PlayScreen.ID)).onTurnCalled(newTurn);
}
|
diff --git a/src/main/java/org/basex/gui/layout/BaseXFileChooser.java b/src/main/java/org/basex/gui/layout/BaseXFileChooser.java
index 44b03f129..bcc2b744c 100644
--- a/src/main/java/org/basex/gui/layout/BaseXFileChooser.java
+++ b/src/main/java/org/basex/gui/layout/BaseXFileChooser.java
@@ -1,197 +1,198 @@
package org.basex.gui.layout;
import static org.basex.core.Text.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import org.basex.gui.*;
import org.basex.io.*;
import org.basex.util.*;
/**
* Project specific File Chooser implementation.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public final class BaseXFileChooser {
/** File dialog mode. */
public enum Mode {
/** Open file. */ FOPEN,
/** Open file or directory. */ FDOPEN,
/** Open directory. */ DOPEN,
/** Save file. */ FSAVE,
/** Save file or directory. */ DSAVE,
}
/** Reference to main window. */
private GUI gui;
/** Swing file chooser. */
private JFileChooser fc;
/** Simple file dialog. */
private FileDialog fd;
/** File suffix. */
private String suffix;
/**
* Default constructor.
* @param title dialog title
* @param path initial path
* @param main reference to main window
*/
public BaseXFileChooser(final String title, final String path,
final GUI main) {
if(main.gprop.is(GUIProp.SIMPLEFD)) {
fd = new FileDialog(main, title);
fd.setDirectory(new File(path).getPath());
} else {
fc = new JFileChooser(path);
final File file = new File(path);
if(!file.isDirectory()) fc.setSelectedFile(file);
fc.setDialogTitle(title);
gui = main;
}
}
/**
* Sets a file filter.
* @param dsc description
* @param suf suffix
* @return self reference
*/
public BaseXFileChooser filter(final String dsc, final String... suf) {
if(fc != null) {
final FileFilter ff = fc.getFileFilter();
fc.addChoosableFileFilter(new Filter(suf, dsc));
fc.setFileFilter(ff);
} else {
fd.setFile('*' + suf[0]);
}
// treat first filter as default
if(suffix == null) suffix = suf[0];
return this;
}
/**
* Allow multiple choice.
* @return self reference
*/
public BaseXFileChooser multi() {
if(fc != null) fc.setMultiSelectionEnabled(true);
return this;
}
/**
* Selects a file or directory.
* @param mode type defined by {@link Mode}
* @return resulting input reference, or {@code null} if no file was selected
*/
public IOFile select(final Mode mode) {
final IOFile[] files = selectAll(mode);
return files.length == 0 ? null : files[0];
}
/**
* Selects a file or directory.
* @param mode type defined by {@link Mode}
* @return resulting input reference
*/
public IOFile[] selectAll(final Mode mode) {
if(fd != null) {
if(mode == Mode.FDOPEN) fd.setFile(" ");
fd.setMode(mode == Mode.FSAVE || mode == Mode.DSAVE ?
FileDialog.SAVE : FileDialog.LOAD);
fd.setVisible(true);
final String f = fd.getFile();
if(f == null) return new IOFile[0];
final String dir = fd.getDirectory();
return new IOFile[] { new IOFile(mode == Mode.DOPEN || mode == Mode.DSAVE ? dir :
dir + '/' + fd.getFile()) };
}
int state = 0;
switch(mode) {
case FOPEN:
state = fc.showOpenDialog(gui);
break;
case FDOPEN:
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
state = fc.showOpenDialog(gui);
break;
case FSAVE:
state = fc.showSaveDialog(gui);
break;
case DOPEN:
case DSAVE:
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
state = fc.showDialog(gui, null);
break;
}
if(state != JFileChooser.APPROVE_OPTION) return new IOFile[0];
- final File[] fl = fc.getSelectedFiles();
+ final File[] fl = fc.isMultiSelectionEnabled() ? fc.getSelectedFiles() :
+ new File[] { fc.getSelectedFile() };
final IOFile[] files = new IOFile[fl.length];
for(int f = 0; f < fl.length; f++) files[f] = new IOFile(fl[f].getPath());
if(mode == Mode.FSAVE) {
// add file suffix to files
if(suffix != null) {
- for(int f = 0; f < fl.length; f++) {
+ for(int f = 0; f < files.length; f++) {
final String path = files[f].path();
- if(path.contains(".")) files[f] = new IOFile(path + suffix);
+ if(!path.contains(".")) files[f] = new IOFile(path + suffix);
}
}
// show replace dialog
for(final IOFile io : files) {
if(io.exists() && !BaseXDialog.confirm(gui, Util.info(FILE_EXISTS_X, io))) {
return new IOFile[0];
}
}
}
return files;
}
/**
* Defines a file filter for a list of extensions.
*/
private static class Filter extends FileFilter {
/** Suffixes. */
private final String[] sufs;
/** Description. */
private final String desc;
/**
* Constructor.
* @param s suffixes
* @param d description
*/
Filter(final String[] s, final String d) {
sufs = s;
desc = d;
}
@Override
public boolean accept(final File file) {
if(file.isDirectory()) return true;
final String name = file.getName().toLowerCase(Locale.ENGLISH);
for(final String s : sufs) if(name.endsWith(s)) return true;
return false;
}
@Override
public String getDescription() {
final StringBuilder sb = new StringBuilder();
for(final String s : sufs) {
if(sb.length() != 0) sb.append(", ");
sb.append('*').append(s);
}
return desc + " (" + sb + ')';
}
}
}
| false | true | public IOFile[] selectAll(final Mode mode) {
if(fd != null) {
if(mode == Mode.FDOPEN) fd.setFile(" ");
fd.setMode(mode == Mode.FSAVE || mode == Mode.DSAVE ?
FileDialog.SAVE : FileDialog.LOAD);
fd.setVisible(true);
final String f = fd.getFile();
if(f == null) return new IOFile[0];
final String dir = fd.getDirectory();
return new IOFile[] { new IOFile(mode == Mode.DOPEN || mode == Mode.DSAVE ? dir :
dir + '/' + fd.getFile()) };
}
int state = 0;
switch(mode) {
case FOPEN:
state = fc.showOpenDialog(gui);
break;
case FDOPEN:
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
state = fc.showOpenDialog(gui);
break;
case FSAVE:
state = fc.showSaveDialog(gui);
break;
case DOPEN:
case DSAVE:
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
state = fc.showDialog(gui, null);
break;
}
if(state != JFileChooser.APPROVE_OPTION) return new IOFile[0];
final File[] fl = fc.getSelectedFiles();
final IOFile[] files = new IOFile[fl.length];
for(int f = 0; f < fl.length; f++) files[f] = new IOFile(fl[f].getPath());
if(mode == Mode.FSAVE) {
// add file suffix to files
if(suffix != null) {
for(int f = 0; f < fl.length; f++) {
final String path = files[f].path();
if(path.contains(".")) files[f] = new IOFile(path + suffix);
}
}
// show replace dialog
for(final IOFile io : files) {
if(io.exists() && !BaseXDialog.confirm(gui, Util.info(FILE_EXISTS_X, io))) {
return new IOFile[0];
}
}
}
return files;
}
| public IOFile[] selectAll(final Mode mode) {
if(fd != null) {
if(mode == Mode.FDOPEN) fd.setFile(" ");
fd.setMode(mode == Mode.FSAVE || mode == Mode.DSAVE ?
FileDialog.SAVE : FileDialog.LOAD);
fd.setVisible(true);
final String f = fd.getFile();
if(f == null) return new IOFile[0];
final String dir = fd.getDirectory();
return new IOFile[] { new IOFile(mode == Mode.DOPEN || mode == Mode.DSAVE ? dir :
dir + '/' + fd.getFile()) };
}
int state = 0;
switch(mode) {
case FOPEN:
state = fc.showOpenDialog(gui);
break;
case FDOPEN:
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
state = fc.showOpenDialog(gui);
break;
case FSAVE:
state = fc.showSaveDialog(gui);
break;
case DOPEN:
case DSAVE:
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
state = fc.showDialog(gui, null);
break;
}
if(state != JFileChooser.APPROVE_OPTION) return new IOFile[0];
final File[] fl = fc.isMultiSelectionEnabled() ? fc.getSelectedFiles() :
new File[] { fc.getSelectedFile() };
final IOFile[] files = new IOFile[fl.length];
for(int f = 0; f < fl.length; f++) files[f] = new IOFile(fl[f].getPath());
if(mode == Mode.FSAVE) {
// add file suffix to files
if(suffix != null) {
for(int f = 0; f < files.length; f++) {
final String path = files[f].path();
if(!path.contains(".")) files[f] = new IOFile(path + suffix);
}
}
// show replace dialog
for(final IOFile io : files) {
if(io.exists() && !BaseXDialog.confirm(gui, Util.info(FILE_EXISTS_X, io))) {
return new IOFile[0];
}
}
}
return files;
}
|
diff --git a/src/main/java/org/hbase/async/HBaseClient.java b/src/main/java/org/hbase/async/HBaseClient.java
index f1b8ce3..21b4ae8 100644
--- a/src/main/java/org/hbase/async/HBaseClient.java
+++ b/src/main/java/org/hbase/async/HBaseClient.java
@@ -1,209 +1,209 @@
package org.hbase.async;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchDeleter;
import org.apache.accumulo.core.client.BatchScanner;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.MultiTableBatchWriter;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.ZooKeeperInstance;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicLong;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.hadoop.io.Text;
import com.stumbleupon.async.Deferred;
public class HBaseClient {
public static final byte[] EMPTY_ARRAY = new byte[0];
private static final BatchWriterConfig batchWriterConfig = new BatchWriterConfig();
String keepers = "localhost";
String instanceId = "test";
String user = "root";
String password = "secret";
private Connector conn;
private CuratorFramework curator;
private Map<String, DistributedAtomicLong> counters = new HashMap<String, DistributedAtomicLong>();
private MultiTableBatchWriter mtbw;
public HBaseClient(String zkq) {
// TODO: get instance, user and password from zkq
keepers = zkq;
Instance instance = new ZooKeeperInstance(instanceId, keepers);
try {
conn = instance.getConnector(user, new PasswordToken(password.getBytes()));
curator = CuratorFrameworkFactory.newClient(keepers, new ExponentialBackoffRetry(1000, 3));
curator.start();
} catch (AccumuloException e) {
throw new RuntimeException(e);
} catch (AccumuloSecurityException e) {
throw new RuntimeException(e);
}
}
public HBaseClient(String zkq, String string) {
this(zkq);
}
// use curator/zookeeper to implement globally unique numbers
synchronized public Deferred<Long> atomicIncrement(AtomicIncrementRequest atomicIncrementRequest) {
String kind = new String(atomicIncrementRequest.getKind());
DistributedAtomicLong counter = counters.get(kind);
if (counter == null) {
RetryPolicy policy = new ExponentialBackoffRetry(10, Integer.MAX_VALUE, 1000);
counters.put(kind, counter = new DistributedAtomicLong(curator, zooPath("/counters/" + kind), policy));
}
AtomicValue<Long> increment;
try {
increment = counter.increment();
} catch (Exception e) {
return Deferred.fromError(e);
}
if (increment.succeeded())
return Deferred.fromResult(increment.postValue());
return Deferred.fromError(new Exception("failed to increment " + kind));
}
private String zooPath(String path) {
return "/opentsdb" + path;
}
synchronized private void update(String table, Mutation m) throws TableNotFoundException, AccumuloException, AccumuloSecurityException {
if (mtbw == null)
mtbw = conn.createMultiTableBatchWriter(batchWriterConfig);
mtbw.getBatchWriter(table).addMutation(m);
}
// This just does an update, but the one place where it is called is only
// doing a double-check that the expected location is empty.
public Deferred<Boolean> compareAndSet(PutRequest put, byte[] value) {
try {
update(put.getTable(), put.getMutation());
} catch (Exception e) {
return Deferred.fromError(e);
}
return Deferred.fromResult(new Boolean(true));
}
// the deleterow implementation is slow; could use iterators to make it efficient
public Deferred<Object> delete(DeleteRequest request) {
try {
if (request.isDeleteRow()) {
BatchDeleter deleter = conn.createBatchDeleter(request.getTable(), Constants.NO_AUTHS, batchWriterConfig.getMaxWriteThreads(), batchWriterConfig);
deleter.setRanges(Collections.singletonList(new Range(new Text(request.getKey()))));
deleter.delete();
} else {
update(request.getTable(), request.getDeleteMutation());
}
} catch (Exception e) {
return Deferred.fromError(e);
}
return Deferred.fromResult(new Object());
}
public Scanner newScanner(byte[] table) {
return new Scanner(table, conn);
}
public Deferred<ArrayList<KeyValue>> get(GetRequest get) {
ArrayList<KeyValue> result = new ArrayList<KeyValue>();
BatchScanner bs;
try {
bs = conn.createBatchScanner(get.getTable(), Constants.NO_AUTHS, 5);
} catch (TableNotFoundException e) {
return Deferred.fromError(e);
}
try {
- bs.setRanges(Collections.singletonList(new Range(new Text(get.getKey()))));
+ bs.setRanges(Collections.singletonList(new Range(new Text(get.key()))));
if (get.getFamily() != null || get.getQualifier() != null) {
if (get.getQualifier() != null)
bs.fetchColumn(new Text(get.getFamily()), new Text(get.getQualifier()));
else
bs.fetchColumnFamily(new Text(get.getFamily()));
}
for (Entry<Key,Value> entry : bs) {
result.add(new KeyValue(entry));
}
} finally {
bs.close();
}
return Deferred.fromResult(result);
}
public Deferred<Object> put(PutRequest put) {
try {
update(put.getTable(), put.getMutation());
return Deferred.fromResult(new Object());
} catch (Exception ex) {
return Deferred.fromError(ex);
}
}
public ClientStats stats() {
return new ClientStats();
}
public Deferred<Object> flush() {
if (mtbw != null)
try {
mtbw.flush();
} catch (MutationsRejectedException e) {
return Deferred.fromError(e);
}
return Deferred.fromResult(new Object());
}
public Deferred<Object> ensureTableExists(String table) {
if (!conn.tableOperations().exists(table))
try {
conn.tableOperations().create(table);
} catch (Exception e) {
Deferred.fromError(e);
}
return Deferred.fromResult(new Object());
}
public Deferred<Object> shutdown() {
try {
if (mtbw != null)
mtbw.close();
mtbw = null;
return Deferred.fromResult(new Object());
} catch (MutationsRejectedException e) {
return Deferred.fromError(e);
}
}
public long getFlushInterval() {
return batchWriterConfig.getMaxLatency(TimeUnit.MILLISECONDS);
}
public void setFlushInterval(short ms) {
batchWriterConfig.setMaxLatency((long) ms, TimeUnit.MILLISECONDS);
}
}
| true | true | public Deferred<ArrayList<KeyValue>> get(GetRequest get) {
ArrayList<KeyValue> result = new ArrayList<KeyValue>();
BatchScanner bs;
try {
bs = conn.createBatchScanner(get.getTable(), Constants.NO_AUTHS, 5);
} catch (TableNotFoundException e) {
return Deferred.fromError(e);
}
try {
bs.setRanges(Collections.singletonList(new Range(new Text(get.getKey()))));
if (get.getFamily() != null || get.getQualifier() != null) {
if (get.getQualifier() != null)
bs.fetchColumn(new Text(get.getFamily()), new Text(get.getQualifier()));
else
bs.fetchColumnFamily(new Text(get.getFamily()));
}
for (Entry<Key,Value> entry : bs) {
result.add(new KeyValue(entry));
}
} finally {
bs.close();
}
return Deferred.fromResult(result);
}
| public Deferred<ArrayList<KeyValue>> get(GetRequest get) {
ArrayList<KeyValue> result = new ArrayList<KeyValue>();
BatchScanner bs;
try {
bs = conn.createBatchScanner(get.getTable(), Constants.NO_AUTHS, 5);
} catch (TableNotFoundException e) {
return Deferred.fromError(e);
}
try {
bs.setRanges(Collections.singletonList(new Range(new Text(get.key()))));
if (get.getFamily() != null || get.getQualifier() != null) {
if (get.getQualifier() != null)
bs.fetchColumn(new Text(get.getFamily()), new Text(get.getQualifier()));
else
bs.fetchColumnFamily(new Text(get.getFamily()));
}
for (Entry<Key,Value> entry : bs) {
result.add(new KeyValue(entry));
}
} finally {
bs.close();
}
return Deferred.fromResult(result);
}
|
diff --git a/KalenderProsjekt/src/framePackage/AppointmentOverView.java b/KalenderProsjekt/src/framePackage/AppointmentOverView.java
index ce26495..d44c6c5 100644
--- a/KalenderProsjekt/src/framePackage/AppointmentOverView.java
+++ b/KalenderProsjekt/src/framePackage/AppointmentOverView.java
@@ -1,246 +1,246 @@
package framePackage;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import client.Program;
import data.Alarm;
import data.CalendarModel;
import data.Meeting;
import data.MeetingRoom;
import data.Notification;
import data.Person;
import data.Team;
public class AppointmentOverView {
private JFrame frame;
private JLabel headLine, lblMoreInfo, lblParticipant, lblInfo,
lblYourStatus, lblStatus;
private JList participantList;
private DefaultListModel listModel;
private JTextArea moreInfo;
private JComboBox<ImageIcon> yourStatus;
private JPanel overViewPanel;
private Meeting meeting;
private Person user;
private JButton change, delete;
private ImageIcon check, cross, question,star;
private List<Notification> notifications;
private Notification userNotification;
private NewAppointmentView newAppointment;
private CalendarModel calendarModel;
private Alarm alarm;
public AppointmentOverView(Meeting meeting) {
this.calendarModel = Program.calendarModel;
this.meeting = meeting;
this.user = calendarModel.getUser();
notifications = calendarModel.getAllNotificationsOfMeeting(meeting);
for (Notification n : notifications) {
if(n.getPerson().getUsername().equals(user.getUsername())) {
userNotification = n;
}
}
initialize();
}
private void initialize() {
check = new ImageIcon("res/icons/icon_check.png");
cross = new ImageIcon("res/icons/icon_cross.png");
question = new ImageIcon("res/icons/icon_question.png");
star = new ImageIcon("res/icons/icon_star.png");
overViewPanel = new JPanel(new GridBagLayout());
overViewPanel.setPreferredSize(new Dimension(700, 450));
overViewPanel.setVisible(true);
GridBagConstraints c = new GridBagConstraints();
headLine = new JLabel(meeting.getTitle());
c.gridx = 0;
c.gridy = 0;
headLine.setPreferredSize(new Dimension(300, 25));
headLine.setFont(new Font(headLine.getFont().getName(),headLine.getFont().getStyle(), 20 ));
overViewPanel.add(headLine, c);
lblInfo = new JLabel(getTime() + " p� rom: " + getLoc());
c.gridx = 0;
c.gridy = 1;
lblInfo.setPreferredSize(new Dimension(300,25));
overViewPanel.add(lblInfo, c);
c.insets = new Insets(10,0,10,0);
lblMoreInfo = new JLabel("Beskrivelse:");
c.gridx = 0;
c.gridy = 2;
overViewPanel.add(lblMoreInfo, c);
lblParticipant = new JLabel("Deltakere:");
c.gridx = 0;
c.gridy = 3;
overViewPanel.add(lblParticipant, c);
lblYourStatus = new JLabel("Din status:");
c.gridx = 0;
c.gridy = 4;
overViewPanel.add(lblYourStatus, c);
change = new JButton("Endre avtale");
c.gridx = 0;
c.gridy = 5;
overViewPanel.add(change, c);
change.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newAppointment = new NewAppointmentView(meeting);
frame.setVisible(false);
overViewPanel.setVisible(true);
}
});
delete = new JButton("Slett avtale");
c.gridx = 1;
c.gridy = 5;
overViewPanel.add(delete, c);
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calendarModel.removeMeeting(meeting);
}
});
- if(!meeting.getCreator().getUsername().equals(calendarModel.getUser().getUsername())){
+ if(meeting.getCreator().getUsername().equals(calendarModel.getUser().getUsername()) == false ){
delete.setEnabled(false);
change.setEnabled(false);
}
yourStatus = new JComboBox<ImageIcon>();
yourStatus.addItem(check);
yourStatus.addItem(cross);
yourStatus.addItem(question);
yourStatus.addItem(star);
c.gridx = 1;
c.gridy = 4;
overViewPanel.add(yourStatus, c);
c.gridx = 2;
c.gridy = 4;
lblStatus = new JLabel();
lblStatus.setPreferredSize(new Dimension(70, 25));
overViewPanel.add(lblStatus, c);
if (userNotification != null) {
if (userNotification.getApproved() == 'y') {
yourStatus.setSelectedItem(check);
lblStatus.setText("Deltar");
}
if (userNotification.getApproved() == 'n') {
yourStatus.setSelectedItem(cross);
lblStatus.setText("Deltar Ikke");
}
if (userNotification.getApproved() == 'w') {
yourStatus.setSelectedItem(question);
lblStatus.setText("Vet Ikke");
}
}
if(calendarModel.getUser().getUsername().equals(meeting.getCreator().getUsername()) ){
System.out.println(calendarModel.getUser().getUsername());
System.out.println(meeting.getCreator().getUsername());
change.setEnabled(true);
delete.setEnabled(true);
yourStatus.setSelectedItem(star);
yourStatus.setEnabled(false);
}
yourStatus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (yourStatus.getSelectedItem() == check) {
lblStatus.setText("Deltar");
calendarModel.setStatus('y',userNotification);
}
if (yourStatus.getSelectedItem() == cross) {
lblStatus.setText("Deltar Ikke");
calendarModel.setStatus('n',userNotification);
}
if (yourStatus.getSelectedItem() == question) {
lblStatus.setText("Ikke svart");
calendarModel.setStatus('w',userNotification);
}
frame.setVisible(false);
}
});
moreInfo = new JTextArea(meeting.getDescription());
moreInfo.setEditable(false);
moreInfo.setFocusable(false);
moreInfo.setPreferredSize(new Dimension(320, 100));
c.gridx = 1;
c.gridy = 2;
overViewPanel.add(moreInfo, c);
listModel = new DefaultListModel();
for (int i = 0; i < notifications.size(); i++) {
listModel.addElement(notifications.get(i));
}
participantList = new JList<Notification>();
participantList.setModel(listModel);
participantList.setFixedCellWidth(300);
participantList.setCellRenderer(new overViewRender());
JScrollPane myJScrollPane = new JScrollPane(participantList);
myJScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
c.gridx = 1;
c.gridy = 3;
overViewPanel.add(myJScrollPane, c);
frame = new JFrame();
frame.setContentPane(overViewPanel);
frame.pack();
frame.setVisible(true);
}
private String getTime() {
GregorianCalendar cal = new GregorianCalendar();
GregorianCalendar cal2 = new GregorianCalendar();
cal.setTimeInMillis(meeting.getStartTime());
cal2.setTimeInMillis(meeting.getEndTime());
SimpleDateFormat spl1 = new SimpleDateFormat("dd.MMMM");
SimpleDateFormat spl2 = new SimpleDateFormat("HH:mm");
String time = spl1.format(cal.getTime()) + ". Fra kl "
+ spl2.format(cal.getTime()) + " til "
+ spl2.format(cal2.getTime());
return time;
}
private String getLoc() {
return meeting.getLocation();
}
public JPanel getPanel() {
return overViewPanel;
}
public void showFrame(){
frame.setVisible(true);
}
}
| true | true | private void initialize() {
check = new ImageIcon("res/icons/icon_check.png");
cross = new ImageIcon("res/icons/icon_cross.png");
question = new ImageIcon("res/icons/icon_question.png");
star = new ImageIcon("res/icons/icon_star.png");
overViewPanel = new JPanel(new GridBagLayout());
overViewPanel.setPreferredSize(new Dimension(700, 450));
overViewPanel.setVisible(true);
GridBagConstraints c = new GridBagConstraints();
headLine = new JLabel(meeting.getTitle());
c.gridx = 0;
c.gridy = 0;
headLine.setPreferredSize(new Dimension(300, 25));
headLine.setFont(new Font(headLine.getFont().getName(),headLine.getFont().getStyle(), 20 ));
overViewPanel.add(headLine, c);
lblInfo = new JLabel(getTime() + " p� rom: " + getLoc());
c.gridx = 0;
c.gridy = 1;
lblInfo.setPreferredSize(new Dimension(300,25));
overViewPanel.add(lblInfo, c);
c.insets = new Insets(10,0,10,0);
lblMoreInfo = new JLabel("Beskrivelse:");
c.gridx = 0;
c.gridy = 2;
overViewPanel.add(lblMoreInfo, c);
lblParticipant = new JLabel("Deltakere:");
c.gridx = 0;
c.gridy = 3;
overViewPanel.add(lblParticipant, c);
lblYourStatus = new JLabel("Din status:");
c.gridx = 0;
c.gridy = 4;
overViewPanel.add(lblYourStatus, c);
change = new JButton("Endre avtale");
c.gridx = 0;
c.gridy = 5;
overViewPanel.add(change, c);
change.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newAppointment = new NewAppointmentView(meeting);
frame.setVisible(false);
overViewPanel.setVisible(true);
}
});
delete = new JButton("Slett avtale");
c.gridx = 1;
c.gridy = 5;
overViewPanel.add(delete, c);
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calendarModel.removeMeeting(meeting);
}
});
if(!meeting.getCreator().getUsername().equals(calendarModel.getUser().getUsername())){
delete.setEnabled(false);
change.setEnabled(false);
}
yourStatus = new JComboBox<ImageIcon>();
yourStatus.addItem(check);
yourStatus.addItem(cross);
yourStatus.addItem(question);
yourStatus.addItem(star);
c.gridx = 1;
c.gridy = 4;
overViewPanel.add(yourStatus, c);
c.gridx = 2;
c.gridy = 4;
lblStatus = new JLabel();
lblStatus.setPreferredSize(new Dimension(70, 25));
overViewPanel.add(lblStatus, c);
if (userNotification != null) {
if (userNotification.getApproved() == 'y') {
yourStatus.setSelectedItem(check);
lblStatus.setText("Deltar");
}
if (userNotification.getApproved() == 'n') {
yourStatus.setSelectedItem(cross);
lblStatus.setText("Deltar Ikke");
}
if (userNotification.getApproved() == 'w') {
yourStatus.setSelectedItem(question);
lblStatus.setText("Vet Ikke");
}
}
if(calendarModel.getUser().getUsername().equals(meeting.getCreator().getUsername()) ){
System.out.println(calendarModel.getUser().getUsername());
System.out.println(meeting.getCreator().getUsername());
change.setEnabled(true);
delete.setEnabled(true);
yourStatus.setSelectedItem(star);
yourStatus.setEnabled(false);
}
yourStatus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (yourStatus.getSelectedItem() == check) {
lblStatus.setText("Deltar");
calendarModel.setStatus('y',userNotification);
}
if (yourStatus.getSelectedItem() == cross) {
lblStatus.setText("Deltar Ikke");
calendarModel.setStatus('n',userNotification);
}
if (yourStatus.getSelectedItem() == question) {
lblStatus.setText("Ikke svart");
calendarModel.setStatus('w',userNotification);
}
frame.setVisible(false);
}
});
moreInfo = new JTextArea(meeting.getDescription());
moreInfo.setEditable(false);
moreInfo.setFocusable(false);
moreInfo.setPreferredSize(new Dimension(320, 100));
c.gridx = 1;
c.gridy = 2;
overViewPanel.add(moreInfo, c);
listModel = new DefaultListModel();
for (int i = 0; i < notifications.size(); i++) {
listModel.addElement(notifications.get(i));
}
participantList = new JList<Notification>();
participantList.setModel(listModel);
participantList.setFixedCellWidth(300);
participantList.setCellRenderer(new overViewRender());
JScrollPane myJScrollPane = new JScrollPane(participantList);
myJScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
c.gridx = 1;
c.gridy = 3;
overViewPanel.add(myJScrollPane, c);
frame = new JFrame();
frame.setContentPane(overViewPanel);
frame.pack();
frame.setVisible(true);
}
| private void initialize() {
check = new ImageIcon("res/icons/icon_check.png");
cross = new ImageIcon("res/icons/icon_cross.png");
question = new ImageIcon("res/icons/icon_question.png");
star = new ImageIcon("res/icons/icon_star.png");
overViewPanel = new JPanel(new GridBagLayout());
overViewPanel.setPreferredSize(new Dimension(700, 450));
overViewPanel.setVisible(true);
GridBagConstraints c = new GridBagConstraints();
headLine = new JLabel(meeting.getTitle());
c.gridx = 0;
c.gridy = 0;
headLine.setPreferredSize(new Dimension(300, 25));
headLine.setFont(new Font(headLine.getFont().getName(),headLine.getFont().getStyle(), 20 ));
overViewPanel.add(headLine, c);
lblInfo = new JLabel(getTime() + " p� rom: " + getLoc());
c.gridx = 0;
c.gridy = 1;
lblInfo.setPreferredSize(new Dimension(300,25));
overViewPanel.add(lblInfo, c);
c.insets = new Insets(10,0,10,0);
lblMoreInfo = new JLabel("Beskrivelse:");
c.gridx = 0;
c.gridy = 2;
overViewPanel.add(lblMoreInfo, c);
lblParticipant = new JLabel("Deltakere:");
c.gridx = 0;
c.gridy = 3;
overViewPanel.add(lblParticipant, c);
lblYourStatus = new JLabel("Din status:");
c.gridx = 0;
c.gridy = 4;
overViewPanel.add(lblYourStatus, c);
change = new JButton("Endre avtale");
c.gridx = 0;
c.gridy = 5;
overViewPanel.add(change, c);
change.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newAppointment = new NewAppointmentView(meeting);
frame.setVisible(false);
overViewPanel.setVisible(true);
}
});
delete = new JButton("Slett avtale");
c.gridx = 1;
c.gridy = 5;
overViewPanel.add(delete, c);
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calendarModel.removeMeeting(meeting);
}
});
if(meeting.getCreator().getUsername().equals(calendarModel.getUser().getUsername()) == false ){
delete.setEnabled(false);
change.setEnabled(false);
}
yourStatus = new JComboBox<ImageIcon>();
yourStatus.addItem(check);
yourStatus.addItem(cross);
yourStatus.addItem(question);
yourStatus.addItem(star);
c.gridx = 1;
c.gridy = 4;
overViewPanel.add(yourStatus, c);
c.gridx = 2;
c.gridy = 4;
lblStatus = new JLabel();
lblStatus.setPreferredSize(new Dimension(70, 25));
overViewPanel.add(lblStatus, c);
if (userNotification != null) {
if (userNotification.getApproved() == 'y') {
yourStatus.setSelectedItem(check);
lblStatus.setText("Deltar");
}
if (userNotification.getApproved() == 'n') {
yourStatus.setSelectedItem(cross);
lblStatus.setText("Deltar Ikke");
}
if (userNotification.getApproved() == 'w') {
yourStatus.setSelectedItem(question);
lblStatus.setText("Vet Ikke");
}
}
if(calendarModel.getUser().getUsername().equals(meeting.getCreator().getUsername()) ){
System.out.println(calendarModel.getUser().getUsername());
System.out.println(meeting.getCreator().getUsername());
change.setEnabled(true);
delete.setEnabled(true);
yourStatus.setSelectedItem(star);
yourStatus.setEnabled(false);
}
yourStatus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (yourStatus.getSelectedItem() == check) {
lblStatus.setText("Deltar");
calendarModel.setStatus('y',userNotification);
}
if (yourStatus.getSelectedItem() == cross) {
lblStatus.setText("Deltar Ikke");
calendarModel.setStatus('n',userNotification);
}
if (yourStatus.getSelectedItem() == question) {
lblStatus.setText("Ikke svart");
calendarModel.setStatus('w',userNotification);
}
frame.setVisible(false);
}
});
moreInfo = new JTextArea(meeting.getDescription());
moreInfo.setEditable(false);
moreInfo.setFocusable(false);
moreInfo.setPreferredSize(new Dimension(320, 100));
c.gridx = 1;
c.gridy = 2;
overViewPanel.add(moreInfo, c);
listModel = new DefaultListModel();
for (int i = 0; i < notifications.size(); i++) {
listModel.addElement(notifications.get(i));
}
participantList = new JList<Notification>();
participantList.setModel(listModel);
participantList.setFixedCellWidth(300);
participantList.setCellRenderer(new overViewRender());
JScrollPane myJScrollPane = new JScrollPane(participantList);
myJScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
c.gridx = 1;
c.gridy = 3;
overViewPanel.add(myJScrollPane, c);
frame = new JFrame();
frame.setContentPane(overViewPanel);
frame.pack();
frame.setVisible(true);
}
|
diff --git a/src/org/apache/xpath/objects/XStringForFSB.java b/src/org/apache/xpath/objects/XStringForFSB.java
index 7e059e03..5ba079b6 100644
--- a/src/org/apache/xpath/objects/XStringForFSB.java
+++ b/src/org/apache/xpath/objects/XStringForFSB.java
@@ -1,1116 +1,1113 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, Lotus
* Development Corporation., http://www.lotus.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xpath.objects;
import org.apache.xml.utils.FastStringBuffer;
import org.apache.xml.utils.XMLString;
import org.apache.xml.utils.XMLStringFactory;
import org.apache.xml.utils.XMLCharacterRecognizer;
import java.util.Locale;
/**
* This class will wrap a FastStringBuffer and allow for
*/
public class XStringForFSB extends XString
{
static long MAX_NO_OVERFLOW_RISK=(Long.MAX_VALUE-'9')/10;
/** The start position in the fsb. */
int m_start;
/** The length of the string. */
int m_length;
/** If the str() function is called, the string will be cached here. */
protected String m_strCache = null;
/** cached hash code */
protected int m_hash = 0;
/**
* Construct a XNodeSet object.
*
* @param val FastStringBuffer object this will wrap, must be non-null.
* @param start The start position in the array.
* @param length The number of characters to read from the array.
*/
public XStringForFSB(FastStringBuffer val, int start, int length)
{
super(val);
m_start = start;
m_length = length;
if (null == val)
throw new IllegalArgumentException(
"The FastStringBuffer argument can not be null!!");
}
/**
* Construct a XNodeSet object.
*
* @param val String object this will wrap.
*/
private XStringForFSB(String val)
{
super(val);
throw new IllegalArgumentException(
"XStringForFSB can not take a string for an argument!");
}
/**
* Cast result object to a string.
*
* @return The string this wraps or the empty string if null
*/
public FastStringBuffer fsb()
{
return ((FastStringBuffer) m_obj);
}
/**
* Cast result object to a string.
*
* @return The string this wraps or the empty string if null
*/
public void appendToFsb(org.apache.xml.utils.FastStringBuffer fsb)
{
// %OPT% !!! FSB has to be updated to take partial fsb's for append.
fsb.append(str());
}
/**
* Tell if this object contains a java String object.
*
* @return true if this XMLString can return a string without creating one.
*/
public boolean hasString()
{
return (null != m_strCache);
}
// /** NEEDSDOC Field strCount */
// public static int strCount = 0;
//
// /** NEEDSDOC Field xtable */
// static java.util.Hashtable xtable = new java.util.Hashtable();
/**
* Since this object is incomplete without the length and the offset, we
* have to convert to a string when this function is called.
*
* @return The java String representation of this object.
*/
public Object object()
{
return str();
}
/**
* Cast result object to a string.
*
* @return The string this wraps or the empty string if null
*/
public String str()
{
if (null == m_strCache)
{
m_strCache = fsb().getString(m_start, m_length);
// strCount++;
//
// RuntimeException e = new RuntimeException("Bad! Bad!");
// java.io.CharArrayWriter writer = new java.io.CharArrayWriter();
// java.io.PrintWriter pw = new java.io.PrintWriter(writer);
//
// e.printStackTrace(pw);
//
// String str = writer.toString();
//
// str = str.substring(0, 600);
//
// if (null == xtable.get(str))
// {
// xtable.put(str, str);
// System.out.println(str);
// }
// System.out.println("strCount: " + strCount);
// throw e;
// e.printStackTrace();
// System.exit(-1);
}
return m_strCache;
}
/**
* Directly call the
* characters method on the passed ContentHandler for the
* string-value. Multiple calls to the
* ContentHandler's characters methods may well occur for a single call to
* this method.
*
* @param ch A non-null reference to a ContentHandler.
*
* @throws org.xml.sax.SAXException
*/
public void dispatchCharactersEvents(org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
fsb().sendSAXcharacters(ch, m_start, m_length);
}
/**
* Directly call the
* comment method on the passed LexicalHandler for the
* string-value.
*
* @param lh A non-null reference to a LexicalHandler.
*
* @throws org.xml.sax.SAXException
*/
public void dispatchAsComment(org.xml.sax.ext.LexicalHandler lh)
throws org.xml.sax.SAXException
{
fsb().sendSAXComment(lh, m_start, m_length);
}
/**
* Returns the length of this string.
*
* @return the length of the sequence of characters represented by this
* object.
*/
public int length()
{
return m_length;
}
/**
* Returns the character at the specified index. An index ranges
* from <code>0</code> to <code>length() - 1</code>. The first character
* of the sequence is at index <code>0</code>, the next at index
* <code>1</code>, and so on, as for array indexing.
*
* @param index the index of the character.
* @return the character at the specified index of this string.
* The first character is at index <code>0</code>.
* @exception IndexOutOfBoundsException if the <code>index</code>
* argument is negative or not less than the length of this
* string.
*/
public char charAt(int index)
{
return fsb().charAt(m_start + index);
}
/**
* Copies characters from this string into the destination character
* array.
*
* @param srcBegin index of the first character in the string
* to copy.
* @param srcEnd index after the last character in the string
* to copy.
* @param dst the destination array.
* @param dstBegin the start offset in the destination array.
* @exception IndexOutOfBoundsException If any of the following
* is true:
* <ul><li><code>srcBegin</code> is negative.
* <li><code>srcBegin</code> is greater than <code>srcEnd</code>
* <li><code>srcEnd</code> is greater than the length of this
* string
* <li><code>dstBegin</code> is negative
* <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
* <code>dst.length</code></ul>
* @exception NullPointerException if <code>dst</code> is <code>null</code>
*/
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
{
// %OPT% Need to call this on FSB when it is implemented.
// %UNTESTED% (I don't think anyone calls this yet?)
int n = srcEnd - srcBegin;
if (n > m_length)
n = m_length;
if (n > (dst.length - dstBegin))
n = (dst.length - dstBegin);
int end = srcBegin + m_start + n;
int d = dstBegin;
FastStringBuffer fsb = fsb();
for (int i = srcBegin + m_start; i < end; i++)
{
dst[d++] = fsb.charAt(i);
}
}
/**
* Compares this string to the specified object.
* The result is <code>true</code> if and only if the argument is not
* <code>null</code> and is a <code>String</code> object that represents
* the same sequence of characters as this object.
*
* @param anObject the object to compare this <code>String</code>
* against.
*
* NEEDSDOC @param obj2
* @return <code>true</code> if the <code>String </code>are equal;
* <code>false</code> otherwise.
* @see java.lang.String#compareTo(java.lang.String)
* @see java.lang.String#equalsIgnoreCase(java.lang.String)
*/
public boolean equals(XMLString obj2)
{
if (this == obj2)
{
return true;
}
int n = m_length;
if (n == obj2.length())
{
FastStringBuffer fsb = fsb();
int i = m_start;
int j = 0;
while (n-- != 0)
{
if (fsb.charAt(i) != obj2.charAt(j))
{
return false;
}
i++;
j++;
}
return true;
}
return false;
}
/**
* Tell if two objects are functionally equal.
*
* @param obj2 Object to compare this to
*
* @return true if the two objects are equal
*
* @throws javax.xml.transform.TransformerException
*/
public boolean equals(XObject obj2)
{
if (this == obj2)
{
return true;
}
String str = obj2.str();
int n = m_length;
if (n == str.length())
{
FastStringBuffer fsb = fsb();
int i = m_start;
int j = 0;
while (n-- != 0)
{
if (fsb.charAt(i) != str.charAt(j))
{
return false;
}
i++;
j++;
}
return true;
}
return false;
}
/**
* Tell if two objects are functionally equal.
*
* @param obj2 Object to compare this to
*
* NEEDSDOC @param anotherString
*
* @return true if the two objects are equal
*
* @throws javax.xml.transform.TransformerException
*/
public boolean equals(String anotherString)
{
int n = m_length;
if (n == anotherString.length())
{
FastStringBuffer fsb = fsb();
int i = m_start;
int j = 0;
while (n-- != 0)
{
if (fsb.charAt(i) != anotherString.charAt(j))
{
return false;
}
i++;
j++;
}
return true;
}
return false;
}
/**
* Compares this string to the specified object.
* The result is <code>true</code> if and only if the argument is not
* <code>null</code> and is a <code>String</code> object that represents
* the same sequence of characters as this object.
*
* @param anObject the object to compare this <code>String</code>
* against.
*
* NEEDSDOC @param obj2
* @return <code>true</code> if the <code>String </code>are equal;
* <code>false</code> otherwise.
* @see java.lang.String#compareTo(java.lang.String)
* @see java.lang.String#equalsIgnoreCase(java.lang.String)
*/
public boolean equals(Object obj2)
{
if (null == obj2)
return false;
// In order to handle the 'all' semantics of
// nodeset comparisons, we always call the
// nodeset function.
else if (obj2 instanceof XNodeSet)
return obj2.equals(this);
else if (obj2 instanceof XStringForFSB)
return equals((XMLString) this);
else
return equals(obj2.toString());
}
/**
* Compares this <code>String</code> to another <code>String</code>,
* ignoring case considerations. Two strings are considered equal
* ignoring case if they are of the same length, and corresponding
* characters in the two strings are equal ignoring case.
*
* @param anotherString the <code>String</code> to compare this
* <code>String</code> against.
* @return <code>true</code> if the argument is not <code>null</code>
* and the <code>String</code>s are equal,
* ignoring case; <code>false</code> otherwise.
* @see #equals(Object)
* @see java.lang.Character#toLowerCase(char)
* @see java.lang.Character#toUpperCase(char)
*/
public boolean equalsIgnoreCase(String anotherString)
{
return (m_length == anotherString.length())
? str().equalsIgnoreCase(anotherString) : false;
}
/**
* Compares two strings lexicographically.
*
* @param anotherString the <code>String</code> to be compared.
*
* NEEDSDOC @param xstr
* @return the value <code>0</code> if the argument string is equal to
* this string; a value less than <code>0</code> if this string
* is lexicographically less than the string argument; and a
* value greater than <code>0</code> if this string is
* lexicographically greater than the string argument.
* @exception java.lang.NullPointerException if <code>anotherString</code>
* is <code>null</code>.
*/
public int compareTo(XMLString xstr)
{
int len1 = m_length;
int len2 = xstr.length();
int n = Math.min(len1, len2);
FastStringBuffer fsb = fsb();
int i = m_start;
int j = 0;
while (n-- != 0)
{
char c1 = fsb.charAt(i);
char c2 = xstr.charAt(j);
if (c1 != c2)
{
return c1 - c2;
}
i++;
j++;
}
return len1 - len2;
}
/**
* Compares two strings lexicographically, ignoring case considerations.
* This method returns an integer whose sign is that of
* <code>this.toUpperCase().toLowerCase().compareTo(
* str.toUpperCase().toLowerCase())</code>.
* <p>
* Note that this method does <em>not</em> take locale into account,
* and will result in an unsatisfactory ordering for certain locales.
* The java.text package provides <em>collators</em> to allow
* locale-sensitive ordering.
*
* @param str the <code>String</code> to be compared.
*
* NEEDSDOC @param xstr
* @return a negative integer, zero, or a positive integer as the
* the specified String is greater than, equal to, or less
* than this String, ignoring case considerations.
* @see java.text.Collator#compare(String, String)
* @since 1.2
*/
public int compareToIgnoreCase(XMLString xstr)
{
int len1 = m_length;
int len2 = xstr.length();
int n = Math.min(len1, len2);
FastStringBuffer fsb = fsb();
int i = m_start;
int j = 0;
while (n-- != 0)
{
char c1 = Character.toLowerCase(fsb.charAt(i));
char c2 = Character.toLowerCase(xstr.charAt(j));
if (c1 != c2)
{
return c1 - c2;
}
i++;
j++;
}
return len1 - len2;
}
/**
* Returns a hashcode for this string. The hashcode for a
* <code>String</code> object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using <code>int</code> arithmetic, where <code>s[i]</code> is the
* <i>i</i>th character of the string, <code>n</code> is the length of
* the string, and <code>^</code> indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode()
{
// Commenting this out because in JDK1.1.8 and VJ++
// we don't match XMLStrings. Defaulting to the super
// causes us to create a string, but at this point
// this only seems to get called in key processing.
// Maybe we can live with it?
/*
int h = m_hash;
if (h == 0)
{
int off = m_start;
int len = m_length;
FastStringBuffer fsb = fsb();
for (int i = 0; i < len; i++)
{
h = 31 * h + fsb.charAt(off);
off++;
}
m_hash = h;
}
*/
return super.hashCode(); // h;
}
/**
* Tests if this string starts with the specified prefix beginning
* a specified index.
*
* @param prefix the prefix.
* @param toffset where to begin looking in the string.
* @return <code>true</code> if the character sequence represented by the
* argument is a prefix of the substring of this object starting
* at index <code>toffset</code>; <code>false</code> otherwise.
* The result is <code>false</code> if <code>toffset</code> is
* negative or greater than the length of this
* <code>String</code> object; otherwise the result is the same
* as the result of the expression
* <pre>
* this.subString(toffset).startsWith(prefix)
* </pre>
* @exception java.lang.NullPointerException if <code>prefix</code> is
* <code>null</code>.
*/
public boolean startsWith(XMLString prefix, int toffset)
{
FastStringBuffer fsb = fsb();
int to = m_start + toffset;
int tlim = m_start + m_length;
int po = 0;
int pc = prefix.length();
// Note: toffset might be near -1>>>1.
if ((toffset < 0) || (toffset > m_length - pc))
{
return false;
}
while (--pc >= 0)
{
if (fsb.charAt(to) != prefix.charAt(po))
{
return false;
}
to++;
po++;
}
return true;
}
/**
* Tests if this string starts with the specified prefix.
*
* @param prefix the prefix.
* @return <code>true</code> if the character sequence represented by the
* argument is a prefix of the character sequence represented by
* this string; <code>false</code> otherwise.
* Note also that <code>true</code> will be returned if the
* argument is an empty string or is equal to this
* <code>String</code> object as determined by the
* {@link #equals(Object)} method.
* @exception java.lang.NullPointerException if <code>prefix</code> is
* <code>null</code>.
* @since JDK1. 0
*/
public boolean startsWith(XMLString prefix)
{
return startsWith(prefix, 0);
}
/**
* Returns the index within this string of the first occurrence of the
* specified character. If a character with value <code>ch</code> occurs
* in the character sequence represented by this <code>String</code>
* object, then the index of the first such occurrence is returned --
* that is, the smallest value <i>k</i> such that:
* <blockquote><pre>
* this.charAt(<i>k</i>) == ch
* </pre></blockquote>
* is <code>true</code>. If no such character occurs in this string,
* then <code>-1</code> is returned.
*
* @param ch a character.
* @return the index of the first occurrence of the character in the
* character sequence represented by this object, or
* <code>-1</code> if the character does not occur.
*/
public int indexOf(int ch)
{
return indexOf(ch, 0);
}
/**
* Returns the index within this string of the first occurrence of the
* specified character, starting the search at the specified index.
* <p>
* If a character with value <code>ch</code> occurs in the character
* sequence represented by this <code>String</code> object at an index
* no smaller than <code>fromIndex</code>, then the index of the first
* such occurrence is returned--that is, the smallest value <i>k</i>
* such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
* </pre></blockquote>
* is true. If no such character occurs in this string at or after
* position <code>fromIndex</code>, then <code>-1</code> is returned.
* <p>
* There is no restriction on the value of <code>fromIndex</code>. If it
* is negative, it has the same effect as if it were zero: this entire
* string may be searched. If it is greater than the length of this
* string, it has the same effect as if it were equal to the length of
* this string: <code>-1</code> is returned.
*
* @param ch a character.
* @param fromIndex the index to start the search from.
* @return the index of the first occurrence of the character in the
* character sequence represented by this object that is greater
* than or equal to <code>fromIndex</code>, or <code>-1</code>
* if the character does not occur.
*/
public int indexOf(int ch, int fromIndex)
{
int max = m_start + m_length;
FastStringBuffer fsb = fsb();
if (fromIndex < 0)
{
fromIndex = 0;
}
else if (fromIndex >= m_length)
{
// Note: fromIndex might be near -1>>>1.
return -1;
}
for (int i = m_start + fromIndex; i < max; i++)
{
if (fsb.charAt(i) == ch)
{
return i - m_start;
}
}
return -1;
}
/**
* Returns a new string that is a substring of this string. The
* substring begins with the character at the specified index and
* extends to the end of this string. <p>
* Examples:
* <blockquote><pre>
* "unhappy".substring(2) returns "happy"
* "Harbison".substring(3) returns "bison"
* "emptiness".substring(9) returns "" (an empty string)
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if
* <code>beginIndex</code> is negative or larger than the
* length of this <code>String</code> object.
*/
public XMLString substring(int beginIndex)
{
int len = m_length - beginIndex;
if (len <= 0)
return XString.EMPTYSTRING;
else
{
int start = m_start + beginIndex;
return new XStringForFSB(fsb(), start, len);
}
}
/**
* Returns a new string that is a substring of this string. The
* substring begins at the specified <code>beginIndex</code> and
* extends to the character at index <code>endIndex - 1</code>.
* Thus the length of the substring is <code>endIndex-beginIndex</code>.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of
* this <code>String</code> object, or
* <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
public XMLString substring(int beginIndex, int endIndex)
{
int len = endIndex - beginIndex;
if (len > m_length)
len = m_length;
if (len <= 0)
return XString.EMPTYSTRING;
else
{
int start = m_start + beginIndex;
return new XStringForFSB(fsb(), start, len);
}
}
/**
* Concatenates the specified string to the end of this string.
*
* @param str the <code>String</code> that is concatenated to the end
* of this <code>String</code>.
* @return a string that represents the concatenation of this object's
* characters followed by the string argument's characters.
* @exception java.lang.NullPointerException if <code>str</code> is
* <code>null</code>.
*/
public XMLString concat(String str)
{
// %OPT% Make an FSB here?
return new XString(str().concat(str));
}
/**
* Removes white space from both ends of this string.
*
* @return this string, with white space removed from the front and end.
*/
public XMLString trim()
{
return fixWhiteSpace(true, true, false);
}
/**
* Returns whether the specified <var>ch</var> conforms to the XML 1.0 definition
* of whitespace. Refer to <A href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S">
* the definition of <CODE>S</CODE></A> for details.
* @param ch Character to check as XML whitespace.
* @return =true if <var>ch</var> is XML whitespace; otherwise =false.
*/
private static boolean isSpace(char ch)
{
return XMLCharacterRecognizer.isWhiteSpace(ch); // Take the easy way out for now.
}
/**
* Conditionally trim all leading and trailing whitespace in the specified String.
* All strings of white space are
* replaced by a single space character (#x20), except spaces after punctuation which
* receive double spaces if doublePunctuationSpaces is true.
* This function may be useful to a formatter, but to get first class
* results, the formatter should probably do it's own white space handling
* based on the semantics of the formatting object.
*
* @param trimHead Trim leading whitespace?
* @param trimTail Trim trailing whitespace?
* @param doublePunctuationSpaces Use double spaces for punctuation?
* @return The trimmed string.
*/
public XMLString fixWhiteSpace(boolean trimHead, boolean trimTail,
boolean doublePunctuationSpaces)
{
int end = m_length + m_start;
char[] buf = new char[m_length];
FastStringBuffer fsb = fsb();
boolean edit = false;
/* replace S to ' '. and ' '+ -> single ' '. */
int d = 0;
boolean pres = false;
for (int s = m_start; s < end; s++)
{
char c = fsb.charAt(s);
if (isSpace(c))
{
if (!pres)
{
if (' ' != c)
{
edit = true;
}
buf[d++] = ' ';
if (doublePunctuationSpaces && (d != 0))
{
char prevChar = buf[d - 1];
if (!((prevChar == '.') || (prevChar == '!')
|| (prevChar == '?')))
{
pres = true;
}
}
else
{
pres = true;
}
}
else
{
edit = true;
pres = true;
}
}
else
{
buf[d++] = c;
pres = false;
}
}
if (trimTail && 1 <= d && ' ' == buf[d - 1])
{
edit = true;
d--;
}
int start = 0;
if (trimHead && 0 < d && ' ' == buf[0])
{
edit = true;
start++;
}
XMLStringFactory xsf = XMLStringFactoryImpl.getFactory();
return edit ? xsf.newstr(buf, start, d - start) : this;
}
/**
* Convert a string to a double -- Allowed input is in fixed
* notation ddd.fff.
*
* %OPT% CHECK PERFORMANCE against generating a Java String and
* converting it to double. The advantage of running in native
* machine code -- perhaps even microcode, on some systems -- may
* more than make up for the cost of allocating and discarding the
* additional object. We need to benchmark this.
*
* %OPT% More importantly, we need to decide whether we _care_ about
* the performance of this operation. Does XString.toDouble constitute
* any measurable percentage of our typical runtime? I suspect not!
*
* %REVIEW%
*
* @return A double value representation of the string, or return Double.NaN
* if the string can not be converted. */
public double toDouble()
{
int end = m_length+m_start;
if(0 == end)
return Double.NaN;
int start = m_start;
FastStringBuffer fsb = fsb();
long longResult=0;
boolean isNegative=false;
boolean trailingSpace=false;
int[] digitsFound={0,0}; // intpart,fracpart
int digitType=0; // Index to which kind of digit we're accumulating
double doubleResult;
int overflow=0;
// Scan past leading whitespace characters
while(start< end &&
XMLCharacterRecognizer.isWhiteSpace( fsb.charAt(start) )
)
++start;
if (start < end && fsb.charAt(start) == '-')
{
isNegative=true;
start++;
}
// parse the string from left to right converting as an integer.
for (int i = start; i < end; i++)
{
char c = fsb.charAt(i);
if(XMLCharacterRecognizer.isWhiteSpace(c))
{
trailingSpace=true;
break; // Trailing whitespace is ignored
}
else if(trailingSpace)
return Double.NaN; // Nonspace after space is poorly formed
switch(c)
{
case '.':
if(digitType==0)
digitType=1;
else
return Double.NaN; // Second period is error
break;
case '0': // NOT Unicode isDigit(); ASCII digits _only_
- if(digitType==0 && digitsFound[0]==0) // Ignore leading zeros
- break;
- // Else fall through into normal digit handling.
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// We have a potential overflow issue that we need
// to guard against. See Bugzilla 5346.
//
// %REVIEW% MUST BE RECONSIDERED. I _think_ the truncation of
// the 64-bit long before it overflows is well within the acceptable
// error range of the double's 53-bit mantissa...
if(longResult>MAX_NO_OVERFLOW_RISK)
{
if(digitType==0) ++overflow;
}
else
{
longResult=longResult*10 + (c - '0');
++digitsFound[digitType]; // Remember scaling
}
break;
default:
return Double.NaN; // Nonnumeric is error
}
}
if(0 ==digitsFound[0]&& 0==digitsFound[1])
return Double.NaN;
// Convert from scaled integer to floating point. This will come close.
// There's an alternative solution involving Double.longBitsToDouble
// followed by a combined renormalize/scale operation... but I honestly
// think the more straightforward solution comes out to just about
// the same thing.
long scale=1; // AFAIK, java doesn't have an easier 10^n operation
doubleResult=(double)longResult;
if(digitsFound[1]==0) // Integer overflow scaling
{
for(int i=overflow;i>0;--i)
scale*=10;
doubleResult*=scale;
}
else // Fractional-part scaling
{
// Complication: In values <0, the fractional part may want to be divided
// by a power of 10 too large to fit in a long! In that case, resort to
// successive divisions.
//
// %REVIEW% This can't be an optimal solution. Need a better algorithm.
int i=digitsFound[1];
while(i>0)
{
int j=(i<18) ? i : 18;
i-=j;
for(scale=1;j>0;--j)
scale*=10;
doubleResult/=scale;
}
}
if(isNegative)
doubleResult *= -1;
return doubleResult;
}
}
| true | true | public double toDouble()
{
int end = m_length+m_start;
if(0 == end)
return Double.NaN;
int start = m_start;
FastStringBuffer fsb = fsb();
long longResult=0;
boolean isNegative=false;
boolean trailingSpace=false;
int[] digitsFound={0,0}; // intpart,fracpart
int digitType=0; // Index to which kind of digit we're accumulating
double doubleResult;
int overflow=0;
// Scan past leading whitespace characters
while(start< end &&
XMLCharacterRecognizer.isWhiteSpace( fsb.charAt(start) )
)
++start;
if (start < end && fsb.charAt(start) == '-')
{
isNegative=true;
start++;
}
// parse the string from left to right converting as an integer.
for (int i = start; i < end; i++)
{
char c = fsb.charAt(i);
if(XMLCharacterRecognizer.isWhiteSpace(c))
{
trailingSpace=true;
break; // Trailing whitespace is ignored
}
else if(trailingSpace)
return Double.NaN; // Nonspace after space is poorly formed
switch(c)
{
case '.':
if(digitType==0)
digitType=1;
else
return Double.NaN; // Second period is error
break;
case '0': // NOT Unicode isDigit(); ASCII digits _only_
if(digitType==0 && digitsFound[0]==0) // Ignore leading zeros
break;
// Else fall through into normal digit handling.
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// We have a potential overflow issue that we need
// to guard against. See Bugzilla 5346.
//
// %REVIEW% MUST BE RECONSIDERED. I _think_ the truncation of
// the 64-bit long before it overflows is well within the acceptable
// error range of the double's 53-bit mantissa...
if(longResult>MAX_NO_OVERFLOW_RISK)
{
if(digitType==0) ++overflow;
}
else
{
longResult=longResult*10 + (c - '0');
++digitsFound[digitType]; // Remember scaling
}
break;
default:
return Double.NaN; // Nonnumeric is error
}
}
if(0 ==digitsFound[0]&& 0==digitsFound[1])
return Double.NaN;
// Convert from scaled integer to floating point. This will come close.
// There's an alternative solution involving Double.longBitsToDouble
// followed by a combined renormalize/scale operation... but I honestly
// think the more straightforward solution comes out to just about
// the same thing.
long scale=1; // AFAIK, java doesn't have an easier 10^n operation
doubleResult=(double)longResult;
if(digitsFound[1]==0) // Integer overflow scaling
{
for(int i=overflow;i>0;--i)
scale*=10;
doubleResult*=scale;
}
else // Fractional-part scaling
{
// Complication: In values <0, the fractional part may want to be divided
// by a power of 10 too large to fit in a long! In that case, resort to
// successive divisions.
//
// %REVIEW% This can't be an optimal solution. Need a better algorithm.
int i=digitsFound[1];
while(i>0)
{
int j=(i<18) ? i : 18;
i-=j;
for(scale=1;j>0;--j)
scale*=10;
doubleResult/=scale;
}
}
if(isNegative)
doubleResult *= -1;
return doubleResult;
}
| public double toDouble()
{
int end = m_length+m_start;
if(0 == end)
return Double.NaN;
int start = m_start;
FastStringBuffer fsb = fsb();
long longResult=0;
boolean isNegative=false;
boolean trailingSpace=false;
int[] digitsFound={0,0}; // intpart,fracpart
int digitType=0; // Index to which kind of digit we're accumulating
double doubleResult;
int overflow=0;
// Scan past leading whitespace characters
while(start< end &&
XMLCharacterRecognizer.isWhiteSpace( fsb.charAt(start) )
)
++start;
if (start < end && fsb.charAt(start) == '-')
{
isNegative=true;
start++;
}
// parse the string from left to right converting as an integer.
for (int i = start; i < end; i++)
{
char c = fsb.charAt(i);
if(XMLCharacterRecognizer.isWhiteSpace(c))
{
trailingSpace=true;
break; // Trailing whitespace is ignored
}
else if(trailingSpace)
return Double.NaN; // Nonspace after space is poorly formed
switch(c)
{
case '.':
if(digitType==0)
digitType=1;
else
return Double.NaN; // Second period is error
break;
case '0': // NOT Unicode isDigit(); ASCII digits _only_
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// We have a potential overflow issue that we need
// to guard against. See Bugzilla 5346.
//
// %REVIEW% MUST BE RECONSIDERED. I _think_ the truncation of
// the 64-bit long before it overflows is well within the acceptable
// error range of the double's 53-bit mantissa...
if(longResult>MAX_NO_OVERFLOW_RISK)
{
if(digitType==0) ++overflow;
}
else
{
longResult=longResult*10 + (c - '0');
++digitsFound[digitType]; // Remember scaling
}
break;
default:
return Double.NaN; // Nonnumeric is error
}
}
if(0 ==digitsFound[0]&& 0==digitsFound[1])
return Double.NaN;
// Convert from scaled integer to floating point. This will come close.
// There's an alternative solution involving Double.longBitsToDouble
// followed by a combined renormalize/scale operation... but I honestly
// think the more straightforward solution comes out to just about
// the same thing.
long scale=1; // AFAIK, java doesn't have an easier 10^n operation
doubleResult=(double)longResult;
if(digitsFound[1]==0) // Integer overflow scaling
{
for(int i=overflow;i>0;--i)
scale*=10;
doubleResult*=scale;
}
else // Fractional-part scaling
{
// Complication: In values <0, the fractional part may want to be divided
// by a power of 10 too large to fit in a long! In that case, resort to
// successive divisions.
//
// %REVIEW% This can't be an optimal solution. Need a better algorithm.
int i=digitsFound[1];
while(i>0)
{
int j=(i<18) ? i : 18;
i-=j;
for(scale=1;j>0;--j)
scale*=10;
doubleResult/=scale;
}
}
if(isNegative)
doubleResult *= -1;
return doubleResult;
}
|
diff --git a/src/de/schildbach/pte/SbbProvider.java b/src/de/schildbach/pte/SbbProvider.java
index 99183e5..af6ceff 100644
--- a/src/de/schildbach/pte/SbbProvider.java
+++ b/src/de/schildbach/pte/SbbProvider.java
@@ -1,206 +1,206 @@
/*
* Copyright 2010, 2011 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.schildbach.pte;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.schildbach.pte.dto.Location;
import de.schildbach.pte.dto.LocationType;
import de.schildbach.pte.dto.NearbyStationsResult;
import de.schildbach.pte.dto.QueryDeparturesResult;
import de.schildbach.pte.util.ParserUtils;
/**
* @author Andreas Schildbach
*/
public class SbbProvider extends AbstractHafasProvider
{
public static final NetworkId NETWORK_ID = NetworkId.SBB;
public static final String OLD_NETWORK_ID = "fahrplan.sbb.ch";
private static final String API_BASE = "http://fahrplan.sbb.ch/bin/";
private static final String API_URI = "http://fahrplan.sbb.ch/bin/extxml.exe"; // xmlfahrplan.sbb.ch
public SbbProvider(final String accessId)
{
super(API_URI, 10, accessId);
}
public NetworkId id()
{
return NETWORK_ID;
}
public boolean hasCapabilities(final Capability... capabilities)
{
for (final Capability capability : capabilities)
if (capability == Capability.AUTOCOMPLETE_ONE_LINE || capability == Capability.DEPARTURES || capability == Capability.CONNECTIONS)
return true;
return false;
}
@Override
protected void setProductBits(final StringBuilder productBits, final char product)
{
if (product == 'I')
{
productBits.setCharAt(0, '1'); // ICE/TGV/IRJ
productBits.setCharAt(1, '1'); // EC/IC
}
else if (product == 'R')
{
productBits.setCharAt(2, '1'); // IR
productBits.setCharAt(3, '1'); // RE/D
productBits.setCharAt(8, '1'); // ARZ/EXT
}
else if (product == 'S')
{
productBits.setCharAt(5, '1'); // S/SN/R
}
else if (product == 'U' || product == 'T')
{
- productBits.setCharAt(7, '1'); // Tram/Metro
+ productBits.setCharAt(9, '1'); // Tram/Metro
}
else if (product == 'B' || product == 'P')
{
productBits.setCharAt(6, '1'); // Bus
}
else if (product == 'F')
{
productBits.setCharAt(4, '1'); // Schiff
}
else if (product == 'C')
{
productBits.setCharAt(7, '1'); // Seilbahn
}
else
{
throw new IllegalArgumentException("cannot handle: " + product);
}
}
public NearbyStationsResult queryNearbyStations(final Location location, final int maxDistance, final int maxStations) throws IOException
{
final StringBuilder uri = new StringBuilder(API_BASE);
if (location.hasLocation())
{
uri.append("query.exe/dny");
uri.append("?performLocating=2&tpl=stop2json");
uri.append("&look_maxno=").append(maxStations != 0 ? maxStations : 200);
uri.append("&look_maxdist=").append(maxDistance != 0 ? maxDistance : 5000);
uri.append("&look_stopclass=").append(allProductsInt());
uri.append("&look_x=").append(location.lon);
uri.append("&look_y=").append(location.lat);
return jsonNearbyStations(uri.toString());
}
else if (location.type == LocationType.STATION && location.hasId())
{
uri.append("stboard.exe/dn");
uri.append("?productsFilter=").append(allProductsString());
uri.append("&boardType=dep");
uri.append("&input=").append(location.id);
uri.append("&sTI=1&start=yes&hcount=0");
uri.append("&L=vs_java3");
return xmlNearbyStations(uri.toString());
}
else
{
throw new IllegalArgumentException("cannot handle: " + location.toDebugString());
}
}
public QueryDeparturesResult queryDepartures(final int stationId, final int maxDepartures, final boolean equivs) throws IOException
{
final StringBuilder uri = new StringBuilder();
uri.append(API_BASE).append("stboard.exe/dn");
uri.append("?productsFilter=").append(allProductsString());
uri.append("&boardType=dep");
uri.append("&disableEquivs=yes"); // don't use nearby stations
uri.append("&maxJourneys=50"); // ignore maxDepartures because result contains other stations
uri.append("&start=yes");
uri.append("&L=vs_java3");
uri.append("&input=").append(stationId);
return xmlQueryDepartures(uri.toString(), stationId);
}
private static final String AUTOCOMPLETE_URI = API_BASE + "ajax-getstop.exe/dn?getstop=1&REQ0JourneyStopsS0A=255&S=%s?&js=true&";
private static final String ENCODING = "ISO-8859-1";
public List<Location> autocompleteStations(final CharSequence constraint) throws IOException
{
final String uri = String.format(AUTOCOMPLETE_URI, ParserUtils.urlEncode(constraint.toString(), ENCODING));
return jsonGetStops(uri);
}
private static final Pattern P_NORMALIZE_LINE_AND_TYPE = Pattern.compile("([^#]*)#(.*)");
@Override
protected String normalizeLine(final String line)
{
final Matcher m = P_NORMALIZE_LINE_AND_TYPE.matcher(line);
if (m.matches())
{
final String number = m.group(1).replaceAll("\\s+", " ");
final String type = m.group(2);
final char normalizedType = normalizeType(type);
if (normalizedType != 0)
return normalizedType + number;
throw new IllegalStateException("cannot normalize type " + type + " number " + number + " line " + line);
}
throw new IllegalStateException("cannot normalize line " + line);
}
@Override
protected char normalizeType(final String type)
{
final String ucType = type.toUpperCase();
if ("IN".equals(ucType)) // Italien Roma-Lecce
return 'I';
if ("E".equals(ucType))
return 'R';
if ("T".equals(ucType))
return 'R';
if ("M".equals(ucType)) // Metro Wien
return 'U';
if ("TX".equals(ucType))
return 'B';
if ("NFO".equals(ucType))
return 'B';
final char t = super.normalizeType(type);
if (t != 0)
return t;
return 0;
}
}
| true | true | protected void setProductBits(final StringBuilder productBits, final char product)
{
if (product == 'I')
{
productBits.setCharAt(0, '1'); // ICE/TGV/IRJ
productBits.setCharAt(1, '1'); // EC/IC
}
else if (product == 'R')
{
productBits.setCharAt(2, '1'); // IR
productBits.setCharAt(3, '1'); // RE/D
productBits.setCharAt(8, '1'); // ARZ/EXT
}
else if (product == 'S')
{
productBits.setCharAt(5, '1'); // S/SN/R
}
else if (product == 'U' || product == 'T')
{
productBits.setCharAt(7, '1'); // Tram/Metro
}
else if (product == 'B' || product == 'P')
{
productBits.setCharAt(6, '1'); // Bus
}
else if (product == 'F')
{
productBits.setCharAt(4, '1'); // Schiff
}
else if (product == 'C')
{
productBits.setCharAt(7, '1'); // Seilbahn
}
else
{
throw new IllegalArgumentException("cannot handle: " + product);
}
}
| protected void setProductBits(final StringBuilder productBits, final char product)
{
if (product == 'I')
{
productBits.setCharAt(0, '1'); // ICE/TGV/IRJ
productBits.setCharAt(1, '1'); // EC/IC
}
else if (product == 'R')
{
productBits.setCharAt(2, '1'); // IR
productBits.setCharAt(3, '1'); // RE/D
productBits.setCharAt(8, '1'); // ARZ/EXT
}
else if (product == 'S')
{
productBits.setCharAt(5, '1'); // S/SN/R
}
else if (product == 'U' || product == 'T')
{
productBits.setCharAt(9, '1'); // Tram/Metro
}
else if (product == 'B' || product == 'P')
{
productBits.setCharAt(6, '1'); // Bus
}
else if (product == 'F')
{
productBits.setCharAt(4, '1'); // Schiff
}
else if (product == 'C')
{
productBits.setCharAt(7, '1'); // Seilbahn
}
else
{
throw new IllegalArgumentException("cannot handle: " + product);
}
}
|
diff --git a/src/main/java/org/ghana/mtn/App.java b/src/main/java/org/ghana/mtn/App.java
index 02543d3..62e0ef5 100644
--- a/src/main/java/org/ghana/mtn/App.java
+++ b/src/main/java/org/ghana/mtn/App.java
@@ -1,9 +1,9 @@
package org.ghana.mtn;
public class App
{
public static void main( String[] args )
{
- System.out.println( "Hello World!" );
+ System.out.println( "Hello Ghana!" );
}
}
| true | true | public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
| public static void main( String[] args )
{
System.out.println( "Hello Ghana!" );
}
|
diff --git a/src/com/iCo6/handlers/Payment.java b/src/com/iCo6/handlers/Payment.java
index bc97d83..7489d59 100644
--- a/src/com/iCo6/handlers/Payment.java
+++ b/src/com/iCo6/handlers/Payment.java
@@ -1,106 +1,106 @@
package com.iCo6.handlers;
import java.util.LinkedHashMap;
import com.iCo6.command.Handler;
import com.iCo6.command.Parser.Argument;
import com.iCo6.command.exceptions.InvalidUsage;
import com.iCo6.iConomy;
import com.iCo6.system.Account;
import com.iCo6.system.Accounts;
import com.iCo6.system.Holdings;
import com.iCo6.util.Common;
import com.iCo6.util.Messaging;
import com.iCo6.util.Template;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Payment extends Handler {
private Accounts Accounts = new Accounts();
public Payment(iConomy plugin) {
super(plugin, plugin.Template);
}
@Override
public boolean perform(CommandSender sender, LinkedHashMap<String, Argument> arguments) throws InvalidUsage {
if(!hasPermissions(sender, "pay"))
return false;
if(isConsole(sender)) {
Messaging.send(sender, "`rCannot remove money from a non-living organism.");
return false;
}
Player from = (Player) sender;
String name = arguments.get("name").getStringValue();
String tag = template.color(Template.Node.TAG_MONEY);
Double amount;
if(name.equals("0"))
throw new InvalidUsage("Missing <white>name<rose>: /money pay <name> <amount>");
if(arguments.get("amount").getStringValue().equals("empty"))
throw new InvalidUsage("Missing <white>amount<rose>: /money pay <name> <amount>");
try {
amount = arguments.get("amount").getDoubleValue();
} catch(NumberFormatException e) {
throw new InvalidUsage("Invalid <white>amount<rose>, must be double.");
}
if(Double.isInfinite(amount) || Double.isNaN(amount))
throw new InvalidUsage("Invalid <white>amount<rose>, must be double.");
if(amount < 0.1)
throw new InvalidUsage("Invalid <white>amount<rose>, cannot be less than 0.1");
if(Common.matches(from.getName(), name)) {
template.set(Template.Node.PAYMENT_SELF);
Messaging.send(sender, template.parse());
return false;
}
if(!Accounts.exists(name)) {
template.set(Template.Node.ERROR_ACCOUNT);
template.add("name", name);
Messaging.send(sender, tag + template.parse());
return false;
}
Account holder = new Account(from.getName());
Holdings holdings = holder.getHoldings();
if(holdings.getBalance() < amount) {
template.set(Template.Node.ERROR_FUNDS);
Messaging.send(sender, tag + template.parse());
return false;
}
Account account = new Account(name);
holdings.subtract(amount);
account.getHoldings().add(amount);
template.set(Template.Node.PAYMENT_TO);
template.add("name", name);
template.add("amount", iConomy.format(amount));
Messaging.send(sender, tag + template.parse());
Player to = iConomy.Server.getPlayer(name);
if(to != null) {
template.set(Template.Node.PAYMENT_FROM);
- template.add("name", name);
+ template.add("name", from.getName());
template.add("amount", iConomy.format(amount));
Messaging.send(to, tag + template.parse());
}
return false;
}
}
| true | true | public boolean perform(CommandSender sender, LinkedHashMap<String, Argument> arguments) throws InvalidUsage {
if(!hasPermissions(sender, "pay"))
return false;
if(isConsole(sender)) {
Messaging.send(sender, "`rCannot remove money from a non-living organism.");
return false;
}
Player from = (Player) sender;
String name = arguments.get("name").getStringValue();
String tag = template.color(Template.Node.TAG_MONEY);
Double amount;
if(name.equals("0"))
throw new InvalidUsage("Missing <white>name<rose>: /money pay <name> <amount>");
if(arguments.get("amount").getStringValue().equals("empty"))
throw new InvalidUsage("Missing <white>amount<rose>: /money pay <name> <amount>");
try {
amount = arguments.get("amount").getDoubleValue();
} catch(NumberFormatException e) {
throw new InvalidUsage("Invalid <white>amount<rose>, must be double.");
}
if(Double.isInfinite(amount) || Double.isNaN(amount))
throw new InvalidUsage("Invalid <white>amount<rose>, must be double.");
if(amount < 0.1)
throw new InvalidUsage("Invalid <white>amount<rose>, cannot be less than 0.1");
if(Common.matches(from.getName(), name)) {
template.set(Template.Node.PAYMENT_SELF);
Messaging.send(sender, template.parse());
return false;
}
if(!Accounts.exists(name)) {
template.set(Template.Node.ERROR_ACCOUNT);
template.add("name", name);
Messaging.send(sender, tag + template.parse());
return false;
}
Account holder = new Account(from.getName());
Holdings holdings = holder.getHoldings();
if(holdings.getBalance() < amount) {
template.set(Template.Node.ERROR_FUNDS);
Messaging.send(sender, tag + template.parse());
return false;
}
Account account = new Account(name);
holdings.subtract(amount);
account.getHoldings().add(amount);
template.set(Template.Node.PAYMENT_TO);
template.add("name", name);
template.add("amount", iConomy.format(amount));
Messaging.send(sender, tag + template.parse());
Player to = iConomy.Server.getPlayer(name);
if(to != null) {
template.set(Template.Node.PAYMENT_FROM);
template.add("name", name);
template.add("amount", iConomy.format(amount));
Messaging.send(to, tag + template.parse());
}
return false;
}
| public boolean perform(CommandSender sender, LinkedHashMap<String, Argument> arguments) throws InvalidUsage {
if(!hasPermissions(sender, "pay"))
return false;
if(isConsole(sender)) {
Messaging.send(sender, "`rCannot remove money from a non-living organism.");
return false;
}
Player from = (Player) sender;
String name = arguments.get("name").getStringValue();
String tag = template.color(Template.Node.TAG_MONEY);
Double amount;
if(name.equals("0"))
throw new InvalidUsage("Missing <white>name<rose>: /money pay <name> <amount>");
if(arguments.get("amount").getStringValue().equals("empty"))
throw new InvalidUsage("Missing <white>amount<rose>: /money pay <name> <amount>");
try {
amount = arguments.get("amount").getDoubleValue();
} catch(NumberFormatException e) {
throw new InvalidUsage("Invalid <white>amount<rose>, must be double.");
}
if(Double.isInfinite(amount) || Double.isNaN(amount))
throw new InvalidUsage("Invalid <white>amount<rose>, must be double.");
if(amount < 0.1)
throw new InvalidUsage("Invalid <white>amount<rose>, cannot be less than 0.1");
if(Common.matches(from.getName(), name)) {
template.set(Template.Node.PAYMENT_SELF);
Messaging.send(sender, template.parse());
return false;
}
if(!Accounts.exists(name)) {
template.set(Template.Node.ERROR_ACCOUNT);
template.add("name", name);
Messaging.send(sender, tag + template.parse());
return false;
}
Account holder = new Account(from.getName());
Holdings holdings = holder.getHoldings();
if(holdings.getBalance() < amount) {
template.set(Template.Node.ERROR_FUNDS);
Messaging.send(sender, tag + template.parse());
return false;
}
Account account = new Account(name);
holdings.subtract(amount);
account.getHoldings().add(amount);
template.set(Template.Node.PAYMENT_TO);
template.add("name", name);
template.add("amount", iConomy.format(amount));
Messaging.send(sender, tag + template.parse());
Player to = iConomy.Server.getPlayer(name);
if(to != null) {
template.set(Template.Node.PAYMENT_FROM);
template.add("name", from.getName());
template.add("amount", iConomy.format(amount));
Messaging.send(to, tag + template.parse());
}
return false;
}
|
diff --git a/src/net/slipcor/pvparena/runnables/InventoryRefillRunnable.java b/src/net/slipcor/pvparena/runnables/InventoryRefillRunnable.java
index 3d740e95..4cf29af4 100644
--- a/src/net/slipcor/pvparena/runnables/InventoryRefillRunnable.java
+++ b/src/net/slipcor/pvparena/runnables/InventoryRefillRunnable.java
@@ -1,59 +1,59 @@
package net.slipcor.pvparena.runnables;
import java.util.List;
import net.slipcor.pvparena.PVPArena;
import net.slipcor.pvparena.arena.Arena;
import net.slipcor.pvparena.arena.ArenaClass;
import net.slipcor.pvparena.arena.ArenaPlayer;
import net.slipcor.pvparena.arena.ArenaPlayer.Status;
import net.slipcor.pvparena.core.Config.CFG;
import net.slipcor.pvparena.managers.InventoryManager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* <pre>Arena Runnable class "Inventory"</pre>
*
* An arena timer to restore a player's inventory
*
* @author slipcor
*
* @version v0.9.6
*/
public class InventoryRefillRunnable implements Runnable {
private Player player;
private ItemStack[] items;
private Arena arena;
public InventoryRefillRunnable(Arena a, Player p, List<ItemStack> isi) {
- if (!arena.getArenaConfig().getBoolean(CFG.PLAYER_REFILLINVENTORY)) {
+ if (!a.getArenaConfig().getBoolean(CFG.PLAYER_REFILLINVENTORY)) {
return;
}
Bukkit.getScheduler().scheduleSyncDelayedTask(PVPArena.instance, this, 3L);
player = p;
items = new ItemStack[isi.size()];
arena = a;
int i = 0;
for (ItemStack item : isi) {
items[i++] = item.clone();
}
}
@Override
public void run() {
ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName());
if (ap.getStatus().equals(Status.FIGHT)) {
if (ap.getClass().equals("custom") || !arena.getArenaConfig().getBoolean(CFG.PLAYER_REFILLINVENTORY)) {
ArenaClass.equip(player, items);
} else {
InventoryManager.clearInventory(player);
ArenaPlayer.givePlayerFightItems(arena, player);
}
}
player.setFireTicks(0);
}
}
| true | true | public InventoryRefillRunnable(Arena a, Player p, List<ItemStack> isi) {
if (!arena.getArenaConfig().getBoolean(CFG.PLAYER_REFILLINVENTORY)) {
return;
}
Bukkit.getScheduler().scheduleSyncDelayedTask(PVPArena.instance, this, 3L);
player = p;
items = new ItemStack[isi.size()];
arena = a;
int i = 0;
for (ItemStack item : isi) {
items[i++] = item.clone();
}
}
| public InventoryRefillRunnable(Arena a, Player p, List<ItemStack> isi) {
if (!a.getArenaConfig().getBoolean(CFG.PLAYER_REFILLINVENTORY)) {
return;
}
Bukkit.getScheduler().scheduleSyncDelayedTask(PVPArena.instance, this, 3L);
player = p;
items = new ItemStack[isi.size()];
arena = a;
int i = 0;
for (ItemStack item : isi) {
items[i++] = item.clone();
}
}
|
diff --git a/freeplane/src/org/freeplane/features/export/mindmapmode/ExportToOoWriter.java b/freeplane/src/org/freeplane/features/export/mindmapmode/ExportToOoWriter.java
index 911b28d00..f13ec881f 100644
--- a/freeplane/src/org/freeplane/features/export/mindmapmode/ExportToOoWriter.java
+++ b/freeplane/src/org/freeplane/features/export/mindmapmode/ExportToOoWriter.java
@@ -1,134 +1,134 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.export.mindmapmode;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.swing.filechooser.FileFilter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.freeplane.core.resources.ResourceController;
import org.freeplane.core.ui.ExampleFileFilter;
import org.freeplane.core.ui.components.UITools;
import org.freeplane.core.util.FileUtils;
import org.freeplane.core.util.LogUtils;
import org.freeplane.core.util.TextUtils;
import org.freeplane.features.map.MapModel;
import org.freeplane.features.map.MapWriter.Mode;
import org.freeplane.features.mode.Controller;
import org.freeplane.features.mode.ModeController;
/**
* @author foltin
*/
public class ExportToOoWriter implements IExportEngine {
public ExportToOoWriter() {
}
public FileFilter getFileFilter(){
return new ExampleFileFilter("odt", TextUtils.getText("ExportToOoWriter.text"));
}
public void export(MapModel map, File chosenFile) {
Controller.getCurrentController().getViewController().setWaitingCursor(true);
try {
exportToOoWriter(map, chosenFile);
}
catch (final Exception ex) {
LogUtils.warn(ex);
UITools.errorMessage(TextUtils.getText("export_failed"));
}
finally{
Controller.getCurrentController().getViewController().setWaitingCursor(false);
}
}
/**
* @return true, if successful.
*/
private void applyXsltFile(final String xsltFileName, final StringWriter writer, final Result result)
throws IOException {
final URL xsltUrl = ResourceController.getResourceController().getResource(xsltFileName);
if (xsltUrl == null) {
LogUtils.severe("Can't find " + xsltFileName + " as resource.");
throw new IllegalArgumentException("Can't find " + xsltFileName + " as resource.");
}
final InputStream xsltStream = new BufferedInputStream(xsltUrl.openStream());
final Source xsltSource = new StreamSource(xsltStream);
try {
final StringReader reader = new StringReader(writer.getBuffer().toString());
final TransformerFactory transFact = TransformerFactory.newInstance();
final Transformer trans = transFact.newTransformer(xsltSource);
trans.transform(new StreamSource(reader), result);
return;
}
catch (final Exception e) {
UITools.errorMessage(e.getMessage());
LogUtils.warn(e);
return;
}
finally {
FileUtils.silentlyClose(xsltStream);
}
}
public void exportToOoWriter(MapModel map, final File file) throws IOException {
final ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(file));
try {
final StringWriter writer = new StringWriter();
final ModeController controller = Controller.getCurrentModeController();
controller.getMapController().getFilteredXml(map, writer, Mode.EXPORT, true);
final Result result = new StreamResult(zipout);
ZipEntry entry = new ZipEntry("content.xml");
zipout.putNextEntry(entry);
- applyXsltFile("/xslt/mm2oowriter.xsl", writer, result);
+ applyXsltFile("/xslt/export2oowriter.xsl", writer, result);
zipout.closeEntry();
entry = new ZipEntry("META-INF/manifest.xml");
zipout.putNextEntry(entry);
- applyXsltFile("/xslt/mm2oowriter.manifest.xsl", writer, result);
+ applyXsltFile("/xslt/export2oowriter.manifest.xsl", writer, result);
zipout.closeEntry();
entry = new ZipEntry("styles.xml");
zipout.putNextEntry(entry);
- applyXsltFile("/xslt/mm2oowriter.styles.xsl", writer, result);
+ applyXsltFile("/xslt/export2oowriter.styles.xsl", writer, result);
zipout.closeEntry();
}
finally {
zipout.close();
}
}
}
| false | true | public void exportToOoWriter(MapModel map, final File file) throws IOException {
final ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(file));
try {
final StringWriter writer = new StringWriter();
final ModeController controller = Controller.getCurrentModeController();
controller.getMapController().getFilteredXml(map, writer, Mode.EXPORT, true);
final Result result = new StreamResult(zipout);
ZipEntry entry = new ZipEntry("content.xml");
zipout.putNextEntry(entry);
applyXsltFile("/xslt/mm2oowriter.xsl", writer, result);
zipout.closeEntry();
entry = new ZipEntry("META-INF/manifest.xml");
zipout.putNextEntry(entry);
applyXsltFile("/xslt/mm2oowriter.manifest.xsl", writer, result);
zipout.closeEntry();
entry = new ZipEntry("styles.xml");
zipout.putNextEntry(entry);
applyXsltFile("/xslt/mm2oowriter.styles.xsl", writer, result);
zipout.closeEntry();
}
finally {
zipout.close();
}
}
| public void exportToOoWriter(MapModel map, final File file) throws IOException {
final ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(file));
try {
final StringWriter writer = new StringWriter();
final ModeController controller = Controller.getCurrentModeController();
controller.getMapController().getFilteredXml(map, writer, Mode.EXPORT, true);
final Result result = new StreamResult(zipout);
ZipEntry entry = new ZipEntry("content.xml");
zipout.putNextEntry(entry);
applyXsltFile("/xslt/export2oowriter.xsl", writer, result);
zipout.closeEntry();
entry = new ZipEntry("META-INF/manifest.xml");
zipout.putNextEntry(entry);
applyXsltFile("/xslt/export2oowriter.manifest.xsl", writer, result);
zipout.closeEntry();
entry = new ZipEntry("styles.xml");
zipout.putNextEntry(entry);
applyXsltFile("/xslt/export2oowriter.styles.xsl", writer, result);
zipout.closeEntry();
}
finally {
zipout.close();
}
}
|
diff --git a/src-data/com/openbravo/data/loader/MetaSentence.java b/src-data/com/openbravo/data/loader/MetaSentence.java
index aed5507..9425e88 100644
--- a/src-data/com/openbravo/data/loader/MetaSentence.java
+++ b/src-data/com/openbravo/data/loader/MetaSentence.java
@@ -1,175 +1,175 @@
// Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007-2009 Openbravo, S.L.
// http://www.openbravo.com/product/pos
//
// This file is part of Openbravo POS.
//
// Openbravo POS 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.
//
// Openbravo POS 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 Openbravo POS. If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.data.loader;
import java.sql.*;
import java.util.*;
import javax.sql.DataSource;
import com.openbravo.basic.BasicException;
import com.openbravo.data.loader.JDBCSentence.JDBCDataResultSet;
public class MetaSentence extends JDBCSentence {
private String m_sSentence;
protected SerializerRead m_SerRead = null;
protected SerializerWrite m_SerWrite = null;
/** Creates a new instance of MetaDataSentence */
public MetaSentence(Session s, String sSentence, SerializerWrite serwrite, SerializerRead serread) {
super(s);
m_sSentence = sSentence;
m_SerWrite = serwrite;
m_SerRead = serread;
}
public MetaSentence(Session s, String sSentence, SerializerRead serread) {
this(s, sSentence, null, serread);
}
private static class MetaParameter implements DataWrite {
private ArrayList m_aParams;
/** Creates a new instance of MetaParameter */
public MetaParameter() {
m_aParams = new ArrayList();
}
public void setDouble(int paramIndex, Double dValue) throws BasicException {
throw new BasicException(LocalRes.getIntString("exception.noparamtype"));
}
public void setBoolean(int paramIndex, Boolean bValue) throws BasicException {
throw new BasicException(LocalRes.getIntString("exception.noparamtype"));
}
public void setInt(int paramIndex, Integer iValue) throws BasicException {
throw new BasicException(LocalRes.getIntString("exception.noparamtype"));
}
public void setString(int paramIndex, String sValue) throws BasicException {
ensurePlace(paramIndex - 1);
m_aParams.set(paramIndex - 1, sValue);
}
public void setTimestamp(int paramIndex, java.util.Date dValue) throws BasicException {
throw new BasicException(LocalRes.getIntString("exception.noparamtype"));
}
// public void setBinaryStream(int paramIndex, java.io.InputStream in, int length) throws DataException {
// throw new DataException("Param type not allowed");
// }
public void setBytes(int paramIndex, byte[] value) throws BasicException {
throw new BasicException(LocalRes.getIntString("exception.noparamtype"));
}
public void setObject(int paramIndex, Object value) throws BasicException {
setString(paramIndex, (value == null) ? null : value.toString());
}
public String getString(int index) {
return (String) m_aParams.get(index);
}
private void ensurePlace(int i) {
m_aParams.ensureCapacity(i);
while (i >= m_aParams.size()){
m_aParams.add(null);
}
}
}
public DataResultSet openExec(Object params) throws BasicException {
closeExec();
try {
DatabaseMetaData db = m_s.getConnection().getMetaData();
MetaParameter mp = new MetaParameter();
if (params != null) {
// si m_SerWrite fuera null deberiamos cascar
m_SerWrite.writeValues(mp, params);
}
// Catalogs Has Schemas Has Objects
// Lo generico de la base de datos
if ("getCatalogs".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getCatalogs(), m_SerRead);
} else if ("getSchemas".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getSchemas(), m_SerRead);
} else if ("getTableTypes".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTableTypes(), m_SerRead);
} else if ("getTypeInfo".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTypeInfo(), m_SerRead);
// Los objetos por catalogo, esquema
// Los tipos definidos por usuario
} else if ("getUDTs".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getUDTs(mp.getString(0), mp.getString(1), null, null), m_SerRead);
} else if ("getSuperTypes".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getSuperTypes(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
// Los atributos
} else if ("getAttributes".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getAttributes(mp.getString(0), mp.getString(1), null, null), m_SerRead);
// Las Tablas y sus objetos relacionados
} else if ("getTables".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTables(mp.getString(0), mp.getString(1), null, null), m_SerRead);
} else if ("getSuperTables".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getSuperTables(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getTablePrivileges".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTablePrivileges(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getBestRowIdentifier".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getBestRowIdentifier(mp.getString(0), mp.getString(1), mp.getString(2), 0, true), m_SerRead);
} else if ("getPrimaryKeys".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getPrimaryKeys(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getColumnPrivileges".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getColumnPrivileges(mp.getString(0), mp.getString(1), mp.getString(2), null), m_SerRead);
} else if ("getColumns".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getColumns(mp.getString(0), mp.getString(1), mp.getString(2), null), m_SerRead);
} else if ("getVersionColumns".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getVersionColumns(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getIndexInfo".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getIndexInfo(mp.getString(0), mp.getString(1), mp.getString(2), false, false), m_SerRead);
} else if ("getExportedKeys".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getExportedKeys(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getImportedKeys".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getImportedKeys(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
- } else if ("getImportedKeys".equals(m_sSentence)) {
+ } else if ("getCrossReference".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getCrossReference(mp.getString(0), mp.getString(1), mp.getString(2), null, null, null), m_SerRead);
// Los procedimientos y sus objetos relacionados
} else if ("getProcedures".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getProcedures(mp.getString(0), mp.getString(1), null), m_SerRead);
} else if ("getProcedureColumns".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getProcedureColumns(mp.getString(0), mp.getString(1), mp.getString(2), null), m_SerRead);
} else {
return null;
}
} catch (SQLException eSQL) {
throw new BasicException(eSQL);
}
}
public void closeExec() throws BasicException {
}
public DataResultSet moreResults() throws BasicException {
return null;
}
}
| true | true | public DataResultSet openExec(Object params) throws BasicException {
closeExec();
try {
DatabaseMetaData db = m_s.getConnection().getMetaData();
MetaParameter mp = new MetaParameter();
if (params != null) {
// si m_SerWrite fuera null deberiamos cascar
m_SerWrite.writeValues(mp, params);
}
// Catalogs Has Schemas Has Objects
// Lo generico de la base de datos
if ("getCatalogs".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getCatalogs(), m_SerRead);
} else if ("getSchemas".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getSchemas(), m_SerRead);
} else if ("getTableTypes".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTableTypes(), m_SerRead);
} else if ("getTypeInfo".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTypeInfo(), m_SerRead);
// Los objetos por catalogo, esquema
// Los tipos definidos por usuario
} else if ("getUDTs".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getUDTs(mp.getString(0), mp.getString(1), null, null), m_SerRead);
} else if ("getSuperTypes".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getSuperTypes(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
// Los atributos
} else if ("getAttributes".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getAttributes(mp.getString(0), mp.getString(1), null, null), m_SerRead);
// Las Tablas y sus objetos relacionados
} else if ("getTables".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTables(mp.getString(0), mp.getString(1), null, null), m_SerRead);
} else if ("getSuperTables".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getSuperTables(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getTablePrivileges".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTablePrivileges(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getBestRowIdentifier".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getBestRowIdentifier(mp.getString(0), mp.getString(1), mp.getString(2), 0, true), m_SerRead);
} else if ("getPrimaryKeys".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getPrimaryKeys(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getColumnPrivileges".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getColumnPrivileges(mp.getString(0), mp.getString(1), mp.getString(2), null), m_SerRead);
} else if ("getColumns".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getColumns(mp.getString(0), mp.getString(1), mp.getString(2), null), m_SerRead);
} else if ("getVersionColumns".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getVersionColumns(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getIndexInfo".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getIndexInfo(mp.getString(0), mp.getString(1), mp.getString(2), false, false), m_SerRead);
} else if ("getExportedKeys".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getExportedKeys(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getImportedKeys".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getImportedKeys(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getImportedKeys".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getCrossReference(mp.getString(0), mp.getString(1), mp.getString(2), null, null, null), m_SerRead);
// Los procedimientos y sus objetos relacionados
} else if ("getProcedures".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getProcedures(mp.getString(0), mp.getString(1), null), m_SerRead);
} else if ("getProcedureColumns".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getProcedureColumns(mp.getString(0), mp.getString(1), mp.getString(2), null), m_SerRead);
} else {
return null;
}
} catch (SQLException eSQL) {
throw new BasicException(eSQL);
}
}
| public DataResultSet openExec(Object params) throws BasicException {
closeExec();
try {
DatabaseMetaData db = m_s.getConnection().getMetaData();
MetaParameter mp = new MetaParameter();
if (params != null) {
// si m_SerWrite fuera null deberiamos cascar
m_SerWrite.writeValues(mp, params);
}
// Catalogs Has Schemas Has Objects
// Lo generico de la base de datos
if ("getCatalogs".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getCatalogs(), m_SerRead);
} else if ("getSchemas".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getSchemas(), m_SerRead);
} else if ("getTableTypes".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTableTypes(), m_SerRead);
} else if ("getTypeInfo".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTypeInfo(), m_SerRead);
// Los objetos por catalogo, esquema
// Los tipos definidos por usuario
} else if ("getUDTs".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getUDTs(mp.getString(0), mp.getString(1), null, null), m_SerRead);
} else if ("getSuperTypes".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getSuperTypes(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
// Los atributos
} else if ("getAttributes".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getAttributes(mp.getString(0), mp.getString(1), null, null), m_SerRead);
// Las Tablas y sus objetos relacionados
} else if ("getTables".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTables(mp.getString(0), mp.getString(1), null, null), m_SerRead);
} else if ("getSuperTables".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getSuperTables(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getTablePrivileges".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getTablePrivileges(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getBestRowIdentifier".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getBestRowIdentifier(mp.getString(0), mp.getString(1), mp.getString(2), 0, true), m_SerRead);
} else if ("getPrimaryKeys".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getPrimaryKeys(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getColumnPrivileges".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getColumnPrivileges(mp.getString(0), mp.getString(1), mp.getString(2), null), m_SerRead);
} else if ("getColumns".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getColumns(mp.getString(0), mp.getString(1), mp.getString(2), null), m_SerRead);
} else if ("getVersionColumns".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getVersionColumns(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getIndexInfo".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getIndexInfo(mp.getString(0), mp.getString(1), mp.getString(2), false, false), m_SerRead);
} else if ("getExportedKeys".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getExportedKeys(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getImportedKeys".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getImportedKeys(mp.getString(0), mp.getString(1), mp.getString(2)), m_SerRead);
} else if ("getCrossReference".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getCrossReference(mp.getString(0), mp.getString(1), mp.getString(2), null, null, null), m_SerRead);
// Los procedimientos y sus objetos relacionados
} else if ("getProcedures".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getProcedures(mp.getString(0), mp.getString(1), null), m_SerRead);
} else if ("getProcedureColumns".equals(m_sSentence)) {
return new JDBCDataResultSet(db.getProcedureColumns(mp.getString(0), mp.getString(1), mp.getString(2), null), m_SerRead);
} else {
return null;
}
} catch (SQLException eSQL) {
throw new BasicException(eSQL);
}
}
|
diff --git a/Main/src/com/lunaticedit/legendofwaffles/implementations/scene/MainMenu.java b/Main/src/com/lunaticedit/legendofwaffles/implementations/scene/MainMenu.java
index db9a9c7..55f4d48 100644
--- a/Main/src/com/lunaticedit/legendofwaffles/implementations/scene/MainMenu.java
+++ b/Main/src/com/lunaticedit/legendofwaffles/implementations/scene/MainMenu.java
@@ -1,91 +1,92 @@
package com.lunaticedit.legendofwaffles.implementations.scene;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.lunaticedit.legendofwaffles.contracts.Scene;
import com.lunaticedit.legendofwaffles.factories.SpriteBatchFactory;
import com.lunaticedit.legendofwaffles.helpers.Constants;
import com.lunaticedit.legendofwaffles.implementations.Input;
import com.lunaticedit.legendofwaffles.implementations.MusicPlayer;
import com.lunaticedit.legendofwaffles.implementations.generators.TilesetGraphicsGenerator;
public final class MainMenu implements Scene {
private final Texture _texture;
private int _menuSelection = 0;
public MainMenu() {
_texture = new Texture(Constants.MainMenuBackgroundFile);
MusicPlayer.getInstance().stopSong();
MusicPlayer.getInstance().playSong(Constants.MainMenuSong);
}
@Override
public void render() {
final SpriteBatch s = new SpriteBatchFactory().generate();
final TilesetGraphicsGenerator g = (new TilesetGraphicsGenerator());
// Render the background image
s.draw(_texture, -128f, -110f);
// Render the main menu options.
- g.drawText(110, 90, "NEW GAME");
- g.drawText(110, 115, "CONTINUE");
- g.drawText(110, 140, " CONFIG ");
- g.drawText(110, 165, " QUIT ");
+ final int centerX = (Constants.GameWidth / 2);
+ g.drawText(centerX - ((8 * 8) / 2), 90, "NEW GAME");
+ g.drawText(centerX - ((8 * 8) / 2), 115, "CONTINUE");
+ g.drawText(centerX - ((8 * 8) / 2), 140, " CONFIG ");
+ g.drawText(centerX - ((8 * 8) / 2), 165, " QUIT ");
// Render the menu selector if not on a touch screen
if (Gdx.app.getType() == Application.ApplicationType.Android) {
} else {
- g.drawTile(94, 90 + (_menuSelection * 25), 1);
- g.drawTile(180, 90 + (_menuSelection * 25), 1);
+ g.drawTile(centerX - ((8 * 10) / 2), 90 + (_menuSelection * 25), 1);
+ g.drawTile(centerX + ((8 * 8) / 2), 90 + (_menuSelection * 25), 1);
}
}
@Override
public void update() {
if (Input.getInstance().getKeyState(Keys.DPAD_UP)) {
Input.getInstance().setKeyState(Keys.DPAD_UP, false);
moveSelectionUp();
} else if (Input.getInstance().getKeyState(Keys.DPAD_DOWN)) {
Input.getInstance().setKeyState(com.badlogic.gdx.Input.Keys.DPAD_DOWN, false);
moveSelectionDown();
} else if (Input.getInstance().getKeyState(Keys.ENTER) ||
Input.getInstance().getKeyState(Keys.BUTTON_A)) {
Input.getInstance().setKeyState(Keys.ENTER, false);
Input.getInstance().setKeyState(Keys.BUTTON_A, false);
activateMenuOption();
}
}
private void moveSelectionUp() {
if (--_menuSelection < 0)
{ _menuSelection = 3; }
}
private void moveSelectionDown() {
if (++_menuSelection > 3)
{ _menuSelection = 0; }
}
private void activateMenuOption() {
switch (_menuSelection) {
case 0: {
// Start new game
} break;
case 1: {
// Continue existing game
} break;
case 2: {
// Configure
} break;
case 3: {
// Quit
Gdx.app.exit();
} break;
}
}
}
| false | true | public void render() {
final SpriteBatch s = new SpriteBatchFactory().generate();
final TilesetGraphicsGenerator g = (new TilesetGraphicsGenerator());
// Render the background image
s.draw(_texture, -128f, -110f);
// Render the main menu options.
g.drawText(110, 90, "NEW GAME");
g.drawText(110, 115, "CONTINUE");
g.drawText(110, 140, " CONFIG ");
g.drawText(110, 165, " QUIT ");
// Render the menu selector if not on a touch screen
if (Gdx.app.getType() == Application.ApplicationType.Android) {
} else {
g.drawTile(94, 90 + (_menuSelection * 25), 1);
g.drawTile(180, 90 + (_menuSelection * 25), 1);
}
}
| public void render() {
final SpriteBatch s = new SpriteBatchFactory().generate();
final TilesetGraphicsGenerator g = (new TilesetGraphicsGenerator());
// Render the background image
s.draw(_texture, -128f, -110f);
// Render the main menu options.
final int centerX = (Constants.GameWidth / 2);
g.drawText(centerX - ((8 * 8) / 2), 90, "NEW GAME");
g.drawText(centerX - ((8 * 8) / 2), 115, "CONTINUE");
g.drawText(centerX - ((8 * 8) / 2), 140, " CONFIG ");
g.drawText(centerX - ((8 * 8) / 2), 165, " QUIT ");
// Render the menu selector if not on a touch screen
if (Gdx.app.getType() == Application.ApplicationType.Android) {
} else {
g.drawTile(centerX - ((8 * 10) / 2), 90 + (_menuSelection * 25), 1);
g.drawTile(centerX + ((8 * 8) / 2), 90 + (_menuSelection * 25), 1);
}
}
|
diff --git a/src/test/java/com/bragi/sonify/composer/riffology/TestScenarioTest.java b/src/test/java/com/bragi/sonify/composer/riffology/TestScenarioTest.java
index 38bdcd9..96ebbb0 100644
--- a/src/test/java/com/bragi/sonify/composer/riffology/TestScenarioTest.java
+++ b/src/test/java/com/bragi/sonify/composer/riffology/TestScenarioTest.java
@@ -1,390 +1,390 @@
/*******************************************************************************
* Copyright (c) 2012 BragiSoft, Inc.
* This source is subject to the BragiSoft Permissive License.
* Please see the License.txt file for more information.
* All other rights reserved.
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Contributors:
* Jan-Christoph Klie - Everything
*
*******************************************************************************/
package com.bragi.sonify.composer.riffology;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedList;
import java.util.List;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import junit.framework.TestCase;
import junitx.framework.FileAssert;
import com.bragi.sonify.composer.AComposer;
/**
* This unit test is home of the tests which are described in chapter 10 of the
* functional specifications document. (As far as software tests can achieve it).
*/
public class TestScenarioTest extends TestCase {
private File getTestFile(String name) {
URL url = this.getClass().getResource("/literature/" + name);
return new File(url.getFile());
}
private final File drama = getTestFile("drama.txt");
private final File kidsBook = getTestFile("kinderbuch.txt");
private final File lyric = getTestFile("lyrik.txt");
private final File novel = getTestFile("roman.txt");
private final File nonFiction = getTestFile("sachbuch.txt");
private static final long THIRTY_SECONDS = 30000;
private static final long TEN_MINUTES = 600000000;
private List<File> tempFiles;
public TestScenarioTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
tempFiles = new LinkedList<File>();
}
@Override
protected void tearDown() throws Exception {
for( File f : tempFiles ) {
f.delete();
}
}
/**
* /TS0010/ Generating MIDI
*
* This tests uses every implementation of the AComposer, generates a MIDI file
* and saves it afterwards. It is then imported with the MidiFileReader class.
*
* If the file is invalid MIDI, an InvalidMidiDataException is thrown and the test fails.
*/
public void testGeneratingMidi() {
}
/**
* /TS0020/ Playing time
*
* The playing time of a sequence has to be at least 30 seconds and at most 10 minutes.
*
* @throws IOException
* @throws InvalidMidiDataException
*/
public void testPlayingTime() throws IOException, InvalidMidiDataException {
AComposer composer;
Sequence sequence;
long playtime;
/*
* Mozart trio composer
*/
composer = new MozartTrioDiceGame(drama);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new MozartTrioDiceGame(kidsBook);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new MozartTrioDiceGame(lyric);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new MozartTrioDiceGame(novel);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new MozartTrioDiceGame(nonFiction);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
/*
* Mozart waltz composer
*/
composer = new MozartWaltzDiceGame(drama);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new MozartWaltzDiceGame(kidsBook);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new MozartWaltzDiceGame(lyric);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new MozartWaltzDiceGame(novel);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new MozartWaltzDiceGame(nonFiction);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
/*
* Kirnberger composer
*/
composer = new KirnbergerDiceGame(drama);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new KirnbergerDiceGame(kidsBook);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new KirnbergerDiceGame(lyric);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new KirnbergerDiceGame(novel);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
composer = new KirnbergerDiceGame(nonFiction);
sequence = composer.createSequence();
playtime = sequence.getMicrosecondLength();
assertTrue(playtime > THIRTY_SECONDS && playtime <= TEN_MINUTES);
}
/**
* /TS0030/ Reproducibility
*
* Identic input yields identic output.
*
* In this test, a text is sonified twice with the same text and the both
* results are compared binary. Since the result of sonifiing the same text
* twice should yield the exact same file, this case is asserted.
*
* @throws IOException
* @throws InvalidMidiDataException
*/
public void testReproducibility() throws IOException, InvalidMidiDataException {
AComposer firstComposer;
AComposer secondComposer;
Sequence firstSequence;
Sequence secondSequence;
Path firstTempPath;
Path secondTempPath;
File firstFile;
File secondFile;
/*
* Mozart trio composer
*/
// Drama
firstComposer = new MozartTrioDiceGame(drama);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(drama);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
// Non-Fiction
firstComposer = new MozartTrioDiceGame(nonFiction);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(nonFiction);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
/*
* Mozart trio composer
*/
// Drama
firstComposer = new MozartTrioDiceGame(drama);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(drama);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
// Non-Fiction
firstComposer = new MozartTrioDiceGame(nonFiction);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(nonFiction);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
/*
* Mozart trio composer
*/
// Kids book
firstComposer = new MozartWaltzDiceGame(kidsBook);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(kidsBook);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
- // Non-Fiction
+ // Novel
firstComposer = new MozartWaltzDiceGame(novel);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(novel);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
/*
* Kirnberger composer
*/
// Lyric
firstComposer = new MozartWaltzDiceGame(lyric);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(lyric);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
- // Non-Fiction
+ // Novel
firstComposer = new MozartWaltzDiceGame(novel);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(novel);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
}
}
| false | true | public void testReproducibility() throws IOException, InvalidMidiDataException {
AComposer firstComposer;
AComposer secondComposer;
Sequence firstSequence;
Sequence secondSequence;
Path firstTempPath;
Path secondTempPath;
File firstFile;
File secondFile;
/*
* Mozart trio composer
*/
// Drama
firstComposer = new MozartTrioDiceGame(drama);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(drama);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
// Non-Fiction
firstComposer = new MozartTrioDiceGame(nonFiction);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(nonFiction);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
/*
* Mozart trio composer
*/
// Drama
firstComposer = new MozartTrioDiceGame(drama);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(drama);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
// Non-Fiction
firstComposer = new MozartTrioDiceGame(nonFiction);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(nonFiction);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
/*
* Mozart trio composer
*/
// Kids book
firstComposer = new MozartWaltzDiceGame(kidsBook);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(kidsBook);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
// Non-Fiction
firstComposer = new MozartWaltzDiceGame(novel);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(novel);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
/*
* Kirnberger composer
*/
// Lyric
firstComposer = new MozartWaltzDiceGame(lyric);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(lyric);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
// Non-Fiction
firstComposer = new MozartWaltzDiceGame(novel);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(novel);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
}
| public void testReproducibility() throws IOException, InvalidMidiDataException {
AComposer firstComposer;
AComposer secondComposer;
Sequence firstSequence;
Sequence secondSequence;
Path firstTempPath;
Path secondTempPath;
File firstFile;
File secondFile;
/*
* Mozart trio composer
*/
// Drama
firstComposer = new MozartTrioDiceGame(drama);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(drama);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
// Non-Fiction
firstComposer = new MozartTrioDiceGame(nonFiction);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(nonFiction);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
/*
* Mozart trio composer
*/
// Drama
firstComposer = new MozartTrioDiceGame(drama);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(drama);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
// Non-Fiction
firstComposer = new MozartTrioDiceGame(nonFiction);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartTrioDiceGame(nonFiction);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
/*
* Mozart trio composer
*/
// Kids book
firstComposer = new MozartWaltzDiceGame(kidsBook);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(kidsBook);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
// Novel
firstComposer = new MozartWaltzDiceGame(novel);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(novel);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
/*
* Kirnberger composer
*/
// Lyric
firstComposer = new MozartWaltzDiceGame(lyric);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(lyric);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
// Novel
firstComposer = new MozartWaltzDiceGame(novel);
firstSequence = firstComposer.createSequence();
firstTempPath = Files.createTempFile("test", null );
firstFile = firstTempPath.toFile();
MidiSystem.write( firstSequence, 1, firstFile);
secondComposer = new MozartWaltzDiceGame(novel);
secondSequence = secondComposer.createSequence();
secondTempPath = Files.createTempFile("test", null );
secondFile = secondTempPath.toFile();
MidiSystem.write( secondSequence, 1, secondFile);
tempFiles.add(firstFile);
tempFiles.add(secondFile);
FileAssert.assertBinaryEquals(firstFile, secondFile);
}
|
diff --git a/src/test/java/org/junit/contrib/truth/IntegerTest.java b/src/test/java/org/junit/contrib/truth/IntegerTest.java
index 87f73834..2be853bd 100644
--- a/src/test/java/org/junit/contrib/truth/IntegerTest.java
+++ b/src/test/java/org/junit/contrib/truth/IntegerTest.java
@@ -1,100 +1,104 @@
/*
* Copyright (c) 2011 David Saff
* Copyright (c) 2011 Christian Gruber
*
* 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.junit.contrib.truth;
import static org.junit.Assert.fail;
import static org.junit.contrib.truth.Truth.ASSERT;
import static org.junit.contrib.truth.Truth.ASSUME;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.truth.Expect;
import org.junit.internal.AssumptionViolatedException;
/**
* Tests for Integer Subjects.
*
* @author David Saff
* @author Christian Gruber ([email protected])
*/
public class IntegerTest {
@Rule public Expect EXPECT = Expect.create();
@Test public void simpleEquality() {
ASSERT.that(2 + 2).isEqualTo(4);
}
@Test public void additionFail() {
try {
ASSERT.that(2 + 2).isEqualTo(5);
fail("Should have thrown");
} catch (AssertionError expected) {
ASSERT.that(expected.getMessage()).contains("Not true that <4> is equal to <5>");
}
}
@Test public void additionAssumptionFail() {
try {
ASSUME.that(2 + 2).isEqualTo(5);
fail("Should have thrown");
} catch (AssumptionViolatedException expected) {}
}
@Test public void inclusiveRangeContainment() {
EXPECT.that(2).isInclusivelyInRange(2, 4);
EXPECT.that(3).isInclusivelyInRange(2, 4);
EXPECT.that(4).isInclusivelyInRange(2, 4);
}
@Test public void inclusiveRangeContainmentFailure() {
try {
ASSERT.that(1).isInclusivelyInRange(2, 4);
fail("Should have thrown");
- } catch (AssertionError e) {}
+ } catch (AssertionError e) {
+ ASSERT.that(e.getMessage()).contains("Not true that <1> is inclusively in range <2> <4>");
+ }
try {
ASSERT.that(5).isInclusivelyInRange(2, 4);
fail("Should have thrown");
- } catch (AssertionError e) {}
+ } catch (AssertionError e) {
+ ASSERT.that(e.getMessage()).contains("Not true that <5> is inclusively in range <2> <4>");
+ }
}
@Test public void inclusiveRangeContainmentInversionError() {
try {
ASSERT.that(Integer.MAX_VALUE).isInclusivelyInRange(4, 2);
fail("Should have thrown");
} catch (IllegalArgumentException e) {}
}
@Test public void exclusiveRangeContainment() {
EXPECT.that(3).isBetween(2, 5);
EXPECT.that(4).isBetween(2, 5);
}
@Test public void exclusiveRangeContainmentFailure() {
try {
ASSERT.that(Integer.MAX_VALUE).isBetween(2, 5);
fail("Should have thrown");
} catch (AssertionError e) {}
}
@Test public void exclusiveRangeContainmentInversionError() {
try {
ASSERT.that(Integer.MAX_VALUE).isBetween(5, 2);
fail("Should have thrown");
} catch (IllegalArgumentException e) {}
}
}
| false | true | @Test public void inclusiveRangeContainmentFailure() {
try {
ASSERT.that(1).isInclusivelyInRange(2, 4);
fail("Should have thrown");
} catch (AssertionError e) {}
try {
ASSERT.that(5).isInclusivelyInRange(2, 4);
fail("Should have thrown");
} catch (AssertionError e) {}
}
| @Test public void inclusiveRangeContainmentFailure() {
try {
ASSERT.that(1).isInclusivelyInRange(2, 4);
fail("Should have thrown");
} catch (AssertionError e) {
ASSERT.that(e.getMessage()).contains("Not true that <1> is inclusively in range <2> <4>");
}
try {
ASSERT.that(5).isInclusivelyInRange(2, 4);
fail("Should have thrown");
} catch (AssertionError e) {
ASSERT.that(e.getMessage()).contains("Not true that <5> is inclusively in range <2> <4>");
}
}
|
diff --git a/server/base/src/main/java/org/apache/accumulo/server/Accumulo.java b/server/base/src/main/java/org/apache/accumulo/server/Accumulo.java
index 83f54b030..c54659016 100644
--- a/server/base/src/main/java/org/apache/accumulo/server/Accumulo.java
+++ b/server/base/src/main/java/org/apache/accumulo/server/Accumulo.java
@@ -1,264 +1,264 @@
/*
* 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.accumulo.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.trace.DistributedTrace;
import org.apache.accumulo.core.util.UtilWaitThread;
import org.apache.accumulo.core.util.Version;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.server.client.HdfsZooInstance;
import org.apache.accumulo.server.conf.ServerConfiguration;
import org.apache.accumulo.server.fs.VolumeManager;
import org.apache.accumulo.server.util.time.SimpleTimer;
import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.helpers.FileWatchdog;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.xml.DOMConfigurator;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
public class Accumulo {
private static final Logger log = Logger.getLogger(Accumulo.class);
public static synchronized void updateAccumuloVersion(VolumeManager fs) {
try {
if (getAccumuloPersistentVersion(fs) == ServerConstants.PREV_DATA_VERSION) {
fs.create(new Path(ServerConstants.getDataVersionLocation() + "/" + ServerConstants.DATA_VERSION));
fs.delete(new Path(ServerConstants.getDataVersionLocation() + "/" + ServerConstants.PREV_DATA_VERSION));
}
} catch (IOException e) {
throw new RuntimeException("Unable to set accumulo version: an error occurred.", e);
}
}
public static synchronized int getAccumuloPersistentVersion(VolumeManager fs) {
int dataVersion;
try {
FileStatus[] files = fs.getDefaultVolume().listStatus(ServerConstants.getDataVersionLocation());
if (files == null || files.length == 0) {
dataVersion = -1; // assume it is 0.5 or earlier
} else {
dataVersion = Integer.parseInt(files[0].getPath().getName());
}
return dataVersion;
} catch (IOException e) {
throw new RuntimeException("Unable to read accumulo version: an error occurred.", e);
}
}
public static void enableTracing(String address, String application) {
try {
DistributedTrace.enable(HdfsZooInstance.getInstance(), ZooReaderWriter.getInstance(), application, address);
} catch (Exception ex) {
log.error("creating remote sink for trace spans", ex);
}
}
private static class LogMonitor extends FileWatchdog implements Watcher {
String path;
protected LogMonitor(String instance, String filename, int delay) {
super(filename);
setDelay(delay);
this.path = ZooUtil.getRoot(instance) + Constants.ZMONITOR_LOG4J_PORT;
}
private void setMonitorPort() {
try {
String port = new String(ZooReaderWriter.getInstance().getData(path, null));
System.setProperty("org.apache.accumulo.core.host.log.port", port);
log.info("Changing monitor log4j port to "+port);
doOnChange();
} catch (Exception e) {
log.error("Error reading zookeeper data for monitor log4j port", e);
}
}
@Override
public void run() {
try {
if (ZooReaderWriter.getInstance().getZooKeeper().exists(path, this) != null)
setMonitorPort();
log.info("Set watch for monitor log4j port");
} catch (Exception e) {
log.error("Unable to set watch for monitor log4j port " + path);
}
super.run();
}
@Override
protected void doOnChange() {
LogManager.resetConfiguration();
new DOMConfigurator().doConfigure(filename, LogManager.getLoggerRepository());
}
@Override
public void process(WatchedEvent event) {
setMonitorPort();
if (event.getPath() != null) {
try {
ZooReaderWriter.getInstance().exists(event.getPath(), this);
} catch (Exception ex) {
log.error("Unable to reset watch for monitor log4j port", ex);
}
}
}
}
public static void init(VolumeManager fs, ServerConfiguration config, String application) throws UnknownHostException {
System.setProperty("org.apache.accumulo.core.application", application);
if (System.getenv("ACCUMULO_LOG_DIR") != null)
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_LOG_DIR"));
else
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_HOME") + "/logs/");
String localhost = InetAddress.getLocalHost().getHostName();
System.setProperty("org.apache.accumulo.core.ip.localhost.hostname", localhost);
if (System.getenv("ACCUMULO_LOG_HOST") != null)
System.setProperty("org.apache.accumulo.core.host.log", System.getenv("ACCUMULO_LOG_HOST"));
else
System.setProperty("org.apache.accumulo.core.host.log", localhost);
int logPort = config.getConfiguration().getPort(Property.MONITOR_LOG4J_PORT);
System.setProperty("org.apache.accumulo.core.host.log.port", Integer.toString(logPort));
// Use a specific log config, if it exists
- String logConfig = String.format("%s/%s_logger.xml", System.getenv("ACCUMULO_CONF_DIR"), application);
+ String logConfig = String.format("%s/%s_logger.xml", System.getenv("ACCUMULO_CONF_DIR"));
if (!new File(logConfig).exists()) {
// otherwise, use the generic config
logConfig = String.format("%s/generic_logger.xml", System.getenv("ACCUMULO_CONF_DIR"));
}
// Turn off messages about not being able to reach the remote logger... we protect against that.
LogLog.setQuietMode(true);
// Configure logging
if (logPort==0)
new LogMonitor(config.getInstance().getInstanceID(), logConfig, 5000).start();
else
DOMConfigurator.configureAndWatch(logConfig, 5000);
// Read the auditing config
String auditConfig = String.format("%s/auditLog.xml", System.getenv("ACCUMULO_CONF_DIR"));
DOMConfigurator.configureAndWatch(auditConfig, 5000);
log.info(application + " starting");
log.info("Instance " + config.getInstance().getInstanceID());
int dataVersion = Accumulo.getAccumuloPersistentVersion(fs);
log.info("Data Version " + dataVersion);
Accumulo.waitForZookeeperAndHdfs(fs);
Version codeVersion = new Version(Constants.VERSION);
if (dataVersion != ServerConstants.DATA_VERSION && dataVersion != ServerConstants.PREV_DATA_VERSION) {
throw new RuntimeException("This version of accumulo (" + codeVersion + ") is not compatible with files stored using data version " + dataVersion);
}
TreeMap<String,String> sortedProps = new TreeMap<String,String>();
for (Entry<String,String> entry : config.getConfiguration())
sortedProps.put(entry.getKey(), entry.getValue());
for (Entry<String,String> entry : sortedProps.entrySet()) {
String key = entry.getKey();
log.info(key + " = " + (Property.isSensitive(key) ? "<hidden>" : entry.getValue()));
}
monitorSwappiness();
}
/**
*
*/
public static void monitorSwappiness() {
SimpleTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
try {
String procFile = "/proc/sys/vm/swappiness";
File swappiness = new File(procFile);
if (swappiness.exists() && swappiness.canRead()) {
InputStream is = new FileInputStream(procFile);
try {
byte[] buffer = new byte[10];
int bytes = is.read(buffer);
String setting = new String(buffer, 0, bytes);
setting = setting.trim();
if (bytes > 0 && Integer.parseInt(setting) > 10) {
log.warn("System swappiness setting is greater than ten (" + setting + ") which can cause time-sensitive operations to be delayed. "
+ " Accumulo is time sensitive because it needs to maintain distributed lock agreement.");
}
} finally {
is.close();
}
}
} catch (Throwable t) {
log.error(t, t);
}
}
}, 1000, 10 * 60 * 1000);
}
public static void waitForZookeeperAndHdfs(VolumeManager fs) {
log.info("Attempting to talk to zookeeper");
while (true) {
try {
ZooReaderWriter.getInstance().getChildren(Constants.ZROOT);
break;
} catch (InterruptedException e) {
// ignored
} catch (KeeperException ex) {
log.info("Waiting for accumulo to be initialized");
UtilWaitThread.sleep(1000);
}
}
log.info("Zookeeper connected and initialized, attemping to talk to HDFS");
long sleep = 1000;
while (true) {
try {
if (fs.isReady())
break;
log.warn("Waiting for the NameNode to leave safemode");
} catch (IOException ex) {
log.warn("Unable to connect to HDFS");
}
log.info("Sleeping " + sleep / 1000. + " seconds");
UtilWaitThread.sleep(sleep);
sleep = Math.min(60 * 1000, sleep * 2);
}
log.info("Connected to HDFS");
}
}
| true | true | public static void init(VolumeManager fs, ServerConfiguration config, String application) throws UnknownHostException {
System.setProperty("org.apache.accumulo.core.application", application);
if (System.getenv("ACCUMULO_LOG_DIR") != null)
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_LOG_DIR"));
else
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_HOME") + "/logs/");
String localhost = InetAddress.getLocalHost().getHostName();
System.setProperty("org.apache.accumulo.core.ip.localhost.hostname", localhost);
if (System.getenv("ACCUMULO_LOG_HOST") != null)
System.setProperty("org.apache.accumulo.core.host.log", System.getenv("ACCUMULO_LOG_HOST"));
else
System.setProperty("org.apache.accumulo.core.host.log", localhost);
int logPort = config.getConfiguration().getPort(Property.MONITOR_LOG4J_PORT);
System.setProperty("org.apache.accumulo.core.host.log.port", Integer.toString(logPort));
// Use a specific log config, if it exists
String logConfig = String.format("%s/%s_logger.xml", System.getenv("ACCUMULO_CONF_DIR"), application);
if (!new File(logConfig).exists()) {
// otherwise, use the generic config
logConfig = String.format("%s/generic_logger.xml", System.getenv("ACCUMULO_CONF_DIR"));
}
// Turn off messages about not being able to reach the remote logger... we protect against that.
LogLog.setQuietMode(true);
// Configure logging
if (logPort==0)
new LogMonitor(config.getInstance().getInstanceID(), logConfig, 5000).start();
else
DOMConfigurator.configureAndWatch(logConfig, 5000);
// Read the auditing config
String auditConfig = String.format("%s/auditLog.xml", System.getenv("ACCUMULO_CONF_DIR"));
DOMConfigurator.configureAndWatch(auditConfig, 5000);
log.info(application + " starting");
log.info("Instance " + config.getInstance().getInstanceID());
int dataVersion = Accumulo.getAccumuloPersistentVersion(fs);
log.info("Data Version " + dataVersion);
Accumulo.waitForZookeeperAndHdfs(fs);
Version codeVersion = new Version(Constants.VERSION);
if (dataVersion != ServerConstants.DATA_VERSION && dataVersion != ServerConstants.PREV_DATA_VERSION) {
throw new RuntimeException("This version of accumulo (" + codeVersion + ") is not compatible with files stored using data version " + dataVersion);
}
TreeMap<String,String> sortedProps = new TreeMap<String,String>();
for (Entry<String,String> entry : config.getConfiguration())
sortedProps.put(entry.getKey(), entry.getValue());
for (Entry<String,String> entry : sortedProps.entrySet()) {
String key = entry.getKey();
log.info(key + " = " + (Property.isSensitive(key) ? "<hidden>" : entry.getValue()));
}
monitorSwappiness();
}
| public static void init(VolumeManager fs, ServerConfiguration config, String application) throws UnknownHostException {
System.setProperty("org.apache.accumulo.core.application", application);
if (System.getenv("ACCUMULO_LOG_DIR") != null)
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_LOG_DIR"));
else
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_HOME") + "/logs/");
String localhost = InetAddress.getLocalHost().getHostName();
System.setProperty("org.apache.accumulo.core.ip.localhost.hostname", localhost);
if (System.getenv("ACCUMULO_LOG_HOST") != null)
System.setProperty("org.apache.accumulo.core.host.log", System.getenv("ACCUMULO_LOG_HOST"));
else
System.setProperty("org.apache.accumulo.core.host.log", localhost);
int logPort = config.getConfiguration().getPort(Property.MONITOR_LOG4J_PORT);
System.setProperty("org.apache.accumulo.core.host.log.port", Integer.toString(logPort));
// Use a specific log config, if it exists
String logConfig = String.format("%s/%s_logger.xml", System.getenv("ACCUMULO_CONF_DIR"));
if (!new File(logConfig).exists()) {
// otherwise, use the generic config
logConfig = String.format("%s/generic_logger.xml", System.getenv("ACCUMULO_CONF_DIR"));
}
// Turn off messages about not being able to reach the remote logger... we protect against that.
LogLog.setQuietMode(true);
// Configure logging
if (logPort==0)
new LogMonitor(config.getInstance().getInstanceID(), logConfig, 5000).start();
else
DOMConfigurator.configureAndWatch(logConfig, 5000);
// Read the auditing config
String auditConfig = String.format("%s/auditLog.xml", System.getenv("ACCUMULO_CONF_DIR"));
DOMConfigurator.configureAndWatch(auditConfig, 5000);
log.info(application + " starting");
log.info("Instance " + config.getInstance().getInstanceID());
int dataVersion = Accumulo.getAccumuloPersistentVersion(fs);
log.info("Data Version " + dataVersion);
Accumulo.waitForZookeeperAndHdfs(fs);
Version codeVersion = new Version(Constants.VERSION);
if (dataVersion != ServerConstants.DATA_VERSION && dataVersion != ServerConstants.PREV_DATA_VERSION) {
throw new RuntimeException("This version of accumulo (" + codeVersion + ") is not compatible with files stored using data version " + dataVersion);
}
TreeMap<String,String> sortedProps = new TreeMap<String,String>();
for (Entry<String,String> entry : config.getConfiguration())
sortedProps.put(entry.getKey(), entry.getValue());
for (Entry<String,String> entry : sortedProps.entrySet()) {
String key = entry.getKey();
log.info(key + " = " + (Property.isSensitive(key) ? "<hidden>" : entry.getValue()));
}
monitorSwappiness();
}
|
diff --git a/hazelcast/src/main/java/com/hazelcast/impl/partition/MigrationRequestTask.java b/hazelcast/src/main/java/com/hazelcast/impl/partition/MigrationRequestTask.java
index 5a95f457bb..158d9d79ef 100644
--- a/hazelcast/src/main/java/com/hazelcast/impl/partition/MigrationRequestTask.java
+++ b/hazelcast/src/main/java/com/hazelcast/impl/partition/MigrationRequestTask.java
@@ -1,149 +1,151 @@
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.impl.partition;
import com.hazelcast.core.*;
import com.hazelcast.impl.FactoryImpl;
import com.hazelcast.impl.Node;
import com.hazelcast.impl.PartitionManager;
import com.hazelcast.impl.concurrentmap.CostAwareRecordList;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.DataSerializable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
public class MigrationRequestTask extends MigratingPartition implements Callable<Boolean>, DataSerializable, HazelcastInstanceAware {
private boolean migration; // migration or copy
private boolean diffOnly;
private int selfCopyReplicaIndex = -1;
private transient HazelcastInstance hazelcast;
public MigrationRequestTask() {
}
public MigrationRequestTask(int partitionId, Address from, Address to, int replicaIndex, boolean migration) {
this(partitionId, from, to, replicaIndex, migration, false);
}
public MigrationRequestTask(int partitionId, Address from, Address to, int replicaIndex,
boolean migration, boolean diffOnly) {
super(partitionId, replicaIndex, from, to);
this.migration = migration;
this.diffOnly = diffOnly;
}
public boolean isMigration() {
return migration;
}
public int getSelfCopyReplicaIndex() {
return selfCopyReplicaIndex;
}
public void setSelfCopyReplicaIndex(final int selfCopyReplicaIndex) {
this.selfCopyReplicaIndex = selfCopyReplicaIndex;
}
public void setFromAddress(final Address from) {
this.from = from;
}
public Boolean call() throws Exception {
+ final ILogger logger = getLogger();
if (to.equals(from)) {
- getLogger().log(Level.FINEST, "To and from addresses are same! => " + toString());
+ logger.log(Level.FINEST, "To and from addresses are same! => " + toString());
return Boolean.TRUE;
}
if (from == null) {
- getLogger().log(Level.FINEST, "From address is null => " + toString());
+ logger.log(Level.FINEST, "From address is null => " + toString());
}
final Node node = ((FactoryImpl) hazelcast).node;
PartitionManager pm = node.concurrentMapManager.getPartitionManager();
try {
Member target = pm.getMember(to);
if (target == null) {
- getLogger().log(Level.WARNING, "Target member of task could not be found! => " + toString());
+ logger.log(Level.WARNING, "Target member of task could not be found! => " + toString());
return Boolean.FALSE;
}
final CostAwareRecordList costAwareRecordList = pm.getActivePartitionRecords(partitionId, replicaIndex, to, diffOnly);
DistributedTask task = new DistributedTask(new MigrationTask(partitionId, costAwareRecordList,
replicaIndex, from), target);
Future future = node.factory.getExecutorService(PartitionManager.MIGRATION_EXECUTOR_NAME).submit(task);
final long timeout = node.groupProperties.PARTITION_MIGRATION_TIMEOUT.getLong();
return (Boolean) future.get(timeout, TimeUnit.SECONDS);
} catch (Throwable e) {
Level level = Level.WARNING;
if (e instanceof ExecutionException) {
- e = e.getCause();
+ final Throwable cause = e.getCause();
+ e = cause != null ? cause : e;
}
if (e instanceof MemberLeftException || e instanceof IllegalStateException) {
level = Level.FINEST;
}
- getLogger().log(level, e.getMessage(), e);
+ logger.log(level, e.getMessage(), e);
}
return Boolean.FALSE;
}
private ILogger getLogger() {
if (hazelcast == null) {
return Logger.getLogger(MigrationRequestTask.class.getName());
}
return ((FactoryImpl) hazelcast).node.getLogger(MigrationRequestTask.class.getName());
}
public void writeData(DataOutput out) throws IOException {
super.writeData(out);
out.writeBoolean(migration);
out.writeBoolean(diffOnly);
out.writeInt(selfCopyReplicaIndex);
}
public void readData(DataInput in) throws IOException {
super.readData(in);
migration = in.readBoolean();
diffOnly = in.readBoolean();
selfCopyReplicaIndex = in.readInt();
}
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hazelcast = hazelcastInstance;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("MigrationRequestTask");
sb.append("{partitionId=").append(partitionId);
sb.append(", from=").append(from);
sb.append(", to=").append(to);
sb.append(", replicaIndex=").append(replicaIndex);
sb.append(", migration=").append(migration);
sb.append(", diffOnly=").append(diffOnly);
sb.append(", selfCopyReplicaIndex=").append(selfCopyReplicaIndex);
sb.append('}');
return sb.toString();
}
}
| false | true | public Boolean call() throws Exception {
if (to.equals(from)) {
getLogger().log(Level.FINEST, "To and from addresses are same! => " + toString());
return Boolean.TRUE;
}
if (from == null) {
getLogger().log(Level.FINEST, "From address is null => " + toString());
}
final Node node = ((FactoryImpl) hazelcast).node;
PartitionManager pm = node.concurrentMapManager.getPartitionManager();
try {
Member target = pm.getMember(to);
if (target == null) {
getLogger().log(Level.WARNING, "Target member of task could not be found! => " + toString());
return Boolean.FALSE;
}
final CostAwareRecordList costAwareRecordList = pm.getActivePartitionRecords(partitionId, replicaIndex, to, diffOnly);
DistributedTask task = new DistributedTask(new MigrationTask(partitionId, costAwareRecordList,
replicaIndex, from), target);
Future future = node.factory.getExecutorService(PartitionManager.MIGRATION_EXECUTOR_NAME).submit(task);
final long timeout = node.groupProperties.PARTITION_MIGRATION_TIMEOUT.getLong();
return (Boolean) future.get(timeout, TimeUnit.SECONDS);
} catch (Throwable e) {
Level level = Level.WARNING;
if (e instanceof ExecutionException) {
e = e.getCause();
}
if (e instanceof MemberLeftException || e instanceof IllegalStateException) {
level = Level.FINEST;
}
getLogger().log(level, e.getMessage(), e);
}
return Boolean.FALSE;
}
| public Boolean call() throws Exception {
final ILogger logger = getLogger();
if (to.equals(from)) {
logger.log(Level.FINEST, "To and from addresses are same! => " + toString());
return Boolean.TRUE;
}
if (from == null) {
logger.log(Level.FINEST, "From address is null => " + toString());
}
final Node node = ((FactoryImpl) hazelcast).node;
PartitionManager pm = node.concurrentMapManager.getPartitionManager();
try {
Member target = pm.getMember(to);
if (target == null) {
logger.log(Level.WARNING, "Target member of task could not be found! => " + toString());
return Boolean.FALSE;
}
final CostAwareRecordList costAwareRecordList = pm.getActivePartitionRecords(partitionId, replicaIndex, to, diffOnly);
DistributedTask task = new DistributedTask(new MigrationTask(partitionId, costAwareRecordList,
replicaIndex, from), target);
Future future = node.factory.getExecutorService(PartitionManager.MIGRATION_EXECUTOR_NAME).submit(task);
final long timeout = node.groupProperties.PARTITION_MIGRATION_TIMEOUT.getLong();
return (Boolean) future.get(timeout, TimeUnit.SECONDS);
} catch (Throwable e) {
Level level = Level.WARNING;
if (e instanceof ExecutionException) {
final Throwable cause = e.getCause();
e = cause != null ? cause : e;
}
if (e instanceof MemberLeftException || e instanceof IllegalStateException) {
level = Level.FINEST;
}
logger.log(level, e.getMessage(), e);
}
return Boolean.FALSE;
}
|
diff --git a/src/de/schildbach/pte/VbbProvider.java b/src/de/schildbach/pte/VbbProvider.java
index e2923f4..07a2540 100644
--- a/src/de/schildbach/pte/VbbProvider.java
+++ b/src/de/schildbach/pte/VbbProvider.java
@@ -1,193 +1,196 @@
/*
* Copyright 2010, 2011 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.schildbach.pte;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.schildbach.pte.dto.Location;
import de.schildbach.pte.dto.LocationType;
import de.schildbach.pte.dto.NearbyStationsResult;
import de.schildbach.pte.dto.QueryDeparturesResult;
import de.schildbach.pte.util.ParserUtils;
/**
* @author Andreas Schildbach
*/
public class VbbProvider extends AbstractHafasProvider
{
public static final NetworkId NETWORK_ID = NetworkId.VBB;
private static final String API_BASE = "http://www.vbb-fahrinfo.de/hafas/";
public VbbProvider()
{
super(API_BASE + "query.exe/dn", 7, null);
}
public NetworkId id()
{
return NETWORK_ID;
}
public boolean hasCapabilities(final Capability... capabilities)
{
for (final Capability capability : capabilities)
if (capability == Capability.DEPARTURES || capability == Capability.AUTOCOMPLETE_ONE_LINE || capability == Capability.CONNECTIONS)
return true;
return false;
}
@Override
protected void setProductBits(final StringBuilder productBits, final char product)
{
if (product == 'I')
{
productBits.setCharAt(5, '1');
}
else if (product == 'R')
{
productBits.setCharAt(6, '1');
}
else if (product == 'S')
{
productBits.setCharAt(0, '1');
}
else if (product == 'U')
{
productBits.setCharAt(1, '1');
}
else if (product == 'T')
{
productBits.setCharAt(2, '1');
}
else if (product == 'B' || product == 'P')
{
productBits.setCharAt(3, '1');
}
else if (product == 'F')
{
productBits.setCharAt(4, '1');
}
+ else if (product == 'C')
+ {
+ }
else
{
throw new IllegalArgumentException("cannot handle: " + product);
}
}
private static final Pattern P_SPLIT_NAME_PAREN = Pattern.compile("(.*?) \\((.{4,}?)\\)(?: \\((U|S|S\\+U)\\))?");
private static final Pattern P_SPLIT_NAME_COMMA = Pattern.compile("([^,]*), ([^,]*)");
@Override
protected String[] splitPlaceAndName(final String name)
{
final Matcher mParen = P_SPLIT_NAME_PAREN.matcher(name);
if (mParen.matches())
{
final String su = mParen.group(3);
return new String[] { mParen.group(2), mParen.group(1) + (su != null ? " (" + su + ")" : "") };
}
final Matcher mComma = P_SPLIT_NAME_COMMA.matcher(name);
if (mComma.matches())
return new String[] { mComma.group(1), mComma.group(2) };
return super.splitPlaceAndName(name);
}
public NearbyStationsResult queryNearbyStations(final Location location, final int maxDistance, final int maxStations) throws IOException
{
final StringBuilder uri = new StringBuilder(API_BASE);
if (location.hasLocation())
{
uri.append("query.exe/dny");
uri.append("?performLocating=2&tpl=stop2json");
uri.append("&look_maxno=").append(maxStations != 0 ? maxStations : 200);
uri.append("&look_maxdist=").append(maxDistance != 0 ? maxDistance : 5000);
uri.append("&look_stopclass=").append(allProductsInt());
uri.append("&look_x=").append(location.lon);
uri.append("&look_y=").append(location.lat);
return jsonNearbyStations(uri.toString());
}
else if (location.type == LocationType.STATION && location.hasId())
{
uri.append("stboard.exe/dn");
uri.append("?productsFilter=").append(allProductsString());
uri.append("&boardType=dep");
uri.append("&input=").append(location.id);
uri.append("&sTI=1&start=yes&hcount=0");
uri.append("&L=vs_java3");
return xmlNearbyStations(uri.toString());
}
else
{
throw new IllegalArgumentException("cannot handle: '" + location.toDebugString());
}
}
public QueryDeparturesResult queryDepartures(final int stationId, final int maxDepartures, final boolean equivs) throws IOException
{
final StringBuilder uri = new StringBuilder();
uri.append(API_BASE).append("stboard.exe/dn");
uri.append("?productsFilter=").append(allProductsString());
uri.append("&boardType=dep");
uri.append("&disableEquivs=yes"); // don't use nearby stations
uri.append("&maxJourneys=50"); // ignore maxDepartures because result contains other stations
uri.append("&start=yes");
uri.append("&L=vs_java3");
uri.append("&input=").append(stationId);
return xmlQueryDepartures(uri.toString(), stationId);
}
private static final String AUTOCOMPLETE_URI = API_BASE + "ajax-getstop.exe/dn?getstop=1&REQ0JourneyStopsS0A=255&S=%s?&js=true&";
private static final String ENCODING = "ISO-8859-1";
public List<Location> autocompleteStations(final CharSequence constraint) throws IOException
{
final String uri = String.format(AUTOCOMPLETE_URI, ParserUtils.urlEncode(constraint.toString(), ENCODING));
return jsonGetStops(uri);
}
private static final Pattern P_NORMALIZE_LINE_AND_TYPE = Pattern.compile("([^#]*)#(.*)");
@Override
protected String normalizeLine(final String line)
{
final Matcher m = P_NORMALIZE_LINE_AND_TYPE.matcher(line);
if (m.matches())
{
final String number = m.group(1).replaceAll("\\s+", " ");
final String type = m.group(2);
final char normalizedType = normalizeType(type);
if (normalizedType != 0)
return normalizedType + number;
throw new IllegalStateException("cannot normalize type " + type + " number " + number + " line " + line);
}
throw new IllegalStateException("cannot normalize line " + line);
}
}
| true | true | protected void setProductBits(final StringBuilder productBits, final char product)
{
if (product == 'I')
{
productBits.setCharAt(5, '1');
}
else if (product == 'R')
{
productBits.setCharAt(6, '1');
}
else if (product == 'S')
{
productBits.setCharAt(0, '1');
}
else if (product == 'U')
{
productBits.setCharAt(1, '1');
}
else if (product == 'T')
{
productBits.setCharAt(2, '1');
}
else if (product == 'B' || product == 'P')
{
productBits.setCharAt(3, '1');
}
else if (product == 'F')
{
productBits.setCharAt(4, '1');
}
else
{
throw new IllegalArgumentException("cannot handle: " + product);
}
}
| protected void setProductBits(final StringBuilder productBits, final char product)
{
if (product == 'I')
{
productBits.setCharAt(5, '1');
}
else if (product == 'R')
{
productBits.setCharAt(6, '1');
}
else if (product == 'S')
{
productBits.setCharAt(0, '1');
}
else if (product == 'U')
{
productBits.setCharAt(1, '1');
}
else if (product == 'T')
{
productBits.setCharAt(2, '1');
}
else if (product == 'B' || product == 'P')
{
productBits.setCharAt(3, '1');
}
else if (product == 'F')
{
productBits.setCharAt(4, '1');
}
else if (product == 'C')
{
}
else
{
throw new IllegalArgumentException("cannot handle: " + product);
}
}
|
diff --git a/src/cf.java b/src/cf.java
index 6d05990..28da23e 100644
--- a/src/cf.java
+++ b/src/cf.java
@@ -1,98 +1,98 @@
public class cf extends gm {
private int a;
public cf(int paramInt) {
super(paramInt);
this.a = (paramInt + 256);
a(gv.m[(paramInt + 256)].a(2));
}
public boolean a(il paramik, gq paramgp, ff paramff, int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
// hMod: Bail if we have nothing of the items in hand
if (paramik.a == 0) {
return false;
}
// hMod: Store blockInfo of the one we clicked
int blockClickedId = paramff.a(paramInt1, paramInt2, paramInt3);
Block blockClicked = new Block(blockClickedId, paramInt1, paramInt2, paramInt3 );
if (paramff.a(paramInt1, paramInt2, paramInt3) == gv.aS.bh) {
paramInt4 = 0;
} else {
if (paramInt4 == 0) {
paramInt2--;
}
if (paramInt4 == 1) {
paramInt2++;
}
if (paramInt4 == 2) {
paramInt3--;
}
if (paramInt4 == 3) {
paramInt3++;
}
if (paramInt4 == 4) {
paramInt1--;
}
if (paramInt4 == 5) {
paramInt1++;
}
}
if (paramik.a == 0) {
return false;
}
// hMod: Store faceClicked (must be here to have the 'snow' special case).
blockClicked.setFaceClicked(Block.Face.fromId( paramInt4 ));
// hMod: And the block we're about to place
Block blockPlaced = new Block( this.a, paramInt1, paramInt2, paramInt3 );
// hMod Store all the old settings 'externally' in case someone changes blockPlaced.
int oldMaterial = paramff.a(paramInt1, paramInt2, paramInt3);
int oldData = paramff.b(paramInt1, paramInt2, paramInt3);
if (paramff.a(this.a, paramInt1, paramInt2, paramInt3, false)) {
gv localgu = gv.m[this.a];
//hMod: Take over block placement
if (paramff.a(paramInt1, paramInt2, paramInt3, this.a)) {
// hMod: Check if this was playerPlaced and call the hook
if (paramgp instanceof fi && (Boolean) etc.getLoader().callHook(PluginLoader.Hook.BLOCK_PLACE, ((fi)paramgp).getPlayer(), blockPlaced, blockClicked, new Item(paramik))) {
// hMod: Undo!
// Specialcase iceblocks, replace with 'glass' first (so it doesnt explode into water)
if (this.a == 79) {
paramff.a(paramInt1, paramInt2, paramInt3, 20 );
}
paramff.a(paramInt1, paramInt2, paramInt3, oldMaterial );
paramff.c(paramInt1, paramInt2, paramInt3, oldData );
// hMod: Refund the item the player lost >.>
// or not, this occasionally dupes items! we'lm do this when notch implements serverside invs.
//((fi)paramgp).a.b(new fh(paramhn, 1));
return false;
} else {
- paramff.f(paramInt1, paramInt2, paramInt3);
+ paramff.g(paramInt1, paramInt2, paramInt3);
paramff.g(paramInt1, paramInt2, paramInt3, this.a);
gv.m[this.a].c(paramff, paramInt1, paramInt2, paramInt3, paramInt4);
// hMod: Downcast demanded for inheritance to work >.>
gv.m[this.a].a(paramff, paramInt1, paramInt2, paramInt3, (lc)paramgp);
paramff.a(paramInt1 + 0.5F, paramInt2 + 0.5F, paramInt3 + 0.5F, localgu.bq.c(), (localgu.bq.a() + 1.0F) / 2.0F, localgu.bq.b() * 0.8F);
paramik.a -= 1;
}
}
}
return true;
}
public String a() {
return gv.m[this.a].e();
}
}
| true | true | public boolean a(il paramik, gq paramgp, ff paramff, int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
// hMod: Bail if we have nothing of the items in hand
if (paramik.a == 0) {
return false;
}
// hMod: Store blockInfo of the one we clicked
int blockClickedId = paramff.a(paramInt1, paramInt2, paramInt3);
Block blockClicked = new Block(blockClickedId, paramInt1, paramInt2, paramInt3 );
if (paramff.a(paramInt1, paramInt2, paramInt3) == gv.aS.bh) {
paramInt4 = 0;
} else {
if (paramInt4 == 0) {
paramInt2--;
}
if (paramInt4 == 1) {
paramInt2++;
}
if (paramInt4 == 2) {
paramInt3--;
}
if (paramInt4 == 3) {
paramInt3++;
}
if (paramInt4 == 4) {
paramInt1--;
}
if (paramInt4 == 5) {
paramInt1++;
}
}
if (paramik.a == 0) {
return false;
}
// hMod: Store faceClicked (must be here to have the 'snow' special case).
blockClicked.setFaceClicked(Block.Face.fromId( paramInt4 ));
// hMod: And the block we're about to place
Block blockPlaced = new Block( this.a, paramInt1, paramInt2, paramInt3 );
// hMod Store all the old settings 'externally' in case someone changes blockPlaced.
int oldMaterial = paramff.a(paramInt1, paramInt2, paramInt3);
int oldData = paramff.b(paramInt1, paramInt2, paramInt3);
if (paramff.a(this.a, paramInt1, paramInt2, paramInt3, false)) {
gv localgu = gv.m[this.a];
//hMod: Take over block placement
if (paramff.a(paramInt1, paramInt2, paramInt3, this.a)) {
// hMod: Check if this was playerPlaced and call the hook
if (paramgp instanceof fi && (Boolean) etc.getLoader().callHook(PluginLoader.Hook.BLOCK_PLACE, ((fi)paramgp).getPlayer(), blockPlaced, blockClicked, new Item(paramik))) {
// hMod: Undo!
// Specialcase iceblocks, replace with 'glass' first (so it doesnt explode into water)
if (this.a == 79) {
paramff.a(paramInt1, paramInt2, paramInt3, 20 );
}
paramff.a(paramInt1, paramInt2, paramInt3, oldMaterial );
paramff.c(paramInt1, paramInt2, paramInt3, oldData );
// hMod: Refund the item the player lost >.>
// or not, this occasionally dupes items! we'lm do this when notch implements serverside invs.
//((fi)paramgp).a.b(new fh(paramhn, 1));
return false;
} else {
paramff.f(paramInt1, paramInt2, paramInt3);
paramff.g(paramInt1, paramInt2, paramInt3, this.a);
gv.m[this.a].c(paramff, paramInt1, paramInt2, paramInt3, paramInt4);
// hMod: Downcast demanded for inheritance to work >.>
gv.m[this.a].a(paramff, paramInt1, paramInt2, paramInt3, (lc)paramgp);
paramff.a(paramInt1 + 0.5F, paramInt2 + 0.5F, paramInt3 + 0.5F, localgu.bq.c(), (localgu.bq.a() + 1.0F) / 2.0F, localgu.bq.b() * 0.8F);
paramik.a -= 1;
}
}
}
return true;
}
| public boolean a(il paramik, gq paramgp, ff paramff, int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
// hMod: Bail if we have nothing of the items in hand
if (paramik.a == 0) {
return false;
}
// hMod: Store blockInfo of the one we clicked
int blockClickedId = paramff.a(paramInt1, paramInt2, paramInt3);
Block blockClicked = new Block(blockClickedId, paramInt1, paramInt2, paramInt3 );
if (paramff.a(paramInt1, paramInt2, paramInt3) == gv.aS.bh) {
paramInt4 = 0;
} else {
if (paramInt4 == 0) {
paramInt2--;
}
if (paramInt4 == 1) {
paramInt2++;
}
if (paramInt4 == 2) {
paramInt3--;
}
if (paramInt4 == 3) {
paramInt3++;
}
if (paramInt4 == 4) {
paramInt1--;
}
if (paramInt4 == 5) {
paramInt1++;
}
}
if (paramik.a == 0) {
return false;
}
// hMod: Store faceClicked (must be here to have the 'snow' special case).
blockClicked.setFaceClicked(Block.Face.fromId( paramInt4 ));
// hMod: And the block we're about to place
Block blockPlaced = new Block( this.a, paramInt1, paramInt2, paramInt3 );
// hMod Store all the old settings 'externally' in case someone changes blockPlaced.
int oldMaterial = paramff.a(paramInt1, paramInt2, paramInt3);
int oldData = paramff.b(paramInt1, paramInt2, paramInt3);
if (paramff.a(this.a, paramInt1, paramInt2, paramInt3, false)) {
gv localgu = gv.m[this.a];
//hMod: Take over block placement
if (paramff.a(paramInt1, paramInt2, paramInt3, this.a)) {
// hMod: Check if this was playerPlaced and call the hook
if (paramgp instanceof fi && (Boolean) etc.getLoader().callHook(PluginLoader.Hook.BLOCK_PLACE, ((fi)paramgp).getPlayer(), blockPlaced, blockClicked, new Item(paramik))) {
// hMod: Undo!
// Specialcase iceblocks, replace with 'glass' first (so it doesnt explode into water)
if (this.a == 79) {
paramff.a(paramInt1, paramInt2, paramInt3, 20 );
}
paramff.a(paramInt1, paramInt2, paramInt3, oldMaterial );
paramff.c(paramInt1, paramInt2, paramInt3, oldData );
// hMod: Refund the item the player lost >.>
// or not, this occasionally dupes items! we'lm do this when notch implements serverside invs.
//((fi)paramgp).a.b(new fh(paramhn, 1));
return false;
} else {
paramff.g(paramInt1, paramInt2, paramInt3);
paramff.g(paramInt1, paramInt2, paramInt3, this.a);
gv.m[this.a].c(paramff, paramInt1, paramInt2, paramInt3, paramInt4);
// hMod: Downcast demanded for inheritance to work >.>
gv.m[this.a].a(paramff, paramInt1, paramInt2, paramInt3, (lc)paramgp);
paramff.a(paramInt1 + 0.5F, paramInt2 + 0.5F, paramInt3 + 0.5F, localgu.bq.c(), (localgu.bq.a() + 1.0F) / 2.0F, localgu.bq.b() * 0.8F);
paramik.a -= 1;
}
}
}
return true;
}
|
diff --git a/src/org/jitsi/impl/neomedia/RTCPFeedbackPacket.java b/src/org/jitsi/impl/neomedia/RTCPFeedbackPacket.java
index 9a97ed6f..ac30fbf4 100644
--- a/src/org/jitsi/impl/neomedia/RTCPFeedbackPacket.java
+++ b/src/org/jitsi/impl/neomedia/RTCPFeedbackPacket.java
@@ -1,87 +1,87 @@
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jitsi.impl.neomedia;
import javax.media.rtp.*;
/**
* Represents an RTCP feedback packet as described in RFC4585.
*
* @author Sebastien Vincent
*/
public class RTCPFeedbackPacket
{
/**
* Feedback message type.
*/
private int fmt = 0;
/**
* Payload type.
*/
private int payloadType = 0;
/**
* SSRC of packet sender.
*/
private long senderSSRC = 0;
/**
* SSRC of media source.
*/
private long sourceSSRC = 0;
/**
* Constructor.
*
* @param type feedback message type
* @param payloadType payload type
* @param sender sender SSRC
* @param src source SSRC
*/
public RTCPFeedbackPacket(int type, int payloadType, long sender, long src)
{
this.fmt = type;
this.payloadType = payloadType;
this.senderSSRC = sender;
this.sourceSSRC = src;
}
/**
* Write RTCP packet to output stream of a <tt>DatagramSocket</tt>.
*
* @param out <tt>OutputDataStream</tt> of a <tt>DatagramSocket</tt>
*/
public void writeTo(OutputDataStream out)
{
byte data[] = new byte[12];
- byte vpfmt = (byte)((2 << 7) | (0 << 6) | (byte)fmt);
+ byte vpfmt = (byte) (0x80 /* RTP version */ | (fmt & 0x1F));
data[0] = vpfmt;
- data[1] = (byte)payloadType;
+ data[1] = (byte) payloadType;
/* length (in 32-bit words minus one) */
data[2] = 0;
data[3] = 2; /* common packet is 12 bytes so (12/4) - 1 */
/* sender SSRC */
- data[4] = (byte)(senderSSRC >> 24);
- data[5] = (byte)((senderSSRC >> 16) & 0xFF);
- data[6] = (byte)((senderSSRC >> 8) & 0xFF);
- data[7] = (byte)(senderSSRC & 0xFF);
+ data[4] = (byte) (senderSSRC >> 24);
+ data[5] = (byte) ((senderSSRC >> 16) & 0xFF);
+ data[6] = (byte) ((senderSSRC >> 8) & 0xFF);
+ data[7] = (byte) (senderSSRC & 0xFF);
/* source SSRC */
- data[8] = (byte)(sourceSSRC >> 24);
- data[9] = (byte)((sourceSSRC >> 16) & 0xFF);
- data[10] = (byte)((sourceSSRC >> 8) & 0xFF);
- data[11] = (byte)(sourceSSRC & 0xFF);
+ data[8] = (byte) (sourceSSRC >> 24);
+ data[9] = (byte) ((sourceSSRC >> 16) & 0xFF);
+ data[10] = (byte) ((sourceSSRC >> 8) & 0xFF);
+ data[11] = (byte) (sourceSSRC & 0xFF);
/* effective write */
out.write(data, 0, 12);
}
}
| false | true | public void writeTo(OutputDataStream out)
{
byte data[] = new byte[12];
byte vpfmt = (byte)((2 << 7) | (0 << 6) | (byte)fmt);
data[0] = vpfmt;
data[1] = (byte)payloadType;
/* length (in 32-bit words minus one) */
data[2] = 0;
data[3] = 2; /* common packet is 12 bytes so (12/4) - 1 */
/* sender SSRC */
data[4] = (byte)(senderSSRC >> 24);
data[5] = (byte)((senderSSRC >> 16) & 0xFF);
data[6] = (byte)((senderSSRC >> 8) & 0xFF);
data[7] = (byte)(senderSSRC & 0xFF);
/* source SSRC */
data[8] = (byte)(sourceSSRC >> 24);
data[9] = (byte)((sourceSSRC >> 16) & 0xFF);
data[10] = (byte)((sourceSSRC >> 8) & 0xFF);
data[11] = (byte)(sourceSSRC & 0xFF);
/* effective write */
out.write(data, 0, 12);
}
| public void writeTo(OutputDataStream out)
{
byte data[] = new byte[12];
byte vpfmt = (byte) (0x80 /* RTP version */ | (fmt & 0x1F));
data[0] = vpfmt;
data[1] = (byte) payloadType;
/* length (in 32-bit words minus one) */
data[2] = 0;
data[3] = 2; /* common packet is 12 bytes so (12/4) - 1 */
/* sender SSRC */
data[4] = (byte) (senderSSRC >> 24);
data[5] = (byte) ((senderSSRC >> 16) & 0xFF);
data[6] = (byte) ((senderSSRC >> 8) & 0xFF);
data[7] = (byte) (senderSSRC & 0xFF);
/* source SSRC */
data[8] = (byte) (sourceSSRC >> 24);
data[9] = (byte) ((sourceSSRC >> 16) & 0xFF);
data[10] = (byte) ((sourceSSRC >> 8) & 0xFF);
data[11] = (byte) (sourceSSRC & 0xFF);
/* effective write */
out.write(data, 0, 12);
}
|
diff --git a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/WikiServletScalaris.java b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/WikiServletScalaris.java
index 74d59292..49719708 100644
--- a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/WikiServletScalaris.java
+++ b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/WikiServletScalaris.java
@@ -1,519 +1,519 @@
/**
* Copyright 2011 Zuse Institute Berlin
*
* 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 de.zib.scalaris.examples.wikipedia.bliki;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.TreeSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import de.zib.scalaris.Connection;
import de.zib.scalaris.ConnectionFactory;
import de.zib.scalaris.ConnectionPool;
import de.zib.scalaris.TransactionSingleOp;
import de.zib.scalaris.examples.wikipedia.BigIntegerResult;
import de.zib.scalaris.examples.wikipedia.CircularByteArrayOutputStream;
import de.zib.scalaris.examples.wikipedia.PageHistoryResult;
import de.zib.scalaris.examples.wikipedia.PageListResult;
import de.zib.scalaris.examples.wikipedia.RandomTitleResult;
import de.zib.scalaris.examples.wikipedia.RevisionResult;
import de.zib.scalaris.examples.wikipedia.SavePageResult;
import de.zib.scalaris.examples.wikipedia.ScalarisDataHandler;
import de.zib.scalaris.examples.wikipedia.data.Revision;
import de.zib.scalaris.examples.wikipedia.data.SiteInfo;
import de.zib.scalaris.examples.wikipedia.data.xml.SAXParsingInterruptedException;
import de.zib.scalaris.examples.wikipedia.data.xml.WikiDump;
import de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpHandler;
import de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpPreparedSQLiteToScalaris;
import de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpToScalarisHandler;
/**
* Wiki servlet connecting to Scalaris.
*
* @author Nico Kruber, [email protected]
*/
public class WikiServletScalaris extends WikiServlet<Connection> {
private static final long serialVersionUID = 1L;
private static final int CONNECTION_POOL_SIZE = 100;
private static final int MAX_WAIT_FOR_CONNECTION = 10000; // 10s
private ConnectionPool cPool;
/**
* Default constructor creating the servlet.
*/
public WikiServletScalaris() {
super();
}
/**
* Servlet initialisation: creates the connection to the erlang node and
* imports site information.
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
Properties properties = new Properties();
try {
InputStream fis = config.getServletContext().getResourceAsStream("/WEB-INF/scalaris.properties");
if (fis != null) {
properties.load(fis);
properties.setProperty("PropertyLoader.loadedfile", "/WEB-INF/scalaris.properties");
fis.close();
} else {
properties = null;
}
} catch (IOException e) {
// e.printStackTrace();
properties = null;
}
ConnectionFactory cFactory;
if (properties != null) {
cFactory = new ConnectionFactory(properties);
} else {
cFactory = new ConnectionFactory();
cFactory.setClientName("wiki");
}
Random random = new Random();
String clientName = new BigInteger(128, random).toString(16);
cFactory.setClientName(cFactory.getClientName() + '_' + clientName);
cFactory.setClientNameAppendUUID(true);
// cFactory.setConnectionPolicy(new RoundRobinConnectionPolicy(cFactory.getNodes()));
cPool = new ConnectionPool(cFactory, CONNECTION_POOL_SIZE);
loadSiteInfo();
loadPlugins();
}
/**
* Loads the siteinfo object from Scalaris.
*
* @return <tt>true</tt> on success,
* <tt>false</tt> if not found or no connection available
*/
@Override
protected synchronized boolean loadSiteInfo() {
TransactionSingleOp scalaris_single;
try {
Connection conn = cPool.getConnection(MAX_WAIT_FOR_CONNECTION);
if (conn == null) {
System.err.println("Could not get a connection to Scalaris for siteinfo, waited " + MAX_WAIT_FOR_CONNECTION + "ms");
return false;
}
scalaris_single = new TransactionSingleOp(conn);
try {
siteinfo = scalaris_single.read("siteinfo").jsonValue(SiteInfo.class);
// TODO: fix siteinfo's base url
namespace = new MyNamespace(siteinfo);
initialized = true;
} catch (Exception e) {
// no warning here - this probably is an empty wiki
return false;
}
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
return false;
}
return true;
}
/**
* Sets up the connection to the Scalaris erlang node once on the server.
*
* @param request
* the request to the servlet
*/
@Override
protected Connection getConnection(HttpServletRequest request) {
try {
Connection conn = cPool.getConnection(MAX_WAIT_FOR_CONNECTION);
if (conn == null) {
System.err.println("Could not get a connection to Scalaris, waited " + MAX_WAIT_FOR_CONNECTION + "ms");
if (request != null) {
setParam_error(request, "ERROR: DB unavailable");
addToParam_notice(request, "error: <pre>Could not get a connection to Scalaris, waited " + MAX_WAIT_FOR_CONNECTION + "ms</pre>");
}
return null;
}
return conn;
} catch (Exception e) {
if (request != null) {
setParam_error(request, "ERROR: DB unavailable");
addToParam_notice(request, "error: <pre>" + e.getMessage() + "</pre>");
} else {
System.out.println(e);
e.printStackTrace();
}
return null;
}
}
/**
* Releases the connection back into the Scalaris connection pool.
*
* @param request
* the request to the servlet
* @param conn
* the connection to release
*/
@Override
protected void releaseConnection(HttpServletRequest request, Connection conn) {
cPool.releaseConnection(conn);
}
/**
* Shows a page for importing a DB dump.
*
* @param request
* the request of the current operation
* @param response
* the response of the current operation
*
* @throws IOException
* @throws ServletException
*/
@Override
protected synchronized void showImportPage(HttpServletRequest request,
HttpServletResponse response, Connection connection)
throws ServletException, IOException {
WikiPageBean page = new WikiPageBean();
page.setNotAvailable(true);
request.setAttribute("pageBean", page);
StringBuilder content = new StringBuilder();
String dumpsPath = getServletContext().getRealPath("/WEB-INF/dumps");
if (currentImport.isEmpty() && importHandler == null) {
TreeSet<String> availableDumps = new TreeSet<String>();
File dumpsDir = new File(dumpsPath);
if (dumpsDir.isDirectory()) {
availableDumps.addAll(Arrays.asList(dumpsDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return MATCH_WIKI_IMPORT_FILE.matcher(name).matches();
}
})));
}
// get parameters:
String req_import = request.getParameter("import");
if (req_import == null || !availableDumps.contains(req_import)) {
content.append("<h2>Please select a wiki dump to import</h2>\n");
content.append("<form method=\"get\" action=\"wiki\">\n");
content.append("<p>\n");
content.append(" <select name=\"import\" size=\"10\" style=\"width:500px;\">\n");
for (String dump: availableDumps) {
content.append(" <option>" + dump + "</option>\n");
}
content.append(" </select>\n");
content.append(" </p>\n");
content.append(" <p>Maximum number of revisions per page: <input name=\"max_revisions\" size=\"2\" value=\"2\" /></br><span style=\"font-size:80%\">(<tt>-1</tt> to import everything)</span></p>\n");
- content.append(" <p>No entra newer than: <input name=\"max_time\" size=\"20\" value=\"\" /></br><span style=\"font-size:80%\">(ISO8601 format, e.g. <tt>2004-01-07T08:09:29Z</tt> - leave empty to import everything)</span></p>\n");
+ content.append(" <p>No entry newer than: <input name=\"max_time\" size=\"20\" value=\"\" /></br><span style=\"font-size:80%\">(ISO8601 format, e.g. <tt>2004-01-07T08:09:29Z</tt> - leave empty to import everything)</span></p>\n");
content.append(" <input type=\"submit\" value=\"Import\" />\n");
content.append("</form>\n");
content.append("<p>Note: You will be re-directed to the main page when the import finishes.</p>");
} else {
content.append("<h2>Importing \"" + req_import + "\"...</h2>\n");
try {
currentImport = req_import;
int maxRevisions = parseInt(request.getParameter("max_revisions"), 2);
Calendar maxTime = parseDate(request.getParameter("max_time"), null);
importLog = new CircularByteArrayOutputStream(1024 * 1024);
PrintStream ps = new PrintStream(importLog);
ps.println("starting import...");
String fileName = dumpsPath + File.separator + req_import;
if (fileName.endsWith(".db")) {
importHandler = new WikiDumpPreparedSQLiteToScalaris(fileName, cPool.getConnectionFactory());
} else {
importHandler = new WikiDumpToScalarisHandler(
de.zib.scalaris.examples.wikipedia.data.xml.Main.blacklist,
null, maxRevisions, null, maxTime, cPool.getConnectionFactory());
}
importHandler.setMsgOut(ps);
this.new ImportThread(importHandler, fileName, ps).start();
response.setHeader("Refresh", "2; url = wiki?import=" + currentImport);
content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n");
content.append("<pre>");
content.append("starting import...\n");
content.append("</pre>");
content.append("<p><a href=\"wiki?import=" + currentImport + "\">refresh</a></p>");
content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>");
} catch (Exception e) {
setParam_error(request, "ERROR: import failed");
addToParam_notice(request, "error: <pre>" + e.getMessage() + "</pre>");
currentImport = "";
}
}
} else {
content.append("<h2>Importing \"" + currentImport + "\"...</h2>\n");
String req_stop_import = request.getParameter("stop_import");
boolean stopImport;
if (req_stop_import == null || req_stop_import.isEmpty()) {
stopImport = false;
response.setHeader("Refresh", IMPORT_REDIRECT_EVERY + "; url = wiki?import=" + currentImport);
content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n");
} else {
stopImport = true;
importHandler.stopParsing();
content.append("<p>Current log file:</p>\n");
}
content.append("<pre>");
String log = importLog.toString();
int start = log.indexOf("\n");
if (start != -1) {
content.append(log.substring(start));
}
content.append("</pre>");
if (!stopImport) {
content.append("<p><a href=\"wiki?import=" + currentImport + "\">refresh</a></p>");
content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>");
} else {
content.append("<p>Import has been stopped by the user. Return to <a href=\"wiki?title=" + MAIN_PAGE + "\">" + MAIN_PAGE + "</a>.</p>");
}
}
page.setNotice(WikiServlet.getParam_notice(request));
page.setError(getParam_error(request));
page.setTitle("Import Wiki dump");
page.setPage(content.toString());
RequestDispatcher dispatcher = request.getRequestDispatcher("page.jsp");
dispatcher.forward(request, response);
}
private class ImportThread extends Thread {
private WikiDump handler;
private String fileName;
private PrintStream ps;
public ImportThread(WikiDump handler, String fileName, PrintStream ps) {
this.handler = handler;
this.fileName = fileName;
this.ps = ps;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
InputSource is = null;
try {
handler.setUp();
if (handler instanceof WikiDumpHandler) {
WikiDumpHandler xmlHandler = (WikiDumpHandler) handler;
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(xmlHandler);
is = de.zib.scalaris.examples.wikipedia.data.xml.Main.getFileReader(fileName);
reader.parse(is);
xmlHandler.new ReportAtShutDown().run();
ps.println("import finished");
} else if (handler instanceof WikiDumpPreparedSQLiteToScalaris) {
WikiDumpPreparedSQLiteToScalaris sqlHandler =
(WikiDumpPreparedSQLiteToScalaris) handler;
sqlHandler.writeToScalaris();
sqlHandler.new ReportAtShutDown().run();
}
} catch (Exception e) {
if (e instanceof SAXParsingInterruptedException) {
// this is ok - we told the parser to stop
} else {
e.printStackTrace(ps);
}
} finally {
handler.tearDown();
if (is != null) {
try {
is.getCharacterStream().close();
} catch (IOException e) {
// don't care
}
}
}
synchronized (WikiServletScalaris.this) {
WikiServletScalaris.this.currentImport = "";
WikiServletScalaris.this.importHandler = null;
}
}
}
@Override
protected MyScalarisWikiModel getWikiModel(Connection connection) {
return new MyScalarisWikiModel(WikiServlet.imageBaseURL,
WikiServlet.linkBaseURL, connection, namespace);
}
@Override
public String getSiteInfoKey() {
return ScalarisDataHandler.getSiteInfoKey();
}
@Override
public String getPageListKey() {
return ScalarisDataHandler.getPageListKey();
}
@Override
public String getPageCountKey() {
return ScalarisDataHandler.getPageCountKey();
}
@Override
public String getArticleListKey() {
return ScalarisDataHandler.getArticleListKey();
}
@Override
public String getArticleCountKey() {
return ScalarisDataHandler.getArticleCountKey();
}
@Override
public String getRevKey(String title, int id, final MyNamespace nsObject) {
return ScalarisDataHandler.getRevKey(title, id, nsObject);
}
@Override
public String getPageKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getPageKey(title, nsObject);
}
@Override
public String getRevListKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getRevListKey(title, nsObject);
}
@Override
public String getCatPageListKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getCatPageListKey(title, nsObject);
}
@Override
public String getCatPageCountKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getCatPageCountKey(title, nsObject);
}
@Override
public String getTplPageListKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getTplPageListKey(title, nsObject);
}
@Override
public String getBackLinksPageListKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getBackLinksPageListKey(title, nsObject);
}
@Override
public String getStatsPageEditsKey() {
return ScalarisDataHandler.getStatsPageEditsKey();
}
@Override
public PageHistoryResult getPageHistory(Connection connection, String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getPageHistory(connection, title, nsObject);
}
@Override
public RevisionResult getRevision(Connection connection, String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getRevision(connection, title, nsObject);
}
@Override
public RevisionResult getRevision(Connection connection, String title, int id, final MyNamespace nsObject) {
return ScalarisDataHandler.getRevision(connection, title, id, nsObject);
}
@Override
public PageListResult getPageList(Connection connection) {
return ScalarisDataHandler.getPageList(connection);
}
@Override
public PageListResult getArticleList(Connection connection) {
return ScalarisDataHandler.getArticleList(connection);
}
@Override
public PageListResult getPagesInCategory(Connection connection, String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getPagesInCategory(connection, title, nsObject);
}
@Override
public PageListResult getPagesInTemplate(Connection connection, String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getPagesInTemplate(connection, title, nsObject);
}
@Override
public PageListResult getPagesLinkingTo(Connection connection, String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getPagesLinkingTo(connection, title, nsObject);
}
@Override
public BigIntegerResult getPageCount(Connection connection) {
return ScalarisDataHandler.getPageCount(connection);
}
@Override
public BigIntegerResult getArticleCount(Connection connection) {
return ScalarisDataHandler.getArticleCount(connection);
}
@Override
public BigIntegerResult getPagesInCategoryCount(Connection connection, String title, final MyNamespace nsObject) {
return ScalarisDataHandler.getPagesInCategoryCount(connection, title, nsObject);
}
@Override
public BigIntegerResult getStatsPageEdits(Connection connection) {
return ScalarisDataHandler.getStatsPageEdits(connection);
}
@Override
public RandomTitleResult getRandomArticle(Connection connection, Random random) {
return ScalarisDataHandler.getRandomArticle(connection, random);
}
@Override
public SavePageResult savePage(Connection connection, String title,
Revision newRev, int prevRevId, Map<String, String> restrictions,
SiteInfo siteinfo, String username, final MyNamespace nsObject) {
return ScalarisDataHandler.savePage(connection, title, newRev,
prevRevId, restrictions, siteinfo, username, nsObject);
}
}
| true | true | protected synchronized void showImportPage(HttpServletRequest request,
HttpServletResponse response, Connection connection)
throws ServletException, IOException {
WikiPageBean page = new WikiPageBean();
page.setNotAvailable(true);
request.setAttribute("pageBean", page);
StringBuilder content = new StringBuilder();
String dumpsPath = getServletContext().getRealPath("/WEB-INF/dumps");
if (currentImport.isEmpty() && importHandler == null) {
TreeSet<String> availableDumps = new TreeSet<String>();
File dumpsDir = new File(dumpsPath);
if (dumpsDir.isDirectory()) {
availableDumps.addAll(Arrays.asList(dumpsDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return MATCH_WIKI_IMPORT_FILE.matcher(name).matches();
}
})));
}
// get parameters:
String req_import = request.getParameter("import");
if (req_import == null || !availableDumps.contains(req_import)) {
content.append("<h2>Please select a wiki dump to import</h2>\n");
content.append("<form method=\"get\" action=\"wiki\">\n");
content.append("<p>\n");
content.append(" <select name=\"import\" size=\"10\" style=\"width:500px;\">\n");
for (String dump: availableDumps) {
content.append(" <option>" + dump + "</option>\n");
}
content.append(" </select>\n");
content.append(" </p>\n");
content.append(" <p>Maximum number of revisions per page: <input name=\"max_revisions\" size=\"2\" value=\"2\" /></br><span style=\"font-size:80%\">(<tt>-1</tt> to import everything)</span></p>\n");
content.append(" <p>No entra newer than: <input name=\"max_time\" size=\"20\" value=\"\" /></br><span style=\"font-size:80%\">(ISO8601 format, e.g. <tt>2004-01-07T08:09:29Z</tt> - leave empty to import everything)</span></p>\n");
content.append(" <input type=\"submit\" value=\"Import\" />\n");
content.append("</form>\n");
content.append("<p>Note: You will be re-directed to the main page when the import finishes.</p>");
} else {
content.append("<h2>Importing \"" + req_import + "\"...</h2>\n");
try {
currentImport = req_import;
int maxRevisions = parseInt(request.getParameter("max_revisions"), 2);
Calendar maxTime = parseDate(request.getParameter("max_time"), null);
importLog = new CircularByteArrayOutputStream(1024 * 1024);
PrintStream ps = new PrintStream(importLog);
ps.println("starting import...");
String fileName = dumpsPath + File.separator + req_import;
if (fileName.endsWith(".db")) {
importHandler = new WikiDumpPreparedSQLiteToScalaris(fileName, cPool.getConnectionFactory());
} else {
importHandler = new WikiDumpToScalarisHandler(
de.zib.scalaris.examples.wikipedia.data.xml.Main.blacklist,
null, maxRevisions, null, maxTime, cPool.getConnectionFactory());
}
importHandler.setMsgOut(ps);
this.new ImportThread(importHandler, fileName, ps).start();
response.setHeader("Refresh", "2; url = wiki?import=" + currentImport);
content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n");
content.append("<pre>");
content.append("starting import...\n");
content.append("</pre>");
content.append("<p><a href=\"wiki?import=" + currentImport + "\">refresh</a></p>");
content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>");
} catch (Exception e) {
setParam_error(request, "ERROR: import failed");
addToParam_notice(request, "error: <pre>" + e.getMessage() + "</pre>");
currentImport = "";
}
}
} else {
content.append("<h2>Importing \"" + currentImport + "\"...</h2>\n");
String req_stop_import = request.getParameter("stop_import");
boolean stopImport;
if (req_stop_import == null || req_stop_import.isEmpty()) {
stopImport = false;
response.setHeader("Refresh", IMPORT_REDIRECT_EVERY + "; url = wiki?import=" + currentImport);
content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n");
} else {
stopImport = true;
importHandler.stopParsing();
content.append("<p>Current log file:</p>\n");
}
content.append("<pre>");
String log = importLog.toString();
int start = log.indexOf("\n");
if (start != -1) {
content.append(log.substring(start));
}
content.append("</pre>");
if (!stopImport) {
content.append("<p><a href=\"wiki?import=" + currentImport + "\">refresh</a></p>");
content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>");
} else {
content.append("<p>Import has been stopped by the user. Return to <a href=\"wiki?title=" + MAIN_PAGE + "\">" + MAIN_PAGE + "</a>.</p>");
}
}
page.setNotice(WikiServlet.getParam_notice(request));
page.setError(getParam_error(request));
page.setTitle("Import Wiki dump");
page.setPage(content.toString());
RequestDispatcher dispatcher = request.getRequestDispatcher("page.jsp");
dispatcher.forward(request, response);
}
| protected synchronized void showImportPage(HttpServletRequest request,
HttpServletResponse response, Connection connection)
throws ServletException, IOException {
WikiPageBean page = new WikiPageBean();
page.setNotAvailable(true);
request.setAttribute("pageBean", page);
StringBuilder content = new StringBuilder();
String dumpsPath = getServletContext().getRealPath("/WEB-INF/dumps");
if (currentImport.isEmpty() && importHandler == null) {
TreeSet<String> availableDumps = new TreeSet<String>();
File dumpsDir = new File(dumpsPath);
if (dumpsDir.isDirectory()) {
availableDumps.addAll(Arrays.asList(dumpsDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return MATCH_WIKI_IMPORT_FILE.matcher(name).matches();
}
})));
}
// get parameters:
String req_import = request.getParameter("import");
if (req_import == null || !availableDumps.contains(req_import)) {
content.append("<h2>Please select a wiki dump to import</h2>\n");
content.append("<form method=\"get\" action=\"wiki\">\n");
content.append("<p>\n");
content.append(" <select name=\"import\" size=\"10\" style=\"width:500px;\">\n");
for (String dump: availableDumps) {
content.append(" <option>" + dump + "</option>\n");
}
content.append(" </select>\n");
content.append(" </p>\n");
content.append(" <p>Maximum number of revisions per page: <input name=\"max_revisions\" size=\"2\" value=\"2\" /></br><span style=\"font-size:80%\">(<tt>-1</tt> to import everything)</span></p>\n");
content.append(" <p>No entry newer than: <input name=\"max_time\" size=\"20\" value=\"\" /></br><span style=\"font-size:80%\">(ISO8601 format, e.g. <tt>2004-01-07T08:09:29Z</tt> - leave empty to import everything)</span></p>\n");
content.append(" <input type=\"submit\" value=\"Import\" />\n");
content.append("</form>\n");
content.append("<p>Note: You will be re-directed to the main page when the import finishes.</p>");
} else {
content.append("<h2>Importing \"" + req_import + "\"...</h2>\n");
try {
currentImport = req_import;
int maxRevisions = parseInt(request.getParameter("max_revisions"), 2);
Calendar maxTime = parseDate(request.getParameter("max_time"), null);
importLog = new CircularByteArrayOutputStream(1024 * 1024);
PrintStream ps = new PrintStream(importLog);
ps.println("starting import...");
String fileName = dumpsPath + File.separator + req_import;
if (fileName.endsWith(".db")) {
importHandler = new WikiDumpPreparedSQLiteToScalaris(fileName, cPool.getConnectionFactory());
} else {
importHandler = new WikiDumpToScalarisHandler(
de.zib.scalaris.examples.wikipedia.data.xml.Main.blacklist,
null, maxRevisions, null, maxTime, cPool.getConnectionFactory());
}
importHandler.setMsgOut(ps);
this.new ImportThread(importHandler, fileName, ps).start();
response.setHeader("Refresh", "2; url = wiki?import=" + currentImport);
content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n");
content.append("<pre>");
content.append("starting import...\n");
content.append("</pre>");
content.append("<p><a href=\"wiki?import=" + currentImport + "\">refresh</a></p>");
content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>");
} catch (Exception e) {
setParam_error(request, "ERROR: import failed");
addToParam_notice(request, "error: <pre>" + e.getMessage() + "</pre>");
currentImport = "";
}
}
} else {
content.append("<h2>Importing \"" + currentImport + "\"...</h2>\n");
String req_stop_import = request.getParameter("stop_import");
boolean stopImport;
if (req_stop_import == null || req_stop_import.isEmpty()) {
stopImport = false;
response.setHeader("Refresh", IMPORT_REDIRECT_EVERY + "; url = wiki?import=" + currentImport);
content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n");
} else {
stopImport = true;
importHandler.stopParsing();
content.append("<p>Current log file:</p>\n");
}
content.append("<pre>");
String log = importLog.toString();
int start = log.indexOf("\n");
if (start != -1) {
content.append(log.substring(start));
}
content.append("</pre>");
if (!stopImport) {
content.append("<p><a href=\"wiki?import=" + currentImport + "\">refresh</a></p>");
content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>");
} else {
content.append("<p>Import has been stopped by the user. Return to <a href=\"wiki?title=" + MAIN_PAGE + "\">" + MAIN_PAGE + "</a>.</p>");
}
}
page.setNotice(WikiServlet.getParam_notice(request));
page.setError(getParam_error(request));
page.setTitle("Import Wiki dump");
page.setPage(content.toString());
RequestDispatcher dispatcher = request.getRequestDispatcher("page.jsp");
dispatcher.forward(request, response);
}
|
diff --git a/opal-shell/src/main/java/org/obiba/opal/shell/CommandJob.java b/opal-shell/src/main/java/org/obiba/opal/shell/CommandJob.java
index 1143ca033..afb1c19a2 100644
--- a/opal-shell/src/main/java/org/obiba/opal/shell/CommandJob.java
+++ b/opal-shell/src/main/java/org/obiba/opal/shell/CommandJob.java
@@ -1,202 +1,201 @@
/*******************************************************************************
* Copyright 2008(c) The OBiBa Consortium. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.obiba.opal.shell;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.obiba.opal.shell.commands.Command;
import org.obiba.opal.web.model.Commands.Message;
import org.obiba.opal.web.model.Commands.CommandStateDto.Status;
/**
* Contains a command and the state of its execution.
*/
public class CommandJob implements OpalShell, Runnable {
//
// Constants
//
private static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH'h'mm";
//
// Instance Variables
//
private final Command<?> command;
private final List<Message> messages;
private Integer id;
private String owner;
private Status status;
private long submitTime;
private Long startTime;
private Long endTime;
//
// CommandJob
//
public CommandJob(Command<?> command) {
if(command == null) throw new IllegalArgumentException("command cannot be null");
this.command = command;
this.command.setShell(this);
this.messages = new ArrayList<Message>();
this.status = Status.NOT_STARTED;
}
//
// OpalShell Methods
//
public void printf(String format, Object... args) {
if(format == null) throw new IllegalArgumentException("format cannot be null");
messages.add(0, createMessage(String.format(format, args)));
}
public void printUsage() {
// nothing to do
}
public char[] passwordPrompt(String format, Object... args) {
// nothing to do -- return null
return null;
}
public String prompt(String format, Object... args) {
// nothing to do -- return null
return null;
}
public void exit() {
// nothing to do
}
public void addExitCallback(OpalShellExitCallback callback) {
// nothing to do
}
//
// Runnable Methods
//
public void run() {
try {
int errorCode = 0;
// Don't execute the command if the job has been cancelled.
if(!status.equals(Status.CANCEL_PENDING)) {
status = Status.IN_PROGRESS;
startTime = getCurrentTime();
errorCode = command.execute();
}
// Update the status. Set to SUCCEEDED/FAILED, based on the error code, unless the status was changed to
- // CANCEL_PENDING (i.e., job was
- // interrupted); in that case set it to CANCELED.
+ // CANCEL_PENDING (i.e., job was interrupted); in that case set it to CANCELED.
if(status.equals(Status.IN_PROGRESS)) {
status = (errorCode == 0) ? Status.SUCCEEDED : Status.FAILED;
} else if(status.equals(Status.CANCEL_PENDING)) {
status = Status.CANCELED;
} else {
// Should never get here!
throw new IllegalStateException("Unexpected CommandJob status: " + status);
}
} catch(RuntimeException ex) {
status = Status.FAILED;
ex.printStackTrace();
} finally {
endTime = getCurrentTime();
}
}
//
// Methods
//
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Command<?> getCommand() {
return command;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Date getSubmitTime() {
return new Date(submitTime);
}
public void setSubmitTime(Date submitTime) {
this.submitTime = submitTime.getTime();
}
public Date getStartTime() {
return startTime != null ? new Date(startTime) : null;
}
public String getStartTimeAsString() {
return formatTime(getStartTime());
}
public Date getEndTime() {
return endTime != null ? new Date(endTime) : null;
}
public String getEndTimeAsString() {
return formatTime(getEndTime());
}
public List<Message> getMessages() {
return Collections.unmodifiableList(messages);
}
protected long getCurrentTime() {
return System.currentTimeMillis();
}
protected Message createMessage(String msg) {
return Message.newBuilder().setMsg(msg).setTimestamp(System.currentTimeMillis()).build();
}
protected String formatTime(Date date) {
if(date == null) return null;
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_PATTERN);
return dateFormat.format(date);
}
}
| true | true | public void run() {
try {
int errorCode = 0;
// Don't execute the command if the job has been cancelled.
if(!status.equals(Status.CANCEL_PENDING)) {
status = Status.IN_PROGRESS;
startTime = getCurrentTime();
errorCode = command.execute();
}
// Update the status. Set to SUCCEEDED/FAILED, based on the error code, unless the status was changed to
// CANCEL_PENDING (i.e., job was
// interrupted); in that case set it to CANCELED.
if(status.equals(Status.IN_PROGRESS)) {
status = (errorCode == 0) ? Status.SUCCEEDED : Status.FAILED;
} else if(status.equals(Status.CANCEL_PENDING)) {
status = Status.CANCELED;
} else {
// Should never get here!
throw new IllegalStateException("Unexpected CommandJob status: " + status);
}
} catch(RuntimeException ex) {
status = Status.FAILED;
ex.printStackTrace();
} finally {
endTime = getCurrentTime();
}
}
| public void run() {
try {
int errorCode = 0;
// Don't execute the command if the job has been cancelled.
if(!status.equals(Status.CANCEL_PENDING)) {
status = Status.IN_PROGRESS;
startTime = getCurrentTime();
errorCode = command.execute();
}
// Update the status. Set to SUCCEEDED/FAILED, based on the error code, unless the status was changed to
// CANCEL_PENDING (i.e., job was interrupted); in that case set it to CANCELED.
if(status.equals(Status.IN_PROGRESS)) {
status = (errorCode == 0) ? Status.SUCCEEDED : Status.FAILED;
} else if(status.equals(Status.CANCEL_PENDING)) {
status = Status.CANCELED;
} else {
// Should never get here!
throw new IllegalStateException("Unexpected CommandJob status: " + status);
}
} catch(RuntimeException ex) {
status = Status.FAILED;
ex.printStackTrace();
} finally {
endTime = getCurrentTime();
}
}
|
diff --git a/compiler/src/main/java/org/robovm/compiler/TrampolineCompiler.java b/compiler/src/main/java/org/robovm/compiler/TrampolineCompiler.java
index f6bf9d34c..1eae764bf 100644
--- a/compiler/src/main/java/org/robovm/compiler/TrampolineCompiler.java
+++ b/compiler/src/main/java/org/robovm/compiler/TrampolineCompiler.java
@@ -1,695 +1,698 @@
/*
* Copyright (C) 2012 RoboVM
*
* 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, see <http://www.gnu.org/licenses/gpl-2.0.html>.
*/
package org.robovm.compiler;
import static org.robovm.compiler.Access.*;
import static org.robovm.compiler.Functions.*;
import static org.robovm.compiler.Mangler.*;
import static org.robovm.compiler.Types.*;
import static org.robovm.compiler.llvm.FunctionAttribute.*;
import static org.robovm.compiler.llvm.Linkage.*;
import static org.robovm.compiler.llvm.Type.*;
import java.util.Collections;
import org.robovm.compiler.clazz.Clazz;
import org.robovm.compiler.llvm.Bitcast;
import org.robovm.compiler.llvm.Br;
import org.robovm.compiler.llvm.FloatingPointConstant;
import org.robovm.compiler.llvm.FloatingPointType;
import org.robovm.compiler.llvm.Function;
import org.robovm.compiler.llvm.FunctionAttribute;
import org.robovm.compiler.llvm.FunctionDeclaration;
import org.robovm.compiler.llvm.FunctionRef;
import org.robovm.compiler.llvm.FunctionType;
import org.robovm.compiler.llvm.Global;
import org.robovm.compiler.llvm.GlobalRef;
import org.robovm.compiler.llvm.Icmp;
import org.robovm.compiler.llvm.Icmp.Condition;
import org.robovm.compiler.llvm.IntegerConstant;
import org.robovm.compiler.llvm.IntegerType;
import org.robovm.compiler.llvm.Label;
import org.robovm.compiler.llvm.Load;
import org.robovm.compiler.llvm.NullConstant;
import org.robovm.compiler.llvm.PointerType;
import org.robovm.compiler.llvm.Ret;
import org.robovm.compiler.llvm.Unreachable;
import org.robovm.compiler.llvm.Value;
import org.robovm.compiler.llvm.Variable;
import org.robovm.compiler.trampoline.Anewarray;
import org.robovm.compiler.trampoline.Checkcast;
import org.robovm.compiler.trampoline.ExceptionMatch;
import org.robovm.compiler.trampoline.FieldAccessor;
import org.robovm.compiler.trampoline.GetField;
import org.robovm.compiler.trampoline.Instanceof;
import org.robovm.compiler.trampoline.Invoke;
import org.robovm.compiler.trampoline.Invokeinterface;
import org.robovm.compiler.trampoline.Invokespecial;
import org.robovm.compiler.trampoline.Invokevirtual;
import org.robovm.compiler.trampoline.LdcClass;
import org.robovm.compiler.trampoline.LdcString;
import org.robovm.compiler.trampoline.Multianewarray;
import org.robovm.compiler.trampoline.NativeCall;
import org.robovm.compiler.trampoline.New;
import org.robovm.compiler.trampoline.PutField;
import org.robovm.compiler.trampoline.Trampoline;
import soot.ClassMember;
import soot.IntType;
import soot.Modifier;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
/**
* @author niklas
*
*/
public class TrampolineCompiler {
public static final String ATTEMPT_TO_WRITE_TO_FINAL_FIELD = "Attempt to write to final field %s.%s from class %s";
public static final String EXPECTED_INTERFACE_BUT_FOUND_CLASS = "Expected interface but found class %s";
public static final String EXPECTED_NON_STATIC_METHOD = "Expected non-static method %s.%s%s";
public static final String EXPECTED_STATIC_METHOD = "Expected static method %s.%s%s";
public static final String EXPECTED_CLASS_BUT_FOUND_INTERFACE = "Expected class but found interface %s";
public static final String EXPECTED_NON_STATIC_FIELD = "Expected non-static field %s.%s";
public static final String EXPECTED_STATIC_FIELD = "Expected static field %s.%s";
public static final String NO_SUCH_FIELD_ERROR = "%s.%s";
public static final String NO_SUCH_METHOD_ERROR = "%s.%s%s";
private final Config config;
private ModuleBuilder mb;
public TrampolineCompiler(Config config) {
this.config = config;
}
public void compile(ModuleBuilder mb, Trampoline t) {
this.mb = mb;
if (t instanceof LdcString) {
Function f = new Function(weak, t.getFunctionRef());
mb.addFunction(f);
Value result = call(f, BC_LDC_STRING, f.getParameterRef(0),
mb.getString(t.getTarget()));
f.add(new Ret(result));
return;
}
/*
* Check if the target class exists and is accessible. Also check that
* field accesses and method calls are compatible with the target
* field/method and that the field/method is accessible to the caller.
* If any of the tests fail the weak trampoline function created by the
* ClassCompiler will be overridden with a function which throws an
* appropriate exception.
*/
Function f = new Function(external, t.getFunctionRef());
if (!checkClassExists(f, t) || !checkClassAccessible(f, t)) {
mb.addFunction(f);
return;
}
if (t instanceof New) {
SootClass target = config.getClazzes().load(t.getTarget()).getSootClass();
if (target.isAbstract() || target.isInterface()) {
call(f, BC_THROW_INSTANTIATION_ERROR, f.getParameterRef(0), mb.getString(t.getTarget()));
f.add(new Unreachable());
mb.addFunction(f);
return;
}
String fnName = mangleClass(t.getTarget()) + "_allocator_clinit";
alias(t, fnName);
} else if (t instanceof ExceptionMatch) {
String fnName = mangleClass(t.getTarget()) + "_exmatch";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
FunctionRef exInfoFn = getInfoStructFn(t.getTarget());
Value exInfo = call(fn, exInfoFn);
if (!mb.hasSymbol(exInfoFn.getName())) {
mb.addFunctionDeclaration(new FunctionDeclaration(exInfoFn));
}
Value result = call(fn, BC_EXCEPTION_MATCH, f.getParameterRef(0), exInfo);
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else if (t instanceof Instanceof) {
if (isArray(t.getTarget())) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_instanceof";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_INSTANCEOF_ARRAY, fn.getParameterRef(0), arrayClass, fn.getParameterRef(1));
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else {
String fnName = mangleClass(t.getTarget()) + "_instanceof";
alias(t, fnName);
}
} else if (t instanceof Checkcast) {
if (isArray(t.getTarget())) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_checkcast";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_CHECKCAST_ARRAY, fn.getParameterRef(0), arrayClass, fn.getParameterRef(1));
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else {
String fnName = mangleClass(t.getTarget()) + "_checkcast";
alias(t, fnName);
}
} else if (t instanceof LdcClass) {
if (isArray(t.getTarget())) {
FunctionRef fn = createLdcArray(t.getTarget());
alias(t, fn.getName());
} else {
String fnName = mangleClass(t.getTarget()) + "_ldc_load";
alias(t, fnName);
}
} else if (t instanceof Anewarray) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_new";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_NEW_OBJECT_ARRAY, fn.getParameterRef(0),
fn.getParameterRef(1), arrayClass);
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else if (t instanceof Multianewarray) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_multi";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_NEW_MULTI_ARRAY, fn.getParameterRef(0),
fn.getParameterRef(1), fn.getParameterRef(2), arrayClass);
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else if (t instanceof NativeCall) {
Clazz target = config.getClazzes().load(t.getTarget());
NativeCall nc = (NativeCall) t;
String shortName = mangleNativeMethod(target.getInternalName(), nc.getMethodName());
String longName = mangleNativeMethod(target.getInternalName(), nc.getMethodName(), nc.getMethodDesc());
if (target.isInBootClasspath()) {
Function fnLong = new Function(weak, longName, nc.getFunctionType());
+ // The NativeCall caller pushed a GatewayFrame and will only pop it
+ // if the native method exists. So we need to pop it here.
+ popNativeFrame(fnLong);
call(fnLong, BC_THROW_UNSATISIFED_LINK_ERROR, fnLong.getParameterRef(0));
fnLong.add(new Unreachable());
mb.addFunction(fnLong);
// mb.addFunctionDeclaration(new FunctionDeclaration(fnLong.ref()));
FunctionRef targetFn = fnLong.ref();
if (!isLongNativeFunctionNameRequired(nc)) {
Function fnShort = new Function(weak, shortName, nc.getFunctionType());
Value resultInner = call(fnShort, fnLong.ref(), fnShort.getParameterRefs());
fnShort.add(new Ret(resultInner));
mb.addFunction(fnShort);
// mb.addFunctionDeclaration(new FunctionDeclaration(fnShort.ref()));
targetFn = fnShort.ref();
}
Function fn = new Function(external, nc.getFunctionRef());
Value result = call(fn, targetFn, fn.getParameterRefs());
fn.add(new Ret(result));
mb.addFunction(fn);
} else {
Global g = new Global("native_" + mangleMethod(nc.getTarget(),
nc.getMethodName(), nc.getMethodDesc()) + "_ptr",
new NullConstant(I8_PTR));
mb.addGlobal(g);
Function fn = new Function(external, nc.getFunctionRef());
FunctionRef ldcFn = new FunctionRef(mangleClass(nc.getTarget()) + "_ldc",
new FunctionType(OBJECT_PTR, ENV_PTR));
Value theClass = call(fn, ldcFn, fn.getParameterRef(0));
Value implI8Ptr = call(fn, BC_RESOLVE_NATIVE, fn.getParameterRef(0),
theClass,
mb.getString(nc.getMethodName()),
mb.getString(nc.getMethodDesc()),
mb.getString(mangleNativeMethod(nc.getTarget(), nc.getMethodName())),
mb.getString(mangleNativeMethod(nc.getTarget(), nc.getMethodName(), nc.getMethodDesc())),
g.ref());
Variable nullTest = fn.newVariable(I1);
fn.add(new Icmp(nullTest, Condition.ne, implI8Ptr, new NullConstant(I8_PTR)));
Label trueLabel = new Label();
Label falseLabel = new Label();
fn.add(new Br(nullTest.ref(), fn.newBasicBlockRef(trueLabel), fn.newBasicBlockRef(falseLabel)));
fn.newBasicBlock(falseLabel);
if (fn.getType().getReturnType() instanceof IntegerType) {
fn.add(new Ret(new IntegerConstant(0, (IntegerType) fn.getType().getReturnType())));
} else if (fn.getType().getReturnType() instanceof FloatingPointType) {
fn.add(new Ret(new FloatingPointConstant(0.0, (FloatingPointType) fn.getType().getReturnType())));
} else if (fn.getType().getReturnType() instanceof PointerType) {
fn.add(new Ret(new NullConstant((PointerType) fn.getType().getReturnType())));
} else {
fn.add(new Ret());
}
fn.newBasicBlock(trueLabel);
Variable impl = fn.newVariable(nc.getFunctionType());
fn.add(new Bitcast(impl, implI8Ptr, impl.getType()));
Value result = call(fn, impl.ref(), fn.getParameterRefs());
fn.add(new Ret(result));
mb.addFunction(fn);
}
} else if (t instanceof FieldAccessor) {
SootField field = resolveField(f, (FieldAccessor) t);
if (field == null || !checkMemberAccessible(f, t, field)) {
mb.addFunction(f);
return;
}
Clazz caller = config.getClazzes().load(t.getCallingClass());
Clazz target = config.getClazzes().load(t.getTarget());
if (!((FieldAccessor) t).isGetter() && field.isFinal() && caller != target) {
// Only the class declaring a final field may write to it.
// (Actually only <init>/<clinit> methods may write to it but we
// don't know which method is accessing the field at this point)
throwIllegalAccessError(f, ATTEMPT_TO_WRITE_TO_FINAL_FIELD,
target, field.getName(), caller);
mb.addFunction(f);
return;
}
createTrampolineAliasForField((FieldAccessor) t, field);
} else if (t instanceof Invokeinterface) {
SootMethod rm = resolveInterfaceMethod(f, (Invokeinterface) t);
if (rm == null || !checkMemberAccessible(f, t, rm)) {
mb.addFunction(f);
return;
}
createTrampolineAliasForMethod((Invoke) t, rm);
} else if (t instanceof Invoke) {
SootMethod method = resolveMethod(f, (Invoke) t);
if (method == null || !checkMemberAccessible(f, t, method)) {
mb.addFunction(f);
return;
}
if (t instanceof Invokespecial && method.isAbstract()) {
call(f, BC_THROW_ABSTRACT_METHOD_ERROR, f.getParameterRef(0),
mb.getString(String.format(NO_SUCH_METHOD_ERROR,
method.getDeclaringClass(), method.getName(),
getDescriptor(method))));
f.add(new Unreachable());
mb.addFunction(f);
return;
}
createTrampolineAliasForMethod((Invoke) t, method);
}
}
private void alias(Trampoline t, String fnName) {
FunctionRef aliasee = new FunctionRef(fnName, t.getFunctionType());
if (!mb.hasSymbol(fnName)) {
mb.addFunctionDeclaration(new FunctionDeclaration(aliasee));
}
Function fn = new Function(_private, new FunctionAttribute[] {alwaysinline, optsize},
t.getFunctionName(), t.getFunctionType());
Value result = call(fn, aliasee, fn.getParameterRefs());
fn.add(new Ret(result));
mb.addFunction(fn);
}
private void createTrampolineAliasForField(FieldAccessor t, SootField field) {
String fnName = mangleField(field);
fnName += t.isGetter() ? "_getter" : "_setter";
if (t.isStatic()) {
fnName += "_clinit";
}
alias(t, fnName);
}
private void createTrampolineAliasForMethod(Invoke t, SootMethod rm) {
String fnName = mangleMethod(rm);
if (t instanceof Invokeinterface) {
fnName += "_lookup";
} else if (t instanceof Invokevirtual
&& !Modifier.isFinal(rm.getDeclaringClass().getModifiers())
&& !Modifier.isFinal(rm.getModifiers())) {
fnName += "_lookup";
} else if (rm.isSynchronized()) {
fnName += "_synchronized";
}
if (t.isStatic()) {
fnName += "_clinit";
}
alias(t, fnName);
}
private boolean isLongNativeFunctionNameRequired(NativeCall nc) {
if (nc.getMethodDesc().startsWith("()")) {
// If the method takes no parameters the long and short names are the same
return true;
}
Clazz target = config.getClazzes().load(nc.getTarget());
int nativeCount = 0;
for (SootMethod m : target.getSootClass().getMethods()) {
if (m.isNative() && m.getName().equals(nc.getMethodName())) {
nativeCount++;
}
}
return nativeCount > 1;
}
private Value callLdcArray(Function function, String targetClass) {
FunctionRef fnRef = createLdcArray(targetClass);
return call(function, fnRef, function.getParameterRef(0));
}
private FunctionRef createLdcArray(String targetClass) {
String fnName = "array_" + mangleClass(targetClass) + "_ldc";
FunctionRef fnRef = new FunctionRef(fnName, new FunctionType(OBJECT_PTR, ENV_PTR));
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, fnRef, fnName);
Value arrayClass = null;
if (isPrimitiveComponentType(targetClass)) {
String primitiveDesc = targetClass.substring(1);
Variable result = fn.newVariable(OBJECT_PTR);
fn.add(new Load(result, new GlobalRef("array_" + primitiveDesc, OBJECT_PTR)));
arrayClass = result.ref();
} else {
Global g = new Global("array_" + mangleClass(targetClass) + "_ptr", weak, new NullConstant(OBJECT_PTR));
if (!mb.hasSymbol(g.getName())) {
mb.addGlobal(g);
}
FunctionRef ldcArrayClassFn = BC_LDC_ARRAY_BOOT_CLASS;
if (!isPrimitiveBaseType(targetClass)) {
Clazz baseType = config.getClazzes().load(getBaseType(targetClass));
if (!baseType.isInBootClasspath()) {
ldcArrayClassFn = BC_LDC_ARRAY_CLASS;
}
}
arrayClass = call(fn, ldcArrayClassFn, fn.getParameterRef(0), g.ref(), mb.getString(targetClass));
}
fn.add(new Ret(arrayClass));
mb.addFunction(fn);
}
return fnRef;
}
private boolean checkClassExists(Function f, Trampoline t) {
String targetClassName = t.getTarget();
if (isArray(targetClassName)) {
if (isPrimitiveBaseType(targetClassName)) {
return true;
}
targetClassName = getBaseType(targetClassName);
}
Clazz target = config.getClazzes().load(targetClassName);
if (target != null) {
Clazz caller = config.getClazzes().load(t.getCallingClass());
// If caller is in the bootclasspath it only sees classes in the bootclasspath
if (!caller.isInBootClasspath() || target.isInBootClasspath()) {
return true;
}
}
call(f, BC_THROW_NO_CLASS_DEF_FOUND_ERROR, f.getParameterRef(0),
mb.getString(t.getTarget()));
f.add(new Unreachable());
return false;
}
private boolean checkClassAccessible(Function f, Trampoline t) {
Clazz caller = config.getClazzes().load(t.getCallingClass());
String targetClassName = t.getTarget();
if (isArray(targetClassName)) {
if (isPrimitiveBaseType(targetClassName)) {
return true;
}
targetClassName = getBaseType(targetClassName);
}
Clazz target = config.getClazzes().load(targetClassName);
if (Access.checkClassAccessible(target.getSootClass(), caller.getSootClass())) {
return true;
}
throwIllegalAccessError(f, ILLEGAL_ACCESS_ERROR_CLASS,
target, caller);
f.add(new Unreachable());
return false;
}
private boolean checkMemberAccessible(Function f, Trampoline t, ClassMember member) {
SootClass caller = config.getClazzes().load(t.getCallingClass()).getSootClass();
String runtimeClassName = null;
runtimeClassName = t instanceof Invokevirtual
? ((Invokevirtual) t).getRuntimeClass() : runtimeClassName;
runtimeClassName = t instanceof Invokespecial
? ((Invokespecial) t).getRuntimeClass() : runtimeClassName;
runtimeClassName = t instanceof GetField
? ((GetField) t).getRuntimeClass() : runtimeClassName;
runtimeClassName = t instanceof PutField
? ((PutField) t).getRuntimeClass() : runtimeClassName;
SootClass runtimeClass = null;
if (runtimeClassName != null && !isArray(runtimeClassName)) {
runtimeClass = config.getClazzes().load(runtimeClassName).getSootClass();
}
if (Access.checkMemberAccessible(member, caller, runtimeClass)) {
return true;
}
if (member instanceof SootMethod) {
SootMethod method = (SootMethod) member;
throwIllegalAccessError(f, ILLEGAL_ACCESS_ERROR_METHOD,
method.getDeclaringClass(), method.getName(),
getDescriptor(method), caller);
} else {
SootField field = (SootField) member;
throwIllegalAccessError(f, ILLEGAL_ACCESS_ERROR_FIELD,
field.getDeclaringClass(), field.getName(), caller);
}
f.add(new Unreachable());
return false;
}
private void throwNoSuchMethodError(Function f, Invoke invoke) {
call(f, BC_THROW_NO_SUCH_METHOD_ERROR, f.getParameterRef(0),
mb.getString(String.format(NO_SUCH_METHOD_ERROR,
invoke.getTarget().replace('/', '.'),
invoke.getMethodName(), invoke.getMethodDesc())));
f.add(new Unreachable());
}
private void throwNoSuchFieldError(Function f, FieldAccessor accessor) {
call(f, BC_THROW_NO_SUCH_FIELD_ERROR, f.getParameterRef(0),
mb.getString(String.format(NO_SUCH_FIELD_ERROR,
accessor.getTarget().replace('/', '.'),
accessor.getFieldName())));
f.add(new Unreachable());
}
private void throwIncompatibleChangeError(Function f, String message, Object ... args) {
call(f, BC_THROW_INCOMPATIBLE_CLASS_CHANGE_ERROR, f.getParameterRef(0),
mb.getString(String.format(message, args)));
f.add(new Unreachable());
}
private void throwIllegalAccessError(Function f, String message, Object ... args) {
call(f, BC_THROW_ILLEGAL_ACCESS_ERROR, f.getParameterRef(0),
mb.getString(String.format(message, args)));
f.add(new Unreachable());
}
private SootField resolveField(Function f, FieldAccessor t) {
SootClass target = config.getClazzes().load(t.getTarget()).getSootClass();
String name = t.getFieldName();
String desc = t.getFieldDesc();
SootField field = resolveField(target, name, desc);
if (field == null) {
throwNoSuchFieldError(f, t);
return null;
}
if (!field.isStatic() && t.isStatic()) {
throwIncompatibleChangeError(f, EXPECTED_STATIC_FIELD,
field.getDeclaringClass(), t.getFieldName());
return null;
}
if (field.isStatic() && !t.isStatic()) {
throwIncompatibleChangeError(f, EXPECTED_NON_STATIC_FIELD,
field.getDeclaringClass(), t.getFieldName());
return null;
}
return field;
}
private SootField resolveField(SootClass clazz, String name, String desc) {
if (clazz != null && !clazz.isPhantom()) {
SootField field = getField(clazz, name, desc);
if (field != null) {
return field;
}
for (SootClass interfaze : clazz.getInterfaces()) {
field = resolveField(interfaze, name, desc);
if (field != null) {
return field;
}
}
if (!clazz.isInterface() && clazz.hasSuperclass()) {
return resolveField(clazz.getSuperclass(), name, desc);
}
}
return null;
}
private SootMethod resolveMethod(Function f, Invoke t) {
SootClass target = config.getClazzes().load(t.getTarget()).getSootClass();
String name = t.getMethodName();
String desc = t.getMethodDesc();
if (target.isInterface()) {
throwIncompatibleChangeError(f, EXPECTED_CLASS_BUT_FOUND_INTERFACE, target);
return null;
}
if ("<init>".equals(name) && t instanceof Invokespecial) {
SootMethod method = getMethod(target, name, desc);
if (method != null) {
return method;
}
}
if ("<clinit>".equals(name) || "<init>".equals(name)) {
// This is not part of method resolution but we
// need to handle it somehow.
throwNoSuchMethodError(f, t);
return null;
}
SootMethod method = resolveMethod(target, name, desc);
if (method == null) {
throwNoSuchMethodError(f, t);
return null;
}
if (t.isStatic() && !method.isStatic()) {
throwIncompatibleChangeError(f, EXPECTED_STATIC_METHOD,
target, name, desc);
return null;
} else if (!t.isStatic() && method.isStatic()) {
throwIncompatibleChangeError(f, EXPECTED_NON_STATIC_METHOD,
target, name, desc);
return null;
}
return method;
}
private SootMethod resolveMethod(SootClass clazz, String name, String desc) {
if (clazz != null && !clazz.isPhantom()) {
SootMethod method = getMethod(clazz, name, desc);
if (method != null) {
return method;
}
if (name.equals("sizeOf") && isStruct(clazz)) {
method = new SootMethod("sizeOf", Collections.EMPTY_LIST, IntType.v(),
Modifier.PUBLIC | Modifier.STATIC);
method.setDeclaringClass(clazz);
method.setDeclared(true);
return method;
}
SootClass c = !clazz.isInterface() && clazz.hasSuperclass() ? clazz.getSuperclass() : null;
while (c != null) {
method = getMethod(c, name, desc);
if (method != null) {
return method;
}
c = !c.isInterface() && c.hasSuperclass() ? c.getSuperclass() : null;
}
c = clazz;
while (c != null) {
for (SootClass interfaze : c.getInterfaces()) {
method = resolveInterfaceMethod(interfaze, name, desc);
if (method != null) {
return method;
}
}
c = !c.isInterface() && c.hasSuperclass() ? c.getSuperclass() : null;
}
}
return null;
}
private SootMethod resolveInterfaceMethod(Function f, Invokeinterface t) {
SootClass target = config.getClazzes().load(t.getTarget()).getSootClass();
String name = t.getMethodName();
String desc = t.getMethodDesc();
if (!target.isInterface()) {
throwIncompatibleChangeError(f, EXPECTED_INTERFACE_BUT_FOUND_CLASS, target);
return null;
}
if ("<clinit>".equals(name) || "<init>".equals(name)) {
// This is not part of interface method resolution but we
// need to handle it somehow.
throwNoSuchMethodError(f, t);
return null;
}
SootMethod method = resolveInterfaceMethod(target, name, desc);
if (method == null) {
SootClass javaLangObject = config.getClazzes().load("java/lang/Object").getSootClass();
method = getMethod(javaLangObject, name, desc);
}
if (method == null) {
throwNoSuchMethodError(f, t);
return null;
}
if (method.isStatic()) {
throwIncompatibleChangeError(f, EXPECTED_NON_STATIC_METHOD,
target, name, desc);
return null;
}
return method;
}
private SootMethod resolveInterfaceMethod(SootClass clazz, String name, String desc) {
if (clazz != null && !clazz.isPhantom()) {
SootMethod method = getMethod(clazz, name, desc);
if (method != null) {
return method;
}
for (SootClass interfaze : clazz.getInterfaces()) {
method = resolveInterfaceMethod(interfaze, name, desc);
if (method != null) {
return method;
}
}
}
return null;
}
private SootField getField(SootClass clazz, String name, String desc) {
for (SootField f : clazz.getFields()) {
if (name.equals(f.getName()) && desc.equals(getDescriptor(f))) {
return f;
}
}
return null;
}
private SootMethod getMethod(SootClass clazz, String name, String desc) {
for (SootMethod m : clazz.getMethods()) {
if (name.equals(m.getName()) && desc.equals(getDescriptor(m))) {
return m;
}
}
return null;
}
}
| true | true | public void compile(ModuleBuilder mb, Trampoline t) {
this.mb = mb;
if (t instanceof LdcString) {
Function f = new Function(weak, t.getFunctionRef());
mb.addFunction(f);
Value result = call(f, BC_LDC_STRING, f.getParameterRef(0),
mb.getString(t.getTarget()));
f.add(new Ret(result));
return;
}
/*
* Check if the target class exists and is accessible. Also check that
* field accesses and method calls are compatible with the target
* field/method and that the field/method is accessible to the caller.
* If any of the tests fail the weak trampoline function created by the
* ClassCompiler will be overridden with a function which throws an
* appropriate exception.
*/
Function f = new Function(external, t.getFunctionRef());
if (!checkClassExists(f, t) || !checkClassAccessible(f, t)) {
mb.addFunction(f);
return;
}
if (t instanceof New) {
SootClass target = config.getClazzes().load(t.getTarget()).getSootClass();
if (target.isAbstract() || target.isInterface()) {
call(f, BC_THROW_INSTANTIATION_ERROR, f.getParameterRef(0), mb.getString(t.getTarget()));
f.add(new Unreachable());
mb.addFunction(f);
return;
}
String fnName = mangleClass(t.getTarget()) + "_allocator_clinit";
alias(t, fnName);
} else if (t instanceof ExceptionMatch) {
String fnName = mangleClass(t.getTarget()) + "_exmatch";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
FunctionRef exInfoFn = getInfoStructFn(t.getTarget());
Value exInfo = call(fn, exInfoFn);
if (!mb.hasSymbol(exInfoFn.getName())) {
mb.addFunctionDeclaration(new FunctionDeclaration(exInfoFn));
}
Value result = call(fn, BC_EXCEPTION_MATCH, f.getParameterRef(0), exInfo);
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else if (t instanceof Instanceof) {
if (isArray(t.getTarget())) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_instanceof";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_INSTANCEOF_ARRAY, fn.getParameterRef(0), arrayClass, fn.getParameterRef(1));
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else {
String fnName = mangleClass(t.getTarget()) + "_instanceof";
alias(t, fnName);
}
} else if (t instanceof Checkcast) {
if (isArray(t.getTarget())) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_checkcast";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_CHECKCAST_ARRAY, fn.getParameterRef(0), arrayClass, fn.getParameterRef(1));
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else {
String fnName = mangleClass(t.getTarget()) + "_checkcast";
alias(t, fnName);
}
} else if (t instanceof LdcClass) {
if (isArray(t.getTarget())) {
FunctionRef fn = createLdcArray(t.getTarget());
alias(t, fn.getName());
} else {
String fnName = mangleClass(t.getTarget()) + "_ldc_load";
alias(t, fnName);
}
} else if (t instanceof Anewarray) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_new";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_NEW_OBJECT_ARRAY, fn.getParameterRef(0),
fn.getParameterRef(1), arrayClass);
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else if (t instanceof Multianewarray) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_multi";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_NEW_MULTI_ARRAY, fn.getParameterRef(0),
fn.getParameterRef(1), fn.getParameterRef(2), arrayClass);
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else if (t instanceof NativeCall) {
Clazz target = config.getClazzes().load(t.getTarget());
NativeCall nc = (NativeCall) t;
String shortName = mangleNativeMethod(target.getInternalName(), nc.getMethodName());
String longName = mangleNativeMethod(target.getInternalName(), nc.getMethodName(), nc.getMethodDesc());
if (target.isInBootClasspath()) {
Function fnLong = new Function(weak, longName, nc.getFunctionType());
call(fnLong, BC_THROW_UNSATISIFED_LINK_ERROR, fnLong.getParameterRef(0));
fnLong.add(new Unreachable());
mb.addFunction(fnLong);
// mb.addFunctionDeclaration(new FunctionDeclaration(fnLong.ref()));
FunctionRef targetFn = fnLong.ref();
if (!isLongNativeFunctionNameRequired(nc)) {
Function fnShort = new Function(weak, shortName, nc.getFunctionType());
Value resultInner = call(fnShort, fnLong.ref(), fnShort.getParameterRefs());
fnShort.add(new Ret(resultInner));
mb.addFunction(fnShort);
// mb.addFunctionDeclaration(new FunctionDeclaration(fnShort.ref()));
targetFn = fnShort.ref();
}
Function fn = new Function(external, nc.getFunctionRef());
Value result = call(fn, targetFn, fn.getParameterRefs());
fn.add(new Ret(result));
mb.addFunction(fn);
} else {
Global g = new Global("native_" + mangleMethod(nc.getTarget(),
nc.getMethodName(), nc.getMethodDesc()) + "_ptr",
new NullConstant(I8_PTR));
mb.addGlobal(g);
Function fn = new Function(external, nc.getFunctionRef());
FunctionRef ldcFn = new FunctionRef(mangleClass(nc.getTarget()) + "_ldc",
new FunctionType(OBJECT_PTR, ENV_PTR));
Value theClass = call(fn, ldcFn, fn.getParameterRef(0));
Value implI8Ptr = call(fn, BC_RESOLVE_NATIVE, fn.getParameterRef(0),
theClass,
mb.getString(nc.getMethodName()),
mb.getString(nc.getMethodDesc()),
mb.getString(mangleNativeMethod(nc.getTarget(), nc.getMethodName())),
mb.getString(mangleNativeMethod(nc.getTarget(), nc.getMethodName(), nc.getMethodDesc())),
g.ref());
Variable nullTest = fn.newVariable(I1);
fn.add(new Icmp(nullTest, Condition.ne, implI8Ptr, new NullConstant(I8_PTR)));
Label trueLabel = new Label();
Label falseLabel = new Label();
fn.add(new Br(nullTest.ref(), fn.newBasicBlockRef(trueLabel), fn.newBasicBlockRef(falseLabel)));
fn.newBasicBlock(falseLabel);
if (fn.getType().getReturnType() instanceof IntegerType) {
fn.add(new Ret(new IntegerConstant(0, (IntegerType) fn.getType().getReturnType())));
} else if (fn.getType().getReturnType() instanceof FloatingPointType) {
fn.add(new Ret(new FloatingPointConstant(0.0, (FloatingPointType) fn.getType().getReturnType())));
} else if (fn.getType().getReturnType() instanceof PointerType) {
fn.add(new Ret(new NullConstant((PointerType) fn.getType().getReturnType())));
} else {
fn.add(new Ret());
}
fn.newBasicBlock(trueLabel);
Variable impl = fn.newVariable(nc.getFunctionType());
fn.add(new Bitcast(impl, implI8Ptr, impl.getType()));
Value result = call(fn, impl.ref(), fn.getParameterRefs());
fn.add(new Ret(result));
mb.addFunction(fn);
}
} else if (t instanceof FieldAccessor) {
SootField field = resolveField(f, (FieldAccessor) t);
if (field == null || !checkMemberAccessible(f, t, field)) {
mb.addFunction(f);
return;
}
Clazz caller = config.getClazzes().load(t.getCallingClass());
Clazz target = config.getClazzes().load(t.getTarget());
if (!((FieldAccessor) t).isGetter() && field.isFinal() && caller != target) {
// Only the class declaring a final field may write to it.
// (Actually only <init>/<clinit> methods may write to it but we
// don't know which method is accessing the field at this point)
throwIllegalAccessError(f, ATTEMPT_TO_WRITE_TO_FINAL_FIELD,
target, field.getName(), caller);
mb.addFunction(f);
return;
}
createTrampolineAliasForField((FieldAccessor) t, field);
} else if (t instanceof Invokeinterface) {
SootMethod rm = resolveInterfaceMethod(f, (Invokeinterface) t);
if (rm == null || !checkMemberAccessible(f, t, rm)) {
mb.addFunction(f);
return;
}
createTrampolineAliasForMethod((Invoke) t, rm);
} else if (t instanceof Invoke) {
SootMethod method = resolveMethod(f, (Invoke) t);
if (method == null || !checkMemberAccessible(f, t, method)) {
mb.addFunction(f);
return;
}
if (t instanceof Invokespecial && method.isAbstract()) {
call(f, BC_THROW_ABSTRACT_METHOD_ERROR, f.getParameterRef(0),
mb.getString(String.format(NO_SUCH_METHOD_ERROR,
method.getDeclaringClass(), method.getName(),
getDescriptor(method))));
f.add(new Unreachable());
mb.addFunction(f);
return;
}
createTrampolineAliasForMethod((Invoke) t, method);
}
}
| public void compile(ModuleBuilder mb, Trampoline t) {
this.mb = mb;
if (t instanceof LdcString) {
Function f = new Function(weak, t.getFunctionRef());
mb.addFunction(f);
Value result = call(f, BC_LDC_STRING, f.getParameterRef(0),
mb.getString(t.getTarget()));
f.add(new Ret(result));
return;
}
/*
* Check if the target class exists and is accessible. Also check that
* field accesses and method calls are compatible with the target
* field/method and that the field/method is accessible to the caller.
* If any of the tests fail the weak trampoline function created by the
* ClassCompiler will be overridden with a function which throws an
* appropriate exception.
*/
Function f = new Function(external, t.getFunctionRef());
if (!checkClassExists(f, t) || !checkClassAccessible(f, t)) {
mb.addFunction(f);
return;
}
if (t instanceof New) {
SootClass target = config.getClazzes().load(t.getTarget()).getSootClass();
if (target.isAbstract() || target.isInterface()) {
call(f, BC_THROW_INSTANTIATION_ERROR, f.getParameterRef(0), mb.getString(t.getTarget()));
f.add(new Unreachable());
mb.addFunction(f);
return;
}
String fnName = mangleClass(t.getTarget()) + "_allocator_clinit";
alias(t, fnName);
} else if (t instanceof ExceptionMatch) {
String fnName = mangleClass(t.getTarget()) + "_exmatch";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
FunctionRef exInfoFn = getInfoStructFn(t.getTarget());
Value exInfo = call(fn, exInfoFn);
if (!mb.hasSymbol(exInfoFn.getName())) {
mb.addFunctionDeclaration(new FunctionDeclaration(exInfoFn));
}
Value result = call(fn, BC_EXCEPTION_MATCH, f.getParameterRef(0), exInfo);
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else if (t instanceof Instanceof) {
if (isArray(t.getTarget())) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_instanceof";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_INSTANCEOF_ARRAY, fn.getParameterRef(0), arrayClass, fn.getParameterRef(1));
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else {
String fnName = mangleClass(t.getTarget()) + "_instanceof";
alias(t, fnName);
}
} else if (t instanceof Checkcast) {
if (isArray(t.getTarget())) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_checkcast";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_CHECKCAST_ARRAY, fn.getParameterRef(0), arrayClass, fn.getParameterRef(1));
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else {
String fnName = mangleClass(t.getTarget()) + "_checkcast";
alias(t, fnName);
}
} else if (t instanceof LdcClass) {
if (isArray(t.getTarget())) {
FunctionRef fn = createLdcArray(t.getTarget());
alias(t, fn.getName());
} else {
String fnName = mangleClass(t.getTarget()) + "_ldc_load";
alias(t, fnName);
}
} else if (t instanceof Anewarray) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_new";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_NEW_OBJECT_ARRAY, fn.getParameterRef(0),
fn.getParameterRef(1), arrayClass);
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else if (t instanceof Multianewarray) {
String fnName = "array_" + mangleClass(t.getTarget()) + "_multi";
if (!mb.hasSymbol(fnName)) {
Function fn = new Function(weak, t.getFunctionRef(), fnName);
Value arrayClass = callLdcArray(fn, t.getTarget());
Value result = call(fn, BC_NEW_MULTI_ARRAY, fn.getParameterRef(0),
fn.getParameterRef(1), fn.getParameterRef(2), arrayClass);
fn.add(new Ret(result));
mb.addFunction(fn);
}
alias(t, fnName);
} else if (t instanceof NativeCall) {
Clazz target = config.getClazzes().load(t.getTarget());
NativeCall nc = (NativeCall) t;
String shortName = mangleNativeMethod(target.getInternalName(), nc.getMethodName());
String longName = mangleNativeMethod(target.getInternalName(), nc.getMethodName(), nc.getMethodDesc());
if (target.isInBootClasspath()) {
Function fnLong = new Function(weak, longName, nc.getFunctionType());
// The NativeCall caller pushed a GatewayFrame and will only pop it
// if the native method exists. So we need to pop it here.
popNativeFrame(fnLong);
call(fnLong, BC_THROW_UNSATISIFED_LINK_ERROR, fnLong.getParameterRef(0));
fnLong.add(new Unreachable());
mb.addFunction(fnLong);
// mb.addFunctionDeclaration(new FunctionDeclaration(fnLong.ref()));
FunctionRef targetFn = fnLong.ref();
if (!isLongNativeFunctionNameRequired(nc)) {
Function fnShort = new Function(weak, shortName, nc.getFunctionType());
Value resultInner = call(fnShort, fnLong.ref(), fnShort.getParameterRefs());
fnShort.add(new Ret(resultInner));
mb.addFunction(fnShort);
// mb.addFunctionDeclaration(new FunctionDeclaration(fnShort.ref()));
targetFn = fnShort.ref();
}
Function fn = new Function(external, nc.getFunctionRef());
Value result = call(fn, targetFn, fn.getParameterRefs());
fn.add(new Ret(result));
mb.addFunction(fn);
} else {
Global g = new Global("native_" + mangleMethod(nc.getTarget(),
nc.getMethodName(), nc.getMethodDesc()) + "_ptr",
new NullConstant(I8_PTR));
mb.addGlobal(g);
Function fn = new Function(external, nc.getFunctionRef());
FunctionRef ldcFn = new FunctionRef(mangleClass(nc.getTarget()) + "_ldc",
new FunctionType(OBJECT_PTR, ENV_PTR));
Value theClass = call(fn, ldcFn, fn.getParameterRef(0));
Value implI8Ptr = call(fn, BC_RESOLVE_NATIVE, fn.getParameterRef(0),
theClass,
mb.getString(nc.getMethodName()),
mb.getString(nc.getMethodDesc()),
mb.getString(mangleNativeMethod(nc.getTarget(), nc.getMethodName())),
mb.getString(mangleNativeMethod(nc.getTarget(), nc.getMethodName(), nc.getMethodDesc())),
g.ref());
Variable nullTest = fn.newVariable(I1);
fn.add(new Icmp(nullTest, Condition.ne, implI8Ptr, new NullConstant(I8_PTR)));
Label trueLabel = new Label();
Label falseLabel = new Label();
fn.add(new Br(nullTest.ref(), fn.newBasicBlockRef(trueLabel), fn.newBasicBlockRef(falseLabel)));
fn.newBasicBlock(falseLabel);
if (fn.getType().getReturnType() instanceof IntegerType) {
fn.add(new Ret(new IntegerConstant(0, (IntegerType) fn.getType().getReturnType())));
} else if (fn.getType().getReturnType() instanceof FloatingPointType) {
fn.add(new Ret(new FloatingPointConstant(0.0, (FloatingPointType) fn.getType().getReturnType())));
} else if (fn.getType().getReturnType() instanceof PointerType) {
fn.add(new Ret(new NullConstant((PointerType) fn.getType().getReturnType())));
} else {
fn.add(new Ret());
}
fn.newBasicBlock(trueLabel);
Variable impl = fn.newVariable(nc.getFunctionType());
fn.add(new Bitcast(impl, implI8Ptr, impl.getType()));
Value result = call(fn, impl.ref(), fn.getParameterRefs());
fn.add(new Ret(result));
mb.addFunction(fn);
}
} else if (t instanceof FieldAccessor) {
SootField field = resolveField(f, (FieldAccessor) t);
if (field == null || !checkMemberAccessible(f, t, field)) {
mb.addFunction(f);
return;
}
Clazz caller = config.getClazzes().load(t.getCallingClass());
Clazz target = config.getClazzes().load(t.getTarget());
if (!((FieldAccessor) t).isGetter() && field.isFinal() && caller != target) {
// Only the class declaring a final field may write to it.
// (Actually only <init>/<clinit> methods may write to it but we
// don't know which method is accessing the field at this point)
throwIllegalAccessError(f, ATTEMPT_TO_WRITE_TO_FINAL_FIELD,
target, field.getName(), caller);
mb.addFunction(f);
return;
}
createTrampolineAliasForField((FieldAccessor) t, field);
} else if (t instanceof Invokeinterface) {
SootMethod rm = resolveInterfaceMethod(f, (Invokeinterface) t);
if (rm == null || !checkMemberAccessible(f, t, rm)) {
mb.addFunction(f);
return;
}
createTrampolineAliasForMethod((Invoke) t, rm);
} else if (t instanceof Invoke) {
SootMethod method = resolveMethod(f, (Invoke) t);
if (method == null || !checkMemberAccessible(f, t, method)) {
mb.addFunction(f);
return;
}
if (t instanceof Invokespecial && method.isAbstract()) {
call(f, BC_THROW_ABSTRACT_METHOD_ERROR, f.getParameterRef(0),
mb.getString(String.format(NO_SUCH_METHOD_ERROR,
method.getDeclaringClass(), method.getName(),
getDescriptor(method))));
f.add(new Unreachable());
mb.addFunction(f);
return;
}
createTrampolineAliasForMethod((Invoke) t, method);
}
}
|
diff --git a/src/com/smouring/android/psalterapp/ViewPsalms.java b/src/com/smouring/android/psalterapp/ViewPsalms.java
index 47c4bb0..d6c7d31 100644
--- a/src/com/smouring/android/psalterapp/ViewPsalms.java
+++ b/src/com/smouring/android/psalterapp/ViewPsalms.java
@@ -1,120 +1,120 @@
package com.smouring.android.psalterapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import static com.smouring.android.psalterapp.Constants.*;
/**
* @author Stephen Mouring
*/
public class ViewPsalms extends Activity {
private int selectedPsalm;
private boolean restore;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpsalms);
System.setProperty("log.tag.1650ForAndroid", "INFO");
- int restoredSelectedPsalm = 150;
+ int restoredSelectedPsalm = 1;
if (savedInstanceState == null) {
Log.i("1650ForAndroid", "No saved instance state.");
} else {
Log.i("1650ForAndroid", "Restoring saved instance state.");
if (savedInstanceState.containsKey(SELECTED_PSALM_KEY)) {
restoredSelectedPsalm = savedInstanceState.getInt(SELECTED_PSALM_KEY);
Log.i("1650ForAndroid", "Found key: " + SELECTED_PSALM_KEY + " - " + restoredSelectedPsalm);
} else {
Log.e("1650ForAndroid", "No valid key stored in saved instance state!");
}
}
restore = true;
final int bookIndex = getBookForPsalm(restoredSelectedPsalm) - 1;
Log.i("1650ForAndroid", "bookIndex - " + bookIndex);
final int psalmIndex = (bookIndex == 0 ? (restoredSelectedPsalm - 1) : (restoredSelectedPsalm - 1) - BOOKS[bookIndex -1]);
Log.i("1650ForAndroid", "psalmIndex - " + psalmIndex);
Spinner chooseBook = (Spinner) findViewById(R.id.choosebook);
ArrayAdapter<String> bookNameAdapter = new ArrayAdapter<String>(this, R.layout.psalmselector, BOOK_NAMES);
bookNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
chooseBook.setAdapter(bookNameAdapter);
chooseBook.setSelection(bookIndex);
chooseBook.setOnItemSelectedListener(new OnItemSelectedListenerAdapter() {
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
Log.i("1650ForAndroid", "chooseBook onItemSelectedListener fired.");
int bookIndex = Integer.parseInt(parent.getItemAtPosition(pos).toString().split(" ")[1]) - 1;
Spinner choosePsalm = (Spinner) findViewById(R.id.choosepsalm);
ArrayAdapter<String> psalmNameAdapter = new ArrayAdapter<String>(ViewPsalms.this, R.layout.psalmselector, PSALM_NAMES[bookIndex]);
psalmNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
choosePsalm.setAdapter(psalmNameAdapter);
if (restore) {
choosePsalm.setSelection(psalmIndex);
restore = false;
}
}
});
Spinner choosePsalm = (Spinner) findViewById(R.id.choosepsalm);
choosePsalm.setOnItemSelectedListener(new OnItemSelectedListenerAdapter() {
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
Log.i("1650ForAndroid", "choosePsalm onItemSelectedListener fired.");
selectedPsalm = Integer.parseInt(parent.getItemAtPosition(pos).toString().replace("Psalm ", ""));
Log.i("1650ForAndroid", "selectedPsalm set to: [" + selectedPsalm + "]");
}
});
Button selectButton = (Button) findViewById(R.id.select);
selectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.i("1650ForAndroid", "Launching intent for ViewPsalm activity.");
Intent i = new Intent(ViewPsalms.this, ViewPsalm.class);
i.putExtra(SELECTED_PSALM_KEY, selectedPsalm);
startActivity(i);
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.i("1650ForAndroid", "onSaveInstanceState listener fired.");
savedInstanceState.putInt(SELECTED_PSALM_KEY, selectedPsalm);
}
private int getBookForPsalm(int selectedPsalm) {
for (int i = 0; i < BOOKS.length; ++i) {
if (selectedPsalm <= BOOKS[i]) {
return i+1;
}
}
Log.e("1650ForAndroid", "Invalid selectedPsalm parameter!");
throw new RuntimeException("Invalid selectedPsalm parameter!");
}
public class OnItemSelectedListenerAdapter implements OnItemSelectedListener {
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
}
public void onNothingSelected(AdapterView parent) {
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpsalms);
System.setProperty("log.tag.1650ForAndroid", "INFO");
int restoredSelectedPsalm = 150;
if (savedInstanceState == null) {
Log.i("1650ForAndroid", "No saved instance state.");
} else {
Log.i("1650ForAndroid", "Restoring saved instance state.");
if (savedInstanceState.containsKey(SELECTED_PSALM_KEY)) {
restoredSelectedPsalm = savedInstanceState.getInt(SELECTED_PSALM_KEY);
Log.i("1650ForAndroid", "Found key: " + SELECTED_PSALM_KEY + " - " + restoredSelectedPsalm);
} else {
Log.e("1650ForAndroid", "No valid key stored in saved instance state!");
}
}
restore = true;
final int bookIndex = getBookForPsalm(restoredSelectedPsalm) - 1;
Log.i("1650ForAndroid", "bookIndex - " + bookIndex);
final int psalmIndex = (bookIndex == 0 ? (restoredSelectedPsalm - 1) : (restoredSelectedPsalm - 1) - BOOKS[bookIndex -1]);
Log.i("1650ForAndroid", "psalmIndex - " + psalmIndex);
Spinner chooseBook = (Spinner) findViewById(R.id.choosebook);
ArrayAdapter<String> bookNameAdapter = new ArrayAdapter<String>(this, R.layout.psalmselector, BOOK_NAMES);
bookNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
chooseBook.setAdapter(bookNameAdapter);
chooseBook.setSelection(bookIndex);
chooseBook.setOnItemSelectedListener(new OnItemSelectedListenerAdapter() {
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
Log.i("1650ForAndroid", "chooseBook onItemSelectedListener fired.");
int bookIndex = Integer.parseInt(parent.getItemAtPosition(pos).toString().split(" ")[1]) - 1;
Spinner choosePsalm = (Spinner) findViewById(R.id.choosepsalm);
ArrayAdapter<String> psalmNameAdapter = new ArrayAdapter<String>(ViewPsalms.this, R.layout.psalmselector, PSALM_NAMES[bookIndex]);
psalmNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
choosePsalm.setAdapter(psalmNameAdapter);
if (restore) {
choosePsalm.setSelection(psalmIndex);
restore = false;
}
}
});
Spinner choosePsalm = (Spinner) findViewById(R.id.choosepsalm);
choosePsalm.setOnItemSelectedListener(new OnItemSelectedListenerAdapter() {
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
Log.i("1650ForAndroid", "choosePsalm onItemSelectedListener fired.");
selectedPsalm = Integer.parseInt(parent.getItemAtPosition(pos).toString().replace("Psalm ", ""));
Log.i("1650ForAndroid", "selectedPsalm set to: [" + selectedPsalm + "]");
}
});
Button selectButton = (Button) findViewById(R.id.select);
selectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.i("1650ForAndroid", "Launching intent for ViewPsalm activity.");
Intent i = new Intent(ViewPsalms.this, ViewPsalm.class);
i.putExtra(SELECTED_PSALM_KEY, selectedPsalm);
startActivity(i);
}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpsalms);
System.setProperty("log.tag.1650ForAndroid", "INFO");
int restoredSelectedPsalm = 1;
if (savedInstanceState == null) {
Log.i("1650ForAndroid", "No saved instance state.");
} else {
Log.i("1650ForAndroid", "Restoring saved instance state.");
if (savedInstanceState.containsKey(SELECTED_PSALM_KEY)) {
restoredSelectedPsalm = savedInstanceState.getInt(SELECTED_PSALM_KEY);
Log.i("1650ForAndroid", "Found key: " + SELECTED_PSALM_KEY + " - " + restoredSelectedPsalm);
} else {
Log.e("1650ForAndroid", "No valid key stored in saved instance state!");
}
}
restore = true;
final int bookIndex = getBookForPsalm(restoredSelectedPsalm) - 1;
Log.i("1650ForAndroid", "bookIndex - " + bookIndex);
final int psalmIndex = (bookIndex == 0 ? (restoredSelectedPsalm - 1) : (restoredSelectedPsalm - 1) - BOOKS[bookIndex -1]);
Log.i("1650ForAndroid", "psalmIndex - " + psalmIndex);
Spinner chooseBook = (Spinner) findViewById(R.id.choosebook);
ArrayAdapter<String> bookNameAdapter = new ArrayAdapter<String>(this, R.layout.psalmselector, BOOK_NAMES);
bookNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
chooseBook.setAdapter(bookNameAdapter);
chooseBook.setSelection(bookIndex);
chooseBook.setOnItemSelectedListener(new OnItemSelectedListenerAdapter() {
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
Log.i("1650ForAndroid", "chooseBook onItemSelectedListener fired.");
int bookIndex = Integer.parseInt(parent.getItemAtPosition(pos).toString().split(" ")[1]) - 1;
Spinner choosePsalm = (Spinner) findViewById(R.id.choosepsalm);
ArrayAdapter<String> psalmNameAdapter = new ArrayAdapter<String>(ViewPsalms.this, R.layout.psalmselector, PSALM_NAMES[bookIndex]);
psalmNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
choosePsalm.setAdapter(psalmNameAdapter);
if (restore) {
choosePsalm.setSelection(psalmIndex);
restore = false;
}
}
});
Spinner choosePsalm = (Spinner) findViewById(R.id.choosepsalm);
choosePsalm.setOnItemSelectedListener(new OnItemSelectedListenerAdapter() {
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
Log.i("1650ForAndroid", "choosePsalm onItemSelectedListener fired.");
selectedPsalm = Integer.parseInt(parent.getItemAtPosition(pos).toString().replace("Psalm ", ""));
Log.i("1650ForAndroid", "selectedPsalm set to: [" + selectedPsalm + "]");
}
});
Button selectButton = (Button) findViewById(R.id.select);
selectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.i("1650ForAndroid", "Launching intent for ViewPsalm activity.");
Intent i = new Intent(ViewPsalms.this, ViewPsalm.class);
i.putExtra(SELECTED_PSALM_KEY, selectedPsalm);
startActivity(i);
}
});
}
|
diff --git a/src/main/java/com/sohu/jafka/log/LogManager.java b/src/main/java/com/sohu/jafka/log/LogManager.java
index 396acda..fd1f3a8 100644
--- a/src/main/java/com/sohu/jafka/log/LogManager.java
+++ b/src/main/java/com/sohu/jafka/log/LogManager.java
@@ -1,571 +1,571 @@
/**
* 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 com.sohu.jafka.log;
import static java.lang.String.format;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.log4j.Logger;
import com.sohu.jafka.api.OffsetRequest;
import com.sohu.jafka.api.PartitionChooser;
import com.sohu.jafka.common.InvalidPartitionException;
import com.sohu.jafka.server.ServerConfig;
import com.sohu.jafka.server.ServerRegister;
import com.sohu.jafka.server.TopicTask;
import com.sohu.jafka.server.TopicTask.TaskType;
import com.sohu.jafka.utils.Closer;
import com.sohu.jafka.utils.IteratorTemplate;
import com.sohu.jafka.utils.KV;
import com.sohu.jafka.utils.Pool;
import com.sohu.jafka.utils.Scheduler;
import com.sohu.jafka.utils.Utils;
/**
* @author adyliu ([email protected])
* @since 1.0
*/
public class LogManager implements PartitionChooser, Closeable {
final ServerConfig config;
private final Scheduler scheduler;
final long logCleanupIntervalMs;
final long logCleanupDefaultAgeMs;
final boolean needRecovery;
private final Logger logger = Logger.getLogger(LogManager.class);
///////////////////////////////////////////////////////////////////////
final int numPartitions;
final File logDir;
final int flushInterval;
private final Object logCreationLock = new Object();
final Random random = new Random();
final CountDownLatch startupLatch;
//
private final Pool<String, Pool<Integer, Log>> logs = new Pool<String, Pool<Integer, Log>>();
private final Scheduler logFlusherScheduler = new Scheduler(1, "jafka-logflusher-", false);
//
private final LinkedBlockingQueue<TopicTask> topicRegisterTasks = new LinkedBlockingQueue<TopicTask>();
private volatile boolean stopTopicRegisterTasks = false;
final Map<String, Integer> logFlushIntervalMap;
final Map<String, Long> logRetentionMSMap;
final int logRetentionSize;
/////////////////////////////////////////////////////////////////////////
private ServerRegister serverRegister;
private final Map<String, Integer> topicPartitionsMap;
private RollingStrategy rollingStategy;
public LogManager(ServerConfig config, //
Scheduler scheduler, //
long logCleanupIntervalMs, //
long logCleanupDefaultAgeMs, //
boolean needRecovery) {
super();
this.config = config;
this.scheduler = scheduler;
// this.time = time;
this.logCleanupIntervalMs = logCleanupIntervalMs;
this.logCleanupDefaultAgeMs = logCleanupDefaultAgeMs;
this.needRecovery = needRecovery;
//
this.logDir = Utils.getCanonicalFile(new File(config.getLogDir()));
this.numPartitions = config.getNumPartitions();
this.flushInterval = config.getFlushInterval();
this.topicPartitionsMap = config.getTopicPartitionsMap();
this.startupLatch = config.getEnableZookeeper() ? new CountDownLatch(1) : null;
this.logFlushIntervalMap = config.getFlushIntervalMap();
this.logRetentionSize = config.getLogRetentionSize();
this.logRetentionMSMap = getLogRetentionMSMap(config.getLogRetentionHoursMap());
//
}
public void setRollingStategy(RollingStrategy rollingStategy) {
this.rollingStategy = rollingStategy;
}
public void load() throws IOException {
if (this.rollingStategy == null) {
this.rollingStategy = new FixedSizeRollingStrategy(config.getLogFileSize());
}
if (!logDir.exists()) {
logger.info("No log directory found, creating '" + logDir.getAbsolutePath() + "'");
logDir.mkdirs();
}
if (!logDir.isDirectory() || !logDir.canRead()) {
throw new IllegalArgumentException(logDir.getAbsolutePath() + " is not a readable log directory.");
}
File[] subDirs = logDir.listFiles();
if (subDirs != null) {
for (File dir : subDirs) {
if (!dir.isDirectory()) {
logger.warn("Skipping unexplainable file '" + dir.getAbsolutePath() + "'--should it be there?");
} else {
logger.info("Loading log from " + dir.getAbsolutePath());
final String topicNameAndPartition = dir.getName();
if(-1 == topicNameAndPartition.indexOf('-')) {
throw new IllegalArgumentException("error topic directory: "+dir.getAbsolutePath());
}
final KV<String, Integer> topicPartion = Utils.getTopicPartition(topicNameAndPartition);
final String topic = topicPartion.k;
final int partition = topicPartion.v;
Log log = new Log(dir, partition, this.rollingStategy, flushInterval, needRecovery);
logs.putIfNotExists(topic, new Pool<Integer, Log>());
Pool<Integer, Log> parts = logs.get(topic);
parts.put(partition, log);
int configPartition = getPartition(topic);
- if(configPartition < partition) {
- topicPartitionsMap.put(topic, partition);
+ if(configPartition <= partition) {
+ topicPartitionsMap.put(topic, partition+1);
}
}
}
}
/* Schedule the cleanup task to delete old logs */
if (this.scheduler != null) {
logger.info("starting log cleaner every " + logCleanupIntervalMs + " ms");
this.scheduler.scheduleWithRate(new Runnable() {
public void run() {
try {
cleanupLogs();
} catch (IOException e) {
logger.error("cleanup log failed.", e);
}
}
}, 60 * 1000, logCleanupIntervalMs);
}
//
if (config.getEnableZookeeper()) {
this.serverRegister = new ServerRegister(config, this);
serverRegister.startup();
TopicRegisterTask task = new TopicRegisterTask();
task.setName("jafka.topicregister");
task.setDaemon(true);
task.start();
}
}
private void registeredTaskLooply() {
while (!stopTopicRegisterTasks) {
try {
TopicTask task = topicRegisterTasks.take();
if (task.type == TaskType.SHUTDOWN) break;
serverRegister.processTask(task);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
logger.debug("stop topic register task");
}
class TopicRegisterTask extends Thread {
@Override
public void run() {
registeredTaskLooply();
}
}
private Map<String, Long> getLogRetentionMSMap(Map<String, Integer> logRetentionHourMap) {
Map<String, Long> ret = new HashMap<String, Long>();
for (Map.Entry<String, Integer> e : logRetentionHourMap.entrySet()) {
ret.put(e.getKey(), e.getValue() * 60 * 60 * 1000L);
}
return ret;
}
public void close() {
logFlusherScheduler.shutdown();
Iterator<Log> iter = getLogIterator();
while (iter.hasNext()) {
Closer.closeQuietly(iter.next(), logger);
}
if (config.getEnableZookeeper()) {
stopTopicRegisterTasks = true;
//wake up again and again
topicRegisterTasks.add(new TopicTask(TaskType.SHUTDOWN, null));
topicRegisterTasks.add(new TopicTask(TaskType.SHUTDOWN, null));
Closer.closeQuietly(serverRegister);
}
}
/**
* Runs through the log removing segments older than a certain age
*
* @throws IOException
*/
private void cleanupLogs() throws IOException {
logger.trace("Beginning log cleanup...");
int total = 0;
Iterator<Log> iter = getLogIterator();
long startMs = System.currentTimeMillis();
while (iter.hasNext()) {
Log log = iter.next();
total += cleanupExpiredSegments(log) + cleanupSegmentsToMaintainSize(log);
}
if (total > 0) {
logger.warn("Log cleanup completed. " + total + " files deleted in " + (System.currentTimeMillis() - startMs) / 1000 + " seconds");
} else {
logger.trace("Log cleanup completed. " + total + " files deleted in " + (System.currentTimeMillis() - startMs) / 1000 + " seconds");
}
}
/**
* Runs through the log removing segments until the size of the log is at least
* logRetentionSize bytes in size
*
* @throws IOException
*/
private int cleanupSegmentsToMaintainSize(final Log log) throws IOException {
if (logRetentionSize < 0 || log.size() < logRetentionSize) return 0;
List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() {
long diff = log.size() - logRetentionSize;
public boolean filter(LogSegment segment) {
diff -= segment.size();
return diff >= 0;
}
});
return deleteSegments(log, toBeDeleted);
}
private int cleanupExpiredSegments(Log log) throws IOException {
final long startMs = System.currentTimeMillis();
String topic = Utils.getTopicPartition(log.dir.getName()).k;
Long logCleanupThresholdMS = logRetentionMSMap.get(topic);
if (logCleanupThresholdMS == null) {
logCleanupThresholdMS = this.logCleanupDefaultAgeMs;
}
final long expiredThrshold = logCleanupThresholdMS.longValue();
List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() {
public boolean filter(LogSegment segment) {
//check file which has not been modified in expiredThrshold millionseconds
return startMs - segment.getFile().lastModified() > expiredThrshold;
}
});
return deleteSegments(log, toBeDeleted);
}
/**
* Attemps to delete all provided segments from a log and returns how many it was able to
*/
private int deleteSegments(Log log, List<LogSegment> segments) {
int total = 0;
for (LogSegment segment : segments) {
boolean deleted = false;
try {
try {
segment.getMessageSet().close();
} catch (IOException e) {
logger.warn(e.getMessage(), e);
}
if (!segment.getFile().delete()) {
deleted = true;
} else {
total += 1;
}
} finally {
logger.warn(String.format("DELETE_LOG[%s] %s => %s", log.name, segment.getFile().getAbsolutePath(),
deleted));
}
}
return total;
}
/**
* Register this broker in ZK for the first time.
*/
public void startup() {
if (config.getEnableZookeeper()) {
serverRegister.registerBrokerInZk();
for (String topic : getAllTopics()) {
serverRegister.processTask(new TopicTask(TaskType.CREATE, topic));
}
startupLatch.countDown();
}
logger.info("Starting log flusher every " + config.getFlushSchedulerThreadRate() + " ms with the following overrides " + logFlushIntervalMap);
logFlusherScheduler.scheduleWithRate(new Runnable() {
public void run() {
flushAllLogs(false);
}
}, config.getFlushSchedulerThreadRate(), config.getFlushSchedulerThreadRate());
}
/**
* flush all messages to disk
*
* @param force flush anyway(ignore flush interval)
*/
public void flushAllLogs(final boolean force) {
Iterator<Log> iter = getLogIterator();
while (iter.hasNext()) {
Log log = iter.next();
try {
boolean needFlush = force;
if (!needFlush) {
long timeSinceLastFlush = System.currentTimeMillis() - log.getLastFlushedTime();
Integer logFlushInterval = logFlushIntervalMap.get(log.getTopicName());
if (logFlushInterval == null) {
logFlushInterval = config.getDefaultFlushIntervalMs();
}
final String flushLogFormat = "[%s] flush interval %d, last flushed %d, need flush? %s";
needFlush = timeSinceLastFlush >= logFlushInterval.intValue();
logger.trace(String.format(flushLogFormat, log.getTopicName(), logFlushInterval,
log.getLastFlushedTime(), needFlush));
}
if (needFlush) {
log.flush();
}
} catch (IOException ioe) {
logger.error("Error flushing topic " + log.getTopicName(), ioe);
logger.fatal("Halting due to unrecoverable I/O error while flushing logs: " + ioe.getMessage(), ioe);
Runtime.getRuntime().halt(1);
} catch (Exception e) {
logger.error("Error flushing topic " + log.getTopicName(), e);
}
}
}
private Collection<String> getAllTopics() {
return logs.keySet();
}
private Iterator<Log> getLogIterator() {
return new IteratorTemplate<Log>() {
final Iterator<Pool<Integer, Log>> iterator = logs.values().iterator();
Iterator<Log> logIter;
@Override
protected Log makeNext() {
while (true) {
if (logIter != null && logIter.hasNext()) {
return logIter.next();
}
if (!iterator.hasNext()) {
return allDone();
}
logIter = iterator.next().values().iterator();
}
}
};
}
private void awaitStartup() {
if (config.getEnableZookeeper()) {
try {
startupLatch.await();
} catch (InterruptedException e) {
logger.warn(e.getMessage(), e);
}
}
}
private Pool<Integer, Log> getLogPool(String topic, int partition) {
awaitStartup();
if (topic.length() <= 0) {
throw new IllegalArgumentException("topic name can't be empty");
}
//
Integer definePartition = this.topicPartitionsMap.get(topic);
if (definePartition == null) {
definePartition = numPartitions;
}
if (partition < 0 || partition >= definePartition.intValue()) {
String msg = "Wrong partition [%d] for topic [%s], valid partitions [0,%d)";
msg = format(msg, partition, topic, definePartition.intValue() - 1);
logger.warn(msg);
throw new InvalidPartitionException(msg);
}
return logs.get(topic);
}
/**
* Get the log if exists or return null
*
* @param topic topic name
* @param partition partition index
* @return a log for the topic or null if not exist
*/
public ILog getLog(String topic, int partition) {
Pool<Integer, Log> p = getLogPool(topic, partition);
return p == null ? null : p.get(partition);
}
/**
* Create the log if it does not exist or return back exist log
*
* @param topic
* @param partition
* @return read or create a log
* @throws InterruptedException
* @throws IOException
*/
public ILog getOrCreateLog(String topic, int partition) throws IOException {
boolean hasNewTopic = false;
Pool<Integer, Log> parts = getLogPool(topic, partition);
if (parts == null) {
Pool<Integer, Log> found = logs.putIfNotExists(topic, new Pool<Integer, Log>());
if (found == null) {
hasNewTopic = true;
}
parts = logs.get(topic);
}
//
Log log = parts.get(partition);
if (log == null) {
log = createLog(topic, partition);
Log found = parts.putIfNotExists(partition, log);
if (found != null) {
Closer.closeQuietly(log, logger);
log = found;
} else {
logger.info(format("Created log for [%s-%d]", topic, partition));
}
}
if (hasNewTopic && config.getEnableZookeeper()) {
topicRegisterTasks.add(new TopicTask(TaskType.CREATE, topic));
}
return log;
}
public int createLogs(String topic, final int partitions, final boolean forceEnlarge) {
synchronized (logCreationLock) {
final int configPartitions = getPartition(topic);
if (configPartitions >= partitions || !forceEnlarge) {
return configPartitions;
}
topicPartitionsMap.put(topic, partitions);
if (config.getEnableZookeeper()) {
if (getLogPool(topic, 0) != null) {//created already
topicRegisterTasks.add(new TopicTask(TaskType.ENLARGE, topic));
} else {
topicRegisterTasks.add(new TopicTask(TaskType.CREATE, topic));
}
}
return partitions;
}
}
/**
* delete topic who is never used
* <p>
* This will delete all log files and remove node data from zookeeper
* </p>
* @param topic topic name
* @return number of deleted partitions or -1 if authentication failed
*/
public int deleteLogs(String topic,String password) {
if(!config.getAuthentication().auth(password)) {
return -1;
}
int value = 0;
synchronized (logCreationLock) {
Pool<Integer, Log> parts = logs.remove(topic);
if (parts != null) {
List<Log> deleteLogs = new ArrayList<Log>(parts.values());
for (Log log : deleteLogs) {
log.delete();
value++;
}
}
if(config.getEnableZookeeper()) {
topicRegisterTasks.add(new TopicTask(TaskType.DELETE, topic));
}
}
return value;
}
private Log createLog(String topic, int partition) throws IOException {
synchronized (logCreationLock) {
File d = new File(logDir, topic + "-" + partition);
d.mkdirs();
return new Log(d, partition, this.rollingStategy, flushInterval, false);
}
}
private int getPartition(String topic) {
Integer p = topicPartitionsMap.get(topic);
return p != null ? p.intValue() : this.numPartitions;
}
/**
* Pick a random partition from the given topic
*/
public int choosePartition(String topic) {
return random.nextInt(getPartition(topic));
}
/**
* read offsets before given time
*
* @param offsetRequest
* @return offsets before given time
*/
public List<Long> getOffsets(OffsetRequest offsetRequest) {
ILog log = getLog(offsetRequest.topic, offsetRequest.partition);
if (log != null) {
return log.getOffsetsBefore(offsetRequest);
}
return ILog.EMPTY_OFFSETS;
}
public Map<String, Integer> getTopicPartitionsMap() {
return topicPartitionsMap;
}
}
| true | true | public void load() throws IOException {
if (this.rollingStategy == null) {
this.rollingStategy = new FixedSizeRollingStrategy(config.getLogFileSize());
}
if (!logDir.exists()) {
logger.info("No log directory found, creating '" + logDir.getAbsolutePath() + "'");
logDir.mkdirs();
}
if (!logDir.isDirectory() || !logDir.canRead()) {
throw new IllegalArgumentException(logDir.getAbsolutePath() + " is not a readable log directory.");
}
File[] subDirs = logDir.listFiles();
if (subDirs != null) {
for (File dir : subDirs) {
if (!dir.isDirectory()) {
logger.warn("Skipping unexplainable file '" + dir.getAbsolutePath() + "'--should it be there?");
} else {
logger.info("Loading log from " + dir.getAbsolutePath());
final String topicNameAndPartition = dir.getName();
if(-1 == topicNameAndPartition.indexOf('-')) {
throw new IllegalArgumentException("error topic directory: "+dir.getAbsolutePath());
}
final KV<String, Integer> topicPartion = Utils.getTopicPartition(topicNameAndPartition);
final String topic = topicPartion.k;
final int partition = topicPartion.v;
Log log = new Log(dir, partition, this.rollingStategy, flushInterval, needRecovery);
logs.putIfNotExists(topic, new Pool<Integer, Log>());
Pool<Integer, Log> parts = logs.get(topic);
parts.put(partition, log);
int configPartition = getPartition(topic);
if(configPartition < partition) {
topicPartitionsMap.put(topic, partition);
}
}
}
}
/* Schedule the cleanup task to delete old logs */
if (this.scheduler != null) {
logger.info("starting log cleaner every " + logCleanupIntervalMs + " ms");
this.scheduler.scheduleWithRate(new Runnable() {
public void run() {
try {
cleanupLogs();
} catch (IOException e) {
logger.error("cleanup log failed.", e);
}
}
}, 60 * 1000, logCleanupIntervalMs);
}
//
if (config.getEnableZookeeper()) {
this.serverRegister = new ServerRegister(config, this);
serverRegister.startup();
TopicRegisterTask task = new TopicRegisterTask();
task.setName("jafka.topicregister");
task.setDaemon(true);
task.start();
}
}
| public void load() throws IOException {
if (this.rollingStategy == null) {
this.rollingStategy = new FixedSizeRollingStrategy(config.getLogFileSize());
}
if (!logDir.exists()) {
logger.info("No log directory found, creating '" + logDir.getAbsolutePath() + "'");
logDir.mkdirs();
}
if (!logDir.isDirectory() || !logDir.canRead()) {
throw new IllegalArgumentException(logDir.getAbsolutePath() + " is not a readable log directory.");
}
File[] subDirs = logDir.listFiles();
if (subDirs != null) {
for (File dir : subDirs) {
if (!dir.isDirectory()) {
logger.warn("Skipping unexplainable file '" + dir.getAbsolutePath() + "'--should it be there?");
} else {
logger.info("Loading log from " + dir.getAbsolutePath());
final String topicNameAndPartition = dir.getName();
if(-1 == topicNameAndPartition.indexOf('-')) {
throw new IllegalArgumentException("error topic directory: "+dir.getAbsolutePath());
}
final KV<String, Integer> topicPartion = Utils.getTopicPartition(topicNameAndPartition);
final String topic = topicPartion.k;
final int partition = topicPartion.v;
Log log = new Log(dir, partition, this.rollingStategy, flushInterval, needRecovery);
logs.putIfNotExists(topic, new Pool<Integer, Log>());
Pool<Integer, Log> parts = logs.get(topic);
parts.put(partition, log);
int configPartition = getPartition(topic);
if(configPartition <= partition) {
topicPartitionsMap.put(topic, partition+1);
}
}
}
}
/* Schedule the cleanup task to delete old logs */
if (this.scheduler != null) {
logger.info("starting log cleaner every " + logCleanupIntervalMs + " ms");
this.scheduler.scheduleWithRate(new Runnable() {
public void run() {
try {
cleanupLogs();
} catch (IOException e) {
logger.error("cleanup log failed.", e);
}
}
}, 60 * 1000, logCleanupIntervalMs);
}
//
if (config.getEnableZookeeper()) {
this.serverRegister = new ServerRegister(config, this);
serverRegister.startup();
TopicRegisterTask task = new TopicRegisterTask();
task.setName("jafka.topicregister");
task.setDaemon(true);
task.start();
}
}
|
diff --git a/plugins/jdt.spelling/src/jdt/spelling/enums/JavaType.java b/plugins/jdt.spelling/src/jdt/spelling/enums/JavaType.java
index 82077dd..d405d60 100644
--- a/plugins/jdt.spelling/src/jdt/spelling/enums/JavaType.java
+++ b/plugins/jdt.spelling/src/jdt/spelling/enums/JavaType.java
@@ -1,76 +1,82 @@
package jdt.spelling.enums;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
public enum JavaType {
TYPE("Type", "Classes, Interfaces..."), ENUM_TYPE("Enum", "Enum declaration"), ENUM_INSTANCE("Enumeration",
"Enum instance"), ANNOTATION("Annotation"), FIELD("Field"), LOCAL_VARIABLE("Local variable"), METHOD(
"Method"), PACKAGE_DECLARATION("Package"), CONSTANT("Constant", "static final field");
private final String displayName;
private final String tooltip;
JavaType(String displayName) {
this.displayName = displayName;
this.tooltip = "";
}
JavaType(String displayName, String tooltip) {
this.displayName = displayName;
this.tooltip = tooltip;
}
public String getDisplayName() {
return displayName;
}
public String getTooltip() {
return tooltip;
}
public static JavaType convert(IJavaElement javaElement) {
switch (javaElement.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
return null;
case IJavaElement.ANNOTATION:
return ANNOTATION;
case IJavaElement.FIELD:
IMember member = (IMember) javaElement;
try {
int flags = member.getFlags();
if (Flags.isStatic(flags) && Flags.isFinal(flags)) {
return CONSTANT;
}
if (Flags.isEnum(flags)) {
return ENUM_INSTANCE;
}
+ IJavaElement parent = javaElement.getParent();
+ if (parent instanceof IType) {
+ if (Flags.isInterface(((IType) parent).getFlags())) {
+ return CONSTANT;
+ }
+ }
} catch (JavaModelException e) {
// IGNORE
}
return FIELD;
case IJavaElement.LOCAL_VARIABLE:
return LOCAL_VARIABLE;
case IJavaElement.METHOD:
return METHOD;
case IJavaElement.PACKAGE_DECLARATION:
return PACKAGE_DECLARATION;
case IJavaElement.TYPE:
IType type = (IType) javaElement;
try {
if (type.isEnum()) {
return ENUM_TYPE;
}
} catch (JavaModelException e) {
// IGNORE
}
return TYPE;
default:
return null;
}
}
}
| true | true | public static JavaType convert(IJavaElement javaElement) {
switch (javaElement.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
return null;
case IJavaElement.ANNOTATION:
return ANNOTATION;
case IJavaElement.FIELD:
IMember member = (IMember) javaElement;
try {
int flags = member.getFlags();
if (Flags.isStatic(flags) && Flags.isFinal(flags)) {
return CONSTANT;
}
if (Flags.isEnum(flags)) {
return ENUM_INSTANCE;
}
} catch (JavaModelException e) {
// IGNORE
}
return FIELD;
case IJavaElement.LOCAL_VARIABLE:
return LOCAL_VARIABLE;
case IJavaElement.METHOD:
return METHOD;
case IJavaElement.PACKAGE_DECLARATION:
return PACKAGE_DECLARATION;
case IJavaElement.TYPE:
IType type = (IType) javaElement;
try {
if (type.isEnum()) {
return ENUM_TYPE;
}
} catch (JavaModelException e) {
// IGNORE
}
return TYPE;
default:
return null;
}
}
| public static JavaType convert(IJavaElement javaElement) {
switch (javaElement.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
return null;
case IJavaElement.ANNOTATION:
return ANNOTATION;
case IJavaElement.FIELD:
IMember member = (IMember) javaElement;
try {
int flags = member.getFlags();
if (Flags.isStatic(flags) && Flags.isFinal(flags)) {
return CONSTANT;
}
if (Flags.isEnum(flags)) {
return ENUM_INSTANCE;
}
IJavaElement parent = javaElement.getParent();
if (parent instanceof IType) {
if (Flags.isInterface(((IType) parent).getFlags())) {
return CONSTANT;
}
}
} catch (JavaModelException e) {
// IGNORE
}
return FIELD;
case IJavaElement.LOCAL_VARIABLE:
return LOCAL_VARIABLE;
case IJavaElement.METHOD:
return METHOD;
case IJavaElement.PACKAGE_DECLARATION:
return PACKAGE_DECLARATION;
case IJavaElement.TYPE:
IType type = (IType) javaElement;
try {
if (type.isEnum()) {
return ENUM_TYPE;
}
} catch (JavaModelException e) {
// IGNORE
}
return TYPE;
default:
return null;
}
}
|
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ComponentCore.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ComponentCore.java
index 0d78364b..fed3df0a 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ComponentCore.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ComponentCore.java
@@ -1,88 +1,88 @@
/*******************************************************************************
* Copyright (c) 2003, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.common.componentcore;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.internal.resources.Workspace;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.wst.common.componentcore.internal.ComponentResource;
import org.eclipse.wst.common.componentcore.internal.ModulecorePlugin;
import org.eclipse.wst.common.componentcore.internal.StructureEdit;
import org.eclipse.wst.common.componentcore.internal.resources.FlexibleProject;
import org.eclipse.wst.common.componentcore.internal.resources.VirtualComponent;
import org.eclipse.wst.common.componentcore.internal.resources.VirtualFile;
import org.eclipse.wst.common.componentcore.internal.resources.VirtualFolder;
import org.eclipse.wst.common.componentcore.internal.resources.VirtualReference;
import org.eclipse.wst.common.componentcore.internal.resources.VirtualResource;
import org.eclipse.wst.common.componentcore.resources.IFlexibleProject;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualContainer;
import org.eclipse.wst.common.componentcore.resources.IVirtualFile;
import org.eclipse.wst.common.componentcore.resources.IVirtualFolder;
import org.eclipse.wst.common.componentcore.resources.IVirtualReference;
import org.eclipse.wst.common.componentcore.resources.IVirtualResource;
import org.eclipse.wst.common.frameworks.internal.enablement.nonui.WorkbenchUtil;
public class ComponentCore {
private static final IVirtualResource[] NO_RESOURCES = new VirtualResource[0];
public static IFlexibleProject createFlexibleProject(IProject aProject) {
return new FlexibleProject(aProject);
}
public static IVirtualComponent createComponent(IProject aProject, String aComponentName) {
return new VirtualComponent(aProject, aComponentName, new Path("/")); //$NON-NLS-1$
}
public static IVirtualFolder createFolder(IProject aProject, String aComponentName, IPath aRuntimePath) {
return new VirtualFolder(aProject, aComponentName, aRuntimePath);
}
public static IVirtualFile createFile(IProject aProject, String aComponentName, IPath aRuntimePath) {
return new VirtualFile(aProject, aComponentName, aRuntimePath);
}
public static IVirtualReference createReference(IVirtualComponent aComponent, IVirtualComponent aReferencedComponent) {
return new VirtualReference(aComponent, aReferencedComponent);
}
public static IVirtualResource[] createResources(IResource aResource) {
IProject proj = aResource.getProject();
StructureEdit se = null;
List foundResources = new ArrayList();
try {
se = StructureEdit.getStructureEditForRead(proj);
- ComponentResource[] resources = se.findResourcesBySourcePath(aResource.getFullPath());
+ ComponentResource[] resources = se.findResourcesBySourcePath(aResource.getProjectRelativePath());
for (int i = 0; i < resources.length; i++) {
if (aResource.getType() == IResource.FILE)
foundResources.add(new VirtualFile(proj,resources[i].getComponent().getName(), resources[i].getRuntimePath()));
else
foundResources.add(new VirtualFolder(proj,resources[i].getComponent().getName(), resources[i].getRuntimePath()));
}
}
catch (UnresolveableURIException e) {
e.printStackTrace();
}
finally {
se.dispose();
}
if (foundResources.size() > 0)
return (IVirtualResource[]) foundResources.toArray(new VirtualResource[foundResources.size()]);
return NO_RESOURCES;
}
}
| true | true | public static IVirtualResource[] createResources(IResource aResource) {
IProject proj = aResource.getProject();
StructureEdit se = null;
List foundResources = new ArrayList();
try {
se = StructureEdit.getStructureEditForRead(proj);
ComponentResource[] resources = se.findResourcesBySourcePath(aResource.getFullPath());
for (int i = 0; i < resources.length; i++) {
if (aResource.getType() == IResource.FILE)
foundResources.add(new VirtualFile(proj,resources[i].getComponent().getName(), resources[i].getRuntimePath()));
else
foundResources.add(new VirtualFolder(proj,resources[i].getComponent().getName(), resources[i].getRuntimePath()));
}
}
catch (UnresolveableURIException e) {
e.printStackTrace();
}
finally {
se.dispose();
}
if (foundResources.size() > 0)
return (IVirtualResource[]) foundResources.toArray(new VirtualResource[foundResources.size()]);
return NO_RESOURCES;
}
| public static IVirtualResource[] createResources(IResource aResource) {
IProject proj = aResource.getProject();
StructureEdit se = null;
List foundResources = new ArrayList();
try {
se = StructureEdit.getStructureEditForRead(proj);
ComponentResource[] resources = se.findResourcesBySourcePath(aResource.getProjectRelativePath());
for (int i = 0; i < resources.length; i++) {
if (aResource.getType() == IResource.FILE)
foundResources.add(new VirtualFile(proj,resources[i].getComponent().getName(), resources[i].getRuntimePath()));
else
foundResources.add(new VirtualFolder(proj,resources[i].getComponent().getName(), resources[i].getRuntimePath()));
}
}
catch (UnresolveableURIException e) {
e.printStackTrace();
}
finally {
se.dispose();
}
if (foundResources.size() > 0)
return (IVirtualResource[]) foundResources.toArray(new VirtualResource[foundResources.size()]);
return NO_RESOURCES;
}
|
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/sync/CommitMergeAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/sync/CommitMergeAction.java
index b1dcbea08..29f67d26f 100644
--- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/sync/CommitMergeAction.java
+++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/sync/CommitMergeAction.java
@@ -1,146 +1,150 @@
package org.eclipse.team.internal.ccvs.ui.sync;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.List;
import org.eclipse.compare.structuremergeviewer.Differencer;
import org.eclipse.compare.structuremergeviewer.IDiffElement;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.team.ccvs.core.CVSTeamProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.TeamPlugin;
import org.eclipse.team.core.sync.IRemoteSyncElement;
import org.eclipse.team.internal.ccvs.ui.CVSUIPlugin;
import org.eclipse.team.internal.ccvs.ui.Policy;
import org.eclipse.team.internal.ccvs.ui.RepositoryManager;
import org.eclipse.team.ui.sync.ChangedTeamContainer;
import org.eclipse.team.ui.sync.ITeamNode;
import org.eclipse.team.ui.sync.SyncSet;
import org.eclipse.team.ui.sync.TeamFile;
import org.eclipse.team.ui.sync.UnchangedTeamContainer;
public class CommitMergeAction extends MergeAction {
public CommitMergeAction(CVSSyncCompareInput model, ISelectionProvider sp, int direction, String label, Shell shell) {
super(model, sp, direction, label, shell);
}
protected SyncSet run(SyncSet syncSet, IProgressMonitor monitor) {
// If there is a conflict in the syncSet, we need to prompt the user before proceeding.
if (syncSet.hasConflicts()) {
String[] buttons = new String[] {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL};
String question = Policy.bind("CommitMergeAction.questionRelease");
String title = Policy.bind("CommitMergeAction.titleRelease");
String[] tips = new String[] {
Policy.bind("CommitMergeAction.releaseAll"),
Policy.bind("CommitMergeAction.releasePart"),
Policy.bind("CommitMergeAction.cancelRelease")
};
Shell shell = getShell();
final ToolTipMessageDialog dialog = new ToolTipMessageDialog(shell, title, null, question, MessageDialog.QUESTION, buttons, tips, 0);
shell.getDisplay().syncExec(new Runnable() {
public void run() {
dialog.open();
}
});
switch (dialog.getReturnCode()) {
case 0:
// Yes, synchronize conflicts as well
break;
case 1:
// No, only synchronize non-conflicting changes.
syncSet.removeConflictingNodes();
break;
case 2:
default:
// Cancel
return null;
}
}
ITeamNode[] changed = syncSet.getChangedNodes();
IResource[] changedResources = new IResource[changed.length];
List additions = new ArrayList();
List deletions = new ArrayList();
List conflicts = new ArrayList();
for (int i = 0; i < changed.length; i++) {
changedResources[i] = changed[i].getResource();
// If it's an outgoing addition we need to 'add' it before comitting.
// If it's an outgoing deletion we need to 'delete' it before committing.
switch (changed[i].getKind() & Differencer.CHANGE_TYPE_MASK) {
case Differencer.ADDITION:
additions.add(changed[i].getResource());
break;
case Differencer.DELETION:
deletions.add(changed[i].getResource());
break;
}
// If it's a conflicting change we need to mark it as merged before committing.
if ((changed[i].getKind() & Differencer.DIRECTION_MASK) == Differencer.CONFLICTING) {
if (changed[i] instanceof TeamFile) {
conflicts.add(((TeamFile)changed[i]).getMergeResource().getSyncElement());
}
}
}
try {
RepositoryManager manager = CVSUIPlugin.getPlugin().getRepositoryManager();
String comment = manager.promptForComment(getShell());
if (comment == null) {
// User cancelled. Remove the nodes from the sync set.
return null;
} else {
if (additions.size() != 0) {
manager.add((IResource[])additions.toArray(new IResource[0]), monitor);
}
if (deletions.size() != 0) {
manager.delete((IResource[])deletions.toArray(new IResource[0]), monitor);
}
if (conflicts.size() != 0) {
manager.merged((IRemoteSyncElement[])conflicts.toArray(new IRemoteSyncElement[0]));
}
manager.commit(changedResources, comment, getShell(), monitor);
}
- } catch (TeamException e) {
- ErrorDialog.openError(getShell(), null, null, e.getStatus());
+ } catch (final TeamException e) {
+ getShell().getDisplay().syncExec(new Runnable() {
+ public void run() {
+ ErrorDialog.openError(getShell(), null, null, e.getStatus());
+ }
+ });
return null;
}
return syncSet;
}
protected boolean isEnabled(ITeamNode node) {
int kind = node.getKind();
if (node instanceof TeamFile) {
int direction = kind & Differencer.DIRECTION_MASK;
if (direction == ITeamNode.OUTGOING || direction == Differencer.CONFLICTING) {
return true;
}
//allow to release over incoming deletions
return (kind & Differencer.CHANGE_TYPE_MASK) == Differencer.DELETION;
}
if (node instanceof ChangedTeamContainer) {
if ((kind & Differencer.DIRECTION_MASK) == ITeamNode.OUTGOING) {
return true;
}
// Fall through to UnchangedTeamContainer code
}
if (node instanceof UnchangedTeamContainer) {
IDiffElement[] children = ((UnchangedTeamContainer)node).getChildren();
for (int i = 0; i < children.length; i++) {
ITeamNode child = (ITeamNode)children[i];
if (isEnabled(child)) {
return true;
}
}
return false;
}
return false;
}
}
| true | true | protected SyncSet run(SyncSet syncSet, IProgressMonitor monitor) {
// If there is a conflict in the syncSet, we need to prompt the user before proceeding.
if (syncSet.hasConflicts()) {
String[] buttons = new String[] {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL};
String question = Policy.bind("CommitMergeAction.questionRelease");
String title = Policy.bind("CommitMergeAction.titleRelease");
String[] tips = new String[] {
Policy.bind("CommitMergeAction.releaseAll"),
Policy.bind("CommitMergeAction.releasePart"),
Policy.bind("CommitMergeAction.cancelRelease")
};
Shell shell = getShell();
final ToolTipMessageDialog dialog = new ToolTipMessageDialog(shell, title, null, question, MessageDialog.QUESTION, buttons, tips, 0);
shell.getDisplay().syncExec(new Runnable() {
public void run() {
dialog.open();
}
});
switch (dialog.getReturnCode()) {
case 0:
// Yes, synchronize conflicts as well
break;
case 1:
// No, only synchronize non-conflicting changes.
syncSet.removeConflictingNodes();
break;
case 2:
default:
// Cancel
return null;
}
}
ITeamNode[] changed = syncSet.getChangedNodes();
IResource[] changedResources = new IResource[changed.length];
List additions = new ArrayList();
List deletions = new ArrayList();
List conflicts = new ArrayList();
for (int i = 0; i < changed.length; i++) {
changedResources[i] = changed[i].getResource();
// If it's an outgoing addition we need to 'add' it before comitting.
// If it's an outgoing deletion we need to 'delete' it before committing.
switch (changed[i].getKind() & Differencer.CHANGE_TYPE_MASK) {
case Differencer.ADDITION:
additions.add(changed[i].getResource());
break;
case Differencer.DELETION:
deletions.add(changed[i].getResource());
break;
}
// If it's a conflicting change we need to mark it as merged before committing.
if ((changed[i].getKind() & Differencer.DIRECTION_MASK) == Differencer.CONFLICTING) {
if (changed[i] instanceof TeamFile) {
conflicts.add(((TeamFile)changed[i]).getMergeResource().getSyncElement());
}
}
}
try {
RepositoryManager manager = CVSUIPlugin.getPlugin().getRepositoryManager();
String comment = manager.promptForComment(getShell());
if (comment == null) {
// User cancelled. Remove the nodes from the sync set.
return null;
} else {
if (additions.size() != 0) {
manager.add((IResource[])additions.toArray(new IResource[0]), monitor);
}
if (deletions.size() != 0) {
manager.delete((IResource[])deletions.toArray(new IResource[0]), monitor);
}
if (conflicts.size() != 0) {
manager.merged((IRemoteSyncElement[])conflicts.toArray(new IRemoteSyncElement[0]));
}
manager.commit(changedResources, comment, getShell(), monitor);
}
} catch (TeamException e) {
ErrorDialog.openError(getShell(), null, null, e.getStatus());
return null;
}
return syncSet;
}
| protected SyncSet run(SyncSet syncSet, IProgressMonitor monitor) {
// If there is a conflict in the syncSet, we need to prompt the user before proceeding.
if (syncSet.hasConflicts()) {
String[] buttons = new String[] {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL};
String question = Policy.bind("CommitMergeAction.questionRelease");
String title = Policy.bind("CommitMergeAction.titleRelease");
String[] tips = new String[] {
Policy.bind("CommitMergeAction.releaseAll"),
Policy.bind("CommitMergeAction.releasePart"),
Policy.bind("CommitMergeAction.cancelRelease")
};
Shell shell = getShell();
final ToolTipMessageDialog dialog = new ToolTipMessageDialog(shell, title, null, question, MessageDialog.QUESTION, buttons, tips, 0);
shell.getDisplay().syncExec(new Runnable() {
public void run() {
dialog.open();
}
});
switch (dialog.getReturnCode()) {
case 0:
// Yes, synchronize conflicts as well
break;
case 1:
// No, only synchronize non-conflicting changes.
syncSet.removeConflictingNodes();
break;
case 2:
default:
// Cancel
return null;
}
}
ITeamNode[] changed = syncSet.getChangedNodes();
IResource[] changedResources = new IResource[changed.length];
List additions = new ArrayList();
List deletions = new ArrayList();
List conflicts = new ArrayList();
for (int i = 0; i < changed.length; i++) {
changedResources[i] = changed[i].getResource();
// If it's an outgoing addition we need to 'add' it before comitting.
// If it's an outgoing deletion we need to 'delete' it before committing.
switch (changed[i].getKind() & Differencer.CHANGE_TYPE_MASK) {
case Differencer.ADDITION:
additions.add(changed[i].getResource());
break;
case Differencer.DELETION:
deletions.add(changed[i].getResource());
break;
}
// If it's a conflicting change we need to mark it as merged before committing.
if ((changed[i].getKind() & Differencer.DIRECTION_MASK) == Differencer.CONFLICTING) {
if (changed[i] instanceof TeamFile) {
conflicts.add(((TeamFile)changed[i]).getMergeResource().getSyncElement());
}
}
}
try {
RepositoryManager manager = CVSUIPlugin.getPlugin().getRepositoryManager();
String comment = manager.promptForComment(getShell());
if (comment == null) {
// User cancelled. Remove the nodes from the sync set.
return null;
} else {
if (additions.size() != 0) {
manager.add((IResource[])additions.toArray(new IResource[0]), monitor);
}
if (deletions.size() != 0) {
manager.delete((IResource[])deletions.toArray(new IResource[0]), monitor);
}
if (conflicts.size() != 0) {
manager.merged((IRemoteSyncElement[])conflicts.toArray(new IRemoteSyncElement[0]));
}
manager.commit(changedResources, comment, getShell(), monitor);
}
} catch (final TeamException e) {
getShell().getDisplay().syncExec(new Runnable() {
public void run() {
ErrorDialog.openError(getShell(), null, null, e.getStatus());
}
});
return null;
}
return syncSet;
}
|
diff --git a/LanPlaylistServer/src/main/java/net/kokkeli/resources/authentication/AuthenticationInceptor.java b/LanPlaylistServer/src/main/java/net/kokkeli/resources/authentication/AuthenticationInceptor.java
index e2e2f2b..40ce085 100644
--- a/LanPlaylistServer/src/main/java/net/kokkeli/resources/authentication/AuthenticationInceptor.java
+++ b/LanPlaylistServer/src/main/java/net/kokkeli/resources/authentication/AuthenticationInceptor.java
@@ -1,84 +1,84 @@
package net.kokkeli.resources.authentication;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import net.kokkeli.ISettings;
import net.kokkeli.data.ILogger;
import net.kokkeli.data.LogSeverity;
import net.kokkeli.data.Logging;
import net.kokkeli.data.Role;
import net.kokkeli.data.db.NotFoundInDatabase;
import net.kokkeli.data.services.ISessionService;
import net.kokkeli.resources.Access;
import net.kokkeli.data.*;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import com.google.inject.Inject;
/**
* Authentication checker class
* @author Hekku2
*/
public class AuthenticationInceptor implements MethodInterceptor{
/**
* ILogger. This is protected for injecting.
*/
@Inject
protected ILogger logger;
/**
* ISessionService. This is proteced for injecting.
*/
@Inject
protected ISessionService sessions;
/**
* ISettings. This is protected for injecting
*/
@Inject
protected ISettings settings;
/**
* Creates authencation inceptor for catching Access-annotations
*/
public AuthenticationInceptor(){
}
/**
* This is invoked before method with Access-annotation is invoked.
*/
public Object invoke(MethodInvocation invocation) throws Throwable {
try {
ILogger logger = new Logging();
logger.log("Checking if all can access...", LogSeverity.TRACE);
Access access = AuthenticationUtils.extractRoleAnnotation(invocation.getMethod().getAnnotations());
//If no role is needed, continue proceeded without checking authentication
if (access.value() == Role.NONE){
return invocation.proceed();
}
logger.log("Checking authentication...", LogSeverity.TRACE);
HttpServletRequest request = AuthenticationUtils.extractRequest(invocation.getArguments());
Cookie authCookie = AuthenticationUtils.extractLoginCookie(request.getCookies());
Session session = sessions.get(authCookie.getValue());
logger.log("User authenticated: " + session.getUser().getUserName(), LogSeverity.TRACE);
return invocation.proceed();
} catch (NotFoundInDatabase e) {
logger.log("Old or invalid authentication." + e.getMessage(), LogSeverity.DEBUG);
return Response.seeOther(UriBuilder.fromUri(settings.getBaseURI()).path("/authentication").build()).build();
} catch (AuthenticationException e) {
- logger.log("There were no authenticaiton data: " + e.getMessage(), LogSeverity.DEBUG);
+ logger.log("There were no authentication data: " + e.getMessage(), LogSeverity.DEBUG);
return Response.seeOther(UriBuilder.fromUri(settings.getBaseURI()).path("/authentication").build()).build();
}
}
}
| true | true | public Object invoke(MethodInvocation invocation) throws Throwable {
try {
ILogger logger = new Logging();
logger.log("Checking if all can access...", LogSeverity.TRACE);
Access access = AuthenticationUtils.extractRoleAnnotation(invocation.getMethod().getAnnotations());
//If no role is needed, continue proceeded without checking authentication
if (access.value() == Role.NONE){
return invocation.proceed();
}
logger.log("Checking authentication...", LogSeverity.TRACE);
HttpServletRequest request = AuthenticationUtils.extractRequest(invocation.getArguments());
Cookie authCookie = AuthenticationUtils.extractLoginCookie(request.getCookies());
Session session = sessions.get(authCookie.getValue());
logger.log("User authenticated: " + session.getUser().getUserName(), LogSeverity.TRACE);
return invocation.proceed();
} catch (NotFoundInDatabase e) {
logger.log("Old or invalid authentication." + e.getMessage(), LogSeverity.DEBUG);
return Response.seeOther(UriBuilder.fromUri(settings.getBaseURI()).path("/authentication").build()).build();
} catch (AuthenticationException e) {
logger.log("There were no authenticaiton data: " + e.getMessage(), LogSeverity.DEBUG);
return Response.seeOther(UriBuilder.fromUri(settings.getBaseURI()).path("/authentication").build()).build();
}
}
| public Object invoke(MethodInvocation invocation) throws Throwable {
try {
ILogger logger = new Logging();
logger.log("Checking if all can access...", LogSeverity.TRACE);
Access access = AuthenticationUtils.extractRoleAnnotation(invocation.getMethod().getAnnotations());
//If no role is needed, continue proceeded without checking authentication
if (access.value() == Role.NONE){
return invocation.proceed();
}
logger.log("Checking authentication...", LogSeverity.TRACE);
HttpServletRequest request = AuthenticationUtils.extractRequest(invocation.getArguments());
Cookie authCookie = AuthenticationUtils.extractLoginCookie(request.getCookies());
Session session = sessions.get(authCookie.getValue());
logger.log("User authenticated: " + session.getUser().getUserName(), LogSeverity.TRACE);
return invocation.proceed();
} catch (NotFoundInDatabase e) {
logger.log("Old or invalid authentication." + e.getMessage(), LogSeverity.DEBUG);
return Response.seeOther(UriBuilder.fromUri(settings.getBaseURI()).path("/authentication").build()).build();
} catch (AuthenticationException e) {
logger.log("There were no authentication data: " + e.getMessage(), LogSeverity.DEBUG);
return Response.seeOther(UriBuilder.fromUri(settings.getBaseURI()).path("/authentication").build()).build();
}
}
|
diff --git a/update.java b/update.java
index 8555410..d51be86 100644
--- a/update.java
+++ b/update.java
@@ -1,697 +1,698 @@
// Copyright (c) 1999-2004 Brian Wellington ([email protected])
import java.net.*;
import java.io.*;
import java.util.*;
import org.xbill.DNS.*;
import org.xbill.DNS.utils.*;
/** @author Brian Wellington <[email protected]> */
public class update {
Message query, response;
Resolver res;
String server = null;
Name zone = Name.root;
long defaultTTL;
int defaultClass = DClass.IN;
PrintStream log = null;
void
print(Object o) {
System.out.println(o);
if (log != null)
log.println(o);
}
public
update(InputStream in) throws IOException {
List inputs = new LinkedList();
List istreams = new LinkedList();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
inputs.add(br);
istreams.add(in);
while (true) {
try {
String line = null;
do {
InputStream is;
is = (InputStream)istreams.get(0);
br = (BufferedReader)inputs.get(0);
if (is == System.in)
System.out.print("> ");
line = br.readLine();
if (line == null) {
br.close();
inputs.remove(0);
istreams.remove(0);
if (inputs.isEmpty())
return;
}
} while (line == null);
if (log != null)
log.println("> " + line);
if (line.length() == 0 || line.charAt(0) == '#')
continue;
/* Allows cut and paste from other update sessions */
if (line.charAt(0) == '>')
line = line.substring(1);
Tokenizer st = new Tokenizer(line);
Tokenizer.Token token = st.get();
if (token.isEOL())
continue;
String operation = token.value;
if (operation.equals("server")) {
server = st.getString();
res = new SimpleResolver(server);
token = st.get();
if (token.isString()) {
String portstr = token.value;
res.setPort(Short.parseShort(portstr));
}
}
else if (operation.equals("key")) {
String keyname = st.getString();
String keydata = st.getString();
if (res == null)
res = new SimpleResolver(server);
res.setTSIGKey(keyname, keydata);
}
else if (operation.equals("edns")) {
if (res == null)
res = new SimpleResolver(server);
res.setEDNS(st.getUInt16());
}
else if (operation.equals("port")) {
if (res == null)
res = new SimpleResolver(server);
res.setPort(st.getUInt16());
}
else if (operation.equals("tcp")) {
if (res == null)
res = new SimpleResolver(server);
res.setTCP(true);
}
else if (operation.equals("class")) {
- int newClass = DClass.value(st.getString());
+ String classStr = st.getString();
+ int newClass = DClass.value(classStr);
if (newClass > 0)
defaultClass = newClass;
else
- print("Invalid class " + newClass);
+ print("Invalid class " + classStr);
}
else if (operation.equals("ttl"))
defaultTTL = st.getTTL();
else if (operation.equals("origin") ||
operation.equals("zone"))
{
zone = st.getName(Name.root);
}
else if (operation.equals("require"))
doRequire(st);
else if (operation.equals("prohibit"))
doProhibit(st);
else if (operation.equals("add"))
doAdd(st);
else if (operation.equals("delete"))
doDelete(st);
else if (operation.equals("glue"))
doGlue(st);
else if (operation.equals("help") ||
operation.equals("?"))
{
token = st.get();
if (token.isString())
help(token.value);
else
help(null);
}
else if (operation.equals("echo"))
print(line.substring(4).trim());
else if (operation.equals("send")) {
sendUpdate();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("show")) {
print(query);
}
else if (operation.equals("clear")) {
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("query"))
doQuery(st);
else if (operation.equals("quit") ||
operation.equals("q"))
{
if (log != null)
log.close();
Iterator it = inputs.iterator();
while (it.hasNext()) {
BufferedReader tbr;
tbr = (BufferedReader) it.next();
tbr.close();
}
System.exit(0);
}
else if (operation.equals("file"))
doFile(st, inputs, istreams);
else if (operation.equals("log"))
doLog(st);
else if (operation.equals("assert")) {
if (doAssert(st) == false)
return;
}
else if (operation.equals("sleep")) {
long interval = st.getUInt32();
try {
Thread.sleep(interval);
}
catch (InterruptedException e) {
}
}
else if (operation.equals("date")) {
Date now = new Date();
token = st.get();
if (token.isString() &&
token.value.equals("-ms"))
print(Long.toString(now.getTime()));
else
print(now);
}
else
print("invalid keyword: " + operation);
}
catch (TextParseException tpe) {
System.out.println(tpe.getMessage());
}
catch (NullPointerException npe) {
System.out.println("Parse error");
}
catch (InterruptedIOException iioe) {
System.out.println("Operation timed out");
}
catch (SocketException se) {
System.out.println("Socket error");
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}
void
sendUpdate() throws IOException {
if (query.getHeader().getCount(Section.UPDATE) == 0) {
print("Empty update message. Ignoring.");
return;
}
if (query.getHeader().getCount(Section.ZONE) == 0) {
Name updzone;
updzone = zone;
int dclass = defaultClass;
if (updzone == null) {
Record [] recs = query.getSectionArray(Section.UPDATE);
for (int i = 0; i < recs.length; i++) {
if (updzone == null)
updzone = new Name(recs[i].getName(),
1);
if (recs[i].getDClass() != DClass.NONE &&
recs[i].getDClass() != DClass.ANY)
{
dclass = recs[i].getDClass();
break;
}
}
}
Record soa = Record.newRecord(updzone, Type.SOA, dclass);
query.addRecord(soa, Section.ZONE);
}
if (res == null)
res = new SimpleResolver(server);
response = res.send(query);
print(response);
}
/*
* <name> [ttl] [class] <type> <data>
* Ignore the class, if present.
*/
Record
parseRR(Tokenizer st, int classValue, long TTLValue)
throws IOException
{
Name name = st.getName(zone);
long ttl;
int type;
Record record;
String s = st.getString();
try {
ttl = TTL.parseTTL(s);
s = st.getString();
}
catch (NumberFormatException e) {
ttl = TTLValue;
}
if (DClass.value(s) >= 0) {
classValue = DClass.value(s);
s = st.getString();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
record = Record.fromString(name, type, classValue, ttl, st, zone);
if (record != null)
return (record);
else
throw new IOException("Parse error");
}
void
doRequire(Tokenizer st) throws IOException {
Tokenizer.Token token;
Name name;
Record record;
int type;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
if ((type = Type.value(token.value)) < 0)
throw new IOException("Invalid type: " + token.value);
token = st.get();
boolean iseol = token.isEOL();
st.unget();
if (!iseol) {
record = Record.fromString(name, type, defaultClass,
0, st, zone);
} else
record = Record.newRecord(name, type,
DClass.ANY, 0);
} else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doProhibit(Tokenizer st) throws IOException {
Tokenizer.Token token;
String s;
Name name;
Record record;
int type;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
if ((type = Type.value(token.value)) < 0)
throw new IOException("Invalid type: " + token.value);
} else
type = Type.ANY;
record = Record.newRecord(name, type, DClass.NONE, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doAdd(Tokenizer st) throws IOException {
Record record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doDelete(Tokenizer st) throws IOException {
Tokenizer.Token token;
String s;
Name name;
Record record;
int type;
int dclass;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
s = token.value;
if ((dclass = DClass.value(s)) >= 0) {
s = st.getString();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
token = st.get();
boolean iseol = token.isEOL();
st.unget();
if (!iseol) {
record = Record.fromString(name, type, DClass.NONE,
0, st, zone);
} else
record = Record.newRecord(name, type, DClass.ANY, 0);
}
else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doGlue(Tokenizer st) throws IOException {
Record record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.ADDITIONAL);
print(record);
}
void
doQuery(Tokenizer st) throws IOException {
Record rec;
Tokenizer.Token token;
Name name = null;
int type = Type.A;
int dclass = defaultClass;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
type = Type.value(token.value);
if (type < 0)
throw new IOException("Invalid type");
token = st.get();
if (token.isString()) {
dclass = DClass.value(token.value);
if (dclass < 0)
throw new IOException("Invalid class");
}
}
rec = Record.newRecord(name, type, dclass);
Message newQuery = Message.newQuery(rec);
if (res == null)
res = new SimpleResolver(server);
response = res.send(newQuery);
print(response);
}
void
doFile(Tokenizer st, List inputs, List istreams) throws IOException {
String s = st.getString();
InputStream is;
try {
if (s.equals("-"))
is = System.in;
else
is = new FileInputStream(s);
istreams.add(0, is);
inputs.add(new BufferedReader(new InputStreamReader(is)));
}
catch (FileNotFoundException e) {
print(s + " not found");
}
}
void
doLog(Tokenizer st) throws IOException {
String s = st.getString();
try {
FileOutputStream fos = new FileOutputStream(s);
log = new PrintStream(fos);
}
catch (Exception e) {
print("Error opening " + s);
}
}
boolean
doAssert(Tokenizer st) throws IOException {
String field = st.getString();
String expected = st.getString();
String value = null;
boolean flag = true;
int section;
if (response == null) {
print("No response has been received");
return true;
}
if (field.equalsIgnoreCase("rcode")) {
short rcode = response.getHeader().getRcode();
if (rcode != Rcode.value(expected)) {
value = Rcode.string(rcode);
flag = false;
}
}
else if (field.equalsIgnoreCase("serial")) {
Record [] answers = response.getSectionArray(Section.ANSWER);
if (answers.length < 1 || !(answers[0] instanceof SOARecord))
print("Invalid response (no SOA)");
else {
SOARecord soa = (SOARecord) answers[0];
long serial = soa.getSerial();
if (serial != Long.parseLong(expected)) {
value = Long.toString(serial);
flag = false;
}
}
}
else if (field.equalsIgnoreCase("tsig")) {
if (response.isSigned()) {
if (response.isVerified())
value = "ok";
else
value = "failed";
}
else
value = "unsigned";
if (!value.equalsIgnoreCase(expected))
flag = false;
}
else if ((section = Section.value(field)) >= 0) {
int count = response.getHeader().getCount(section);
if (count != Integer.parseInt(expected)) {
value = new Integer(count).toString();
flag = false;
}
}
else
print("Invalid assertion keyword: " + field);
if (flag == false) {
print("Expected " + field + " " + expected +
", received " + value);
while (true) {
Tokenizer.Token token = st.get();
if (!token.isString())
break;
print(token.value);
}
st.unget();
}
return flag;
}
static void
help(String topic) {
System.out.println();
if (topic == null)
System.out.println("The following are supported commands:\n" +
"add assert class clear date delete\n" +
"echo file glue help log key\n" +
"edns origin port prohibit query quit\n" +
"require send server show sleep tcp\n" +
"ttl zone #\n");
else if (topic.equalsIgnoreCase("add"))
System.out.println(
"add <name> [ttl] [class] <type> <data>\n\n" +
"specify a record to be added\n");
else if (topic.equalsIgnoreCase("assert"))
System.out.println(
"assert <field> <value> [msg]\n\n" +
"asserts that the value of the field in the last\n" +
"response matches the value specified. If not,\n" +
"the message is printed (if present) and the\n" +
"program exits. The field may be any of <rcode>,\n" +
"<serial>, <tsig>, <qu>, <an>, <au>, or <ad>.\n");
else if (topic.equalsIgnoreCase("class"))
System.out.println(
"class <class>\n\n" +
"class of the zone to be updated (default: IN)\n");
else if (topic.equalsIgnoreCase("clear"))
System.out.println(
"clear\n\n" +
"clears the current update packet\n");
else if (topic.equalsIgnoreCase("date"))
System.out.println(
"date [-ms]\n\n" +
"prints the current date and time in human readable\n" +
"format or as the number of milliseconds since the\n" +
"epoch");
else if (topic.equalsIgnoreCase("delete"))
System.out.println(
"delete <name> [ttl] [class] <type> <data> \n" +
"delete <name> <type> \n" +
"delete <name>\n\n" +
"specify a record or set to be deleted, or that\n" +
"all records at a name should be deleted\n");
else if (topic.equalsIgnoreCase("echo"))
System.out.println(
"echo <text>\n\n" +
"prints the text\n");
else if (topic.equalsIgnoreCase("file"))
System.out.println(
"file <file>\n\n" +
"opens the specified file as the new input source\n" +
"(- represents stdin)\n");
else if (topic.equalsIgnoreCase("glue"))
System.out.println(
"glue <name> [ttl] [class] <type> <data>\n\n" +
"specify an additional record\n");
else if (topic.equalsIgnoreCase("help"))
System.out.println(
"?/help\n" +
"help [topic]\n\n" +
"prints a list of commands or help about a specific\n" +
"command\n");
else if (topic.equalsIgnoreCase("log"))
System.out.println(
"log <file>\n\n" +
"opens the specified file and uses it to log output\n");
else if (topic.equalsIgnoreCase("key"))
System.out.println(
"key <name> <data>\n\n" +
"TSIG key used to sign messages\n");
else if (topic.equalsIgnoreCase("edns"))
System.out.println(
"edns <level>\n\n" +
"EDNS level specified when sending messages\n");
else if (topic.equalsIgnoreCase("origin"))
System.out.println(
"origin <origin>\n\n" +
"<same as zone>\n");
else if (topic.equalsIgnoreCase("port"))
System.out.println(
"port <port>\n\n" +
"UDP/TCP port messages are sent to (default: 53)\n");
else if (topic.equalsIgnoreCase("prohibit"))
System.out.println(
"prohibit <name> <type> \n" +
"prohibit <name>\n\n" +
"require that a set or name is not present\n");
else if (topic.equalsIgnoreCase("query"))
System.out.println(
"query <name> [type [class]] \n\n" +
"issues a query\n");
else if (topic.equalsIgnoreCase("q") ||
topic.equalsIgnoreCase("quit"))
System.out.println(
"q/quit\n\n" +
"quits the program\n");
else if (topic.equalsIgnoreCase("require"))
System.out.println(
"require <name> [ttl] [class] <type> <data> \n" +
"require <name> <type> \n" +
"require <name>\n\n" +
"require that a record, set, or name is present\n");
else if (topic.equalsIgnoreCase("send"))
System.out.println(
"send\n\n" +
"sends and resets the current update packet\n");
else if (topic.equalsIgnoreCase("server"))
System.out.println(
"server <name> [port]\n\n" +
"server that receives send updates/queries\n");
else if (topic.equalsIgnoreCase("show"))
System.out.println(
"show\n\n" +
"shows the current update packet\n");
else if (topic.equalsIgnoreCase("sleep"))
System.out.println(
"sleep <milliseconds>\n\n" +
"pause for interval before next command\n");
else if (topic.equalsIgnoreCase("tcp"))
System.out.println(
"tcp\n\n" +
"TCP should be used to send all messages\n");
else if (topic.equalsIgnoreCase("ttl"))
System.out.println(
"ttl <ttl>\n\n" +
"default ttl of added records (default: 0)\n");
else if (topic.equalsIgnoreCase("zone"))
System.out.println(
"zone <zone>\n\n" +
"zone to update (default: .\n");
else if (topic.equalsIgnoreCase("#"))
System.out.println(
"# <text>\n\n" +
"a comment\n");
else
System.out.println ("Topic '" + topic + "' unrecognized\n");
}
public static void
main(String args[]) throws IOException {
InputStream in = null;
if (args.length >= 1) {
try {
in = new FileInputStream(args[0]);
}
catch (FileNotFoundException e) {
System.out.println(args[0] + " not found.");
System.exit(1);
}
}
else
in = System.in;
update u = new update(in);
}
}
| false | true | update(InputStream in) throws IOException {
List inputs = new LinkedList();
List istreams = new LinkedList();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
inputs.add(br);
istreams.add(in);
while (true) {
try {
String line = null;
do {
InputStream is;
is = (InputStream)istreams.get(0);
br = (BufferedReader)inputs.get(0);
if (is == System.in)
System.out.print("> ");
line = br.readLine();
if (line == null) {
br.close();
inputs.remove(0);
istreams.remove(0);
if (inputs.isEmpty())
return;
}
} while (line == null);
if (log != null)
log.println("> " + line);
if (line.length() == 0 || line.charAt(0) == '#')
continue;
/* Allows cut and paste from other update sessions */
if (line.charAt(0) == '>')
line = line.substring(1);
Tokenizer st = new Tokenizer(line);
Tokenizer.Token token = st.get();
if (token.isEOL())
continue;
String operation = token.value;
if (operation.equals("server")) {
server = st.getString();
res = new SimpleResolver(server);
token = st.get();
if (token.isString()) {
String portstr = token.value;
res.setPort(Short.parseShort(portstr));
}
}
else if (operation.equals("key")) {
String keyname = st.getString();
String keydata = st.getString();
if (res == null)
res = new SimpleResolver(server);
res.setTSIGKey(keyname, keydata);
}
else if (operation.equals("edns")) {
if (res == null)
res = new SimpleResolver(server);
res.setEDNS(st.getUInt16());
}
else if (operation.equals("port")) {
if (res == null)
res = new SimpleResolver(server);
res.setPort(st.getUInt16());
}
else if (operation.equals("tcp")) {
if (res == null)
res = new SimpleResolver(server);
res.setTCP(true);
}
else if (operation.equals("class")) {
int newClass = DClass.value(st.getString());
if (newClass > 0)
defaultClass = newClass;
else
print("Invalid class " + newClass);
}
else if (operation.equals("ttl"))
defaultTTL = st.getTTL();
else if (operation.equals("origin") ||
operation.equals("zone"))
{
zone = st.getName(Name.root);
}
else if (operation.equals("require"))
doRequire(st);
else if (operation.equals("prohibit"))
doProhibit(st);
else if (operation.equals("add"))
doAdd(st);
else if (operation.equals("delete"))
doDelete(st);
else if (operation.equals("glue"))
doGlue(st);
else if (operation.equals("help") ||
operation.equals("?"))
{
token = st.get();
if (token.isString())
help(token.value);
else
help(null);
}
else if (operation.equals("echo"))
print(line.substring(4).trim());
else if (operation.equals("send")) {
sendUpdate();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("show")) {
print(query);
}
else if (operation.equals("clear")) {
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("query"))
doQuery(st);
else if (operation.equals("quit") ||
operation.equals("q"))
{
if (log != null)
log.close();
Iterator it = inputs.iterator();
while (it.hasNext()) {
BufferedReader tbr;
tbr = (BufferedReader) it.next();
tbr.close();
}
System.exit(0);
}
else if (operation.equals("file"))
doFile(st, inputs, istreams);
else if (operation.equals("log"))
doLog(st);
else if (operation.equals("assert")) {
if (doAssert(st) == false)
return;
}
else if (operation.equals("sleep")) {
long interval = st.getUInt32();
try {
Thread.sleep(interval);
}
catch (InterruptedException e) {
}
}
else if (operation.equals("date")) {
Date now = new Date();
token = st.get();
if (token.isString() &&
token.value.equals("-ms"))
print(Long.toString(now.getTime()));
else
print(now);
}
else
print("invalid keyword: " + operation);
}
catch (TextParseException tpe) {
System.out.println(tpe.getMessage());
}
catch (NullPointerException npe) {
System.out.println("Parse error");
}
catch (InterruptedIOException iioe) {
System.out.println("Operation timed out");
}
catch (SocketException se) {
System.out.println("Socket error");
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}
| update(InputStream in) throws IOException {
List inputs = new LinkedList();
List istreams = new LinkedList();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
inputs.add(br);
istreams.add(in);
while (true) {
try {
String line = null;
do {
InputStream is;
is = (InputStream)istreams.get(0);
br = (BufferedReader)inputs.get(0);
if (is == System.in)
System.out.print("> ");
line = br.readLine();
if (line == null) {
br.close();
inputs.remove(0);
istreams.remove(0);
if (inputs.isEmpty())
return;
}
} while (line == null);
if (log != null)
log.println("> " + line);
if (line.length() == 0 || line.charAt(0) == '#')
continue;
/* Allows cut and paste from other update sessions */
if (line.charAt(0) == '>')
line = line.substring(1);
Tokenizer st = new Tokenizer(line);
Tokenizer.Token token = st.get();
if (token.isEOL())
continue;
String operation = token.value;
if (operation.equals("server")) {
server = st.getString();
res = new SimpleResolver(server);
token = st.get();
if (token.isString()) {
String portstr = token.value;
res.setPort(Short.parseShort(portstr));
}
}
else if (operation.equals("key")) {
String keyname = st.getString();
String keydata = st.getString();
if (res == null)
res = new SimpleResolver(server);
res.setTSIGKey(keyname, keydata);
}
else if (operation.equals("edns")) {
if (res == null)
res = new SimpleResolver(server);
res.setEDNS(st.getUInt16());
}
else if (operation.equals("port")) {
if (res == null)
res = new SimpleResolver(server);
res.setPort(st.getUInt16());
}
else if (operation.equals("tcp")) {
if (res == null)
res = new SimpleResolver(server);
res.setTCP(true);
}
else if (operation.equals("class")) {
String classStr = st.getString();
int newClass = DClass.value(classStr);
if (newClass > 0)
defaultClass = newClass;
else
print("Invalid class " + classStr);
}
else if (operation.equals("ttl"))
defaultTTL = st.getTTL();
else if (operation.equals("origin") ||
operation.equals("zone"))
{
zone = st.getName(Name.root);
}
else if (operation.equals("require"))
doRequire(st);
else if (operation.equals("prohibit"))
doProhibit(st);
else if (operation.equals("add"))
doAdd(st);
else if (operation.equals("delete"))
doDelete(st);
else if (operation.equals("glue"))
doGlue(st);
else if (operation.equals("help") ||
operation.equals("?"))
{
token = st.get();
if (token.isString())
help(token.value);
else
help(null);
}
else if (operation.equals("echo"))
print(line.substring(4).trim());
else if (operation.equals("send")) {
sendUpdate();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("show")) {
print(query);
}
else if (operation.equals("clear")) {
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("query"))
doQuery(st);
else if (operation.equals("quit") ||
operation.equals("q"))
{
if (log != null)
log.close();
Iterator it = inputs.iterator();
while (it.hasNext()) {
BufferedReader tbr;
tbr = (BufferedReader) it.next();
tbr.close();
}
System.exit(0);
}
else if (operation.equals("file"))
doFile(st, inputs, istreams);
else if (operation.equals("log"))
doLog(st);
else if (operation.equals("assert")) {
if (doAssert(st) == false)
return;
}
else if (operation.equals("sleep")) {
long interval = st.getUInt32();
try {
Thread.sleep(interval);
}
catch (InterruptedException e) {
}
}
else if (operation.equals("date")) {
Date now = new Date();
token = st.get();
if (token.isString() &&
token.value.equals("-ms"))
print(Long.toString(now.getTime()));
else
print(now);
}
else
print("invalid keyword: " + operation);
}
catch (TextParseException tpe) {
System.out.println(tpe.getMessage());
}
catch (NullPointerException npe) {
System.out.println("Parse error");
}
catch (InterruptedIOException iioe) {
System.out.println("Operation timed out");
}
catch (SocketException se) {
System.out.println("Socket error");
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}
|
diff --git a/com.piece_framework.makegood.ui/src/com/piece_framework/makegood/ui/views/ResultViewController.java b/com.piece_framework.makegood.ui/src/com/piece_framework/makegood/ui/views/ResultViewController.java
index 9f98fc51..e73dec0e 100644
--- a/com.piece_framework.makegood.ui/src/com/piece_framework/makegood/ui/views/ResultViewController.java
+++ b/com.piece_framework.makegood.ui/src/com/piece_framework/makegood/ui/views/ResultViewController.java
@@ -1,245 +1,245 @@
/**
* Copyright (c) 2009-2010 MATSUFUJI Hideharu <[email protected]>,
* 2010-2011 KUBO Atsuhiro <[email protected]>,
* All rights reserved.
*
* This file is part of MakeGood.
*
* 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 com.piece_framework.makegood.ui.views;
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.core.runtime.jobs.Job;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.IDebugEventSetListener;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.internal.ui.views.console.ProcessConsole;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.php.internal.debug.core.model.IPHPDebugTarget;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IOConsoleOutputStream;
import org.eclipse.ui.progress.UIJob;
import com.piece_framework.makegood.core.result.TestCaseResult;
import com.piece_framework.makegood.core.result.TestSuiteResult;
import com.piece_framework.makegood.core.run.JUnitXMLReaderListener;
import com.piece_framework.makegood.launch.MakeGoodLaunch;
import com.piece_framework.makegood.launch.TestLifecycle;
import com.piece_framework.makegood.ui.Activator;
import com.piece_framework.makegood.ui.actions.StopTestAction;
import com.piece_framework.makegood.ui.launch.TestRunner;
public class ResultViewController implements IDebugEventSetListener {
/**
* @since 1.2.0
*/
private TestLifecycle testLifecycle;
@Override
public void handleDebugEvents(DebugEvent[] events) {
if (events == null) return;
int size = events.length;
for (int i = 0; i < size; ++i) {
final Object source = events[i].getSource();
ILaunch launch = getLaunch(source);
if (launch == null) continue;
if (!(launch instanceof MakeGoodLaunch)) continue;
if (events[i].getKind() == DebugEvent.CREATE) {
handleCreateEvent((MakeGoodLaunch) launch);
} else if (events[i].getKind() == DebugEvent.TERMINATE) {
handleTerminateEvent((MakeGoodLaunch) launch);
}
}
}
private void handleCreateEvent(final MakeGoodLaunch launch) {
synchronized (this) {
if (testLifecycle != null) return;
}
try {
synchronized (this) {
testLifecycle = new TestLifecycle(launch, new ResultJUnitXMLReaderListener());
}
} catch (CoreException e) {
Activator.getDefault().getLog().log(new Status(Status.WARNING, Activator.PLUGIN_ID, e.getMessage(), e));
return;
}
launch.activate();
testLifecycle.start();
preventConsoleViewFocusing();
Job job = new UIJob("MakeGood Test Start") { //$NON-NLS-1$
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
ResultView resultView = null;
resultView = (ResultView) ViewShow.show(ResultView.ID);
if (resultView == null) return Status.CANCEL_STATUS;
TestRunner.restoreFocusToLastActivePart();
resultView.reset();
resultView.startTest(testLifecycle.getProgress(), testLifecycle.getFailures());
return Status.OK_STATUS;
}
};
job.schedule();
}
private void handleTerminateEvent(final MakeGoodLaunch launch) {
synchronized (this) {
if (testLifecycle == null) return;
}
- if (testLifecycle.validateLaunchIdentity(launch)) return;
+ if (!testLifecycle.validateLaunchIdentity(launch)) return;
testLifecycle.end();
Job job = new UIJob("MakeGood Test End") { //$NON-NLS-1$
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
ResultView resultView = (ResultView) ViewShow.find(ResultView.ID);
if (resultView == null) {
launch.deactivate();
synchronized (ResultViewController.this) {
testLifecycle = null;
}
return Status.CANCEL_STATUS;
}
resultView.endTest();
if (testLifecycle.hasErrors()) {
resultView.markAsStopped();
if (!StopTestAction.isStoppedByAction(launch)) {
ViewShow.show(IConsoleConstants.ID_CONSOLE_VIEW);
}
}
launch.deactivate();
synchronized (ResultViewController.this) {
testLifecycle = null;
}
return Status.OK_STATUS;
}
};
job.schedule();
}
private void preventConsoleViewFocusing() {
for (IConsole console: ConsolePlugin.getDefault().getConsoleManager().getConsoles()) {
if (!(console instanceof ProcessConsole)) continue;
IOConsoleOutputStream stdoutStream = ((ProcessConsole) console).getStream(IDebugUIConstants.ID_STANDARD_OUTPUT_STREAM);
if (stdoutStream == null) continue;
stdoutStream.setActivateOnWrite(false);
IOConsoleOutputStream stderrStream = ((ProcessConsole) console).getStream(IDebugUIConstants.ID_STANDARD_ERROR_STREAM);
if (stderrStream == null) continue;
stderrStream.setActivateOnWrite(false);
}
}
private ILaunch getLaunch(Object eventSource) {
if (eventSource instanceof IPHPDebugTarget) {
return ((IPHPDebugTarget) eventSource).getLaunch();
} else if (eventSource instanceof IProcess) {
return ((IProcess) eventSource).getLaunch();
} else {
return null;
}
}
public class ResultJUnitXMLReaderListener implements JUnitXMLReaderListener {
@Override
public void startTestSuite(TestSuiteResult testSuite) {
testLifecycle.startTestSuite(testSuite);
if (testLifecycle.isProgressInitialized()) {
return;
}
testLifecycle.initializeProgress(testSuite);
Job job = new UIJob("MakeGood Result Tree Set") { //$NON-NLS-1$
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
ResultView resultView = (ResultView) ViewShow.find(ResultView.ID);
if (resultView == null) return Status.CANCEL_STATUS;
resultView.setTreeInput(testLifecycle.getResult());
return Status.OK_STATUS;
}
};
job.schedule();
}
@Override
public void endTestSuite() {}
@Override
public void startTestCase(final TestCaseResult testCase) {
testLifecycle.startTestCase(testCase);
Job job = new UIJob("MakeGood Test Case Start") { //$NON-NLS-1$
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
ResultView resultView = (ResultView) ViewShow.find(ResultView.ID);
if (resultView == null) return Status.CANCEL_STATUS;
resultView.printCurrentlyRunningTestCase(testLifecycle.getCurrentTestCase());
resultView.updateOnStartTestCase(testLifecycle.getCurrentTestCase());
return Status.OK_STATUS;
}
};
job.schedule();
try {
job.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void endTestCase() {
if (!testLifecycle.isProgressInitialized()) return;
testLifecycle.endTestCase();
Job job = new UIJob("MakeGood Test Case End") { //$NON-NLS-1$
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
ResultView resultView = (ResultView) ViewShow.find(ResultView.ID);
if (resultView == null) return Status.CANCEL_STATUS;
if (testLifecycle.hasFailures()) {
resultView.markAsFailed();
}
resultView.updateOnEndTestCase(testLifecycle.getCurrentTestCase());
return Status.OK_STATUS;
}
};
job.schedule();
}
@Override
public void startFailure(TestCaseResult failure) {
testLifecycle.startFailure(failure);
}
@Override
public void endFailure() {}
@Override
public void endTest() {
testLifecycle.endTest();
}
}
}
| true | true | private void handleTerminateEvent(final MakeGoodLaunch launch) {
synchronized (this) {
if (testLifecycle == null) return;
}
if (testLifecycle.validateLaunchIdentity(launch)) return;
testLifecycle.end();
Job job = new UIJob("MakeGood Test End") { //$NON-NLS-1$
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
ResultView resultView = (ResultView) ViewShow.find(ResultView.ID);
if (resultView == null) {
launch.deactivate();
synchronized (ResultViewController.this) {
testLifecycle = null;
}
return Status.CANCEL_STATUS;
}
resultView.endTest();
if (testLifecycle.hasErrors()) {
resultView.markAsStopped();
if (!StopTestAction.isStoppedByAction(launch)) {
ViewShow.show(IConsoleConstants.ID_CONSOLE_VIEW);
}
}
launch.deactivate();
synchronized (ResultViewController.this) {
testLifecycle = null;
}
return Status.OK_STATUS;
}
};
job.schedule();
}
| private void handleTerminateEvent(final MakeGoodLaunch launch) {
synchronized (this) {
if (testLifecycle == null) return;
}
if (!testLifecycle.validateLaunchIdentity(launch)) return;
testLifecycle.end();
Job job = new UIJob("MakeGood Test End") { //$NON-NLS-1$
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
ResultView resultView = (ResultView) ViewShow.find(ResultView.ID);
if (resultView == null) {
launch.deactivate();
synchronized (ResultViewController.this) {
testLifecycle = null;
}
return Status.CANCEL_STATUS;
}
resultView.endTest();
if (testLifecycle.hasErrors()) {
resultView.markAsStopped();
if (!StopTestAction.isStoppedByAction(launch)) {
ViewShow.show(IConsoleConstants.ID_CONSOLE_VIEW);
}
}
launch.deactivate();
synchronized (ResultViewController.this) {
testLifecycle = null;
}
return Status.OK_STATUS;
}
};
job.schedule();
}
|
diff --git a/src/com/android/phone/OutgoingCallBroadcaster.java b/src/com/android/phone/OutgoingCallBroadcaster.java
index bba6b8de..c3cd94c6 100644
--- a/src/com/android/phone/OutgoingCallBroadcaster.java
+++ b/src/com/android/phone/OutgoingCallBroadcaster.java
@@ -1,649 +1,655 @@
/*
* 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.phone;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemProperties;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import com.android.internal.telephony.Phone;
/**
* OutgoingCallBroadcaster receives CALL and CALL_PRIVILEGED Intents, and
* broadcasts the ACTION_NEW_OUTGOING_CALL intent which allows other
* applications to monitor, redirect, or prevent the outgoing call.
* After the other applications have had a chance to see the
* ACTION_NEW_OUTGOING_CALL intent, it finally reaches the
* {@link OutgoingCallReceiver}, which passes the (possibly modified)
* intent on to the {@link SipCallOptionHandler}, which will
* ultimately start the call using the CallController.placeCall() API.
*
* Emergency calls and calls where no number is present (like for a CDMA
* "empty flash" or a nonexistent voicemail number) are exempt from being
* broadcast.
*/
public class OutgoingCallBroadcaster extends Activity
implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener {
private static final String PERMISSION = android.Manifest.permission.PROCESS_OUTGOING_CALLS;
private static final String TAG = "OutgoingCallBroadcaster";
private static final boolean DBG =
(PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
// Do not check in with VDBG = true, since that may write PII to the system log.
private static final boolean VDBG = false;
public static final String ACTION_SIP_SELECT_PHONE = "com.android.phone.SIP_SELECT_PHONE";
public static final String EXTRA_ALREADY_CALLED = "android.phone.extra.ALREADY_CALLED";
public static final String EXTRA_ORIGINAL_URI = "android.phone.extra.ORIGINAL_URI";
public static final String EXTRA_NEW_CALL_INTENT = "android.phone.extra.NEW_CALL_INTENT";
public static final String EXTRA_SIP_PHONE_URI = "android.phone.extra.SIP_PHONE_URI";
public static final String EXTRA_ACTUAL_NUMBER_TO_DIAL =
"android.phone.extra.ACTUAL_NUMBER_TO_DIAL";
/**
* Identifier for intent extra for sending an empty Flash message for
* CDMA networks. This message is used by the network to simulate a
* press/depress of the "hookswitch" of a landline phone. Aka "empty flash".
*
* TODO: Receiving an intent extra to tell the phone to send this flash is a
* temporary measure. To be replaced with an external ITelephony call in the future.
* TODO: Keep in sync with the string defined in TwelveKeyDialer.java in Contacts app
* until this is replaced with the ITelephony API.
*/
public static final String EXTRA_SEND_EMPTY_FLASH = "com.android.phone.extra.SEND_EMPTY_FLASH";
// Dialog IDs
private static final int DIALOG_NOT_VOICE_CAPABLE = 1;
/**
* OutgoingCallReceiver finishes NEW_OUTGOING_CALL broadcasts, starting
* the InCallScreen if the broadcast has not been canceled, possibly with
* a modified phone number and optional provider info (uri + package name + remote views.)
*/
public class OutgoingCallReceiver extends BroadcastReceiver {
private static final String TAG = "OutgoingCallReceiver";
public void onReceive(Context context, Intent intent) {
doReceive(context, intent);
finish();
}
public void doReceive(Context context, Intent intent) {
if (DBG) Log.v(TAG, "doReceive: " + intent);
boolean alreadyCalled;
String number;
String originalUri;
alreadyCalled = intent.getBooleanExtra(
OutgoingCallBroadcaster.EXTRA_ALREADY_CALLED, false);
if (alreadyCalled) {
if (DBG) Log.v(TAG, "CALL already placed -- returning.");
return;
}
// Once the NEW_OUTGOING_CALL broadcast is finished, the resultData
// is used as the actual number to call. (If null, no call will be
// placed.)
number = getResultData();
if (VDBG) Log.v(TAG, "- got number from resultData: '" + number + "'");
final PhoneApp app = PhoneApp.getInstance();
// OTASP-specific checks.
// TODO: This should probably all happen in
// OutgoingCallBroadcaster.onCreate(), since there's no reason to
// even bother with the NEW_OUTGOING_CALL broadcast if we're going
// to disallow the outgoing call anyway...
if (TelephonyCapabilities.supportsOtasp(app.phone)) {
boolean activateState = (app.cdmaOtaScreenState.otaScreenState
== OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION);
boolean dialogState = (app.cdmaOtaScreenState.otaScreenState
== OtaUtils.CdmaOtaScreenState.OtaScreenState
.OTA_STATUS_SUCCESS_FAILURE_DLG);
boolean isOtaCallActive = false;
// TODO: Need cleaner way to check if OTA is active.
// Also, this check seems to be broken in one obscure case: if
// you interrupt an OTASP call by pressing Back then Skip,
// otaScreenState somehow gets left in either PROGRESS or
// LISTENING.
if ((app.cdmaOtaScreenState.otaScreenState
== OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_PROGRESS)
|| (app.cdmaOtaScreenState.otaScreenState
== OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_LISTENING)) {
isOtaCallActive = true;
}
if (activateState || dialogState) {
// The OTASP sequence is active, but either (1) the call
// hasn't started yet, or (2) the call has ended and we're
// showing the success/failure screen. In either of these
// cases it's OK to make a new outgoing call, but we need
// to take down any OTASP-related UI first.
if (dialogState) app.dismissOtaDialogs();
app.clearOtaState();
app.clearInCallScreenMode();
} else if (isOtaCallActive) {
// The actual OTASP call is active. Don't allow new
// outgoing calls at all from this state.
Log.w(TAG, "OTASP call is active: disallowing a new outgoing call.");
return;
}
}
if (number == null) {
if (DBG) Log.v(TAG, "CALL cancelled (null number), returning...");
return;
} else if (TelephonyCapabilities.supportsOtasp(app.phone)
&& (app.phone.getState() != Phone.State.IDLE)
&& (app.phone.isOtaSpNumber(number))) {
if (DBG) Log.v(TAG, "Call is active, a 2nd OTA call cancelled -- returning.");
return;
} else if (PhoneNumberUtils.isPotentialLocalEmergencyNumber(number, context)) {
// Just like 3rd-party apps aren't allowed to place emergency
// calls via the ACTION_CALL intent, we also don't allow 3rd
// party apps to use the NEW_OUTGOING_CALL broadcast to rewrite
// an outgoing call into an emergency number.
Log.w(TAG, "Cannot modify outgoing call to emergency number " + number + ".");
return;
}
originalUri = intent.getStringExtra(
OutgoingCallBroadcaster.EXTRA_ORIGINAL_URI);
if (originalUri == null) {
Log.e(TAG, "Intent is missing EXTRA_ORIGINAL_URI -- returning.");
return;
}
Uri uri = Uri.parse(originalUri);
// We already called convertKeypadLettersToDigits() and
// stripSeparators() way back in onCreate(), before we sent out the
// NEW_OUTGOING_CALL broadcast. But we need to do it again here
// too, since the number might have been modified/rewritten during
// the broadcast (and may now contain letters or separators again.)
number = PhoneNumberUtils.convertKeypadLettersToDigits(number);
number = PhoneNumberUtils.stripSeparators(number);
if (DBG) Log.v(TAG, "doReceive: proceeding with call...");
if (VDBG) Log.v(TAG, "- uri: " + uri);
if (VDBG) Log.v(TAG, "- actual number to dial: '" + number + "'");
startSipCallOptionHandler(context, intent, uri, number);
}
}
/**
* Launch the SipCallOptionHandler, which is the next step(*) in the
* outgoing-call sequence after the outgoing call broadcast is
* complete.
*
* (*) We now know exactly what phone number we need to dial, so the next
* step is for the SipCallOptionHandler to decide which Phone type (SIP
* or PSTN) should be used. (Depending on the user's preferences, this
* decision may also involve popping up a dialog to ask the user to
* choose what type of call this should be.)
*
* @param context used for the startActivity() call
*
* @param intent the intent from the previous step of the outgoing-call
* sequence. Normally this will be the NEW_OUTGOING_CALL broadcast intent
* that came in to the OutgoingCallReceiver, although it can also be the
* original ACTION_CALL intent that started the whole sequence (in cases
* where we don't do the NEW_OUTGOING_CALL broadcast at all, like for
* emergency numbers or SIP addresses).
*
* @param uri the data URI from the original CALL intent, presumably either
* a tel: or sip: URI. For tel: URIs, note that the scheme-specific part
* does *not* necessarily have separators and keypad letters stripped (so
* we might see URIs like "tel:(650)%20555-1234" or "tel:1-800-GOOG-411"
* here.)
*
* @param number the actual number (or SIP address) to dial. This is
* guaranteed to be either a PSTN phone number with separators stripped
* out and keypad letters converted to digits (like "16505551234"), or a
* raw SIP address (like "[email protected]").
*/
private void startSipCallOptionHandler(Context context, Intent intent,
Uri uri, String number) {
if (VDBG) {
Log.i(TAG, "startSipCallOptionHandler...");
Log.i(TAG, "- intent: " + intent);
Log.i(TAG, "- uri: " + uri);
Log.i(TAG, "- number: " + number);
}
// Create a copy of the original CALL intent that started the whole
// outgoing-call sequence. This intent will ultimately be passed to
// CallController.placeCall() after the SipCallOptionHandler step.
Intent newIntent = new Intent(Intent.ACTION_CALL, uri);
newIntent.putExtra(EXTRA_ACTUAL_NUMBER_TO_DIAL, number);
PhoneUtils.checkAndCopyPhoneProviderExtras(intent, newIntent);
// Finally, launch the SipCallOptionHandler, with the copy of the
// original CALL intent stashed away in the EXTRA_NEW_CALL_INTENT
// extra.
Intent selectPhoneIntent = new Intent(ACTION_SIP_SELECT_PHONE, uri);
selectPhoneIntent.setClass(context, SipCallOptionHandler.class);
selectPhoneIntent.putExtra(EXTRA_NEW_CALL_INTENT, newIntent);
selectPhoneIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (DBG) Log.v(TAG, "startSipCallOptionHandler(): " +
"calling startActivity: " + selectPhoneIntent);
context.startActivity(selectPhoneIntent);
// ...and see SipCallOptionHandler.onCreate() for the next step of the sequence.
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// This method is the single point of entry for the CALL intent,
// which is used (by built-in apps like Contacts / Dialer, as well
// as 3rd-party apps) to initiate an outgoing voice call.
//
// We also handle two related intents which are only used internally:
// CALL_PRIVILEGED (which can come from built-in apps like contacts /
// voice dialer / bluetooth), and CALL_EMERGENCY (from the
// EmergencyDialer that's reachable from the lockscreen.)
//
// The exact behavior depends on the intent's data:
//
// - The most typical is a tel: URI, which we handle by starting the
// NEW_OUTGOING_CALL broadcast. That broadcast eventually triggers
// the sequence OutgoingCallReceiver -> SipCallOptionHandler ->
// InCallScreen.
//
// - Or, with a sip: URI we skip the NEW_OUTGOING_CALL broadcast and
// go directly to SipCallOptionHandler, which then leads to the
// InCallScreen.
//
// - voicemail: URIs take the same path as regular tel: URIs.
//
// Other special cases:
//
// - Outgoing calls are totally disallowed on non-voice-capable
// devices (see handleNonVoiceCapable()).
//
// - A CALL intent with the EXTRA_SEND_EMPTY_FLASH extra (and
// presumably no data at all) means "send an empty flash" (which
// is only meaningful on CDMA devices while a call is already
// active.)
Intent intent = getIntent();
final Configuration configuration = getResources().getConfiguration();
if (DBG) Log.v(TAG, "onCreate: this = " + this + ", icicle = " + icicle);
if (DBG) Log.v(TAG, " - getIntent() = " + intent);
if (DBG) Log.v(TAG, " - configuration = " + configuration);
if (icicle != null) {
// A non-null icicle means that this activity is being
// re-initialized after previously being shut down.
//
// In practice this happens very rarely (because the lifetime
// of this activity is so short!), but it *can* happen if the
// framework detects a configuration change at exactly the
// right moment; see bug 2202413.
//
// In this case, do nothing. Our onCreate() method has already
// run once (with icicle==null the first time), which means
// that the NEW_OUTGOING_CALL broadcast for this new call has
// already been sent.
Log.i(TAG, "onCreate: non-null icicle! "
+ "Bailing out, not sending NEW_OUTGOING_CALL broadcast...");
// No need to finish() here, since the OutgoingCallReceiver from
// our original instance will do that. (It'll actually call
// finish() on our original instance, which apparently works fine
// even though the ActivityManager has already shut that instance
// down. And note that if we *do* call finish() here, that just
// results in an "ActivityManager: Duplicate finish request"
// warning when the OutgoingCallReceiver runs.)
return;
}
// Outgoing phone calls are only allowed on "voice-capable" devices.
if (!PhoneApp.sVoiceCapable) {
handleNonVoiceCapable(intent);
// No need to finish() here; handleNonVoiceCapable() will do
// that if necessary.
return;
}
String action = intent.getAction();
String number = PhoneNumberUtils.getNumberFromIntent(intent, this);
// Check the number, don't convert for sip uri
// TODO put uriNumber under PhoneNumberUtils
if (number != null) {
if (!PhoneNumberUtils.isUriNumber(number)) {
number = PhoneNumberUtils.convertKeypadLettersToDigits(number);
number = PhoneNumberUtils.stripSeparators(number);
}
+ } else {
+ Log.w(TAG, "The number obtained from Intent is null.");
}
// If true, this flag will indicate that the current call is a special kind
// of call (most likely an emergency number) that 3rd parties aren't allowed
// to intercept or affect in any way. (In that case, we start the call
// immediately rather than going through the NEW_OUTGOING_CALL sequence.)
boolean callNow;
if (getClass().getName().equals(intent.getComponent().getClassName())) {
// If we were launched directly from the OutgoingCallBroadcaster,
// not one of its more privileged aliases, then make sure that
// only the non-privileged actions are allowed.
if (!Intent.ACTION_CALL.equals(intent.getAction())) {
Log.w(TAG, "Attempt to deliver non-CALL action; forcing to CALL");
intent.setAction(Intent.ACTION_CALL);
}
}
// Check whether or not this is an emergency number, in order to
// enforce the restriction that only the CALL_PRIVILEGED and
// CALL_EMERGENCY intents are allowed to make emergency calls.
//
// (Note that the ACTION_CALL check below depends on the result of
// isPotentialLocalEmergencyNumber() rather than just plain
// isLocalEmergencyNumber(), to be 100% certain that we *don't*
// allow 3rd party apps to make emergency calls by passing in an
// "invalid" number like "9111234" that isn't technically an
// emergency number but might still result in an emergency call
// with some networks.)
final boolean isExactEmergencyNumber =
(number != null) && PhoneNumberUtils.isLocalEmergencyNumber(number, this);
final boolean isPotentialEmergencyNumber =
(number != null) && PhoneNumberUtils.isPotentialLocalEmergencyNumber(number, this);
if (VDBG) {
Log.v(TAG, "- Checking restrictions for number '" + number + "':");
Log.v(TAG, " isExactEmergencyNumber = " + isExactEmergencyNumber);
Log.v(TAG, " isPotentialEmergencyNumber = " + isPotentialEmergencyNumber);
}
/* Change CALL_PRIVILEGED into CALL or CALL_EMERGENCY as needed. */
// TODO: This code is redundant with some code in InCallScreen: refactor.
if (Intent.ACTION_CALL_PRIVILEGED.equals(action)) {
// We're handling a CALL_PRIVILEGED intent, so we know this request came
// from a trusted source (like the built-in dialer.) So even a number
// that's *potentially* an emergency number can safely be promoted to
// CALL_EMERGENCY (since we *should* allow you to dial "91112345" from
// the dialer if you really want to.)
- action = isPotentialEmergencyNumber
- ? Intent.ACTION_CALL_EMERGENCY
- : Intent.ACTION_CALL;
+ if (isPotentialEmergencyNumber) {
+ Log.i(TAG, "ACTION_CALL_PRIVILEGED is used while the number is a potential"
+ + " emergency number. Use ACTION_CALL_EMERGENCY as an action instead.");
+ action = Intent.ACTION_CALL_EMERGENCY;
+ } else {
+ action = Intent.ACTION_CALL;
+ }
if (DBG) Log.v(TAG, "- updating action from CALL_PRIVILEGED to " + action);
intent.setAction(action);
}
if (Intent.ACTION_CALL.equals(action)) {
if (isPotentialEmergencyNumber) {
Log.w(TAG, "Cannot call potential emergency number '" + number
+ "' with CALL Intent " + intent + ".");
Log.i(TAG, "Launching default dialer instead...");
Intent invokeFrameworkDialer = new Intent();
// TwelveKeyDialer is in a tab so we really want
// DialtactsActivity. Build the intent 'manually' to
// use the java resolver to find the dialer class (as
// opposed to a Context which look up known android
// packages only)
invokeFrameworkDialer.setClassName("com.android.contacts",
"com.android.contacts.DialtactsActivity");
invokeFrameworkDialer.setAction(Intent.ACTION_DIAL);
invokeFrameworkDialer.setData(intent.getData());
if (DBG) Log.v(TAG, "onCreate(): calling startActivity for Dialer: "
+ invokeFrameworkDialer);
startActivity(invokeFrameworkDialer);
finish();
return;
}
callNow = false;
} else if (Intent.ACTION_CALL_EMERGENCY.equals(action)) {
// ACTION_CALL_EMERGENCY case: this is either a CALL_PRIVILEGED
// intent that we just turned into a CALL_EMERGENCY intent (see
// above), or else it really is an CALL_EMERGENCY intent that
// came directly from some other app (e.g. the EmergencyDialer
// activity built in to the Phone app.)
// Make sure it's at least *possible* that this is really an
// emergency number.
if (!isPotentialEmergencyNumber) {
Log.w(TAG, "Cannot call non-potential-emergency number " + number
+ " with EMERGENCY_CALL Intent " + intent + ".");
finish();
return;
}
callNow = true;
} else {
Log.e(TAG, "Unhandled Intent " + intent + ".");
finish();
return;
}
// Make sure the screen is turned on. This is probably the right
// thing to do, and more importantly it works around an issue in the
// activity manager where we will not launch activities consistently
// when the screen is off (since it is trying to keep them paused
// and has... issues).
//
// Also, this ensures the device stays awake while doing the following
// broadcast; technically we should be holding a wake lock here
// as well.
PhoneApp.getInstance().wakeUpScreen();
// If number is null, we're probably trying to call a non-existent voicemail number,
// send an empty flash or something else is fishy. Whatever the problem, there's no
// number, so there's no point in allowing apps to modify the number.
- if (number == null || TextUtils.isEmpty(number)) {
+ if (TextUtils.isEmpty(number)) {
if (intent.getBooleanExtra(EXTRA_SEND_EMPTY_FLASH, false)) {
Log.i(TAG, "onCreate: SEND_EMPTY_FLASH...");
PhoneUtils.sendEmptyFlash(PhoneApp.getPhone());
finish();
return;
} else {
Log.i(TAG, "onCreate: null or empty number, setting callNow=true...");
callNow = true;
}
}
if (callNow) {
// This is a special kind of call (most likely an emergency number)
// that 3rd parties aren't allowed to intercept or affect in any way.
// So initiate the outgoing call immediately.
- if (DBG) Log.v(TAG, "onCreate(): callNow case! Calling placeCall(): " + intent);
+ Log.i(TAG, "onCreate(): callNow case! Calling placeCall(): " + intent);
// Initiate the outgoing call, and simultaneously launch the
// InCallScreen to display the in-call UI:
PhoneApp.getInstance().callController.placeCall(intent);
// Note we do *not* "return" here, but instead continue and
// send the ACTION_NEW_OUTGOING_CALL broadcast like for any
// other outgoing call. (But when the broadcast finally
// reaches the OutgoingCallReceiver, we'll know not to
// initiate the call again because of the presence of the
// EXTRA_ALREADY_CALLED extra.)
}
// Remember the call origin so that users will be able to see an appropriate screen
// after the phone call. This should affect both phone calls and SIP calls.
final String callOrigin = intent.getStringExtra(PhoneApp.EXTRA_CALL_ORIGIN);
if (callOrigin != null) {
if (DBG) Log.v(TAG, "Call origin is passed (" + callOrigin + ")");
PhoneApp.getInstance().setLatestActiveCallOrigin(callOrigin);
} else {
if (DBG) Log.v(TAG, "Call origin is not passed. Reset current one.");
PhoneApp.getInstance().resetLatestActiveCallOrigin();
}
// For now, SIP calls will be processed directly without a
// NEW_OUTGOING_CALL broadcast.
//
// TODO: In the future, though, 3rd party apps *should* be allowed to
// intercept outgoing calls to SIP addresses as well. To do this, we should
// (1) update the NEW_OUTGOING_CALL intent documentation to explain this
// case, and (2) pass the outgoing SIP address by *not* overloading the
// EXTRA_PHONE_NUMBER extra, but instead using a new separate extra to hold
// the outgoing SIP address. (Be sure to document whether it's a URI or just
// a plain address, whether it could be a tel: URI, etc.)
Uri uri = intent.getData();
String scheme = uri.getScheme();
if (Constants.SCHEME_SIP.equals(scheme)
|| PhoneNumberUtils.isUriNumber(number)) {
startSipCallOptionHandler(this, intent, uri, number);
finish();
return;
// TODO: if there's ever a way for SIP calls to trigger a
// "callNow=true" case (see above), we'll need to handle that
// case here too (most likely by just doing nothing at all.)
}
Intent broadcastIntent = new Intent(Intent.ACTION_NEW_OUTGOING_CALL);
if (number != null) {
broadcastIntent.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
}
PhoneUtils.checkAndCopyPhoneProviderExtras(intent, broadcastIntent);
broadcastIntent.putExtra(EXTRA_ALREADY_CALLED, callNow);
broadcastIntent.putExtra(EXTRA_ORIGINAL_URI, uri.toString());
if (DBG) Log.v(TAG, "Broadcasting intent: " + broadcastIntent + ".");
sendOrderedBroadcast(broadcastIntent, PERMISSION, new OutgoingCallReceiver(),
null, // scheduler
Activity.RESULT_OK, // initialCode
number, // initialData: initial value for the result data
null); // initialExtras
}
@Override
protected void onStop() {
// Clean up (and dismiss if necessary) any managed dialogs.
//
// We don't do this in onPause() since we can be paused/resumed
// due to orientation changes (in which case we don't want to
// disturb the dialog), but we *do* need it here in onStop() to be
// sure we clean up if the user hits HOME while the dialog is up.
//
// Note it's safe to call removeDialog() even if there's no dialog
// associated with that ID.
removeDialog(DIALOG_NOT_VOICE_CAPABLE);
super.onStop();
}
/**
* Handle the specified CALL or CALL_* intent on a non-voice-capable
* device.
*
* This method may launch a different intent (if there's some useful
* alternative action to take), or otherwise display an error dialog,
* and in either case will finish() the current activity when done.
*/
private void handleNonVoiceCapable(Intent intent) {
if (DBG) Log.v(TAG, "handleNonVoiceCapable: handling " + intent
+ " on non-voice-capable device...");
String action = intent.getAction();
Uri uri = intent.getData();
String scheme = uri.getScheme();
// Handle one special case: If this is a regular CALL to a tel: URI,
// bring up a UI letting you do something useful with the phone number
// (like "Add to contacts" if it isn't a contact yet.)
//
// This UI is provided by the contacts app in response to a DIAL
// intent, so we bring it up here by demoting this CALL to a DIAL and
// relaunching.
//
// TODO: it's strange and unintuitive to manually launch a DIAL intent
// to do this; it would be cleaner to have some shared UI component
// that we could bring up directly. (But for now at least, since both
// Contacts and Phone are built-in apps, this implementation is fine.)
if (Intent.ACTION_CALL.equals(action) && (Constants.SCHEME_TEL.equals(scheme))) {
Intent newIntent = new Intent(Intent.ACTION_DIAL, uri);
if (DBG) Log.v(TAG, "- relaunching as a DIAL intent: " + newIntent);
startActivity(newIntent);
finish();
return;
}
// In all other cases, just show a generic "voice calling not
// supported" dialog.
showDialog(DIALOG_NOT_VOICE_CAPABLE);
// ...and we'll eventually finish() when the user dismisses
// or cancels the dialog.
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch(id) {
case DIALOG_NOT_VOICE_CAPABLE:
dialog = new AlertDialog.Builder(this)
.setTitle(R.string.not_voice_capable)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.ok, this)
.setOnCancelListener(this)
.create();
break;
default:
Log.w(TAG, "onCreateDialog: unexpected ID " + id);
dialog = null;
break;
}
return dialog;
}
// DialogInterface.OnClickListener implementation
public void onClick(DialogInterface dialog, int id) {
// DIALOG_NOT_VOICE_CAPABLE is the only dialog we ever use (so far
// at least), and its only button is "OK".
finish();
}
// DialogInterface.OnCancelListener implementation
public void onCancel(DialogInterface dialog) {
// DIALOG_NOT_VOICE_CAPABLE is the only dialog we ever use (so far
// at least), and canceling it is just like hitting "OK".
finish();
}
// Implement onConfigurationChanged() purely for debugging purposes,
// to make sure that the android:configChanges element in our manifest
// is working properly.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (DBG) Log.v(TAG, "onConfigurationChanged: newConfig = " + newConfig);
}
}
| false | true | protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// This method is the single point of entry for the CALL intent,
// which is used (by built-in apps like Contacts / Dialer, as well
// as 3rd-party apps) to initiate an outgoing voice call.
//
// We also handle two related intents which are only used internally:
// CALL_PRIVILEGED (which can come from built-in apps like contacts /
// voice dialer / bluetooth), and CALL_EMERGENCY (from the
// EmergencyDialer that's reachable from the lockscreen.)
//
// The exact behavior depends on the intent's data:
//
// - The most typical is a tel: URI, which we handle by starting the
// NEW_OUTGOING_CALL broadcast. That broadcast eventually triggers
// the sequence OutgoingCallReceiver -> SipCallOptionHandler ->
// InCallScreen.
//
// - Or, with a sip: URI we skip the NEW_OUTGOING_CALL broadcast and
// go directly to SipCallOptionHandler, which then leads to the
// InCallScreen.
//
// - voicemail: URIs take the same path as regular tel: URIs.
//
// Other special cases:
//
// - Outgoing calls are totally disallowed on non-voice-capable
// devices (see handleNonVoiceCapable()).
//
// - A CALL intent with the EXTRA_SEND_EMPTY_FLASH extra (and
// presumably no data at all) means "send an empty flash" (which
// is only meaningful on CDMA devices while a call is already
// active.)
Intent intent = getIntent();
final Configuration configuration = getResources().getConfiguration();
if (DBG) Log.v(TAG, "onCreate: this = " + this + ", icicle = " + icicle);
if (DBG) Log.v(TAG, " - getIntent() = " + intent);
if (DBG) Log.v(TAG, " - configuration = " + configuration);
if (icicle != null) {
// A non-null icicle means that this activity is being
// re-initialized after previously being shut down.
//
// In practice this happens very rarely (because the lifetime
// of this activity is so short!), but it *can* happen if the
// framework detects a configuration change at exactly the
// right moment; see bug 2202413.
//
// In this case, do nothing. Our onCreate() method has already
// run once (with icicle==null the first time), which means
// that the NEW_OUTGOING_CALL broadcast for this new call has
// already been sent.
Log.i(TAG, "onCreate: non-null icicle! "
+ "Bailing out, not sending NEW_OUTGOING_CALL broadcast...");
// No need to finish() here, since the OutgoingCallReceiver from
// our original instance will do that. (It'll actually call
// finish() on our original instance, which apparently works fine
// even though the ActivityManager has already shut that instance
// down. And note that if we *do* call finish() here, that just
// results in an "ActivityManager: Duplicate finish request"
// warning when the OutgoingCallReceiver runs.)
return;
}
// Outgoing phone calls are only allowed on "voice-capable" devices.
if (!PhoneApp.sVoiceCapable) {
handleNonVoiceCapable(intent);
// No need to finish() here; handleNonVoiceCapable() will do
// that if necessary.
return;
}
String action = intent.getAction();
String number = PhoneNumberUtils.getNumberFromIntent(intent, this);
// Check the number, don't convert for sip uri
// TODO put uriNumber under PhoneNumberUtils
if (number != null) {
if (!PhoneNumberUtils.isUriNumber(number)) {
number = PhoneNumberUtils.convertKeypadLettersToDigits(number);
number = PhoneNumberUtils.stripSeparators(number);
}
}
// If true, this flag will indicate that the current call is a special kind
// of call (most likely an emergency number) that 3rd parties aren't allowed
// to intercept or affect in any way. (In that case, we start the call
// immediately rather than going through the NEW_OUTGOING_CALL sequence.)
boolean callNow;
if (getClass().getName().equals(intent.getComponent().getClassName())) {
// If we were launched directly from the OutgoingCallBroadcaster,
// not one of its more privileged aliases, then make sure that
// only the non-privileged actions are allowed.
if (!Intent.ACTION_CALL.equals(intent.getAction())) {
Log.w(TAG, "Attempt to deliver non-CALL action; forcing to CALL");
intent.setAction(Intent.ACTION_CALL);
}
}
// Check whether or not this is an emergency number, in order to
// enforce the restriction that only the CALL_PRIVILEGED and
// CALL_EMERGENCY intents are allowed to make emergency calls.
//
// (Note that the ACTION_CALL check below depends on the result of
// isPotentialLocalEmergencyNumber() rather than just plain
// isLocalEmergencyNumber(), to be 100% certain that we *don't*
// allow 3rd party apps to make emergency calls by passing in an
// "invalid" number like "9111234" that isn't technically an
// emergency number but might still result in an emergency call
// with some networks.)
final boolean isExactEmergencyNumber =
(number != null) && PhoneNumberUtils.isLocalEmergencyNumber(number, this);
final boolean isPotentialEmergencyNumber =
(number != null) && PhoneNumberUtils.isPotentialLocalEmergencyNumber(number, this);
if (VDBG) {
Log.v(TAG, "- Checking restrictions for number '" + number + "':");
Log.v(TAG, " isExactEmergencyNumber = " + isExactEmergencyNumber);
Log.v(TAG, " isPotentialEmergencyNumber = " + isPotentialEmergencyNumber);
}
/* Change CALL_PRIVILEGED into CALL or CALL_EMERGENCY as needed. */
// TODO: This code is redundant with some code in InCallScreen: refactor.
if (Intent.ACTION_CALL_PRIVILEGED.equals(action)) {
// We're handling a CALL_PRIVILEGED intent, so we know this request came
// from a trusted source (like the built-in dialer.) So even a number
// that's *potentially* an emergency number can safely be promoted to
// CALL_EMERGENCY (since we *should* allow you to dial "91112345" from
// the dialer if you really want to.)
action = isPotentialEmergencyNumber
? Intent.ACTION_CALL_EMERGENCY
: Intent.ACTION_CALL;
if (DBG) Log.v(TAG, "- updating action from CALL_PRIVILEGED to " + action);
intent.setAction(action);
}
if (Intent.ACTION_CALL.equals(action)) {
if (isPotentialEmergencyNumber) {
Log.w(TAG, "Cannot call potential emergency number '" + number
+ "' with CALL Intent " + intent + ".");
Log.i(TAG, "Launching default dialer instead...");
Intent invokeFrameworkDialer = new Intent();
// TwelveKeyDialer is in a tab so we really want
// DialtactsActivity. Build the intent 'manually' to
// use the java resolver to find the dialer class (as
// opposed to a Context which look up known android
// packages only)
invokeFrameworkDialer.setClassName("com.android.contacts",
"com.android.contacts.DialtactsActivity");
invokeFrameworkDialer.setAction(Intent.ACTION_DIAL);
invokeFrameworkDialer.setData(intent.getData());
if (DBG) Log.v(TAG, "onCreate(): calling startActivity for Dialer: "
+ invokeFrameworkDialer);
startActivity(invokeFrameworkDialer);
finish();
return;
}
callNow = false;
} else if (Intent.ACTION_CALL_EMERGENCY.equals(action)) {
// ACTION_CALL_EMERGENCY case: this is either a CALL_PRIVILEGED
// intent that we just turned into a CALL_EMERGENCY intent (see
// above), or else it really is an CALL_EMERGENCY intent that
// came directly from some other app (e.g. the EmergencyDialer
// activity built in to the Phone app.)
// Make sure it's at least *possible* that this is really an
// emergency number.
if (!isPotentialEmergencyNumber) {
Log.w(TAG, "Cannot call non-potential-emergency number " + number
+ " with EMERGENCY_CALL Intent " + intent + ".");
finish();
return;
}
callNow = true;
} else {
Log.e(TAG, "Unhandled Intent " + intent + ".");
finish();
return;
}
// Make sure the screen is turned on. This is probably the right
// thing to do, and more importantly it works around an issue in the
// activity manager where we will not launch activities consistently
// when the screen is off (since it is trying to keep them paused
// and has... issues).
//
// Also, this ensures the device stays awake while doing the following
// broadcast; technically we should be holding a wake lock here
// as well.
PhoneApp.getInstance().wakeUpScreen();
// If number is null, we're probably trying to call a non-existent voicemail number,
// send an empty flash or something else is fishy. Whatever the problem, there's no
// number, so there's no point in allowing apps to modify the number.
if (number == null || TextUtils.isEmpty(number)) {
if (intent.getBooleanExtra(EXTRA_SEND_EMPTY_FLASH, false)) {
Log.i(TAG, "onCreate: SEND_EMPTY_FLASH...");
PhoneUtils.sendEmptyFlash(PhoneApp.getPhone());
finish();
return;
} else {
Log.i(TAG, "onCreate: null or empty number, setting callNow=true...");
callNow = true;
}
}
if (callNow) {
// This is a special kind of call (most likely an emergency number)
// that 3rd parties aren't allowed to intercept or affect in any way.
// So initiate the outgoing call immediately.
if (DBG) Log.v(TAG, "onCreate(): callNow case! Calling placeCall(): " + intent);
// Initiate the outgoing call, and simultaneously launch the
// InCallScreen to display the in-call UI:
PhoneApp.getInstance().callController.placeCall(intent);
// Note we do *not* "return" here, but instead continue and
// send the ACTION_NEW_OUTGOING_CALL broadcast like for any
// other outgoing call. (But when the broadcast finally
// reaches the OutgoingCallReceiver, we'll know not to
// initiate the call again because of the presence of the
// EXTRA_ALREADY_CALLED extra.)
}
// Remember the call origin so that users will be able to see an appropriate screen
// after the phone call. This should affect both phone calls and SIP calls.
final String callOrigin = intent.getStringExtra(PhoneApp.EXTRA_CALL_ORIGIN);
if (callOrigin != null) {
if (DBG) Log.v(TAG, "Call origin is passed (" + callOrigin + ")");
PhoneApp.getInstance().setLatestActiveCallOrigin(callOrigin);
} else {
if (DBG) Log.v(TAG, "Call origin is not passed. Reset current one.");
PhoneApp.getInstance().resetLatestActiveCallOrigin();
}
// For now, SIP calls will be processed directly without a
// NEW_OUTGOING_CALL broadcast.
//
// TODO: In the future, though, 3rd party apps *should* be allowed to
// intercept outgoing calls to SIP addresses as well. To do this, we should
// (1) update the NEW_OUTGOING_CALL intent documentation to explain this
// case, and (2) pass the outgoing SIP address by *not* overloading the
// EXTRA_PHONE_NUMBER extra, but instead using a new separate extra to hold
// the outgoing SIP address. (Be sure to document whether it's a URI or just
// a plain address, whether it could be a tel: URI, etc.)
Uri uri = intent.getData();
String scheme = uri.getScheme();
if (Constants.SCHEME_SIP.equals(scheme)
|| PhoneNumberUtils.isUriNumber(number)) {
startSipCallOptionHandler(this, intent, uri, number);
finish();
return;
// TODO: if there's ever a way for SIP calls to trigger a
// "callNow=true" case (see above), we'll need to handle that
// case here too (most likely by just doing nothing at all.)
}
Intent broadcastIntent = new Intent(Intent.ACTION_NEW_OUTGOING_CALL);
if (number != null) {
broadcastIntent.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
}
PhoneUtils.checkAndCopyPhoneProviderExtras(intent, broadcastIntent);
broadcastIntent.putExtra(EXTRA_ALREADY_CALLED, callNow);
broadcastIntent.putExtra(EXTRA_ORIGINAL_URI, uri.toString());
if (DBG) Log.v(TAG, "Broadcasting intent: " + broadcastIntent + ".");
sendOrderedBroadcast(broadcastIntent, PERMISSION, new OutgoingCallReceiver(),
null, // scheduler
Activity.RESULT_OK, // initialCode
number, // initialData: initial value for the result data
null); // initialExtras
}
| protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// This method is the single point of entry for the CALL intent,
// which is used (by built-in apps like Contacts / Dialer, as well
// as 3rd-party apps) to initiate an outgoing voice call.
//
// We also handle two related intents which are only used internally:
// CALL_PRIVILEGED (which can come from built-in apps like contacts /
// voice dialer / bluetooth), and CALL_EMERGENCY (from the
// EmergencyDialer that's reachable from the lockscreen.)
//
// The exact behavior depends on the intent's data:
//
// - The most typical is a tel: URI, which we handle by starting the
// NEW_OUTGOING_CALL broadcast. That broadcast eventually triggers
// the sequence OutgoingCallReceiver -> SipCallOptionHandler ->
// InCallScreen.
//
// - Or, with a sip: URI we skip the NEW_OUTGOING_CALL broadcast and
// go directly to SipCallOptionHandler, which then leads to the
// InCallScreen.
//
// - voicemail: URIs take the same path as regular tel: URIs.
//
// Other special cases:
//
// - Outgoing calls are totally disallowed on non-voice-capable
// devices (see handleNonVoiceCapable()).
//
// - A CALL intent with the EXTRA_SEND_EMPTY_FLASH extra (and
// presumably no data at all) means "send an empty flash" (which
// is only meaningful on CDMA devices while a call is already
// active.)
Intent intent = getIntent();
final Configuration configuration = getResources().getConfiguration();
if (DBG) Log.v(TAG, "onCreate: this = " + this + ", icicle = " + icicle);
if (DBG) Log.v(TAG, " - getIntent() = " + intent);
if (DBG) Log.v(TAG, " - configuration = " + configuration);
if (icicle != null) {
// A non-null icicle means that this activity is being
// re-initialized after previously being shut down.
//
// In practice this happens very rarely (because the lifetime
// of this activity is so short!), but it *can* happen if the
// framework detects a configuration change at exactly the
// right moment; see bug 2202413.
//
// In this case, do nothing. Our onCreate() method has already
// run once (with icicle==null the first time), which means
// that the NEW_OUTGOING_CALL broadcast for this new call has
// already been sent.
Log.i(TAG, "onCreate: non-null icicle! "
+ "Bailing out, not sending NEW_OUTGOING_CALL broadcast...");
// No need to finish() here, since the OutgoingCallReceiver from
// our original instance will do that. (It'll actually call
// finish() on our original instance, which apparently works fine
// even though the ActivityManager has already shut that instance
// down. And note that if we *do* call finish() here, that just
// results in an "ActivityManager: Duplicate finish request"
// warning when the OutgoingCallReceiver runs.)
return;
}
// Outgoing phone calls are only allowed on "voice-capable" devices.
if (!PhoneApp.sVoiceCapable) {
handleNonVoiceCapable(intent);
// No need to finish() here; handleNonVoiceCapable() will do
// that if necessary.
return;
}
String action = intent.getAction();
String number = PhoneNumberUtils.getNumberFromIntent(intent, this);
// Check the number, don't convert for sip uri
// TODO put uriNumber under PhoneNumberUtils
if (number != null) {
if (!PhoneNumberUtils.isUriNumber(number)) {
number = PhoneNumberUtils.convertKeypadLettersToDigits(number);
number = PhoneNumberUtils.stripSeparators(number);
}
} else {
Log.w(TAG, "The number obtained from Intent is null.");
}
// If true, this flag will indicate that the current call is a special kind
// of call (most likely an emergency number) that 3rd parties aren't allowed
// to intercept or affect in any way. (In that case, we start the call
// immediately rather than going through the NEW_OUTGOING_CALL sequence.)
boolean callNow;
if (getClass().getName().equals(intent.getComponent().getClassName())) {
// If we were launched directly from the OutgoingCallBroadcaster,
// not one of its more privileged aliases, then make sure that
// only the non-privileged actions are allowed.
if (!Intent.ACTION_CALL.equals(intent.getAction())) {
Log.w(TAG, "Attempt to deliver non-CALL action; forcing to CALL");
intent.setAction(Intent.ACTION_CALL);
}
}
// Check whether or not this is an emergency number, in order to
// enforce the restriction that only the CALL_PRIVILEGED and
// CALL_EMERGENCY intents are allowed to make emergency calls.
//
// (Note that the ACTION_CALL check below depends on the result of
// isPotentialLocalEmergencyNumber() rather than just plain
// isLocalEmergencyNumber(), to be 100% certain that we *don't*
// allow 3rd party apps to make emergency calls by passing in an
// "invalid" number like "9111234" that isn't technically an
// emergency number but might still result in an emergency call
// with some networks.)
final boolean isExactEmergencyNumber =
(number != null) && PhoneNumberUtils.isLocalEmergencyNumber(number, this);
final boolean isPotentialEmergencyNumber =
(number != null) && PhoneNumberUtils.isPotentialLocalEmergencyNumber(number, this);
if (VDBG) {
Log.v(TAG, "- Checking restrictions for number '" + number + "':");
Log.v(TAG, " isExactEmergencyNumber = " + isExactEmergencyNumber);
Log.v(TAG, " isPotentialEmergencyNumber = " + isPotentialEmergencyNumber);
}
/* Change CALL_PRIVILEGED into CALL or CALL_EMERGENCY as needed. */
// TODO: This code is redundant with some code in InCallScreen: refactor.
if (Intent.ACTION_CALL_PRIVILEGED.equals(action)) {
// We're handling a CALL_PRIVILEGED intent, so we know this request came
// from a trusted source (like the built-in dialer.) So even a number
// that's *potentially* an emergency number can safely be promoted to
// CALL_EMERGENCY (since we *should* allow you to dial "91112345" from
// the dialer if you really want to.)
if (isPotentialEmergencyNumber) {
Log.i(TAG, "ACTION_CALL_PRIVILEGED is used while the number is a potential"
+ " emergency number. Use ACTION_CALL_EMERGENCY as an action instead.");
action = Intent.ACTION_CALL_EMERGENCY;
} else {
action = Intent.ACTION_CALL;
}
if (DBG) Log.v(TAG, "- updating action from CALL_PRIVILEGED to " + action);
intent.setAction(action);
}
if (Intent.ACTION_CALL.equals(action)) {
if (isPotentialEmergencyNumber) {
Log.w(TAG, "Cannot call potential emergency number '" + number
+ "' with CALL Intent " + intent + ".");
Log.i(TAG, "Launching default dialer instead...");
Intent invokeFrameworkDialer = new Intent();
// TwelveKeyDialer is in a tab so we really want
// DialtactsActivity. Build the intent 'manually' to
// use the java resolver to find the dialer class (as
// opposed to a Context which look up known android
// packages only)
invokeFrameworkDialer.setClassName("com.android.contacts",
"com.android.contacts.DialtactsActivity");
invokeFrameworkDialer.setAction(Intent.ACTION_DIAL);
invokeFrameworkDialer.setData(intent.getData());
if (DBG) Log.v(TAG, "onCreate(): calling startActivity for Dialer: "
+ invokeFrameworkDialer);
startActivity(invokeFrameworkDialer);
finish();
return;
}
callNow = false;
} else if (Intent.ACTION_CALL_EMERGENCY.equals(action)) {
// ACTION_CALL_EMERGENCY case: this is either a CALL_PRIVILEGED
// intent that we just turned into a CALL_EMERGENCY intent (see
// above), or else it really is an CALL_EMERGENCY intent that
// came directly from some other app (e.g. the EmergencyDialer
// activity built in to the Phone app.)
// Make sure it's at least *possible* that this is really an
// emergency number.
if (!isPotentialEmergencyNumber) {
Log.w(TAG, "Cannot call non-potential-emergency number " + number
+ " with EMERGENCY_CALL Intent " + intent + ".");
finish();
return;
}
callNow = true;
} else {
Log.e(TAG, "Unhandled Intent " + intent + ".");
finish();
return;
}
// Make sure the screen is turned on. This is probably the right
// thing to do, and more importantly it works around an issue in the
// activity manager where we will not launch activities consistently
// when the screen is off (since it is trying to keep them paused
// and has... issues).
//
// Also, this ensures the device stays awake while doing the following
// broadcast; technically we should be holding a wake lock here
// as well.
PhoneApp.getInstance().wakeUpScreen();
// If number is null, we're probably trying to call a non-existent voicemail number,
// send an empty flash or something else is fishy. Whatever the problem, there's no
// number, so there's no point in allowing apps to modify the number.
if (TextUtils.isEmpty(number)) {
if (intent.getBooleanExtra(EXTRA_SEND_EMPTY_FLASH, false)) {
Log.i(TAG, "onCreate: SEND_EMPTY_FLASH...");
PhoneUtils.sendEmptyFlash(PhoneApp.getPhone());
finish();
return;
} else {
Log.i(TAG, "onCreate: null or empty number, setting callNow=true...");
callNow = true;
}
}
if (callNow) {
// This is a special kind of call (most likely an emergency number)
// that 3rd parties aren't allowed to intercept or affect in any way.
// So initiate the outgoing call immediately.
Log.i(TAG, "onCreate(): callNow case! Calling placeCall(): " + intent);
// Initiate the outgoing call, and simultaneously launch the
// InCallScreen to display the in-call UI:
PhoneApp.getInstance().callController.placeCall(intent);
// Note we do *not* "return" here, but instead continue and
// send the ACTION_NEW_OUTGOING_CALL broadcast like for any
// other outgoing call. (But when the broadcast finally
// reaches the OutgoingCallReceiver, we'll know not to
// initiate the call again because of the presence of the
// EXTRA_ALREADY_CALLED extra.)
}
// Remember the call origin so that users will be able to see an appropriate screen
// after the phone call. This should affect both phone calls and SIP calls.
final String callOrigin = intent.getStringExtra(PhoneApp.EXTRA_CALL_ORIGIN);
if (callOrigin != null) {
if (DBG) Log.v(TAG, "Call origin is passed (" + callOrigin + ")");
PhoneApp.getInstance().setLatestActiveCallOrigin(callOrigin);
} else {
if (DBG) Log.v(TAG, "Call origin is not passed. Reset current one.");
PhoneApp.getInstance().resetLatestActiveCallOrigin();
}
// For now, SIP calls will be processed directly without a
// NEW_OUTGOING_CALL broadcast.
//
// TODO: In the future, though, 3rd party apps *should* be allowed to
// intercept outgoing calls to SIP addresses as well. To do this, we should
// (1) update the NEW_OUTGOING_CALL intent documentation to explain this
// case, and (2) pass the outgoing SIP address by *not* overloading the
// EXTRA_PHONE_NUMBER extra, but instead using a new separate extra to hold
// the outgoing SIP address. (Be sure to document whether it's a URI or just
// a plain address, whether it could be a tel: URI, etc.)
Uri uri = intent.getData();
String scheme = uri.getScheme();
if (Constants.SCHEME_SIP.equals(scheme)
|| PhoneNumberUtils.isUriNumber(number)) {
startSipCallOptionHandler(this, intent, uri, number);
finish();
return;
// TODO: if there's ever a way for SIP calls to trigger a
// "callNow=true" case (see above), we'll need to handle that
// case here too (most likely by just doing nothing at all.)
}
Intent broadcastIntent = new Intent(Intent.ACTION_NEW_OUTGOING_CALL);
if (number != null) {
broadcastIntent.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
}
PhoneUtils.checkAndCopyPhoneProviderExtras(intent, broadcastIntent);
broadcastIntent.putExtra(EXTRA_ALREADY_CALLED, callNow);
broadcastIntent.putExtra(EXTRA_ORIGINAL_URI, uri.toString());
if (DBG) Log.v(TAG, "Broadcasting intent: " + broadcastIntent + ".");
sendOrderedBroadcast(broadcastIntent, PERMISSION, new OutgoingCallReceiver(),
null, // scheduler
Activity.RESULT_OK, // initialCode
number, // initialData: initial value for the result data
null); // initialExtras
}
|
diff --git a/common/logisticspipes/ticks/ClientPacketBufferHandlerThread.java b/common/logisticspipes/ticks/ClientPacketBufferHandlerThread.java
index a25ce6a3..bc4ea17c 100644
--- a/common/logisticspipes/ticks/ClientPacketBufferHandlerThread.java
+++ b/common/logisticspipes/ticks/ClientPacketBufferHandlerThread.java
@@ -1,198 +1,198 @@
package logisticspipes.ticks;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import logisticspipes.LogisticsPipes;
import logisticspipes.network.ClientPacketHandler;
import logisticspipes.network.packets.PacketBufferTransfer;
import logisticspipes.proxy.MainProxy;
import logisticspipes.utils.Pair;
import net.minecraft.network.packet.Packet250CustomPayload;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.network.Player;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
public class ClientPacketBufferHandlerThread extends Thread {
//Shared
private LinkedList<Packet250CustomPayload> clientList = new LinkedList<Packet250CustomPayload>();
private byte[] clientBuffer = new byte[0];
private byte[] ByteBuffer = new byte[]{};
private Object queueLock = new Object();
private LinkedList<byte[]> queue = new LinkedList<byte[]>();
public boolean pause = false;
private LinkedList<Pair<Player,byte[]>> PacketBuffer = new LinkedList<Pair<Player,byte[]>>();
public ClientPacketBufferHandlerThread() {
super("LogisticsPipes Packet Compressor Client");
this.setDaemon(true);
this.start();
TickRegistry.registerTickHandler(new ITickHandler() {
@Override
public EnumSet<TickType> ticks() {
return EnumSet.of(TickType.CLIENT);
}
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData) {}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData) {
boolean flag = false;
do {
flag = false;
Pair<Player,byte[]> part = null;
synchronized (PacketBuffer) {
if(PacketBuffer.size() > 0) {
flag = true;
part = PacketBuffer.pop();
}
}
if(flag) {
ClientPacketHandler.onPacketData(new DataInputStream(new ByteArrayInputStream(part.getValue2())), part.getValue1());
}
} while(flag);
}
@Override
public String getLabel() {
return "LogisticsPipes Packet Compressor Tick Client";
}
}, Side.CLIENT);
}
public void addPacketToCompressor(Packet250CustomPayload packet) {
if(packet.channel.equals("BCLP")) {
synchronized(clientList) {
clientList.add(packet);
}
}
}
public void handlePacket(PacketBufferTransfer packet) {
synchronized(queueLock) {
queue.addLast(packet.content);
}
}
@Override
public void run() {
while(true) {
if(!pause) {
try {
boolean flag = false;
do {
flag = false;
byte[] buffer = null;
synchronized(queueLock) {
if(queue.size() > 0) {
flag = true;
buffer = queue.getFirst();
queue.removeFirst();
}
}
if(flag && buffer != null) {
byte[] packetbytes = decompress(buffer);
byte[] newBuffer = new byte[packetbytes.length + ByteBuffer.length];
System.arraycopy(ByteBuffer, 0, newBuffer, 0, ByteBuffer.length);
System.arraycopy(packetbytes, 0, newBuffer, ByteBuffer.length, packetbytes.length);
ByteBuffer = newBuffer;
}
}
while(flag);
if(ByteBuffer.length > 0) {
int size = ((ByteBuffer[0] & 255) << 24) + ((ByteBuffer[1] & 255) << 16) + ((ByteBuffer[2] & 255) << 8) + ((ByteBuffer[3] & 255) << 0);
while(size + 4 <= ByteBuffer.length) {
byte[] packet = Arrays.copyOfRange(ByteBuffer, 4, size + 4);
ByteBuffer = Arrays.copyOfRange(ByteBuffer, size + 4, ByteBuffer.length);
synchronized (PacketBuffer) {
PacketBuffer.add(new Pair<Player,byte[]>((Player) MainProxy.proxy.getClientPlayer(),packet));
}
if(ByteBuffer.length > 4) {
size = ((ByteBuffer[0] & 255) << 24) + ((ByteBuffer[1] & 255) << 16) + ((ByteBuffer[2] & 255) << 8) + ((ByteBuffer[3] & 255) << 0);
} else {
size = 0;
}
}
}
synchronized(clientList) {
if(clientList.size() > 0) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream data = new DataOutputStream(out);
data.write(clientBuffer);
LinkedList<Packet250CustomPayload> packets = clientList;
for(Packet250CustomPayload packet:packets) {
data.writeInt(packet.data.length);
data.write(packet.data);
}
packets.clear();
clientBuffer = out.toByteArray();
}
//Send Content
if(clientBuffer.length > 0) {
byte[] sendbuffer = Arrays.copyOf(clientBuffer, Math.min(1024 * 32, clientBuffer.length));
byte[] newbuffer = Arrays.copyOfRange(clientBuffer, Math.min(1024 * 32, clientBuffer.length), clientBuffer.length);
clientBuffer = newbuffer;
byte[] compressed = compress(sendbuffer);
MainProxy.sendPacketToServer(new PacketBufferTransfer(compressed).getPacket());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
boolean toDo = queue.size() > 0;
- if(ByteBuffer.length <= 0) {
+ if(ByteBuffer.length > 0) {
toDo = true;
}
synchronized(clientList) {
if(clientList.size() > 0) {
toDo = true;
}
}
if(!toDo) {
Thread.sleep(100);
}
} catch(Exception e) {}
}
}
private static byte[] compress(byte[] content){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try{
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gzipOutputStream.write(content);
gzipOutputStream.close();
} catch(IOException e){
throw new RuntimeException(e);
}
return byteArrayOutputStream.toByteArray();
}
private static byte[] decompress(byte[] contentBytes){
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(contentBytes));
int buffer = 0;
while((buffer = gzip.read()) != -1) {
out.write(buffer);
}
} catch(IOException e){
throw new RuntimeException(e);
}
return out.toByteArray();
}
}
| true | true | public void run() {
while(true) {
if(!pause) {
try {
boolean flag = false;
do {
flag = false;
byte[] buffer = null;
synchronized(queueLock) {
if(queue.size() > 0) {
flag = true;
buffer = queue.getFirst();
queue.removeFirst();
}
}
if(flag && buffer != null) {
byte[] packetbytes = decompress(buffer);
byte[] newBuffer = new byte[packetbytes.length + ByteBuffer.length];
System.arraycopy(ByteBuffer, 0, newBuffer, 0, ByteBuffer.length);
System.arraycopy(packetbytes, 0, newBuffer, ByteBuffer.length, packetbytes.length);
ByteBuffer = newBuffer;
}
}
while(flag);
if(ByteBuffer.length > 0) {
int size = ((ByteBuffer[0] & 255) << 24) + ((ByteBuffer[1] & 255) << 16) + ((ByteBuffer[2] & 255) << 8) + ((ByteBuffer[3] & 255) << 0);
while(size + 4 <= ByteBuffer.length) {
byte[] packet = Arrays.copyOfRange(ByteBuffer, 4, size + 4);
ByteBuffer = Arrays.copyOfRange(ByteBuffer, size + 4, ByteBuffer.length);
synchronized (PacketBuffer) {
PacketBuffer.add(new Pair<Player,byte[]>((Player) MainProxy.proxy.getClientPlayer(),packet));
}
if(ByteBuffer.length > 4) {
size = ((ByteBuffer[0] & 255) << 24) + ((ByteBuffer[1] & 255) << 16) + ((ByteBuffer[2] & 255) << 8) + ((ByteBuffer[3] & 255) << 0);
} else {
size = 0;
}
}
}
synchronized(clientList) {
if(clientList.size() > 0) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream data = new DataOutputStream(out);
data.write(clientBuffer);
LinkedList<Packet250CustomPayload> packets = clientList;
for(Packet250CustomPayload packet:packets) {
data.writeInt(packet.data.length);
data.write(packet.data);
}
packets.clear();
clientBuffer = out.toByteArray();
}
//Send Content
if(clientBuffer.length > 0) {
byte[] sendbuffer = Arrays.copyOf(clientBuffer, Math.min(1024 * 32, clientBuffer.length));
byte[] newbuffer = Arrays.copyOfRange(clientBuffer, Math.min(1024 * 32, clientBuffer.length), clientBuffer.length);
clientBuffer = newbuffer;
byte[] compressed = compress(sendbuffer);
MainProxy.sendPacketToServer(new PacketBufferTransfer(compressed).getPacket());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
boolean toDo = queue.size() > 0;
if(ByteBuffer.length <= 0) {
toDo = true;
}
synchronized(clientList) {
if(clientList.size() > 0) {
toDo = true;
}
}
if(!toDo) {
Thread.sleep(100);
}
} catch(Exception e) {}
}
}
| public void run() {
while(true) {
if(!pause) {
try {
boolean flag = false;
do {
flag = false;
byte[] buffer = null;
synchronized(queueLock) {
if(queue.size() > 0) {
flag = true;
buffer = queue.getFirst();
queue.removeFirst();
}
}
if(flag && buffer != null) {
byte[] packetbytes = decompress(buffer);
byte[] newBuffer = new byte[packetbytes.length + ByteBuffer.length];
System.arraycopy(ByteBuffer, 0, newBuffer, 0, ByteBuffer.length);
System.arraycopy(packetbytes, 0, newBuffer, ByteBuffer.length, packetbytes.length);
ByteBuffer = newBuffer;
}
}
while(flag);
if(ByteBuffer.length > 0) {
int size = ((ByteBuffer[0] & 255) << 24) + ((ByteBuffer[1] & 255) << 16) + ((ByteBuffer[2] & 255) << 8) + ((ByteBuffer[3] & 255) << 0);
while(size + 4 <= ByteBuffer.length) {
byte[] packet = Arrays.copyOfRange(ByteBuffer, 4, size + 4);
ByteBuffer = Arrays.copyOfRange(ByteBuffer, size + 4, ByteBuffer.length);
synchronized (PacketBuffer) {
PacketBuffer.add(new Pair<Player,byte[]>((Player) MainProxy.proxy.getClientPlayer(),packet));
}
if(ByteBuffer.length > 4) {
size = ((ByteBuffer[0] & 255) << 24) + ((ByteBuffer[1] & 255) << 16) + ((ByteBuffer[2] & 255) << 8) + ((ByteBuffer[3] & 255) << 0);
} else {
size = 0;
}
}
}
synchronized(clientList) {
if(clientList.size() > 0) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream data = new DataOutputStream(out);
data.write(clientBuffer);
LinkedList<Packet250CustomPayload> packets = clientList;
for(Packet250CustomPayload packet:packets) {
data.writeInt(packet.data.length);
data.write(packet.data);
}
packets.clear();
clientBuffer = out.toByteArray();
}
//Send Content
if(clientBuffer.length > 0) {
byte[] sendbuffer = Arrays.copyOf(clientBuffer, Math.min(1024 * 32, clientBuffer.length));
byte[] newbuffer = Arrays.copyOfRange(clientBuffer, Math.min(1024 * 32, clientBuffer.length), clientBuffer.length);
clientBuffer = newbuffer;
byte[] compressed = compress(sendbuffer);
MainProxy.sendPacketToServer(new PacketBufferTransfer(compressed).getPacket());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
boolean toDo = queue.size() > 0;
if(ByteBuffer.length > 0) {
toDo = true;
}
synchronized(clientList) {
if(clientList.size() > 0) {
toDo = true;
}
}
if(!toDo) {
Thread.sleep(100);
}
} catch(Exception e) {}
}
}
|
diff --git a/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java b/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java
index 7f28572..1c4d289 100644
--- a/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java
+++ b/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java
@@ -1,168 +1,170 @@
package hudson.plugins.promoted_builds.conditions;
import hudson.CopyOnWrite;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import hudson.plugins.promoted_builds.JobPropertyImpl;
import hudson.plugins.promoted_builds.PromotionCondition;
import hudson.plugins.promoted_builds.PromotionConditionDescriptor;
import hudson.plugins.promoted_builds.PromotionCriterion;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Kohsuke Kawaguchi
*/
public class DownstreamPassCondition extends PromotionCondition {
/**
* List of downstream jobs that are used as the promotion criteria.
*
* Every job has to have at least one successful build for us to promote a build.
*/
private final String jobs;
public DownstreamPassCondition(String jobs) {
this.jobs = jobs;
}
public String getJobs() {
return jobs;
}
@Override
public boolean isMet(AbstractBuild<?,?> build) {
for (AbstractProject<?,?> j : getJobList()) {
boolean passed = false;
for( AbstractBuild<?,?> b : build.getDownstreamBuilds(j) ) {
if(b.getResult()== Result.SUCCESS) {
passed = true;
break;
}
}
if(!passed) // none of the builds of this job passed.
return false;
}
return true;
}
public PromotionConditionDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
/**
* List of downstream jobs that we need to monitor.
*
* @return never null.
*/
public List<AbstractProject<?,?>> getJobList() {
List<AbstractProject<?,?>> r = new ArrayList<AbstractProject<?,?>>();
for (String name : Util.tokenize(jobs,",")) {
AbstractProject job = Hudson.getInstance().getItemByFullName(name.trim(),AbstractProject.class);
if(job!=null) r.add(job);
}
return r;
}
/**
* Short-cut for {@code getJobList().contains(job)}.
*/
public boolean contains(AbstractProject<?,?> job) {
if(!jobs.contains(job.getFullName())) return false; // quick rejection test
for (String name : Util.tokenize(jobs,",")) {
if(name.trim().equals(job.getFullName()))
return true;
}
return false;
}
public static final class DescriptorImpl extends PromotionConditionDescriptor {
public DescriptorImpl() {
super(DownstreamPassCondition.class);
new RunListenerImpl().register();
}
public boolean isApplicable(AbstractProject<?,?> item) {
return true;
}
public String getDisplayName() {
return "When the following downstream projects build successfully";
}
public PromotionCondition newInstance(StaplerRequest req, JSONObject formData) throws FormException {
return new DownstreamPassCondition(formData.getString("jobs"));
}
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
}
/**
* {@link RunListener} to pick up completions of downstream builds.
*
* <p>
* This is a single instance that receives all the events everywhere in the system.
* @author Kohsuke Kawaguchi
*/
private static final class RunListenerImpl extends RunListener<AbstractBuild<?,?>> {
public RunListenerImpl() {
super((Class)AbstractBuild.class);
}
@Override
public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) {
// this is not terribly efficient,
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
JobPropertyImpl p = j.getProperty(JobPropertyImpl.class);
if(p!=null) {
for (PromotionCriterion c : p.getCriteria()) {
boolean considerPromotion = false;
for (PromotionCondition cond : c.getConditions()) {
if (cond instanceof DownstreamPassCondition) {
DownstreamPassCondition dpcond = (DownstreamPassCondition) cond;
if(dpcond.contains(build.getParent()))
considerPromotion = true;
}
}
if(considerPromotion) {
try {
- c.considerPromotion(build.getUpstreamRelationshipBuild(j));
+ AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j);
+ if(u!=null)
+ c.considerPromotion(u);
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to promote a build"));
}
}
}
}
}
}
/**
* List of downstream jobs that we are interested in.
*/
@CopyOnWrite
private static volatile Set<AbstractProject> DOWNSTREAM_JOBS = Collections.emptySet();
/**
* Called whenever some {@link JobPropertyImpl} changes to update {@link #DOWNSTREAM_JOBS}.
*/
public static void rebuildCache() {
Set<AbstractProject> downstreams = new HashSet<AbstractProject>();
DOWNSTREAM_JOBS = downstreams;
}
}
}
| true | true | public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) {
// this is not terribly efficient,
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
JobPropertyImpl p = j.getProperty(JobPropertyImpl.class);
if(p!=null) {
for (PromotionCriterion c : p.getCriteria()) {
boolean considerPromotion = false;
for (PromotionCondition cond : c.getConditions()) {
if (cond instanceof DownstreamPassCondition) {
DownstreamPassCondition dpcond = (DownstreamPassCondition) cond;
if(dpcond.contains(build.getParent()))
considerPromotion = true;
}
}
if(considerPromotion) {
try {
c.considerPromotion(build.getUpstreamRelationshipBuild(j));
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to promote a build"));
}
}
}
}
}
}
| public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) {
// this is not terribly efficient,
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
JobPropertyImpl p = j.getProperty(JobPropertyImpl.class);
if(p!=null) {
for (PromotionCriterion c : p.getCriteria()) {
boolean considerPromotion = false;
for (PromotionCondition cond : c.getConditions()) {
if (cond instanceof DownstreamPassCondition) {
DownstreamPassCondition dpcond = (DownstreamPassCondition) cond;
if(dpcond.contains(build.getParent()))
considerPromotion = true;
}
}
if(considerPromotion) {
try {
AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j);
if(u!=null)
c.considerPromotion(u);
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to promote a build"));
}
}
}
}
}
}
|
diff --git a/atlas-data-storage/src/main/java/uk/ac/ebi/gxa/data/NetCDFDataCreator.java b/atlas-data-storage/src/main/java/uk/ac/ebi/gxa/data/NetCDFDataCreator.java
index 89deb8c9b..e67e5f420 100644
--- a/atlas-data-storage/src/main/java/uk/ac/ebi/gxa/data/NetCDFDataCreator.java
+++ b/atlas-data-storage/src/main/java/uk/ac/ebi/gxa/data/NetCDFDataCreator.java
@@ -1,574 +1,574 @@
/*
* Copyright 2008-2011 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* 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.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.gxa.data;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ucar.ma2.*;
import ucar.nc2.Dimension;
import ucar.nc2.NetcdfFileWriteable;
import uk.ac.ebi.microarray.atlas.model.ArrayDesign;
import uk.ac.ebi.microarray.atlas.model.Assay;
import uk.ac.ebi.microarray.atlas.model.Experiment;
import uk.ac.ebi.microarray.atlas.model.Sample;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* Efficient NetCDF writer tailored to handle chunked expression values blocks found in
* MAGETAB expression matrixes
*
* @author pashky
*/
public class NetCDFDataCreator {
private final Logger log = LoggerFactory.getLogger(NetCDFDataCreator.class);
private final AtlasDataDAO dataDAO;
private final Experiment experiment;
private final ArrayDesign arrayDesign;
private final List<Assay> assays;
private final LinkedHashSet<Sample> samples = new LinkedHashSet<Sample>();
private final ListMultimap<Assay, Sample> samplesMap = ArrayListMultimap.create();
private Map<String, DataMatrixStorage.ColumnRef> assayDataMap = new HashMap<String, DataMatrixStorage.ColumnRef>();
private final List<DataMatrixStorage> storages = new ArrayList<DataMatrixStorage>();
private final ListMultimap<DataMatrixStorage, Assay> storageAssaysMap = ArrayListMultimap.create();
private Iterable<String> mergedDesignElements;
private Map<String, Integer> mergedDesignElementsMap;
private boolean canWriteFirstFull;
// maps of properties
private LinkedHashMap<String, List<String>> efvMap;
private LinkedHashMap<String, List<String>> scvMap;
private final List<String> warnings = new ArrayList<String>();
private int totalDesignElements;
private int maxDesignElementLength;
private int maxEfLength;
private int maxEfvLength;
private int maxScLength;
private int maxScvLength;
NetCDFDataCreator(AtlasDataDAO dataDAO, Experiment experiment, ArrayDesign arrayDesign) {
this.dataDAO = dataDAO;
this.experiment = experiment;
this.arrayDesign = arrayDesign;
this.assays = new ArrayList<Assay>(experiment.getAssaysForDesign(arrayDesign));
for (Assay a : this.assays) {
for (Sample s : a.getSamples()) {
this.samples.add(s);
this.samplesMap.put(a, s);
}
}
}
public void setAssayDataMap(Map<String, DataMatrixStorage.ColumnRef> assayDataMap) {
this.assayDataMap = assayDataMap;
}
private LinkedHashMap<String, List<String>> extractAssayProperties(List<Assay> assays) {
final LinkedHashMap<String, List<String>> result = new LinkedHashMap<String, List<String>>();
final SortedSet<String> propertyNames = new TreeSet<String>();
for (Assay a : assays) {
propertyNames.addAll(a.getPropertyNames());
}
for (String propertyName : propertyNames) {
final List<String> propertyList = new ArrayList<String>(assays.size());
for (final Assay a : assays) {
propertyList.add(a.getPropertySummary(propertyName));
}
result.put(propertyName, propertyList);
}
return result;
}
private LinkedHashMap<String, List<String>> extractSampleProperties(final List<Sample> samples) {
final LinkedHashMap<String, List<String>> result = new LinkedHashMap<String, List<String>>();
final SortedSet<String> propertyNames = new TreeSet<String>();
for (final Sample s : samples) {
propertyNames.addAll(s.getPropertyNames());
}
for (final String propertyName : propertyNames) {
final List<String> propertyList = new ArrayList<String>(samples.size());
for (final Sample s : samples) {
propertyList.add(s.getPropertySummary(propertyName));
}
result.put(propertyName, propertyList);
}
return result;
}
void prepareData() {
for (Assay a : assays) {
DataMatrixStorage buf = assayDataMap.get(a.getAccession()).storage;
if (!storages.contains(buf))
storages.add(buf);
}
// sort assay in order of buffers and reference numbers in those buffers
Collections.sort(assays, new Comparator<Assay>() {
public int compare(Assay o1, Assay o2) {
DataMatrixStorage.ColumnRef ref1 = assayDataMap.get(o1.getAccession());
DataMatrixStorage buf1 = ref1.storage;
int i1 = storages.indexOf(buf1);
DataMatrixStorage.ColumnRef ref2 = assayDataMap.get(o2.getAccession());
DataMatrixStorage buf2 = ref2.storage;
int i2 = storages.indexOf(buf2);
if (i1 != i2)
return i1 - i2;
return ref1.referenceIndex - ref2.referenceIndex;
}
});
// build reverse map
for (Assay a : assays)
storageAssaysMap.put(assayDataMap.get(a.getAccession()).storage, a);
// reshape available properties to match assays & samples
final List<Sample> samplesList = new ArrayList<Sample>(samples);
efvMap = extractAssayProperties(assays);
scvMap = extractSampleProperties(samplesList);
// find maximum lengths for ef/efv/sc/scv strings
maxEfLength = 0;
maxEfvLength = 0;
for (String ef : efvMap.keySet()) {
maxEfLength = Math.max(maxEfLength, ef.length());
for (String efv : efvMap.get(ef))
maxEfvLength = Math.max(maxEfvLength, efv.length());
}
maxScLength = 0;
maxScvLength = 0;
for (String sc : scvMap.keySet()) {
maxScLength = Math.max(maxScLength, sc.length());
for (String scv : scvMap.get(sc))
maxScvLength = Math.max(maxScvLength, scv.length());
}
// merge available design elements (if needed)
canWriteFirstFull = true;
if (storages.size() == 1)
mergedDesignElements = storages.get(0).getDesignElements();
else {
mergedDesignElementsMap = new LinkedHashMap<String, Integer>();
boolean first = true;
for (DataMatrixStorage buffer : storages) {
for (String de : buffer.getDesignElements())
if (!mergedDesignElementsMap.containsKey(de))
mergedDesignElementsMap.put(de, mergedDesignElementsMap.size());
else if (first)
canWriteFirstFull = false;
first = false;
}
mergedDesignElements = mergedDesignElementsMap.keySet();
}
// calculate number of available DEs, genes and maximum accesion string length
totalDesignElements = 0;
maxDesignElementLength = 0;
for (String de : mergedDesignElements) {
maxDesignElementLength = Math.max(maxDesignElementLength, de.length());
++totalDesignElements;
}
}
private void create(NetcdfFileWriteable netCdf) throws IOException {
// NetCDF doesn't know how to store longs, so we use DataType.DOUBLE for internal DB ids
final Dimension assayDimension = netCdf.addDimension("AS", assays.size());
final Dimension sampleDimension = netCdf.addDimension("BS", samples.size());
netCdf.addVariable(
"BS2AS", DataType.INT,
new Dimension[]{sampleDimension, assayDimension}
);
// update the netCDFs with the genes count
final Dimension designElementDimension =
netCdf.addDimension("DE", totalDesignElements);
final Dimension designElementLenDimension =
netCdf.addDimension("DElen", maxDesignElementLength);
netCdf.addVariable(
"DEacc", DataType.CHAR,
new Dimension[]{designElementDimension, designElementLenDimension}
);
netCdf.addVariable(
- "GN", DataType.DOUBLE,
+ "GN", DataType.LONG,
new Dimension[]{designElementDimension}
);
//accessions for Assays and Samples
int maxAssayLength = 0;
for (Assay assay : assays) {
maxAssayLength = Math.max(maxAssayLength, assay.getAccession().length());
}
final Dimension assayLenDimension = netCdf.addDimension("ASlen", maxAssayLength);
netCdf.addVariable("ASacc", DataType.CHAR, new Dimension[]{assayDimension, assayLenDimension});
int maxSampleLength = 0;
for (Sample sample : samples) {
maxSampleLength = Math.max(maxSampleLength, sample.getAccession().length());
}
final Dimension sampleLenDimension = netCdf.addDimension("BSlen", maxSampleLength);
netCdf.addVariable("BSacc", DataType.CHAR, new Dimension[]{sampleDimension, sampleLenDimension});
if (!scvMap.isEmpty()) {
Dimension scDimension = netCdf.addDimension("SC", scvMap.keySet().size());
Dimension sclenDimension = netCdf.addDimension("SClen", maxScLength);
netCdf.addVariable("SC", DataType.CHAR, new Dimension[]{scDimension, sclenDimension});
Dimension scvlenDimension = netCdf.addDimension("SCVlen", maxScvLength);
netCdf.addVariable("SCV", DataType.CHAR,
new Dimension[]{scDimension, sampleDimension, scvlenDimension});
}
if (!efvMap.isEmpty()) {
Dimension efDimension = netCdf.addDimension("EF", efvMap.keySet().size());
Dimension eflenDimension = netCdf.addDimension("EFlen", maxEfLength);
netCdf.addVariable("EF", DataType.CHAR, new Dimension[]{efDimension, eflenDimension});
Dimension efvlenDimension = netCdf.addDimension("EFVlen", maxEfLength + maxEfvLength + 2);
netCdf.addVariable("EFV", DataType.CHAR, new Dimension[]{efDimension, assayDimension, efvlenDimension});
}
netCdf.addVariable(
"BDC", DataType.FLOAT,
new Dimension[]{designElementDimension, assayDimension}
);
// add metadata global attributes
safeAddGlobalAttribute(
netCdf,
"CreateNetCDF_VERSION",
"2.0");
safeAddGlobalAttribute(
netCdf,
"experiment_accession",
experiment.getAccession());
safeAddGlobalAttribute(
netCdf,
"ADaccession",
arrayDesign.getAccession());
NetCDFHacks.safeCreate(netCdf);
}
private void write(NetcdfFileWriteable netCdf) throws IOException, InvalidRangeException {
writeSamplesAssays(netCdf);
writeSampleAccessions(netCdf);
writeAssayAccessions(netCdf);
if (!efvMap.isEmpty()) {
writeEfvs(netCdf);
}
if (!scvMap.isEmpty()) {
writeScvs(netCdf);
}
writeDesignElements(netCdf);
writeData(netCdf);
if (storages.size() != 1) {
canWriteFirstFull = false;
}
}
private Iterable<Assay> getColumnsForStorage(DataMatrixStorage storage) {
return storageAssaysMap.get(storage);
}
private void writeData(NetcdfFileWriteable netCdf) throws IOException, InvalidRangeException {
boolean first = true;
for (DataMatrixStorage storage : storages) {
if (getColumnsForStorage(storage) == null || !getColumnsForStorage(
storage).iterator().hasNext()) // shouldn't happen, but let's be sure
continue;
if (first) { // skip first
first = false;
if (canWriteFirstFull) {
int deNum = 0;
for (DataMatrixStorage.Block block : storage.getBlocks()) {
writeDataBlock(netCdf, storage, block, deNum, 0, block.size() - 1);
deNum += block.size();
}
continue;
}
// else continue as merging
}
// write other buffers finding continuous (in terms of output sequence) blocks of design elements
for (DataMatrixStorage.Block block : storage.getBlocks()) {
int startSource = -1;
int startDestination = -1;
int currentSource;
for (currentSource = 0; currentSource < block.size(); ++currentSource) {
int currentDestination = mergedDesignElementsMap.get(block.designElements[currentSource]);
if (startSource == -1) {
startSource = currentSource;
startDestination = currentDestination;
} else if (currentDestination != startDestination + (currentSource - startSource)) {
writeDataBlock(netCdf, storage, block, startDestination, startSource, currentSource - 1);
startSource = currentSource;
startDestination = currentDestination;
}
}
writeDataBlock(netCdf, storage, block, startDestination, startSource, currentSource - 1);
}
}
}
private void writeDataBlock(NetcdfFileWriteable netCdf, DataMatrixStorage storage, DataMatrixStorage.Block block,
int deNum, int deBlockFrom, int deBlockTo)
throws IOException, InvalidRangeException {
final String variableName = "BDC";
int width = storage.getWidth();
ArrayFloat data = (ArrayFloat) Array.factory(Float.class, new int[]{block.designElements.length, width},
block.expressionValues);
int startReference = -1;
int startDestination = -1;
int currentDestination = -1;
int currentReference = -1;
for (Assay assay : getColumnsForStorage(storage)) {
int prevReference = currentReference;
currentReference = assayDataMap.get(assay.getAccession()).referenceIndex;
if (currentDestination == -1) {
currentDestination = assays.indexOf(assay);
}
if (startReference == -1) {
startReference = currentReference;
startDestination = currentDestination;
} else if (currentDestination != startDestination + (currentReference - startReference)) {
ArrayFloat adata = (ArrayFloat) data.sectionNoReduce(
Arrays.asList(
new Range(deBlockFrom, deBlockTo),
new Range(startReference, prevReference)));
netCdf.write(variableName, new int[]{deNum, startDestination}, adata);
startReference = currentReference;
startDestination = currentDestination;
}
++currentDestination;
}
ArrayFloat adata = (ArrayFloat) data.sectionNoReduce(
Arrays.asList(
new Range(deBlockFrom, deBlockTo),
new Range(startReference, currentReference)));
netCdf.write(variableName, new int[]{deNum, startDestination}, adata);
}
private void writeDesignElements(NetcdfFileWriteable netCdf) throws IOException, InvalidRangeException {
// store design elements one by one
int i = 0;
ArrayChar deName = new ArrayChar.D2(1, maxDesignElementLength);
ArrayInt deIds = new ArrayInt.D1(totalDesignElements);
ArrayInt gnIds = new ArrayInt.D1(totalDesignElements);
boolean deMapped = false;
boolean geneMapped = false;
for (String de : mergedDesignElements) {
deName.setString(0, de);
netCdf.write("DEacc", new int[]{i, 0}, deName);
Long deId = arrayDesign.getDesignElement(de);
if (deId != null) {
deMapped = true;
deIds.setLong(i, deId);
List<Long> gnId = arrayDesign.getGeneId(deId);
// TODO: currently, we only have one gene per DE; we may want to change it later on
if (gnId != null && !gnId.isEmpty()) {
gnIds.setLong(i, gnId.get(0));
geneMapped = true;
}
}
++i;
}
netCdf.write("GN", gnIds);
if (!deMapped)
warnings.add("No design element mappings were found");
if (!geneMapped)
warnings.add("No gene mappings were found");
}
private void writeAssayAccessions(NetcdfFileWriteable netCdf) throws IOException, InvalidRangeException {
final List<String> accessions = new ArrayList<String>();
for (Assay a : assays) {
accessions.add(a.getAccession());
}
writeList(netCdf, "ASacc", accessions);
}
private void writeSampleAccessions(NetcdfFileWriteable netCdf) throws IOException, InvalidRangeException {
final List<String> accessions = new ArrayList<String>();
for (Sample s : samples) {
accessions.add(s.getAccession());
}
writeList(netCdf, "BSacc", accessions);
}
private void writeList(NetcdfFileWriteable netCdf, String variable,
List<String> values) throws IOException, InvalidRangeException {
int maxValueLength = 0;
for (String value : values) {
if ((null != value) && (value.length() > maxValueLength))
maxValueLength = value.length();
}
ArrayChar valueBuffer = new ArrayChar.D2(1, maxValueLength);
int i = 0;
for (String value : values) {
valueBuffer.setString(0, (null == value ? "" : value));
netCdf.write(variable, new int[]{i, 0}, valueBuffer);
++i;
}
}
private void writeSamplesAssays(NetcdfFileWriteable netCdf) throws IOException, InvalidRangeException {
ArrayInt bs2as = new ArrayInt.D2(samples.size(), assays.size());
IndexIterator bs2asIt = bs2as.getIndexIterator();
// iterate over assays and samples,
for (Sample sample : samples) {
for (Assay assay : assays) {
bs2asIt.setIntNext(samplesMap.containsKey(assay) && samplesMap.get(assay).contains(sample) ? 1 : 0);
}
}
netCdf.write("BS2AS", bs2as);
}
private void writeEfvs(NetcdfFileWriteable netCdf) throws IOException, InvalidRangeException {
// write assay property values
ArrayChar ef = new ArrayChar.D2(efvMap.keySet().size(), maxEfLength);
ArrayChar efv = new ArrayChar.D3(efvMap.keySet().size(), assays.size(), maxEfvLength);
// Populate non-unique efvs
int ei = 0;
for (Map.Entry<String, List<String>> e : efvMap.entrySet()) {
ef.setString(ei, e.getKey());
int vi = 0;
for (String v : e.getValue())
efv.setString(efv.getIndex().set(ei, vi++), v);
++ei;
}
netCdf.write("EF", ef);
netCdf.write("EFV", efv);
}
private void writeScvs(NetcdfFileWriteable netCdf) throws IOException, InvalidRangeException {
ArrayChar sc = new ArrayChar.D2(scvMap.keySet().size(), maxScLength);
ArrayChar scv = new ArrayChar.D3(scvMap.keySet().size(), samples.size(), maxScvLength);
int ei = 0;
for (Map.Entry<String, List<String>> e : scvMap.entrySet()) {
sc.setString(ei, e.getKey());
int vi = 0;
for (String v : e.getValue())
scv.setString(scv.getIndex().set(ei, vi++), v);
++ei;
}
netCdf.write("SC", sc);
netCdf.write("SCV", scv);
}
public void createNetCdf() throws AtlasDataException {
warnings.clear();
prepareData();
try {
final File dataFile = dataDAO.getDataFile(experiment, arrayDesign);
if (!dataFile.getParentFile().exists() && !dataFile.getParentFile().mkdirs()) {
throw new AtlasDataException("Cannot create folder for the output file" + dataFile);
}
final File tempDataFile = File.createTempFile(dataFile.getName(), ".tmp");
log.info("Writing NetCDF file to " + tempDataFile);
final NetcdfFileWriteable netCdf = NetcdfFileWriteable.createNew(tempDataFile.getAbsolutePath(), true);
try {
create(netCdf);
write(netCdf);
} catch (InvalidRangeException e) {
throw new AtlasDataException(e);
} finally {
netCdf.close();
}
log.info("Renaming " + tempDataFile + " to " + dataFile);
if (!tempDataFile.renameTo(dataFile)) {
throw new AtlasDataException("Can't rename " + tempDataFile + " to " + dataFile);
}
} catch (IOException e) {
throw new AtlasDataException(e);
}
}
public List<String> getWarnings() {
return warnings;
}
public boolean hasWarning() {
return !warnings.isEmpty();
}
private void safeAddGlobalAttribute(NetcdfFileWriteable netCdf, String attribute, String value) {
if (attribute != null && value != null) {
netCdf.addGlobalAttribute(attribute, value);
}
}
}
| true | true | private void create(NetcdfFileWriteable netCdf) throws IOException {
// NetCDF doesn't know how to store longs, so we use DataType.DOUBLE for internal DB ids
final Dimension assayDimension = netCdf.addDimension("AS", assays.size());
final Dimension sampleDimension = netCdf.addDimension("BS", samples.size());
netCdf.addVariable(
"BS2AS", DataType.INT,
new Dimension[]{sampleDimension, assayDimension}
);
// update the netCDFs with the genes count
final Dimension designElementDimension =
netCdf.addDimension("DE", totalDesignElements);
final Dimension designElementLenDimension =
netCdf.addDimension("DElen", maxDesignElementLength);
netCdf.addVariable(
"DEacc", DataType.CHAR,
new Dimension[]{designElementDimension, designElementLenDimension}
);
netCdf.addVariable(
"GN", DataType.DOUBLE,
new Dimension[]{designElementDimension}
);
//accessions for Assays and Samples
int maxAssayLength = 0;
for (Assay assay : assays) {
maxAssayLength = Math.max(maxAssayLength, assay.getAccession().length());
}
final Dimension assayLenDimension = netCdf.addDimension("ASlen", maxAssayLength);
netCdf.addVariable("ASacc", DataType.CHAR, new Dimension[]{assayDimension, assayLenDimension});
int maxSampleLength = 0;
for (Sample sample : samples) {
maxSampleLength = Math.max(maxSampleLength, sample.getAccession().length());
}
final Dimension sampleLenDimension = netCdf.addDimension("BSlen", maxSampleLength);
netCdf.addVariable("BSacc", DataType.CHAR, new Dimension[]{sampleDimension, sampleLenDimension});
if (!scvMap.isEmpty()) {
Dimension scDimension = netCdf.addDimension("SC", scvMap.keySet().size());
Dimension sclenDimension = netCdf.addDimension("SClen", maxScLength);
netCdf.addVariable("SC", DataType.CHAR, new Dimension[]{scDimension, sclenDimension});
Dimension scvlenDimension = netCdf.addDimension("SCVlen", maxScvLength);
netCdf.addVariable("SCV", DataType.CHAR,
new Dimension[]{scDimension, sampleDimension, scvlenDimension});
}
if (!efvMap.isEmpty()) {
Dimension efDimension = netCdf.addDimension("EF", efvMap.keySet().size());
Dimension eflenDimension = netCdf.addDimension("EFlen", maxEfLength);
netCdf.addVariable("EF", DataType.CHAR, new Dimension[]{efDimension, eflenDimension});
Dimension efvlenDimension = netCdf.addDimension("EFVlen", maxEfLength + maxEfvLength + 2);
netCdf.addVariable("EFV", DataType.CHAR, new Dimension[]{efDimension, assayDimension, efvlenDimension});
}
netCdf.addVariable(
"BDC", DataType.FLOAT,
new Dimension[]{designElementDimension, assayDimension}
);
// add metadata global attributes
safeAddGlobalAttribute(
netCdf,
"CreateNetCDF_VERSION",
"2.0");
safeAddGlobalAttribute(
netCdf,
"experiment_accession",
experiment.getAccession());
safeAddGlobalAttribute(
netCdf,
"ADaccession",
arrayDesign.getAccession());
NetCDFHacks.safeCreate(netCdf);
}
| private void create(NetcdfFileWriteable netCdf) throws IOException {
// NetCDF doesn't know how to store longs, so we use DataType.DOUBLE for internal DB ids
final Dimension assayDimension = netCdf.addDimension("AS", assays.size());
final Dimension sampleDimension = netCdf.addDimension("BS", samples.size());
netCdf.addVariable(
"BS2AS", DataType.INT,
new Dimension[]{sampleDimension, assayDimension}
);
// update the netCDFs with the genes count
final Dimension designElementDimension =
netCdf.addDimension("DE", totalDesignElements);
final Dimension designElementLenDimension =
netCdf.addDimension("DElen", maxDesignElementLength);
netCdf.addVariable(
"DEacc", DataType.CHAR,
new Dimension[]{designElementDimension, designElementLenDimension}
);
netCdf.addVariable(
"GN", DataType.LONG,
new Dimension[]{designElementDimension}
);
//accessions for Assays and Samples
int maxAssayLength = 0;
for (Assay assay : assays) {
maxAssayLength = Math.max(maxAssayLength, assay.getAccession().length());
}
final Dimension assayLenDimension = netCdf.addDimension("ASlen", maxAssayLength);
netCdf.addVariable("ASacc", DataType.CHAR, new Dimension[]{assayDimension, assayLenDimension});
int maxSampleLength = 0;
for (Sample sample : samples) {
maxSampleLength = Math.max(maxSampleLength, sample.getAccession().length());
}
final Dimension sampleLenDimension = netCdf.addDimension("BSlen", maxSampleLength);
netCdf.addVariable("BSacc", DataType.CHAR, new Dimension[]{sampleDimension, sampleLenDimension});
if (!scvMap.isEmpty()) {
Dimension scDimension = netCdf.addDimension("SC", scvMap.keySet().size());
Dimension sclenDimension = netCdf.addDimension("SClen", maxScLength);
netCdf.addVariable("SC", DataType.CHAR, new Dimension[]{scDimension, sclenDimension});
Dimension scvlenDimension = netCdf.addDimension("SCVlen", maxScvLength);
netCdf.addVariable("SCV", DataType.CHAR,
new Dimension[]{scDimension, sampleDimension, scvlenDimension});
}
if (!efvMap.isEmpty()) {
Dimension efDimension = netCdf.addDimension("EF", efvMap.keySet().size());
Dimension eflenDimension = netCdf.addDimension("EFlen", maxEfLength);
netCdf.addVariable("EF", DataType.CHAR, new Dimension[]{efDimension, eflenDimension});
Dimension efvlenDimension = netCdf.addDimension("EFVlen", maxEfLength + maxEfvLength + 2);
netCdf.addVariable("EFV", DataType.CHAR, new Dimension[]{efDimension, assayDimension, efvlenDimension});
}
netCdf.addVariable(
"BDC", DataType.FLOAT,
new Dimension[]{designElementDimension, assayDimension}
);
// add metadata global attributes
safeAddGlobalAttribute(
netCdf,
"CreateNetCDF_VERSION",
"2.0");
safeAddGlobalAttribute(
netCdf,
"experiment_accession",
experiment.getAccession());
safeAddGlobalAttribute(
netCdf,
"ADaccession",
arrayDesign.getAccession());
NetCDFHacks.safeCreate(netCdf);
}
|
diff --git a/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java b/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java
index 4d07328c7d..30d5bacfbc 100644
--- a/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadTermQuery.java
@@ -1,244 +1,244 @@
package org.apache.lucene.search.payloads;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.DocsAndPositionsEnum;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.ComplexExplanation;
import org.apache.lucene.search.similarities.DefaultSimilarity;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.search.similarities.Similarity.SloppySimScorer;
import org.apache.lucene.search.spans.TermSpans;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.search.spans.SpanWeight;
import org.apache.lucene.search.spans.SpanScorer;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import java.io.IOException;
/**
* This class is very similar to
* {@link org.apache.lucene.search.spans.SpanTermQuery} except that it factors
* in the value of the payload located at each of the positions where the
* {@link org.apache.lucene.index.Term} occurs.
* <p/>
* NOTE: In order to take advantage of this with the default scoring implementation
* ({@link DefaultSimilarity}), you must override {@link DefaultSimilarity#scorePayload(int, int, int, BytesRef)},
* which returns 1 by default.
* <p/>
* Payload scores are aggregated using a pluggable {@link PayloadFunction}.
* @see org.apache.lucene.search.similarities.Similarity.SloppySimScorer#computePayloadFactor(int, int, int, BytesRef)
**/
public class PayloadTermQuery extends SpanTermQuery {
protected PayloadFunction function;
private boolean includeSpanScore;
public PayloadTermQuery(Term term, PayloadFunction function) {
this(term, function, true);
}
public PayloadTermQuery(Term term, PayloadFunction function,
boolean includeSpanScore) {
super(term);
this.function = function;
this.includeSpanScore = includeSpanScore;
}
@Override
public Weight createWeight(IndexSearcher searcher) throws IOException {
return new PayloadTermWeight(this, searcher);
}
protected class PayloadTermWeight extends SpanWeight {
public PayloadTermWeight(PayloadTermQuery query, IndexSearcher searcher)
throws IOException {
super(query, searcher);
}
@Override
public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder,
boolean topScorer, Bits acceptDocs) throws IOException {
return new PayloadTermSpanScorer((TermSpans) query.getSpans(context, acceptDocs, termContexts),
this, similarity.sloppySimScorer(stats, context));
}
protected class PayloadTermSpanScorer extends SpanScorer {
protected BytesRef payload;
protected float payloadScore;
protected int payloadsSeen;
private final TermSpans termSpans;
public PayloadTermSpanScorer(TermSpans spans, Weight weight, Similarity.SloppySimScorer docScorer) throws IOException {
super(spans, weight, docScorer);
termSpans = spans;
}
@Override
protected boolean setFreqCurrentDoc() throws IOException {
if (!more) {
return false;
}
doc = spans.doc();
freq = 0.0f;
payloadScore = 0;
payloadsSeen = 0;
while (more && doc == spans.doc()) {
int matchLength = spans.end() - spans.start();
freq += docScorer.computeSlopFactor(matchLength);
processPayload(similarity);
more = spans.next();// this moves positions to the next match in this
// document
}
return more || (freq != 0);
}
protected void processPayload(Similarity similarity) throws IOException {
final DocsAndPositionsEnum postings = termSpans.getPostings();
if (postings.hasPayload()) {
payload = postings.getPayload();
if (payload != null) {
payloadScore = function.currentScore(doc, term.field(),
spans.start(), spans.end(), payloadsSeen, payloadScore,
docScorer.computePayloadFactor(doc, spans.start(), spans.end(), payload));
} else {
payloadScore = function.currentScore(doc, term.field(),
spans.start(), spans.end(), payloadsSeen, payloadScore, 1F);
}
payloadsSeen++;
} else {
// zero out the payload?
}
}
/**
*
* @return {@link #getSpanScore()} * {@link #getPayloadScore()}
* @throws IOException
*/
@Override
public float score() throws IOException {
return includeSpanScore ? getSpanScore() * getPayloadScore()
: getPayloadScore();
}
/**
* Returns the SpanScorer score only.
* <p/>
* Should not be overridden without good cause!
*
* @return the score for just the Span part w/o the payload
* @throws IOException
*
* @see #score()
*/
protected float getSpanScore() throws IOException {
return super.score();
}
/**
* The score for the payload
*
* @return The score, as calculated by
* {@link PayloadFunction#docScore(int, String, int, float)}
*/
protected float getPayloadScore() {
return function.docScore(doc, term.field(), payloadsSeen, payloadScore);
}
}
@Override
public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
PayloadTermSpanScorer scorer = (PayloadTermSpanScorer) scorer(context, true, false, context.reader().getLiveDocs());
if (scorer != null) {
int newDoc = scorer.advance(doc);
if (newDoc == doc) {
float freq = scorer.freq();
SloppySimScorer docScorer = similarity.sloppySimScorer(stats, context);
Explanation expl = new Explanation();
expl.setDescription("weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:");
Explanation scoreExplanation = docScorer.explain(doc, new Explanation(freq, "phraseFreq=" + freq));
expl.addDetail(scoreExplanation);
expl.setValue(scoreExplanation.getValue());
// now the payloads part
// QUESTION: Is there a way to avoid this skipTo call? We need to know
// whether to load the payload or not
// GSI: I suppose we could toString the payload, but I don't think that
// would be a good idea
- Explanation payloadExpl = new Explanation(scorer.getPayloadScore(), "scorePayload(...)");
+ Explanation payloadExpl = function.explain(doc, scorer.payloadsSeen, scorer.payloadScore);
payloadExpl.setValue(scorer.getPayloadScore());
// combined
ComplexExplanation result = new ComplexExplanation();
if (includeSpanScore) {
result.addDetail(expl);
result.addDetail(payloadExpl);
result.setValue(expl.getValue() * payloadExpl.getValue());
result.setDescription("btq, product of:");
} else {
result.addDetail(payloadExpl);
result.setValue(payloadExpl.getValue());
result.setDescription("btq(includeSpanScore=false), result of:");
}
result.setMatch(true); // LUCENE-1303
return result;
}
}
return new ComplexExplanation(false, 0.0f, "no matching term");
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((function == null) ? 0 : function.hashCode());
result = prime * result + (includeSpanScore ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
PayloadTermQuery other = (PayloadTermQuery) obj;
if (function == null) {
if (other.function != null)
return false;
} else if (!function.equals(other.function))
return false;
if (includeSpanScore != other.includeSpanScore)
return false;
return true;
}
}
| true | true | public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
PayloadTermSpanScorer scorer = (PayloadTermSpanScorer) scorer(context, true, false, context.reader().getLiveDocs());
if (scorer != null) {
int newDoc = scorer.advance(doc);
if (newDoc == doc) {
float freq = scorer.freq();
SloppySimScorer docScorer = similarity.sloppySimScorer(stats, context);
Explanation expl = new Explanation();
expl.setDescription("weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:");
Explanation scoreExplanation = docScorer.explain(doc, new Explanation(freq, "phraseFreq=" + freq));
expl.addDetail(scoreExplanation);
expl.setValue(scoreExplanation.getValue());
// now the payloads part
// QUESTION: Is there a way to avoid this skipTo call? We need to know
// whether to load the payload or not
// GSI: I suppose we could toString the payload, but I don't think that
// would be a good idea
Explanation payloadExpl = new Explanation(scorer.getPayloadScore(), "scorePayload(...)");
payloadExpl.setValue(scorer.getPayloadScore());
// combined
ComplexExplanation result = new ComplexExplanation();
if (includeSpanScore) {
result.addDetail(expl);
result.addDetail(payloadExpl);
result.setValue(expl.getValue() * payloadExpl.getValue());
result.setDescription("btq, product of:");
} else {
result.addDetail(payloadExpl);
result.setValue(payloadExpl.getValue());
result.setDescription("btq(includeSpanScore=false), result of:");
}
result.setMatch(true); // LUCENE-1303
return result;
}
}
return new ComplexExplanation(false, 0.0f, "no matching term");
}
| public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
PayloadTermSpanScorer scorer = (PayloadTermSpanScorer) scorer(context, true, false, context.reader().getLiveDocs());
if (scorer != null) {
int newDoc = scorer.advance(doc);
if (newDoc == doc) {
float freq = scorer.freq();
SloppySimScorer docScorer = similarity.sloppySimScorer(stats, context);
Explanation expl = new Explanation();
expl.setDescription("weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:");
Explanation scoreExplanation = docScorer.explain(doc, new Explanation(freq, "phraseFreq=" + freq));
expl.addDetail(scoreExplanation);
expl.setValue(scoreExplanation.getValue());
// now the payloads part
// QUESTION: Is there a way to avoid this skipTo call? We need to know
// whether to load the payload or not
// GSI: I suppose we could toString the payload, but I don't think that
// would be a good idea
Explanation payloadExpl = function.explain(doc, scorer.payloadsSeen, scorer.payloadScore);
payloadExpl.setValue(scorer.getPayloadScore());
// combined
ComplexExplanation result = new ComplexExplanation();
if (includeSpanScore) {
result.addDetail(expl);
result.addDetail(payloadExpl);
result.setValue(expl.getValue() * payloadExpl.getValue());
result.setDescription("btq, product of:");
} else {
result.addDetail(payloadExpl);
result.setValue(payloadExpl.getValue());
result.setDescription("btq(includeSpanScore=false), result of:");
}
result.setMatch(true); // LUCENE-1303
return result;
}
}
return new ComplexExplanation(false, 0.0f, "no matching term");
}
|
diff --git a/src/com/googlecode/ant_deb_task/Deb.java b/src/com/googlecode/ant_deb_task/Deb.java
index 525a2c7..e6b9231 100644
--- a/src/com/googlecode/ant_deb_task/Deb.java
+++ b/src/com/googlecode/ant_deb_task/Deb.java
@@ -1,738 +1,738 @@
package com.googlecode.ant_deb_task;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.Tar;
import org.apache.tools.ant.types.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.security.MessageDigest;
/**
* Task that creates a Debian package.
*
* @antTaskName deb
*/
public class Deb extends Task
{
private static final Pattern PACKAGE_NAME_PATTERN = Pattern.compile("[a-z0-9][a-z0-9+\\-.]+");
public static class Description extends ProjectComponent
{
private String _synopsis;
private String _extended = "";
public String getSynopsis ()
{
return _synopsis;
}
public void setSynopsis (String synopsis)
{
_synopsis = synopsis.trim ();
}
public void addText (String text)
{
_extended += getProject ().replaceProperties (text);
}
public String getExtended ()
{
return _extended;
}
public String getExtendedFormatted ()
{
StringBuffer buffer = new StringBuffer (_extended.length ());
String lines[] = _extended.split ("\n");
int start = 0;
for (int i = 0; i < lines.length; i++)
{
String line = lines[i].trim ();
if (line.length () > 0)
break;
start++;
}
int end = lines.length;
for (int i = lines.length - 1; i >= 0; i--)
{
String line = lines[i].trim ();
if (line.length () > 0)
break;
end--;
}
for (int i = start; i < end; i++)
{
String line = lines[i].trim ();
buffer.append (' ');
buffer.append (line.length () == 0 ? "." : line);
buffer.append ('\n');
}
buffer.deleteCharAt (buffer.length () - 1);
return buffer.toString ();
}
}
public static class Version extends ProjectComponent
{
private static final Pattern UPSTREAM_VERSION_PATTERN = Pattern.compile("[0-9][A-Za-z0-9+\\-.:]*");
private static final Pattern DEBIAN_VERSION_PATTERN = Pattern.compile("[A-Za-z0-9+\\-]+");
private int _epoch = 0;
private String _upstream;
private String _debian = "1";
public void setEpoch(int epoch)
{
_epoch = epoch;
}
public void setUpstream(String upstream)
{
_upstream = upstream.trim ();
if (!UPSTREAM_VERSION_PATTERN.matcher (_upstream).matches ())
throw new BuildException("Invalid upstream version number!");
}
public void setDebian(String debian)
{
_debian = debian.trim ();
if (!DEBIAN_VERSION_PATTERN.matcher (_debian).matches ())
throw new BuildException("Invalid debian version number!");
}
public String toString()
{
StringBuffer version = new StringBuffer();
if (_epoch > 0)
{
version.append(_epoch);
version.append(':');
}
else if (_upstream.indexOf(':') > -1)
throw new BuildException("Upstream version can contain colons only if epoch is specified!");
version.append(_upstream);
if (_debian.length() > 0)
{
version.append('-');
version.append(_debian);
}
else if (_upstream.indexOf('-') > -1)
throw new BuildException("Upstream version can contain hyphens only if debian version is specified!");
return version.toString();
}
}
public static class Maintainer extends ProjectComponent
{
private String _name;
private String _email;
public void setName (String name)
{
_name = name.trim ();
}
public void setEmail (String email)
{
_email = email.trim ();
}
public String toString()
{
if (_name == null || _name.length () == 0)
return _email;
StringBuffer buffer = new StringBuffer (_name);
buffer.append (" <");
buffer.append (_email);
buffer.append (">");
return buffer.toString ();
}
}
public static class Section extends EnumeratedAttribute
{
private static final String[] PREFIXES = new String[] {"", "contrib/", "non-free/"};
private static final String[] BASIC_SECTIONS = new String[] {"admin", "base", "comm", "devel", "doc", "editors", "electronics", "embedded", "games", "gnome", "graphics", "hamradio", "interpreters", "kde", "libs", "libdevel", "mail", "math", "misc", "net", "news", "oldlibs", "otherosfs", "perl", "python", "science", "shells", "sound", "tex", "text", "utils", "web", "x11"};
private List sections = new ArrayList (PREFIXES.length * BASIC_SECTIONS.length);
public Section ()
{
for (int i = 0; i < PREFIXES.length; i++)
{
String prefix = PREFIXES[i];
for (int j = 0; j < BASIC_SECTIONS.length; j++)
{
String basicSection = BASIC_SECTIONS[j];
sections.add (prefix + basicSection);
}
}
}
public String[] getValues ()
{
return (String[]) sections.toArray (new String[]{});
}
}
public static class Priority extends EnumeratedAttribute
{
public String[] getValues ()
{
return new String[] {"required", "important", "standard", "optional", "extra"};
}
}
private File _toDir;
private String _package;
private String _version;
private Deb.Version _versionObj;
private String _section;
private String _priority = "extra";
private String _architecture = "all";
private String _depends;
private String _preDepends;
private String _recommends;
private String _suggests;
private String _enhances;
private String _conflicts;
private String _maintainer;
private Deb.Maintainer _maintainerObj;
private Deb.Description _description;
private Set _conffiles = new HashSet ();
private List _data = new ArrayList();
private File _preinst;
private File _postinst;
private File _prerm;
private File _postrm;
private File _config;
private File _templates;
private File _tempFolder;
private long _installedSize = 0;
private SortedSet _dataFolders;
private static final Tar.TarCompressionMethod GZIP_COMPRESSION_METHOD = new Tar.TarCompressionMethod ();
private static final Tar.TarLongFileMode GNU_LONGFILE_MODE = new Tar.TarLongFileMode ();
static
{
GZIP_COMPRESSION_METHOD.setValue ("gzip");
GNU_LONGFILE_MODE.setValue(Tar.TarLongFileMode.GNU);
}
public void setToDir (File toDir)
{
_toDir = toDir;
}
public void setPackage (String packageName)
{
if (!PACKAGE_NAME_PATTERN.matcher(packageName).matches())
throw new BuildException("Invalid package name!");
_package = packageName;
}
public void setVersion (String version)
{
_version = version;
}
public void setSection (Section section)
{
_section = section.getValue();
}
public void setPriority (Priority priority)
{
_priority = priority.getValue();
}
public void setArchitecture (String architecture)
{
_architecture = architecture;
}
public void setDepends (String depends)
{
_depends = depends;
}
public void setPreDepends (String preDepends)
{
_preDepends = preDepends;
}
public void setRecommends (String recommends)
{
_recommends = recommends;
}
public void setSuggests (String suggests)
{
_suggests = suggests;
}
public void setEnhances (String enhances)
{
_enhances = enhances;
}
public void setConflicts (String conflicts)
{
_conflicts = conflicts;
}
public void setMaintainer (String maintainer)
{
_maintainer = maintainer;
}
public void setPreinst (File preinst)
{
_preinst = preinst;
}
public void setPostinst (File postinst)
{
_postinst = postinst;
}
public void setPrerm (File prerm)
{
_prerm = prerm;
}
public void setPostrm (File postrm)
{
_postrm = postrm;
}
public void setConfig (File config)
{
_config = config;
}
public void setTemplates (File templates)
{
_templates = templates;
}
public void addConfFiles (TarFileSet conffiles)
{
_conffiles.add (conffiles);
_data.add (conffiles);
}
public void addDescription (Deb.Description description)
{
_description = description;
}
public void add (TarFileSet resourceCollection)
{
_data.add(resourceCollection);
}
public void addVersion(Deb.Version version)
{
_versionObj = version;
}
public void addMaintainer(Deb.Maintainer maintainer)
{
_maintainerObj = maintainer;
}
private void writeControlFile (File controlFile, long installedSize) throws FileNotFoundException
{
log ("Generating control file to: " + controlFile.getAbsolutePath (), Project.MSG_VERBOSE);
PrintWriter control = new UnixPrintWriter (controlFile);
control.print ("Package: ");
control.println (_package);
control.print ("Version: ");
control.println (_version);
if (_section != null)
{
control.print ("Section: ");
control.println (_section);
}
if (_priority != null)
{
control.print ("Priority: ");
control.println (_priority);
}
control.print ("Architecture: ");
control.println (_architecture);
if (_depends != null)
{
control.print ("Depends: ");
control.println (_depends);
}
if (_preDepends != null)
{
control.print ("Pre-Depends: ");
control.println (_preDepends);
}
if (_recommends != null)
{
control.print ("Recommends: ");
control.println (_recommends);
}
if (_suggests != null)
{
control.print ("Suggests: ");
control.println (_suggests);
}
if (_enhances != null)
{
control.print ("Enhances: ");
control.println (_enhances);
}
if (_conflicts != null)
{
control.print ("Conflicts: ");
control.println (_conflicts);
}
if (installedSize > 0)
{
control.print ("Installed-Size: ");
control.println (installedSize / 1024L);
}
control.print ("Maintainer: ");
control.println (_maintainer);
control.print ("Description: ");
control.println (_description.getSynopsis ());
control.println (_description.getExtendedFormatted ());
control.close ();
}
private File createMasterControlFile () throws IOException
{
File controlFile = new File (_tempFolder, "control");
writeControlFile (controlFile, _installedSize);
File md5sumsFile = new File (_tempFolder, "md5sums");
File conffilesFile = new File (_tempFolder, "conffiles");
File masterControlFile = new File (_tempFolder, "control.tar.gz");
Tar controlTar = new Tar ();
controlTar.setProject (getProject ());
controlTar.setTaskName (getTaskName ());
controlTar.setDestFile (masterControlFile);
controlTar.setCompression (GZIP_COMPRESSION_METHOD);
addFileToTar (controlTar, controlFile, "control", "644");
addFileToTar (controlTar, md5sumsFile, "md5sums", "644");
if (conffilesFile.length () > 0)
addFileToTar (controlTar, conffilesFile, "conffiles", "644");
if (_preinst != null)
addFileToTar (controlTar, _preinst, "preinst", "755");
if (_postinst != null)
addFileToTar (controlTar, _postinst, "postinst", "755");
if (_prerm != null)
addFileToTar (controlTar, _prerm, "prerm", "755");
if (_postrm != null)
addFileToTar (controlTar, _postrm, "postrm", "755");
if (_config != null)
addFileToTar (controlTar, _config, "config", "755");
if (_templates != null)
addFileToTar (controlTar, _templates, "templates", "644");
controlTar.perform ();
controlFile.delete ();
return masterControlFile;
}
private void addFileToTar(Tar tar, File file, String fullpath, String fileMode)
{
TarFileSet controlFileSet = tar.createTarFileSet ();
controlFileSet.setFile (file);
controlFileSet.setFullpath (fullpath);
controlFileSet.setFileMode (fileMode);
}
public void execute () throws BuildException
{
try
{
if (_versionObj != null)
_version = _versionObj.toString ();
if (_maintainerObj != null)
_maintainer = _maintainerObj.toString ();
_tempFolder = createTempFolder();
scanData ();
File debFile = new File (_toDir, _package + "_" + _version + "_" + _architecture + ".deb");
File dataFile = createDataFile ();
File masterControlFile = createMasterControlFile ();
log ("Writing deb file to: " + debFile.getAbsolutePath());
BuildDeb.buildDeb (debFile, masterControlFile, dataFile);
masterControlFile.delete ();
dataFile.delete ();
}
catch (IOException e)
{
throw new BuildException (e);
}
}
private File createDataFile () throws IOException
{
File dataFile = new File (_tempFolder, "data.tar.gz");
Tar dataTar = new Tar ();
dataTar.setProject (getProject ());
dataTar.setTaskName (getTaskName ());
dataTar.setDestFile (dataFile);
dataTar.setCompression (GZIP_COMPRESSION_METHOD);
dataTar.setLongfile(GNU_LONGFILE_MODE);
// add folders
for (Iterator dataFoldersIter = _dataFolders.iterator (); dataFoldersIter.hasNext ();)
{
String targetFolder = (String) dataFoldersIter.next ();
TarFileSet targetFolderSet = dataTar.createTarFileSet ();
targetFolderSet.setFile (_tempFolder);
targetFolderSet.setFullpath (targetFolder);
}
// add actual data
for (int i = 0; i < _data.size (); i++)
dataTar.add ((TarFileSet) _data.get (i));
dataTar.execute ();
return dataFile;
}
private File createTempFolder() throws IOException
{
File tempFile = File.createTempFile ("deb", ".dir");
String tempFolderName = tempFile.getAbsolutePath ();
tempFile.delete ();
tempFile = new File (tempFolderName, "removeme");
tempFile.mkdirs ();
tempFile.delete ();
log ("Temp folder: " + tempFolderName, Project.MSG_VERBOSE);
return new File (tempFolderName);
}
private void scanData()
{
try
{
Set existingDirs = new HashSet ();
_installedSize = 0;
PrintWriter md5sums = new UnixPrintWriter (new File (_tempFolder, "md5sums"));
PrintWriter conffiles = new UnixPrintWriter (new File (_tempFolder, "conffiles"));
_dataFolders = new TreeSet ();
Iterator filesets = _data.iterator();
while (filesets.hasNext())
{
TarFileSet fileset = (TarFileSet) filesets.next();
String fullPath = fileset.getFullpath (getProject ());
String prefix = fileset.getPrefix (getProject ());
if (prefix.length () > 0 && !prefix.endsWith ("/"))
prefix += '/';
String [] fileNames = getFileNames(fileset);
for (int i = 0; i < fileNames.length; i++)
{
String targetName;
String fileName = fileNames[i];
File file = new File (fileset.getDir (getProject ()), fileName);
if (fullPath.length () > 0)
targetName = fullPath;
else
targetName = prefix + fileName;
if (file.isDirectory ())
{
log ("existing dir: " + targetName, Project.MSG_DEBUG);
existingDirs.add (targetName);
}
else
{
// calculate installed size in bytes
_installedSize += file.length ();
// calculate and collect md5 sums
md5sums.print (getFileMd5 (file));
md5sums.print (' ');
md5sums.println (targetName.replace (File.separatorChar, '/'));
// get target folder names, and collect them (to be added to _data)
File targetFile = new File(targetName);
File parentFolder = targetFile.getParentFile () ;
while (parentFolder != null)
{
- String parentFolderPath = parentFolder.getPath ();
+ String parentFolderPath = parentFolder.getPath ().replace(File.separatorChar, '/');
if (!existingDirs.contains (parentFolderPath) && !_dataFolders.contains (parentFolderPath))
{
log ("adding dir: " + parentFolderPath + " for " + targetName, Project.MSG_DEBUG);
_dataFolders.add (parentFolderPath);
}
parentFolder = parentFolder.getParentFile ();
}
// write conffiles
if (_conffiles.contains (fileset))
conffiles.println (targetName);
}
}
}
for (Iterator iterator = existingDirs.iterator (); iterator.hasNext ();)
{
String existingDir = (String) iterator.next ();
if (_dataFolders.contains (existingDir))
{
log ("removing existing dir " + existingDir, Project.MSG_DEBUG);
_dataFolders.remove (existingDir);
}
}
md5sums.close ();
conffiles.close ();
}
catch (Exception e)
{
throw new BuildException (e);
}
}
private String[] getFileNames(FileSet fs)
{
DirectoryScanner ds = fs.getDirectoryScanner(fs.getProject());
String[] directories = ds.getIncludedDirectories();
String[] filesPerSe = ds.getIncludedFiles();
String[] files = new String [directories.length + filesPerSe.length];
System.arraycopy(directories, 0, files, 0, directories.length);
System.arraycopy(filesPerSe, 0, files, directories.length, filesPerSe.length);
return files;
}
private String getFileMd5(File file)
{
try
{
MessageDigest md5 = MessageDigest.getInstance ("MD5");
FileInputStream inputStream = new FileInputStream (file);
byte[] buffer = new byte[1024];
while (true)
{
int read = inputStream.read (buffer);
if (read == -1)
break;
md5.update (buffer, 0, read);
}
byte[] md5Bytes = md5.digest ();
StringBuffer md5Buffer = new StringBuffer (md5Bytes.length * 2);
for (int i = 0; i < md5Bytes.length; i++)
{
String hex = Integer.toHexString (md5Bytes[i] & 0x00ff);
if (hex.length () == 1)
md5Buffer.append ('0');
md5Buffer.append (hex);
}
return md5Buffer.toString ();
}
catch (Exception e)
{
throw new BuildException(e);
}
}
}
| true | true | private void scanData()
{
try
{
Set existingDirs = new HashSet ();
_installedSize = 0;
PrintWriter md5sums = new UnixPrintWriter (new File (_tempFolder, "md5sums"));
PrintWriter conffiles = new UnixPrintWriter (new File (_tempFolder, "conffiles"));
_dataFolders = new TreeSet ();
Iterator filesets = _data.iterator();
while (filesets.hasNext())
{
TarFileSet fileset = (TarFileSet) filesets.next();
String fullPath = fileset.getFullpath (getProject ());
String prefix = fileset.getPrefix (getProject ());
if (prefix.length () > 0 && !prefix.endsWith ("/"))
prefix += '/';
String [] fileNames = getFileNames(fileset);
for (int i = 0; i < fileNames.length; i++)
{
String targetName;
String fileName = fileNames[i];
File file = new File (fileset.getDir (getProject ()), fileName);
if (fullPath.length () > 0)
targetName = fullPath;
else
targetName = prefix + fileName;
if (file.isDirectory ())
{
log ("existing dir: " + targetName, Project.MSG_DEBUG);
existingDirs.add (targetName);
}
else
{
// calculate installed size in bytes
_installedSize += file.length ();
// calculate and collect md5 sums
md5sums.print (getFileMd5 (file));
md5sums.print (' ');
md5sums.println (targetName.replace (File.separatorChar, '/'));
// get target folder names, and collect them (to be added to _data)
File targetFile = new File(targetName);
File parentFolder = targetFile.getParentFile () ;
while (parentFolder != null)
{
String parentFolderPath = parentFolder.getPath ();
if (!existingDirs.contains (parentFolderPath) && !_dataFolders.contains (parentFolderPath))
{
log ("adding dir: " + parentFolderPath + " for " + targetName, Project.MSG_DEBUG);
_dataFolders.add (parentFolderPath);
}
parentFolder = parentFolder.getParentFile ();
}
// write conffiles
if (_conffiles.contains (fileset))
conffiles.println (targetName);
}
}
}
for (Iterator iterator = existingDirs.iterator (); iterator.hasNext ();)
{
String existingDir = (String) iterator.next ();
if (_dataFolders.contains (existingDir))
{
log ("removing existing dir " + existingDir, Project.MSG_DEBUG);
_dataFolders.remove (existingDir);
}
}
md5sums.close ();
conffiles.close ();
}
catch (Exception e)
{
throw new BuildException (e);
}
}
| private void scanData()
{
try
{
Set existingDirs = new HashSet ();
_installedSize = 0;
PrintWriter md5sums = new UnixPrintWriter (new File (_tempFolder, "md5sums"));
PrintWriter conffiles = new UnixPrintWriter (new File (_tempFolder, "conffiles"));
_dataFolders = new TreeSet ();
Iterator filesets = _data.iterator();
while (filesets.hasNext())
{
TarFileSet fileset = (TarFileSet) filesets.next();
String fullPath = fileset.getFullpath (getProject ());
String prefix = fileset.getPrefix (getProject ());
if (prefix.length () > 0 && !prefix.endsWith ("/"))
prefix += '/';
String [] fileNames = getFileNames(fileset);
for (int i = 0; i < fileNames.length; i++)
{
String targetName;
String fileName = fileNames[i];
File file = new File (fileset.getDir (getProject ()), fileName);
if (fullPath.length () > 0)
targetName = fullPath;
else
targetName = prefix + fileName;
if (file.isDirectory ())
{
log ("existing dir: " + targetName, Project.MSG_DEBUG);
existingDirs.add (targetName);
}
else
{
// calculate installed size in bytes
_installedSize += file.length ();
// calculate and collect md5 sums
md5sums.print (getFileMd5 (file));
md5sums.print (' ');
md5sums.println (targetName.replace (File.separatorChar, '/'));
// get target folder names, and collect them (to be added to _data)
File targetFile = new File(targetName);
File parentFolder = targetFile.getParentFile () ;
while (parentFolder != null)
{
String parentFolderPath = parentFolder.getPath ().replace(File.separatorChar, '/');
if (!existingDirs.contains (parentFolderPath) && !_dataFolders.contains (parentFolderPath))
{
log ("adding dir: " + parentFolderPath + " for " + targetName, Project.MSG_DEBUG);
_dataFolders.add (parentFolderPath);
}
parentFolder = parentFolder.getParentFile ();
}
// write conffiles
if (_conffiles.contains (fileset))
conffiles.println (targetName);
}
}
}
for (Iterator iterator = existingDirs.iterator (); iterator.hasNext ();)
{
String existingDir = (String) iterator.next ();
if (_dataFolders.contains (existingDir))
{
log ("removing existing dir " + existingDir, Project.MSG_DEBUG);
_dataFolders.remove (existingDir);
}
}
md5sums.close ();
conffiles.close ();
}
catch (Exception e)
{
throw new BuildException (e);
}
}
|
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.structures/src/org/eclipse/linuxtools/systemtap/ui/structures/ui/ExceptionErrorDialog.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.structures/src/org/eclipse/linuxtools/systemtap/ui/structures/ui/ExceptionErrorDialog.java
index 916b8d368..8f4f602b5 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.structures/src/org/eclipse/linuxtools/systemtap/ui/structures/ui/ExceptionErrorDialog.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.structures/src/org/eclipse/linuxtools/systemtap/ui/structures/ui/ExceptionErrorDialog.java
@@ -1,36 +1,38 @@
/*******************************************************************************
* Copyright (c) 2013 Red Hat.
* 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.linuxtools.systemtap.ui.structures.ui;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.linuxtools.internal.systemtap.ui.structures.StructuresPlugin;
import org.eclipse.ui.PlatformUI;
/**
* A convenience class for showing error dialogs which display the full stack
* trace in the details section.
* @since 2.0
*
*/
public class ExceptionErrorDialog {
- public static int openError(String title, Exception e){
- Status status = new Status(IStatus.ERROR, StructuresPlugin.PLUGIN_ID, title, e);
+ public static int openError(String message, Exception e){
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
- return ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), title, writer.toString(), status);
+ Status status = new Status(IStatus.ERROR, StructuresPlugin.PLUGIN_ID, e.toString(), new Throwable(writer.toString()));
+ return ErrorDialog.openError(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getShell(), message,
+ message, status);
}
}
| false | true | public static int openError(String title, Exception e){
Status status = new Status(IStatus.ERROR, StructuresPlugin.PLUGIN_ID, title, e);
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
return ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), title, writer.toString(), status);
}
| public static int openError(String message, Exception e){
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
Status status = new Status(IStatus.ERROR, StructuresPlugin.PLUGIN_ID, e.toString(), new Throwable(writer.toString()));
return ErrorDialog.openError(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getShell(), message,
message, status);
}
|
diff --git a/om/src/main/java/de/escidoc/core/om/business/fedora/FedoraSemanticStoreHandler.java b/om/src/main/java/de/escidoc/core/om/business/fedora/FedoraSemanticStoreHandler.java
index 3dee69e..d20ac41 100644
--- a/om/src/main/java/de/escidoc/core/om/business/fedora/FedoraSemanticStoreHandler.java
+++ b/om/src/main/java/de/escidoc/core/om/business/fedora/FedoraSemanticStoreHandler.java
@@ -1,192 +1,192 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at license/ESCIDOC.LICENSE
* or http://www.escidoc.de/license.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at license/ESCIDOC.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2006-2008 Fachinformationszentrum Karlsruhe Gesellschaft
* fuer wissenschaftlich-technische Information mbH and Max-Planck-
* Gesellschaft zur Foerderung der Wissenschaft e.V.
* All rights reserved. Use is subject to license terms.
*/
package de.escidoc.core.om.business.fedora;
import de.escidoc.core.common.business.TripleStoreConnector;
import de.escidoc.core.common.exceptions.application.invalid.InvalidContentException;
import de.escidoc.core.common.exceptions.application.invalid.InvalidTripleStoreOutputFormatException;
import de.escidoc.core.common.exceptions.application.invalid.InvalidTripleStoreQueryException;
import de.escidoc.core.common.exceptions.application.invalid.InvalidXmlException;
import de.escidoc.core.common.exceptions.application.missing.MissingElementValueException;
import de.escidoc.core.common.exceptions.system.EncodingSystemException;
import de.escidoc.core.common.exceptions.system.TripleStoreSystemException;
import de.escidoc.core.common.exceptions.system.WebserverSystemException;
import de.escidoc.core.common.exceptions.system.XmlParserSystemException;
import de.escidoc.core.common.util.stax.StaxParser;
import de.escidoc.core.common.util.stax.handler.SemanticQueryHandler;
import de.escidoc.core.common.util.xml.XmlUtility;
import de.escidoc.core.om.business.interfaces.SemanticStoreHandlerInterface;
import de.escidoc.core.om.business.stax.handler.filter.RDFRegisteredOntologyFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import java.io.StringReader;
import java.io.StringWriter;
/**
* @author Rozita Friedman
*/
@Service("business.FedoraSemanticStoreHandler")
public class FedoraSemanticStoreHandler implements SemanticStoreHandlerInterface {
private static final Logger LOGGER = LoggerFactory.getLogger(FedoraSemanticStoreHandler.class);
@Autowired
@Qualifier("business.TripleStoreConnector")
private TripleStoreConnector tripleStoreConnector;
/**
* Protected constructor to prevent instantiation outside of the Spring-context.
*/
protected FedoraSemanticStoreHandler() {
}
/**
* Retrieves a result of provided triple store query in a provided output format.
*
* @param taskParam SPO query parameter and return representation type.
* <p/>
* <pre>
*
* <param>
*
* <query><info:fedora/escidoc:111>
*
* <http://www.escidoc.de/ontologies/mpdl-ontologies/content-relations#isRevisionOf>
* /query>
*
* <format>N-Triples</format>
*
* </param>
* </pre>
* @return Returns XML representation of the query result.
* @throws InvalidTripleStoreQueryException
* Thrown if triple store query is invalid.
* @throws InvalidTripleStoreOutputFormatException
* Thrown if triple store output format is wrong defined.
*/
@Override
public String spo(final String taskParam) throws InvalidTripleStoreQueryException,
InvalidTripleStoreOutputFormatException, InvalidXmlException, MissingElementValueException,
EncodingSystemException, TripleStoreSystemException, XmlParserSystemException, WebserverSystemException {
final StaxParser sp = new StaxParser();
final SemanticQueryHandler qh = new SemanticQueryHandler();
sp.addHandler(qh);
try {
sp.parse(taskParam);
sp.clearHandlerChain();
}
catch (final MissingElementValueException e) {
throw e;
}
catch (final Exception e) {
XmlUtility.handleUnexpectedStaxParserException("", e);
}
sp.clearHandlerChain();
final String query = qh.getQuery();
// check predicate
final String predicate = qh.getPredicate();
boolean accept;
try {
accept = OntologyUtility.checkPredicate(predicate);
}
catch (InvalidContentException e) {
throw new WebserverSystemException("Predicate '" + predicate + "' is invalid.", e);
}
if (!"*".equals(predicate) && !accept) {
throw new InvalidTripleStoreQueryException("Predicate '"
+ XmlUtility.escapeForbiddenXmlCharacters(predicate) + "' not allowed.");
}
final String format = qh.getFormat();
String result = tripleStoreConnector.requestMPT(query, format);
if (!"".equals(result) && "*".equals(predicate)) {
// TODO check result for unallowed predicates
if ("N-Triples".equals(format)) {
final String[] triples = result.split("\\s\\.");
final StringBuilder stringBuffer = new StringBuilder();
for (final String triple : triples) {
final String[] tripleParts = triple.trim().split("\\ +", 3);
- if (tripleParts.length == 3) {
+ if (tripleParts.length >= 2) {
try {
accept = OntologyUtility.checkPredicate(tripleParts[1]);
}
catch (InvalidContentException e) {
throw new WebserverSystemException("Predicate '" + tripleParts[1] + "' is invalid.", e);
}
- if (tripleParts.length >= 2 && accept) {
+ if (accept) {
stringBuffer.append(triple);
stringBuffer.append(".\n");
}
}
}
result = stringBuffer.toString();
}
else if ("RDF/XML".equals(format)) {
// TODO revise, move
try {
final XMLInputFactory inf = XMLInputFactory.newInstance();
final XMLEventReader reader =
inf.createFilteredReader(inf.createXMLEventReader(new StringReader(result)),
new RDFRegisteredOntologyFilter());
final StringWriter sw = new StringWriter();
final XMLEventWriter writer = XmlUtility.createXmlEventWriter(sw);
// writer.add(reader);
while (reader.hasNext()) {
final XMLEvent event = reader.nextEvent();
writer.add(event);
}
result = sw.toString();
}
catch (final XMLStreamException e) {
throw new WebserverSystemException(e);
}
}
else {
LOGGER.warn("No filter defined for result format '" + format + "'.");
}
}
return result;
}
}
| false | true | public String spo(final String taskParam) throws InvalidTripleStoreQueryException,
InvalidTripleStoreOutputFormatException, InvalidXmlException, MissingElementValueException,
EncodingSystemException, TripleStoreSystemException, XmlParserSystemException, WebserverSystemException {
final StaxParser sp = new StaxParser();
final SemanticQueryHandler qh = new SemanticQueryHandler();
sp.addHandler(qh);
try {
sp.parse(taskParam);
sp.clearHandlerChain();
}
catch (final MissingElementValueException e) {
throw e;
}
catch (final Exception e) {
XmlUtility.handleUnexpectedStaxParserException("", e);
}
sp.clearHandlerChain();
final String query = qh.getQuery();
// check predicate
final String predicate = qh.getPredicate();
boolean accept;
try {
accept = OntologyUtility.checkPredicate(predicate);
}
catch (InvalidContentException e) {
throw new WebserverSystemException("Predicate '" + predicate + "' is invalid.", e);
}
if (!"*".equals(predicate) && !accept) {
throw new InvalidTripleStoreQueryException("Predicate '"
+ XmlUtility.escapeForbiddenXmlCharacters(predicate) + "' not allowed.");
}
final String format = qh.getFormat();
String result = tripleStoreConnector.requestMPT(query, format);
if (!"".equals(result) && "*".equals(predicate)) {
// TODO check result for unallowed predicates
if ("N-Triples".equals(format)) {
final String[] triples = result.split("\\s\\.");
final StringBuilder stringBuffer = new StringBuilder();
for (final String triple : triples) {
final String[] tripleParts = triple.trim().split("\\ +", 3);
if (tripleParts.length == 3) {
try {
accept = OntologyUtility.checkPredicate(tripleParts[1]);
}
catch (InvalidContentException e) {
throw new WebserverSystemException("Predicate '" + tripleParts[1] + "' is invalid.", e);
}
if (tripleParts.length >= 2 && accept) {
stringBuffer.append(triple);
stringBuffer.append(".\n");
}
}
}
result = stringBuffer.toString();
}
else if ("RDF/XML".equals(format)) {
// TODO revise, move
try {
final XMLInputFactory inf = XMLInputFactory.newInstance();
final XMLEventReader reader =
inf.createFilteredReader(inf.createXMLEventReader(new StringReader(result)),
new RDFRegisteredOntologyFilter());
final StringWriter sw = new StringWriter();
final XMLEventWriter writer = XmlUtility.createXmlEventWriter(sw);
// writer.add(reader);
while (reader.hasNext()) {
final XMLEvent event = reader.nextEvent();
writer.add(event);
}
result = sw.toString();
}
catch (final XMLStreamException e) {
throw new WebserverSystemException(e);
}
}
else {
LOGGER.warn("No filter defined for result format '" + format + "'.");
}
}
return result;
}
| public String spo(final String taskParam) throws InvalidTripleStoreQueryException,
InvalidTripleStoreOutputFormatException, InvalidXmlException, MissingElementValueException,
EncodingSystemException, TripleStoreSystemException, XmlParserSystemException, WebserverSystemException {
final StaxParser sp = new StaxParser();
final SemanticQueryHandler qh = new SemanticQueryHandler();
sp.addHandler(qh);
try {
sp.parse(taskParam);
sp.clearHandlerChain();
}
catch (final MissingElementValueException e) {
throw e;
}
catch (final Exception e) {
XmlUtility.handleUnexpectedStaxParserException("", e);
}
sp.clearHandlerChain();
final String query = qh.getQuery();
// check predicate
final String predicate = qh.getPredicate();
boolean accept;
try {
accept = OntologyUtility.checkPredicate(predicate);
}
catch (InvalidContentException e) {
throw new WebserverSystemException("Predicate '" + predicate + "' is invalid.", e);
}
if (!"*".equals(predicate) && !accept) {
throw new InvalidTripleStoreQueryException("Predicate '"
+ XmlUtility.escapeForbiddenXmlCharacters(predicate) + "' not allowed.");
}
final String format = qh.getFormat();
String result = tripleStoreConnector.requestMPT(query, format);
if (!"".equals(result) && "*".equals(predicate)) {
// TODO check result for unallowed predicates
if ("N-Triples".equals(format)) {
final String[] triples = result.split("\\s\\.");
final StringBuilder stringBuffer = new StringBuilder();
for (final String triple : triples) {
final String[] tripleParts = triple.trim().split("\\ +", 3);
if (tripleParts.length >= 2) {
try {
accept = OntologyUtility.checkPredicate(tripleParts[1]);
}
catch (InvalidContentException e) {
throw new WebserverSystemException("Predicate '" + tripleParts[1] + "' is invalid.", e);
}
if (accept) {
stringBuffer.append(triple);
stringBuffer.append(".\n");
}
}
}
result = stringBuffer.toString();
}
else if ("RDF/XML".equals(format)) {
// TODO revise, move
try {
final XMLInputFactory inf = XMLInputFactory.newInstance();
final XMLEventReader reader =
inf.createFilteredReader(inf.createXMLEventReader(new StringReader(result)),
new RDFRegisteredOntologyFilter());
final StringWriter sw = new StringWriter();
final XMLEventWriter writer = XmlUtility.createXmlEventWriter(sw);
// writer.add(reader);
while (reader.hasNext()) {
final XMLEvent event = reader.nextEvent();
writer.add(event);
}
result = sw.toString();
}
catch (final XMLStreamException e) {
throw new WebserverSystemException(e);
}
}
else {
LOGGER.warn("No filter defined for result format '" + format + "'.");
}
}
return result;
}
|
diff --git a/src/gov/nih/nci/rembrandt/web/struts/action/GPProcessAction.java b/src/gov/nih/nci/rembrandt/web/struts/action/GPProcessAction.java
index ecad1313..f71b2ea2 100644
--- a/src/gov/nih/nci/rembrandt/web/struts/action/GPProcessAction.java
+++ b/src/gov/nih/nci/rembrandt/web/struts/action/GPProcessAction.java
@@ -1,212 +1,215 @@
package gov.nih.nci.rembrandt.web.struts.action;
import gov.nih.nci.caintegrator.enumeration.FindingStatus;
import gov.nih.nci.caintegrator.service.task.GPTask;
import gov.nih.nci.rembrandt.cache.RembrandtPresentationTierCache;
import gov.nih.nci.rembrandt.web.factory.ApplicationFactory;
import gov.nih.nci.rembrandt.web.struts.form.GpProcessForm;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.genepattern.util.StringUtils;
import org.genepattern.webservice.TaskIntegratorProxy;
import org.genepattern.visualizer.RunVisualizerConstants;
/**
* caIntegrator License
*
* Copyright 2001-2005 Science Applications International Corporation ("SAIC").
* The software subject to this notice and license includes both human readable source code form and machine readable,
* binary, object code form ("the caIntegrator Software"). The caIntegrator Software was developed in conjunction with
* the National Cancer Institute ("NCI") by NCI employees and employees of SAIC.
* To the extent government employees are authors, any rights in such works shall be subject to Title 17 of the United States
* Code, section 105.
* This caIntegrator Software License (the "License") is between NCI and You. "You (or "Your") shall mean a person or an
* entity, and all other entities that control, are controlled by, or are under common control with the entity. "Control"
* for purposes of this definition means (i) the direct or indirect power to cause the direction or management of such entity,
* whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii)
* beneficial ownership of such entity.
* This License is granted provided that You agree to the conditions described below. NCI grants You a non-exclusive,
* worldwide, perpetual, fully-paid-up, no-charge, irrevocable, transferable and royalty-free right and license in its rights
* in the caIntegrator Software to (i) use, install, access, operate, execute, copy, modify, translate, market, publicly
* display, publicly perform, and prepare derivative works of the caIntegrator Software; (ii) distribute and have distributed
* to and by third parties the caIntegrator Software and any modifications and derivative works thereof;
* and (iii) sublicense the foregoing rights set out in (i) and (ii) to third parties, including the right to license such
* rights to further third parties. For sake of clarity, and not by way of limitation, NCI shall have no right of accounting
* or right of payment from You or Your sublicensees for the rights granted under this License. This License is granted at no
* charge to You.
* 1. Your redistributions of the source code for the Software must retain the above copyright notice, this list of conditions
* and the disclaimer and limitation of liability of Article 6, below. Your redistributions in object code form must reproduce
* the above copyright notice, this list of conditions and the disclaimer of Article 6 in the documentation and/or other materials
* provided with the distribution, if any.
* 2. Your end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This
* product includes software developed by SAIC and the National Cancer Institute." If You do not include such end-user
* documentation, You shall include this acknowledgment in the Software itself, wherever such third-party acknowledgments
* normally appear.
* 3. You may not use the names "The National Cancer Institute", "NCI" "Science Applications International Corporation" and
* "SAIC" to endorse or promote products derived from this Software. This License does not authorize You to use any
* trademarks, service marks, trade names, logos or product names of either NCI or SAIC, except as required to comply with
* the terms of this License.
* 4. For sake of clarity, and not by way of limitation, You may incorporate this Software into Your proprietary programs and
* into any third party proprietary programs. However, if You incorporate the Software into third party proprietary
* programs, You agree that You are solely responsible for obtaining any permission from such third parties required to
* incorporate the Software into such third party proprietary programs and for informing Your sublicensees, including
* without limitation Your end-users, of their obligation to secure any required permissions from such third parties
* before incorporating the Software into such third party proprietary software programs. In the event that You fail
* to obtain such permissions, You agree to indemnify NCI for any claims against NCI by such third parties, except to
* the extent prohibited by law, resulting from Your failure to obtain such permissions.
* 5. For sake of clarity, and not by way of limitation, You may add Your own copyright statement to Your modifications and
* to the derivative works, and You may provide additional or different license terms and conditions in Your sublicenses
* of modifications of the Software, or any derivative works of the Software as a whole, provided Your use, reproduction,
* and distribution of the Work otherwise complies with the conditions stated in this License.
* 6. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED.
* IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, SAIC, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
public class GPProcessAction extends DispatchAction {
private static Logger logger = Logger.getLogger(GPProcessAction.class);
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
GpProcessForm gpForm = (GpProcessForm) form;
RembrandtPresentationTierCache _cacheManager = ApplicationFactory.getPresentationTierCache();
GPTask gpTask = (GPTask)_cacheManager.getNonPersistableObjectFromSessionCache(
request.getSession().getId(), "latestGpTask");
if (gpTask != null){
request.setAttribute("jobId", gpTask.getJobId());
request.setAttribute("resultName", gpTask.getResultName());
request.setAttribute("jobIdSelect", gpTask.getJobId() + "_jobId");
request.setAttribute("processSelect", gpTask.getJobId() + "_process");
request.setAttribute("submitButton", gpTask.getJobId() + "_submit");
request.setAttribute("gpStatus", gpTask.getStatus().toString());
}
Collection tempGpTaskList = _cacheManager.getAllSessionGPTasks(request.getSession().getId());
gpForm.setJobList(getGPTaskList(tempGpTaskList));
List<String> processList = new ArrayList<String>();
//processList.add("ComparativeMarkerSelection");
//processList.add("GeneNeighbors");
//processList.add("GSEA");
processList.add("HeatMapViewer");
//processList.add("CMS.pipeline");
//processList.add("HC.pipeline");
//processList.add("KNN.pipeline");
gpForm.setProcessList(processList);
return mapping.findForward("success");
}
public ActionForward startApplet(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("Entering startApplet method.......");
GpProcessForm gpForm = (GpProcessForm)form;
HttpSession session = request.getSession();
String jobNumber = gpForm.getJobId();
RembrandtPresentationTierCache _cacheManager = ApplicationFactory.getPresentationTierCache();
Collection tempGpTaskList = _cacheManager.getAllSessionGPTasks(request.getSession().getId());
GPTask gpTask = null;
if (tempGpTaskList != null && !tempGpTaskList.isEmpty()){
for(Iterator i = tempGpTaskList.iterator();i.hasNext();) {
GPTask task = (GPTask) i.next();
if (task.getJobId().equals(jobNumber))
gpTask = task;
}
}
String gpserverURL = System.getProperty("gov.nih.nci.caintegrator.gp.server");
String gpUserId = (String)session.getAttribute("gpUserId");
String password = System.getProperty("gov.nih.nci.caintegrator.gp.publicuser.password");
TaskIntegratorProxy taskIntegratorProxy = new TaskIntegratorProxy(gpserverURL, gpUserId, password, false);
String lsid = System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.gp_lsid");
String[] theFiles = taskIntegratorProxy.getSupportFileNames(lsid);
long[] dateLongs =
taskIntegratorProxy.getLastModificationTimes(System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.gp_lsid"), theFiles);
String[] dateStrings = new String[dateLongs.length];
int index = 0;
for (long dateLong : dateLongs){
dateStrings[index++] = Long.toString(dateLong);
}
request.setAttribute(RunVisualizerConstants.SUPPORT_FILE_DATES, appendString(dateStrings, ","));
request.setAttribute(RunVisualizerConstants.SUPPORT_FILE_NAMES, appendString(theFiles, ","));
String commandline = System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.commandLine");
commandline = StringUtils.htmlEncode(commandline);
request.setAttribute(RunVisualizerConstants.COMMAND_LINE, commandline);
String gpHomeURL = (String)request.getSession().getAttribute("ticketString");
int ppp = gpHomeURL.indexOf("?");
String ticketString = gpHomeURL.substring(ppp);
request.setAttribute("ticketString", ticketString);
String fileName = gpserverURL + "gp/jobResults/" + jobNumber + "/" + gpTask.getResultName() + ".gct";
//fileName = fileName + ticketString;
request.setAttribute(RunVisualizerConstants.DOWNLOAD_FILES, fileName);
logger.info("File URL = " + fileName + ticketString);
String supportFileURL = System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.supportFileURL");
- request.setAttribute("supportFileURL", supportFileURL);
- request.setAttribute("name", "Heat Map View");
+ request.setAttribute("supportFileURL", StringUtils.htmlEncode(supportFileURL));
+ request.setAttribute("name", "HeatMapView");
+ //The line above was set to "Heat Map View" for some bad reason - note the spaces.
+ //this causes the applet to fail on MAC. The JSP removes the spaces, but why were they hardcoded here
+ //changed "Heat Map View" to "HeatMapView" .... RL
gpForm.setJobList(getGPTaskList(tempGpTaskList));
List<String> processList = new ArrayList<String>();
processList.add("HeatMapViewer");
//processList.add("HeatMapImage");
//processList.add("ConcensusClustering");
gpForm.setProcessList(processList);
//////////
return mapping.findForward("appletViewer");
}
private String appendString(String[] str, String token){
StringBuffer sb = new StringBuffer();
int i = 1; //str.length;
for (String string : str){
sb.append(string);
if (i++ != str.length){
sb.append(token);
}
}
return sb.toString();
}
private List<String> getGPTaskList(Collection collection){
List<String> jobList = new ArrayList<String>();
if (collection != null && !collection.isEmpty()){
for(Iterator i = collection.iterator();i.hasNext();) {
GPTask task = (GPTask) i.next();
if (task.getStatus().equals(FindingStatus.Completed))
jobList.add(task.getJobId());
}
}
return jobList;
}
}
| true | true | public ActionForward startApplet(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("Entering startApplet method.......");
GpProcessForm gpForm = (GpProcessForm)form;
HttpSession session = request.getSession();
String jobNumber = gpForm.getJobId();
RembrandtPresentationTierCache _cacheManager = ApplicationFactory.getPresentationTierCache();
Collection tempGpTaskList = _cacheManager.getAllSessionGPTasks(request.getSession().getId());
GPTask gpTask = null;
if (tempGpTaskList != null && !tempGpTaskList.isEmpty()){
for(Iterator i = tempGpTaskList.iterator();i.hasNext();) {
GPTask task = (GPTask) i.next();
if (task.getJobId().equals(jobNumber))
gpTask = task;
}
}
String gpserverURL = System.getProperty("gov.nih.nci.caintegrator.gp.server");
String gpUserId = (String)session.getAttribute("gpUserId");
String password = System.getProperty("gov.nih.nci.caintegrator.gp.publicuser.password");
TaskIntegratorProxy taskIntegratorProxy = new TaskIntegratorProxy(gpserverURL, gpUserId, password, false);
String lsid = System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.gp_lsid");
String[] theFiles = taskIntegratorProxy.getSupportFileNames(lsid);
long[] dateLongs =
taskIntegratorProxy.getLastModificationTimes(System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.gp_lsid"), theFiles);
String[] dateStrings = new String[dateLongs.length];
int index = 0;
for (long dateLong : dateLongs){
dateStrings[index++] = Long.toString(dateLong);
}
request.setAttribute(RunVisualizerConstants.SUPPORT_FILE_DATES, appendString(dateStrings, ","));
request.setAttribute(RunVisualizerConstants.SUPPORT_FILE_NAMES, appendString(theFiles, ","));
String commandline = System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.commandLine");
commandline = StringUtils.htmlEncode(commandline);
request.setAttribute(RunVisualizerConstants.COMMAND_LINE, commandline);
String gpHomeURL = (String)request.getSession().getAttribute("ticketString");
int ppp = gpHomeURL.indexOf("?");
String ticketString = gpHomeURL.substring(ppp);
request.setAttribute("ticketString", ticketString);
String fileName = gpserverURL + "gp/jobResults/" + jobNumber + "/" + gpTask.getResultName() + ".gct";
//fileName = fileName + ticketString;
request.setAttribute(RunVisualizerConstants.DOWNLOAD_FILES, fileName);
logger.info("File URL = " + fileName + ticketString);
String supportFileURL = System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.supportFileURL");
request.setAttribute("supportFileURL", supportFileURL);
request.setAttribute("name", "Heat Map View");
gpForm.setJobList(getGPTaskList(tempGpTaskList));
List<String> processList = new ArrayList<String>();
processList.add("HeatMapViewer");
//processList.add("HeatMapImage");
//processList.add("ConcensusClustering");
gpForm.setProcessList(processList);
//////////
return mapping.findForward("appletViewer");
}
| public ActionForward startApplet(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("Entering startApplet method.......");
GpProcessForm gpForm = (GpProcessForm)form;
HttpSession session = request.getSession();
String jobNumber = gpForm.getJobId();
RembrandtPresentationTierCache _cacheManager = ApplicationFactory.getPresentationTierCache();
Collection tempGpTaskList = _cacheManager.getAllSessionGPTasks(request.getSession().getId());
GPTask gpTask = null;
if (tempGpTaskList != null && !tempGpTaskList.isEmpty()){
for(Iterator i = tempGpTaskList.iterator();i.hasNext();) {
GPTask task = (GPTask) i.next();
if (task.getJobId().equals(jobNumber))
gpTask = task;
}
}
String gpserverURL = System.getProperty("gov.nih.nci.caintegrator.gp.server");
String gpUserId = (String)session.getAttribute("gpUserId");
String password = System.getProperty("gov.nih.nci.caintegrator.gp.publicuser.password");
TaskIntegratorProxy taskIntegratorProxy = new TaskIntegratorProxy(gpserverURL, gpUserId, password, false);
String lsid = System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.gp_lsid");
String[] theFiles = taskIntegratorProxy.getSupportFileNames(lsid);
long[] dateLongs =
taskIntegratorProxy.getLastModificationTimes(System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.gp_lsid"), theFiles);
String[] dateStrings = new String[dateLongs.length];
int index = 0;
for (long dateLong : dateLongs){
dateStrings[index++] = Long.toString(dateLong);
}
request.setAttribute(RunVisualizerConstants.SUPPORT_FILE_DATES, appendString(dateStrings, ","));
request.setAttribute(RunVisualizerConstants.SUPPORT_FILE_NAMES, appendString(theFiles, ","));
String commandline = System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.commandLine");
commandline = StringUtils.htmlEncode(commandline);
request.setAttribute(RunVisualizerConstants.COMMAND_LINE, commandline);
String gpHomeURL = (String)request.getSession().getAttribute("ticketString");
int ppp = gpHomeURL.indexOf("?");
String ticketString = gpHomeURL.substring(ppp);
request.setAttribute("ticketString", ticketString);
String fileName = gpserverURL + "gp/jobResults/" + jobNumber + "/" + gpTask.getResultName() + ".gct";
//fileName = fileName + ticketString;
request.setAttribute(RunVisualizerConstants.DOWNLOAD_FILES, fileName);
logger.info("File URL = " + fileName + ticketString);
String supportFileURL = System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.supportFileURL");
request.setAttribute("supportFileURL", StringUtils.htmlEncode(supportFileURL));
request.setAttribute("name", "HeatMapView");
//The line above was set to "Heat Map View" for some bad reason - note the spaces.
//this causes the applet to fail on MAC. The JSP removes the spaces, but why were they hardcoded here
//changed "Heat Map View" to "HeatMapView" .... RL
gpForm.setJobList(getGPTaskList(tempGpTaskList));
List<String> processList = new ArrayList<String>();
processList.add("HeatMapViewer");
//processList.add("HeatMapImage");
//processList.add("ConcensusClustering");
gpForm.setProcessList(processList);
//////////
return mapping.findForward("appletViewer");
}
|
diff --git a/src/pl/itiner/fetch/GraveFinderProvider.java b/src/pl/itiner/fetch/GraveFinderProvider.java
index 8a285b4..49918f9 100644
--- a/src/pl/itiner/fetch/GraveFinderProvider.java
+++ b/src/pl/itiner/fetch/GraveFinderProvider.java
@@ -1,239 +1,242 @@
package pl.itiner.fetch;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import pl.itiner.model.Departed;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
public final class GraveFinderProvider extends ContentProvider implements
ResponseHandler<List<Departed>> {
private static final String TAG = "GraveFinderProvider";
public static final String NAME_QUERY_PARAM = "name";
public static final String SURENAME_QUERY_PARAM = "surename";
public static final String CEMENTARY_ID_QUERY_PARAM = "cm_id";
public static final String BIRTH_DATE_QUERY_PARAM = "birth_date";
public static final String DEATH_DATE_QUERY_PARAM = "death_date";
public static final String BURIAL_DATE_QUERY_PARAM = "burial_date";
public static final String SIMPLE_AUTHORITY = "pl.itiner.grave.GraveFinderProvider";
public static final String BASE_PATH = "graves";
public static final Uri CONTENT_URI = Uri.parse("content://"
+ SIMPLE_AUTHORITY + "/" + BASE_PATH);
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
+ "/graves";
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
+ "/grave";
// Used for the UriMacher"AA"
private static final int GRAVES_URI_ID = 1;
private static final int GRAVE_URI_ID = 2;
private static final UriMatcher sURIMatcher = new UriMatcher(
UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI(SIMPLE_AUTHORITY, BASE_PATH, GRAVES_URI_ID);
sURIMatcher.addURI(SIMPLE_AUTHORITY, BASE_PATH + "/#", GRAVE_URI_ID);
}
private DepartedDB dbHelper;
static final SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy");
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int match = sURIMatcher.match(uri);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int count = 0;
switch (match) {
case GRAVES_URI_ID:
count = db.delete(DepartedTableHelper.TABLE_NAME, selection,
selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
break;
case GRAVE_URI_ID:
long departedId = ContentUris.parseId(uri);
count = db.delete(DepartedTableHelper.TABLE_NAME,
DepartedTableHelper.COLUMN_ID + " = " + departedId, null);
getContext().getContentResolver().notifyChange(uri, null);
break;
}
return count;
}
@Override
public String getType(Uri uri) {
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case GRAVES_URI_ID:
return CONTENT_TYPE;
case GRAVE_URI_ID:
return CONTENT_ITEM_TYPE;
}
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
if (sURIMatcher.match(uri) == GRAVES_URI_ID) {
final SQLiteDatabase db = dbHelper.getWritableDatabase();
long id = db.insert(DepartedTableHelper.TABLE_NAME, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return Uri.withAppendedPath(CONTENT_URI, id + "");
} else {
throw new IllegalArgumentException("Unknown uri: " + uri);
}
}
@Override
public boolean onCreate() {
dbHelper = new DepartedDB(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
int match = sURIMatcher.match(uri);
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c;
switch (match) {
case GRAVES_URI_ID:
return handleQuery(uri, projection, db);
case GRAVE_URI_ID:
long departedId = ContentUris.parseId(uri);
c = db.query(DepartedTableHelper.TABLE_NAME, projection,
DepartedTableHelper.COLUMN_ID
+ " = "
+ departedId
+ (!TextUtils.isEmpty(selection) ? " AND ("
+ selection + ')' : ""), selectionArgs,
null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), CONTENT_URI);
return c;
default:
throw new IllegalArgumentException("unsupported uri: " + uri);
}
}
private Cursor handleQuery(Uri uri, String[] projection, SQLiteDatabase db) {
try {
QueryParams queryParams = new QueryParams(uri);
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(DepartedTableHelper.TABLE_NAME);
String[] whereArgs = createWhere(uri, builder, queryParams);
DataHandler<List<Departed>> remoteDataHandler = PoznanGeoJSONHandler
.createInstance(queryParams, getContext());
remoteDataHandler.setResponseHandler(this);
new Thread(remoteDataHandler).start();
Cursor c = builder.query(db, projection, null, whereArgs, null,
null, null);
c.setNotificationUri(getContext().getContentResolver(), CONTENT_URI);
return c;
} catch (NumberFormatException e) {
} catch (ParseException e) {
}
return null;
}
private static String[] createWhere(Uri uri, SQLiteQueryBuilder builder,
QueryParams params) {
ArrayList<String> whereArgs = new ArrayList<String>();
boolean delim = putDateToWhere(builder,
DepartedTableHelper.COLUMN_DATE_BIRTH, false, whereArgs,
params.birthDate);
delim = putDateToWhere(builder, DepartedTableHelper.COLUMN_DATE_BURIAL,
delim, whereArgs, params.burialDate);
delim = putDateToWhere(builder, DepartedTableHelper.COLUMN_DATE_DEATH,
delim, whereArgs, params.deathDate);
delim = putStringToWhere(builder, DepartedTableHelper.COLUMN_SURENAME,
delim, whereArgs, params.surename);
delim = putStringToWhere(builder, DepartedTableHelper.COLUMN_NAME,
delim, whereArgs, params.name);
putStringToWhere(builder, DepartedTableHelper.COLUMN_CEMENTERY_ID,
delim, whereArgs, params.cmId);
return whereArgs.toArray(new String[whereArgs.size()]);
}
private static boolean putStringToWhere(SQLiteQueryBuilder builder,
String column, boolean addDelim, List<String> whereArgs,
Object paramValue) {
if (paramValue != null) {
String delim = addDelim ? " AND " : "";
builder.appendWhere(delim + column + "=?");
whereArgs.add(paramValue.toString());
return true;
}
return false;
}
private static boolean putDateToWhere(SQLiteQueryBuilder builder,
String column, boolean addDelim, List<String> whereArgs,
Date paramValue) {
if (paramValue != null) {
String delim = addDelim ? " AND " : "";
builder.appendWhere(delim + column + "=?");
whereArgs.add(paramValue.getTime() + "");
return true;
}
return false;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
if (sURIMatcher.match(uri) == GRAVES_URI_ID) {
final SQLiteDatabase db = dbHelper.getWritableDatabase();
getContext().getContentResolver().notifyChange(uri, null);
return db.update(DepartedTableHelper.TABLE_NAME, values, selection,
selectionArgs);
} else {
throw new IllegalArgumentException("Unknown uri: " + uri);
}
}
@Override
public synchronized void handleResponse(List<Departed> data) {
for (Departed d : data) {
ContentValues values = new ContentValues();
values.put(DepartedTableHelper.COLUMN_ID, d.getId());
- values.put(DepartedTableHelper.COLUMN_DATE_BIRTH, d.getBirthDate()
- .getTime());
+ values.put(DepartedTableHelper.COLUMN_DATE_BIRTH,
+ d.getBirthDate() != null ? d.getBirthDate().getTime()
+ : null);
values.put(DepartedTableHelper.COLUMN_DATE_BURIAL, d
- .getBurialDate().getTime());
- values.put(DepartedTableHelper.COLUMN_DATE_DEATH, d.getDeathDate()
- .getTime());
+ .getBurialDate() != null ? d.getBurialDate().getTime()
+ : null);
+ values.put(DepartedTableHelper.COLUMN_DATE_DEATH,
+ d.getDeathDate() != null ? d.getDeathDate().getTime()
+ : null);
values.put(DepartedTableHelper.COLUMN_FAMILY, d.getFamily());
values.put(DepartedTableHelper.COLUMN_FIELD, d.getField());
values.put(DepartedTableHelper.COLUMN_LAT, d.getLocation()
.getLatitude());
values.put(DepartedTableHelper.COLUMN_LON, d.getLocation()
.getLongitude());
values.put(DepartedTableHelper.COLUMN_NAME, d.getName());
values.put(DepartedTableHelper.COLUMN_PLACE, d.getPlace());
values.put(DepartedTableHelper.COLUMN_QUARTER, d.getQuater());
values.put(DepartedTableHelper.COLUMN_ROW, d.getRow());
values.put(DepartedTableHelper.COLUMN_SIZE, d.getSize());
values.put(DepartedTableHelper.COLUMN_SURENAME, d.getSurname());
getContext().getContentResolver().insert(CONTENT_URI, values);
}
}
}
| false | true | public synchronized void handleResponse(List<Departed> data) {
for (Departed d : data) {
ContentValues values = new ContentValues();
values.put(DepartedTableHelper.COLUMN_ID, d.getId());
values.put(DepartedTableHelper.COLUMN_DATE_BIRTH, d.getBirthDate()
.getTime());
values.put(DepartedTableHelper.COLUMN_DATE_BURIAL, d
.getBurialDate().getTime());
values.put(DepartedTableHelper.COLUMN_DATE_DEATH, d.getDeathDate()
.getTime());
values.put(DepartedTableHelper.COLUMN_FAMILY, d.getFamily());
values.put(DepartedTableHelper.COLUMN_FIELD, d.getField());
values.put(DepartedTableHelper.COLUMN_LAT, d.getLocation()
.getLatitude());
values.put(DepartedTableHelper.COLUMN_LON, d.getLocation()
.getLongitude());
values.put(DepartedTableHelper.COLUMN_NAME, d.getName());
values.put(DepartedTableHelper.COLUMN_PLACE, d.getPlace());
values.put(DepartedTableHelper.COLUMN_QUARTER, d.getQuater());
values.put(DepartedTableHelper.COLUMN_ROW, d.getRow());
values.put(DepartedTableHelper.COLUMN_SIZE, d.getSize());
values.put(DepartedTableHelper.COLUMN_SURENAME, d.getSurname());
getContext().getContentResolver().insert(CONTENT_URI, values);
}
}
| public synchronized void handleResponse(List<Departed> data) {
for (Departed d : data) {
ContentValues values = new ContentValues();
values.put(DepartedTableHelper.COLUMN_ID, d.getId());
values.put(DepartedTableHelper.COLUMN_DATE_BIRTH,
d.getBirthDate() != null ? d.getBirthDate().getTime()
: null);
values.put(DepartedTableHelper.COLUMN_DATE_BURIAL, d
.getBurialDate() != null ? d.getBurialDate().getTime()
: null);
values.put(DepartedTableHelper.COLUMN_DATE_DEATH,
d.getDeathDate() != null ? d.getDeathDate().getTime()
: null);
values.put(DepartedTableHelper.COLUMN_FAMILY, d.getFamily());
values.put(DepartedTableHelper.COLUMN_FIELD, d.getField());
values.put(DepartedTableHelper.COLUMN_LAT, d.getLocation()
.getLatitude());
values.put(DepartedTableHelper.COLUMN_LON, d.getLocation()
.getLongitude());
values.put(DepartedTableHelper.COLUMN_NAME, d.getName());
values.put(DepartedTableHelper.COLUMN_PLACE, d.getPlace());
values.put(DepartedTableHelper.COLUMN_QUARTER, d.getQuater());
values.put(DepartedTableHelper.COLUMN_ROW, d.getRow());
values.put(DepartedTableHelper.COLUMN_SIZE, d.getSize());
values.put(DepartedTableHelper.COLUMN_SURENAME, d.getSurname());
getContext().getContentResolver().insert(CONTENT_URI, values);
}
}
|
diff --git a/CAI.java b/CAI.java
index 6256468..0539fb1 100644
--- a/CAI.java
+++ b/CAI.java
@@ -1,36 +1,36 @@
import java.util.Scanner; // Scanner class
public class CAI
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in); // need to read information
CAIClass assistance = new CAIClass();
while(true)
{
for(int problemLoop = 0; problemLoop < 10; problemLoop++)
{
assistance.generateProblem();
while(assistance.isIncorrect())
{
assistance.printProblem();
int answer = in.nextInt();
if (assistance.checkProblem(answer))
{
assistance.setIncorrect(false);
System.out.println(assistance.generateCorrectMessage());
}
else
System.out.println(assistance.generateIncorrectMessage());
}
assistance.setIncorrect(true);
System.out.println(assistance.getPercent());
}
System.out.printf("You scored %d/%d, that's a %f%%.\n",
- assistance.getCorrect(),
- assistance.getTotal(),
- assistance.getPercent());
+ assistance.getCorrect(),
+ assistance.getTotal(),
+ assistance.getPercent());
assistance.resetGrade();
}
}
}
| true | true | public static void main(String [] args)
{
Scanner in = new Scanner(System.in); // need to read information
CAIClass assistance = new CAIClass();
while(true)
{
for(int problemLoop = 0; problemLoop < 10; problemLoop++)
{
assistance.generateProblem();
while(assistance.isIncorrect())
{
assistance.printProblem();
int answer = in.nextInt();
if (assistance.checkProblem(answer))
{
assistance.setIncorrect(false);
System.out.println(assistance.generateCorrectMessage());
}
else
System.out.println(assistance.generateIncorrectMessage());
}
assistance.setIncorrect(true);
System.out.println(assistance.getPercent());
}
System.out.printf("You scored %d/%d, that's a %f%%.\n",
assistance.getCorrect(),
assistance.getTotal(),
assistance.getPercent());
assistance.resetGrade();
}
}
| public static void main(String [] args)
{
Scanner in = new Scanner(System.in); // need to read information
CAIClass assistance = new CAIClass();
while(true)
{
for(int problemLoop = 0; problemLoop < 10; problemLoop++)
{
assistance.generateProblem();
while(assistance.isIncorrect())
{
assistance.printProblem();
int answer = in.nextInt();
if (assistance.checkProblem(answer))
{
assistance.setIncorrect(false);
System.out.println(assistance.generateCorrectMessage());
}
else
System.out.println(assistance.generateIncorrectMessage());
}
assistance.setIncorrect(true);
System.out.println(assistance.getPercent());
}
System.out.printf("You scored %d/%d, that's a %f%%.\n",
assistance.getCorrect(),
assistance.getTotal(),
assistance.getPercent());
assistance.resetGrade();
}
}
|
diff --git a/src/Core/org/objectweb/proactive/core/component/adl/implementations/ProActiveImplementationBuilderImpl.java b/src/Core/org/objectweb/proactive/core/component/adl/implementations/ProActiveImplementationBuilderImpl.java
index 6679d0db2..0ff9b296a 100644
--- a/src/Core/org/objectweb/proactive/core/component/adl/implementations/ProActiveImplementationBuilderImpl.java
+++ b/src/Core/org/objectweb/proactive/core/component/adl/implementations/ProActiveImplementationBuilderImpl.java
@@ -1,208 +1,210 @@
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* 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 any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.component.adl.implementations;
import java.util.Map;
import org.apache.log4j.Logger;
import org.objectweb.fractal.adl.ADLException;
import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.control.BindingController;
import org.objectweb.fractal.api.type.ComponentType;
import org.objectweb.fractal.util.Fractal;
import org.objectweb.proactive.core.component.Constants;
import org.objectweb.proactive.core.component.ContentDescription;
import org.objectweb.proactive.core.component.ControllerDescription;
import org.objectweb.proactive.core.component.adl.RegistryManager;
import org.objectweb.proactive.core.component.adl.nodes.VirtualNode;
import org.objectweb.proactive.core.component.adl.vnexportation.ExportedVirtualNodesList;
import org.objectweb.proactive.core.component.adl.vnexportation.LinkedVirtualNode;
import org.objectweb.proactive.core.component.factory.ProActiveGenericFactory;
import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor;
import org.objectweb.proactive.core.group.Group;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
/**
* @author Matthieu Morel
*/
public class ProActiveImplementationBuilderImpl
implements ProActiveImplementationBuilder, BindingController {
public final static String REGISTRY_BINDING = "registry";
public RegistryManager registry;
protected static Logger logger = ProActiveLogger.getLogger(Loggers.COMPONENTS_ADL);
// --------------------------------------------------------------------------
// Implementation of the BindingController interface
// --------------------------------------------------------------------------
public String[] listFc() {
return new String[] { REGISTRY_BINDING };
}
public Object lookupFc(final String itf) {
if (itf.equals(REGISTRY_BINDING)) {
return registry;
}
return null;
}
public void bindFc(final String itf, final Object value) {
if (itf.equals(REGISTRY_BINDING)) {
registry = (RegistryManager) value;
}
}
public void unbindFc(final String itf) {
if (itf.equals(REGISTRY_BINDING)) {
registry = null;
}
}
// --------------------------------------------------------------------------
// Implementation of the Implementation Builder and ProActiveImplementationBuilder interfaces
// --------------------------------------------------------------------------
public Object createComponent(Object arg0, String arg1, String arg2,
Object arg3, Object arg4, Object arg5) throws Exception {
return null;
}
public Object createComponent(Object type, String name, String definition,
ControllerDescription controllerDesc, ContentDescription contentDesc,
VirtualNode adlVN, Map context) throws Exception {
ObjectsContainer obj = commonCreation(type, name, definition,
contentDesc, adlVN, context);
return createFComponent(type, obj.getDvn(), controllerDesc,
contentDesc, adlVN, obj.getBootstrapComponent());
}
protected ObjectsContainer commonCreation(Object type, String name,
String definition, ContentDescription contentDesc, VirtualNode adlVN,
Map context) throws Exception {
org.objectweb.proactive.core.descriptor.data.VirtualNodeInternal deploymentVN =
null;
Component bootstrap = null;
if (context != null) {
bootstrap = (Component) ((Map) context).get("bootstrap");
}
if (bootstrap == null) {
bootstrap = Fractal.getBootstrapComponent();
}
if (adlVN != null) {
// consider exported virtual nodes
LinkedVirtualNode exported = ExportedVirtualNodesList.instance()
.getNode(name,
adlVN.getName(), false);
if (exported != null) {
adlVN.setName(exported.getExportedVirtualNodeNameAfterComposition());
adlVN.setCardinality(exported.isMultiple()
? VirtualNode.MULTIPLE : VirtualNode.SINGLE);
} else {
// TODO add self exported virtual node ?
// for the moment, just add a leaf to the linked vns
ExportedVirtualNodesList.instance()
.addLeafVirtualNode(name,
adlVN.getName(), adlVN.getCardinality()); // TODO_M check this
}
if (context.get("deployment-descriptor") != null) {
- deploymentVN = ((ProActiveDescriptor) context
- .get("deployment-descriptor")).getVirtualNode(adlVN.getName())
- .getVirtualNodeInternal();
+ org.objectweb.proactive.core.descriptor.data.VirtualNode vn = ((ProActiveDescriptor) context.get(
+ "deployment-descriptor")).getVirtualNode(adlVN.getName());
+ if (vn != null) {
+ deploymentVN = vn.getVirtualNodeInternal();
+ }
if (deploymentVN == null) {
if (adlVN.getName().equals("null")) {
logger.info(name +
" will be instantiated in the current virtual machine (\"null\" was specified as the virtual node name)");
} else {
throw new ADLException("Could not find virtual node " +
adlVN.getName() + " in the deployment descriptor",
null);
}
} else {
if (deploymentVN.isMultiple() &&
(adlVN.getCardinality().equals(VirtualNode.SINGLE))) {
// there will be only one instance of the component, on one node of the virtual node
contentDesc.forceSingleInstance();
} else if (!(deploymentVN.isMultiple()) &&
(adlVN.getCardinality().equals(VirtualNode.MULTIPLE))) {
throw new ADLException(
"Cannot deploy on a single virtual node when the cardinality of this virtual node named " +
adlVN.getName() + " in the ADL is set to multiple",
null);
}
}
}
}
return new ObjectsContainer(deploymentVN, bootstrap);
}
private Component createFComponent(Object type,
org.objectweb.proactive.core.descriptor.data.VirtualNode deploymentVN,
ControllerDescription controllerDesc, ContentDescription contentDesc,
VirtualNode adlVN, Component bootstrap) throws Exception {
Component result;
// FIXME : exhaustively specify the behaviour
if ((deploymentVN != null) &&
VirtualNode.MULTIPLE.equals(adlVN.getCardinality()) &&
controllerDesc.getHierarchicalType().equals(Constants.PRIMITIVE) &&
!contentDesc.uniqueInstance()) {
result = (Component) ((Group) ((ProActiveGenericFactory) Fractal.getGenericFactory(bootstrap)).newFcInstanceAsList((ComponentType) type,
controllerDesc, contentDesc, deploymentVN)).getGroupByType();
} else {
result = ((ProActiveGenericFactory) Fractal.getGenericFactory(bootstrap)).newFcInstance((ComponentType) type,
controllerDesc, contentDesc, deploymentVN);
}
// registry.addComponent(result); // the registry can handle groups
return result;
}
protected class ObjectsContainer {
private org.objectweb.proactive.core.descriptor.data.VirtualNode deploymentVN;
private Component bootstrap;
public ObjectsContainer(
org.objectweb.proactive.core.descriptor.data.VirtualNode dVn,
Component bstrp) {
deploymentVN = dVn;
bootstrap = bstrp;
}
public org.objectweb.proactive.core.descriptor.data.VirtualNode getDvn() {
return deploymentVN;
}
public Component getBootstrapComponent() {
return bootstrap;
}
}
}
| true | true | protected ObjectsContainer commonCreation(Object type, String name,
String definition, ContentDescription contentDesc, VirtualNode adlVN,
Map context) throws Exception {
org.objectweb.proactive.core.descriptor.data.VirtualNodeInternal deploymentVN =
null;
Component bootstrap = null;
if (context != null) {
bootstrap = (Component) ((Map) context).get("bootstrap");
}
if (bootstrap == null) {
bootstrap = Fractal.getBootstrapComponent();
}
if (adlVN != null) {
// consider exported virtual nodes
LinkedVirtualNode exported = ExportedVirtualNodesList.instance()
.getNode(name,
adlVN.getName(), false);
if (exported != null) {
adlVN.setName(exported.getExportedVirtualNodeNameAfterComposition());
adlVN.setCardinality(exported.isMultiple()
? VirtualNode.MULTIPLE : VirtualNode.SINGLE);
} else {
// TODO add self exported virtual node ?
// for the moment, just add a leaf to the linked vns
ExportedVirtualNodesList.instance()
.addLeafVirtualNode(name,
adlVN.getName(), adlVN.getCardinality()); // TODO_M check this
}
if (context.get("deployment-descriptor") != null) {
deploymentVN = ((ProActiveDescriptor) context
.get("deployment-descriptor")).getVirtualNode(adlVN.getName())
.getVirtualNodeInternal();
if (deploymentVN == null) {
if (adlVN.getName().equals("null")) {
logger.info(name +
" will be instantiated in the current virtual machine (\"null\" was specified as the virtual node name)");
} else {
throw new ADLException("Could not find virtual node " +
adlVN.getName() + " in the deployment descriptor",
null);
}
} else {
if (deploymentVN.isMultiple() &&
(adlVN.getCardinality().equals(VirtualNode.SINGLE))) {
// there will be only one instance of the component, on one node of the virtual node
contentDesc.forceSingleInstance();
} else if (!(deploymentVN.isMultiple()) &&
(adlVN.getCardinality().equals(VirtualNode.MULTIPLE))) {
throw new ADLException(
"Cannot deploy on a single virtual node when the cardinality of this virtual node named " +
adlVN.getName() + " in the ADL is set to multiple",
null);
}
}
}
}
return new ObjectsContainer(deploymentVN, bootstrap);
}
| protected ObjectsContainer commonCreation(Object type, String name,
String definition, ContentDescription contentDesc, VirtualNode adlVN,
Map context) throws Exception {
org.objectweb.proactive.core.descriptor.data.VirtualNodeInternal deploymentVN =
null;
Component bootstrap = null;
if (context != null) {
bootstrap = (Component) ((Map) context).get("bootstrap");
}
if (bootstrap == null) {
bootstrap = Fractal.getBootstrapComponent();
}
if (adlVN != null) {
// consider exported virtual nodes
LinkedVirtualNode exported = ExportedVirtualNodesList.instance()
.getNode(name,
adlVN.getName(), false);
if (exported != null) {
adlVN.setName(exported.getExportedVirtualNodeNameAfterComposition());
adlVN.setCardinality(exported.isMultiple()
? VirtualNode.MULTIPLE : VirtualNode.SINGLE);
} else {
// TODO add self exported virtual node ?
// for the moment, just add a leaf to the linked vns
ExportedVirtualNodesList.instance()
.addLeafVirtualNode(name,
adlVN.getName(), adlVN.getCardinality()); // TODO_M check this
}
if (context.get("deployment-descriptor") != null) {
org.objectweb.proactive.core.descriptor.data.VirtualNode vn = ((ProActiveDescriptor) context.get(
"deployment-descriptor")).getVirtualNode(adlVN.getName());
if (vn != null) {
deploymentVN = vn.getVirtualNodeInternal();
}
if (deploymentVN == null) {
if (adlVN.getName().equals("null")) {
logger.info(name +
" will be instantiated in the current virtual machine (\"null\" was specified as the virtual node name)");
} else {
throw new ADLException("Could not find virtual node " +
adlVN.getName() + " in the deployment descriptor",
null);
}
} else {
if (deploymentVN.isMultiple() &&
(adlVN.getCardinality().equals(VirtualNode.SINGLE))) {
// there will be only one instance of the component, on one node of the virtual node
contentDesc.forceSingleInstance();
} else if (!(deploymentVN.isMultiple()) &&
(adlVN.getCardinality().equals(VirtualNode.MULTIPLE))) {
throw new ADLException(
"Cannot deploy on a single virtual node when the cardinality of this virtual node named " +
adlVN.getName() + " in the ADL is set to multiple",
null);
}
}
}
}
return new ObjectsContainer(deploymentVN, bootstrap);
}
|
diff --git a/HelloWorld/src/com/Rally/demo/Start.java b/HelloWorld/src/com/Rally/demo/Start.java
index 75a7b66..8dfe203 100644
--- a/HelloWorld/src/com/Rally/demo/Start.java
+++ b/HelloWorld/src/com/Rally/demo/Start.java
@@ -1,14 +1,14 @@
package com.Rally.demo;
public class Start {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// This is java
- System.out.println("Hello ACP");
+ System.out.println("Hello");
}
}
| true | true | public static void main(String[] args) {
// TODO Auto-generated method stub
// This is java
System.out.println("Hello ACP");
}
| public static void main(String[] args) {
// TODO Auto-generated method stub
// This is java
System.out.println("Hello");
}
|
diff --git a/src/main/java/net/i2cat/netconf/transport/MockTransport.java b/src/main/java/net/i2cat/netconf/transport/MockTransport.java
index d86d82b..7678c32 100644
--- a/src/main/java/net/i2cat/netconf/transport/MockTransport.java
+++ b/src/main/java/net/i2cat/netconf/transport/MockTransport.java
@@ -1,309 +1,311 @@
/**
* This file is part of Netconf4j.
*
* Netconf4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Netconf4j 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 Netconf4j. If not, see <http://www.gnu.org/licenses/>.
*/
package net.i2cat.netconf.transport;
import java.util.ArrayList;
import java.util.Vector;
import net.i2cat.netconf.SessionContext;
import net.i2cat.netconf.errors.TransportException;
import net.i2cat.netconf.messageQueue.MessageQueue;
import net.i2cat.netconf.rpc.Capability;
import net.i2cat.netconf.rpc.Error;
import net.i2cat.netconf.rpc.ErrorSeverity;
import net.i2cat.netconf.rpc.ErrorTag;
import net.i2cat.netconf.rpc.ErrorType;
import net.i2cat.netconf.rpc.Hello;
import net.i2cat.netconf.rpc.Operation;
import net.i2cat.netconf.rpc.Query;
import net.i2cat.netconf.rpc.RPCElement;
import net.i2cat.netconf.rpc.Reply;
import net.i2cat.netconf.utils.FileHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This class was implemented to be a dummy transport which could simulate a
* real connection with a device. This connection via SSH with netconf
*/
public class MockTransport implements Transport {
private Log log = LogFactory.getLog(MockTransport.class);
Vector<TransportListener> listeners = new Vector<TransportListener>();
SessionContext context;
ArrayList<Capability> supportedCapabilities;
MessageQueue queue;
int lastMessageId = 0;
String subsystem = "";
boolean modeErrors = false;
private static String path = "/mock/";
public static final String fileIPConfiguration = path + "ipconfiguration.xml";
/* Extra capabilities */
public static final String fileIPLogicalRouterConfig = path + "iplogicalconfiguration.xml";
boolean insideLogicalRouter = true;
public void addListener(TransportListener handler) {
listeners.add(handler);
}
public void setMessageQueue(MessageQueue queue) {
this.queue = queue;
}
public void connect(SessionContext sessionContext) throws TransportException {
context = sessionContext;
if (!context.getScheme().equals("mock"))
throw new TransportException("Mock transport initialized with other scheme: " + context.getScheme());
subsystem = sessionContext.getSubsystem();
Hello hello = new Hello();
hello.setMessageId(String.valueOf(lastMessageId));
hello.setSessionId("1234");
supportedCapabilities = new ArrayList<Capability>();
// FIXME more capabilities?
supportedCapabilities.add(Capability.BASE);
hello.setCapabilities(supportedCapabilities);
queue.put(hello);
for (TransportListener listener : listeners)
listener.transportOpenned();
}
public void disconnect() throws TransportException {
for (TransportListener listener : listeners)
listener.transportClosed();
}
public void sendAsyncQuery(RPCElement elem) throws TransportException {
Reply reply = new Reply();
Vector<Error> errors = new Vector<Error>();
if (elem instanceof Hello) {
// Capability b
ArrayList<Capability> capabilities = ((Hello) elem).getCapabilities();
capabilities.retainAll(this.supportedCapabilities);
context.setActiveCapabilities(capabilities);
}
if (elem instanceof Query) {
Query query = (Query) elem;
Operation op = query.getOperation();
if (op.equals(Operation.COPY_CONFIG)) {
} else if (op.equals(Operation.DELETE_CONFIG)) {
reply.setOk(true);
+ reply.setMessageId(query.getMessageId());
} else if (op.equals(Operation.EDIT_CONFIG)) {
reply.setOk(true);
+ reply.setMessageId(query.getMessageId());
} else if (op.equals(Operation.GET)) {
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
reply.setContain(getDataFromFile(fileIPConfiguration));
} else if (op.equals(Operation.GET_CONFIG)) {
if (query.getSource() == null)
errors.add(new Error() {
{
setTag(ErrorTag.MISSING_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : No source configuration specified");
}
});
if (query.getSource() == null && query.getSource().equals("running")) {
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : Wrong configuration.");
}
});
}
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
if (!insideLogicalRouter) {
reply.setContain(getDataFromFile(fileIPConfiguration));
} else {
reply.setContain(getDataFromFile(fileIPLogicalRouterConfig));
}
} else if (op.equals(Operation.KILL_SESSION)) {
insideLogicalRouter = false;
disconnect();
return;
} else if (op.equals(Operation.CLOSE_SESSION)) {
reply.setMessageId(query.getMessageId());
reply.setOk(true);
insideLogicalRouter = false;
disconnect();
} else if (op.equals(Operation.LOCK)) {
error("LOCK not implemented");
} else if (op.equals(Operation.UNLOCK)) {
error("UNLOCK not implemented");
}
/* include junos capabilities operations */
else if (op.equals(Operation.SET_LOGICAL_ROUTER)) {
reply.setMessageId(query.getMessageId());
reply.setContain("<cli><logical-system>" + query.getIdLogicalRouter() + "</logical-system></cli>");
insideLogicalRouter = true;
}
}
// force to add errors in the response message
if (subsystem.equals("errorServer"))
addErrors(errors);
if (errors.size() > 0)
reply.setErrors(errors);
queue.put(reply);
}
public String getDataFromFile(String fileConfig) throws TransportException {
String str = "";
log.info("Trying to open " + fileConfig);
try {
str = FileHelper.getInstance().readStringFromFile(fileConfig);
} catch (Exception e) {
e.printStackTrace();
log.error("error message: " + e.getLocalizedMessage());
throw new TransportException(e.getMessage());
}
log.info("OK! the file was read");
return str;
}
private void error(String msg) throws TransportException {
throw new TransportException(msg);
}
private void addErrors(Vector<Error> errors) {
errors.add(new Error() {
{
setTag(ErrorTag.INVALID_VALUE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("");
}
});
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : ");
}
});
errors.add(new Error() {
{
setTag(ErrorTag.MISSING_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : ");
}
});
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : ");
}
});
errors.add(new Error() {
{
setTag(ErrorTag.MISSING_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : ");
}
});
}
}
| false | true | public void sendAsyncQuery(RPCElement elem) throws TransportException {
Reply reply = new Reply();
Vector<Error> errors = new Vector<Error>();
if (elem instanceof Hello) {
// Capability b
ArrayList<Capability> capabilities = ((Hello) elem).getCapabilities();
capabilities.retainAll(this.supportedCapabilities);
context.setActiveCapabilities(capabilities);
}
if (elem instanceof Query) {
Query query = (Query) elem;
Operation op = query.getOperation();
if (op.equals(Operation.COPY_CONFIG)) {
} else if (op.equals(Operation.DELETE_CONFIG)) {
reply.setOk(true);
} else if (op.equals(Operation.EDIT_CONFIG)) {
reply.setOk(true);
} else if (op.equals(Operation.GET)) {
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
reply.setContain(getDataFromFile(fileIPConfiguration));
} else if (op.equals(Operation.GET_CONFIG)) {
if (query.getSource() == null)
errors.add(new Error() {
{
setTag(ErrorTag.MISSING_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : No source configuration specified");
}
});
if (query.getSource() == null && query.getSource().equals("running")) {
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : Wrong configuration.");
}
});
}
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
if (!insideLogicalRouter) {
reply.setContain(getDataFromFile(fileIPConfiguration));
} else {
reply.setContain(getDataFromFile(fileIPLogicalRouterConfig));
}
} else if (op.equals(Operation.KILL_SESSION)) {
insideLogicalRouter = false;
disconnect();
return;
} else if (op.equals(Operation.CLOSE_SESSION)) {
reply.setMessageId(query.getMessageId());
reply.setOk(true);
insideLogicalRouter = false;
disconnect();
} else if (op.equals(Operation.LOCK)) {
error("LOCK not implemented");
} else if (op.equals(Operation.UNLOCK)) {
error("UNLOCK not implemented");
}
/* include junos capabilities operations */
else if (op.equals(Operation.SET_LOGICAL_ROUTER)) {
reply.setMessageId(query.getMessageId());
reply.setContain("<cli><logical-system>" + query.getIdLogicalRouter() + "</logical-system></cli>");
insideLogicalRouter = true;
}
}
// force to add errors in the response message
if (subsystem.equals("errorServer"))
addErrors(errors);
if (errors.size() > 0)
reply.setErrors(errors);
queue.put(reply);
}
| public void sendAsyncQuery(RPCElement elem) throws TransportException {
Reply reply = new Reply();
Vector<Error> errors = new Vector<Error>();
if (elem instanceof Hello) {
// Capability b
ArrayList<Capability> capabilities = ((Hello) elem).getCapabilities();
capabilities.retainAll(this.supportedCapabilities);
context.setActiveCapabilities(capabilities);
}
if (elem instanceof Query) {
Query query = (Query) elem;
Operation op = query.getOperation();
if (op.equals(Operation.COPY_CONFIG)) {
} else if (op.equals(Operation.DELETE_CONFIG)) {
reply.setOk(true);
reply.setMessageId(query.getMessageId());
} else if (op.equals(Operation.EDIT_CONFIG)) {
reply.setOk(true);
reply.setMessageId(query.getMessageId());
} else if (op.equals(Operation.GET)) {
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
reply.setContain(getDataFromFile(fileIPConfiguration));
} else if (op.equals(Operation.GET_CONFIG)) {
if (query.getSource() == null)
errors.add(new Error() {
{
setTag(ErrorTag.MISSING_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : No source configuration specified");
}
});
if (query.getSource() == null && query.getSource().equals("running")) {
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : Wrong configuration.");
}
});
}
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
if (!insideLogicalRouter) {
reply.setContain(getDataFromFile(fileIPConfiguration));
} else {
reply.setContain(getDataFromFile(fileIPLogicalRouterConfig));
}
} else if (op.equals(Operation.KILL_SESSION)) {
insideLogicalRouter = false;
disconnect();
return;
} else if (op.equals(Operation.CLOSE_SESSION)) {
reply.setMessageId(query.getMessageId());
reply.setOk(true);
insideLogicalRouter = false;
disconnect();
} else if (op.equals(Operation.LOCK)) {
error("LOCK not implemented");
} else if (op.equals(Operation.UNLOCK)) {
error("UNLOCK not implemented");
}
/* include junos capabilities operations */
else if (op.equals(Operation.SET_LOGICAL_ROUTER)) {
reply.setMessageId(query.getMessageId());
reply.setContain("<cli><logical-system>" + query.getIdLogicalRouter() + "</logical-system></cli>");
insideLogicalRouter = true;
}
}
// force to add errors in the response message
if (subsystem.equals("errorServer"))
addErrors(errors);
if (errors.size() > 0)
reply.setErrors(errors);
queue.put(reply);
}
|
diff --git a/tests/org.eclipse.wst.xml.xpath2.processor.tests/src/org/eclipse/wst/xml/xpath2/processor/test/TestBugs.java b/tests/org.eclipse.wst.xml.xpath2.processor.tests/src/org/eclipse/wst/xml/xpath2/processor/test/TestBugs.java
index 07d2b6e3..d9f9d971 100644
--- a/tests/org.eclipse.wst.xml.xpath2.processor.tests/src/org/eclipse/wst/xml/xpath2/processor/test/TestBugs.java
+++ b/tests/org.eclipse.wst.xml.xpath2.processor.tests/src/org/eclipse/wst/xml/xpath2/processor/test/TestBugs.java
@@ -1,908 +1,908 @@
/*******************************************************************************
* Copyright (c) 2009 Standards for Technology in Automotive Retail and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David Carver (STAR) - initial API and implementation
* Mukul Gandhi - bug 273719 - improvements to fn:string-length function
* Mukul Gandhi - bug 273795 - improvements to fn:substring function
* Mukul Gandhi - bug 274471 - improvements to fn:string function
* Mukul Gandhi - bug 274725 - improvements to fn:base-uri function
* Mukul Gandhi - bug 274731 - improvements to fn:document-uri function
* Mukul Gandhi - bug 274784 - improvements to xs:boolean data type
* Mukul Gandhi - bug 274805 - improvements to xs:integer data type
* Mukul Gandhi - bug 274952 - implements xs:long data type
* Mukul Gandhi - bug 277599 - implements xs:nonPositiveInteger data type
* Mukul Gandhi - bug 277602 - implements xs:negativeInteger data type
* Mukul Gandhi - bug 277599 - implements xs:nonPositiveInteger data type
* Mukul Gandhi - bug 277608 implements xs:short data type
* bug 277609 implements xs:nonNegativeInteger data type
* bug 277629 implements xs:unsignedLong data type
* bug 277632 implements xs:positiveInteger data type
* bug 277639 implements xs:byte data type
* bug 277642 implements xs:unsignedInt data type
* bug 277645 implements xs:unsignedShort data type
* bug 277650 implements xs:unsignedByte data type
* bug 279373 improvements to multiply operation on xs:yearMonthDuration
* data type.
* bug 279376 improvements to xs:yearMonthDuration division operation
* bug 281046 implementation of xs:base64Binary data type
*******************************************************************************/
package org.eclipse.wst.xml.xpath2.processor.test;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.xerces.xs.XSModel;
import org.eclipse.wst.xml.xpath2.processor.DefaultEvaluator;
import org.eclipse.wst.xml.xpath2.processor.DynamicContext;
import org.eclipse.wst.xml.xpath2.processor.Evaluator;
import org.eclipse.wst.xml.xpath2.processor.ResultSequence;
import org.eclipse.wst.xml.xpath2.processor.ast.XPath;
import org.eclipse.wst.xml.xpath2.processor.internal.types.XSBoolean;
import org.eclipse.wst.xml.xpath2.processor.internal.types.XSDecimal;
import org.eclipse.wst.xml.xpath2.processor.internal.types.XSDouble;
import org.eclipse.wst.xml.xpath2.processor.internal.types.XSDuration;
import org.eclipse.wst.xml.xpath2.processor.internal.types.XSFloat;
public class TestBugs extends AbstractPsychoPathTest {
public void testStringLengthWithElementArg() throws Exception {
// Bug 273719
URL fileURL = bundle.getEntry("/bugTestFiles/bug273719.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "string-length(x) > 2";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testBug273795Arity2() throws Exception {
// Bug 273795
URL fileURL = bundle.getEntry("/bugTestFiles/bug273795.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// test with arity 2
String xpath = "substring(x, 3) = 'happy'";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testBug273795Arity3() throws Exception {
// Bug 273795
URL fileURL = bundle.getEntry("/bugTestFiles/bug273795.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// test with arity 3
String xpath = "substring(x, 3, 4) = 'happ'";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testStringFunctionBug274471() throws Exception {
// Bug 274471
URL fileURL = bundle.getEntry("/bugTestFiles/bug274471.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "x/string() = 'unhappy'";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testStringLengthFunctionBug274471() throws Exception {
// Bug 274471. string-length() with arity 0
URL fileURL = bundle.getEntry("/bugTestFiles/bug274471.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "x/string-length() = 7";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testNormalizeSpaceFunctionBug274471() throws Exception {
// Bug 274471. normalize-space() with arity 0
URL fileURL = bundle.getEntry("/bugTestFiles/bug274471.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "x/normalize-space() = 'unhappy'";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testAnyUriEqualityBug() throws Exception {
// Bug 274719
// reusing the XML document from another bug
URL fileURL = bundle.getEntry("/bugTestFiles/bug274471.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "xs:anyURI('abc') eq xs:anyURI('abc')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testBaseUriBug() throws Exception {
// Bug 274725
//DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//DocumentBuilder docBuilder = dbf.newDocumentBuilder();
loadDOMDocument(new URL("http://www.w3schools.com/xml/note.xml"));
// for testing this bug, we read the XML document from the web.
// this ensures, that base-uri property of DOM is not null.
//domDoc = docBuilder.parse("http://www.w3schools.com/xml/note.xml");
// we pass XSModel as null for this test case. Otherwise, we would
// get an exception.
DynamicContext dc = setupDynamicContext(null);
String xpath = "base-uri(note) eq xs:anyURI('http://www.w3schools.com/xml/note.xml')";
// please note: The below XPath would also work, with base-uri using
// arity 0.
// String xpath =
// "note/base-uri() eq xs:anyURI('http://www.w3schools.com/xml/note.xml')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
- assertEquals("false", actual);
+ assertEquals("true", actual);
}
public void testDocumentUriBug() throws Exception {
// Bug 274731
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
domDoc = docBuilder.parse("http://www.w3schools.com/xml/note.xml");
DynamicContext dc = setupDynamicContext(null);
String xpath = "document-uri(/) eq xs:anyURI('http://www.w3schools.com/xml/note.xml')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = "false";
if (result != null) {
actual = result.string_value();
}
assertEquals("true", actual);
}
public void testBooleanTypeBug() throws Exception {
// Bug 274784
// reusing the XML document from another bug
URL fileURL = bundle.getEntry("/bugTestFiles/bug273719.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "xs:boolean('1') eq xs:boolean('true')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testDateConstructorBug() throws Exception {
// Bug 274792
URL fileURL = bundle.getEntry("/bugTestFiles/bug274792.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "xs:date(x) eq xs:date('2009-01-01')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testIntegerDataTypeBug() throws Exception {
// Bug 274805
URL fileURL = bundle.getEntry("/bugTestFiles/bug274805.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "xs:integer(x) gt 100";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testLongDataType() throws Exception {
// Bug 274952
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// long min value is -9223372036854775808
// and max value can be 9223372036854775807
String xpath = "xs:long('9223372036854775807') gt 0";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testIntDataType() throws Exception {
// Bug 275105
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// int min value is -2147483648
// and max value can be 2147483647
String xpath = "xs:int('2147483647') gt 0";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testSchemaAwarenessForAttributes() throws Exception {
// Bug 276134
URL fileURL = bundle.getEntry("/bugTestFiles/bug276134.xml");
URL schemaURL = bundle.getEntry("/bugTestFiles/bug276134.xsd");
loadDOMDocument(fileURL, schemaURL);
// Get XSModel object for the Schema
XSModel schema = getGrammar(schemaURL);
DynamicContext dc = setupDynamicContext(schema);
String xpath = "person/@dob eq xs:date('2006-12-10')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testSchemaAwarenessForElements() throws Exception {
// Bug 276134
URL fileURL = bundle.getEntry("/bugTestFiles/bug276134_2.xml");
URL schemaURL = bundle.getEntry("/bugTestFiles/bug276134_2.xsd");
loadDOMDocument(fileURL, schemaURL);
// Get XSModel object for the Schema
XSModel schema = getGrammar(schemaURL);
DynamicContext dc = setupDynamicContext(schema);
String xpath = "person/dob eq xs:date('2006-12-10')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSNonPositiveInteger() throws Exception {
// Bug 277599
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// min value of xs:nonPositiveInteger is -INF
// max value is 0
String xpath = "xs:nonPositiveInteger('0') eq 0";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSNegativeInteger() throws Exception {
// Bug 277602
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// min value of xs:negativeInteger is -INF
// max value is -1
String xpath = "xs:negativeInteger('-1') eq -1";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSShort() throws Exception {
// Bug 277608
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// min value of xs:short is -32768
// max value of xs:short is 32767
String xpath = "xs:short('-32768') eq -32768";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSNonNegativeInteger() throws Exception {
// Bug 277609
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// min value of xs:nonNegativeInteger is 0
// max value of xs:nonNegativeInteger is INF
String xpath = "xs:nonNegativeInteger('0') eq 0";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSUnsignedLong() throws Exception {
// Bug 277629
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// min value of xs:unsignedLong is 0
// max value of xs:unsignedLong is 18446744073709551615
String xpath = "xs:unsignedLong('0') eq 0";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSPositiveInteger() throws Exception {
// Bug 277632
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// min value of xs:positiveInteger is 1
// max value of xs:positiveInteger is INF
String xpath = "xs:positiveInteger('1') eq 1";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSByte() throws Exception {
// Bug 277639
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// min value of xs:byte is -128
// max value of xs:byte is 127
String xpath = "xs:byte('-128') eq -128";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSUnsignedInt() throws Exception {
// Bug 277642
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// min value of xs:unsignedInt is 0
// max value of xs:unsignedInt is 4294967295
String xpath = "xs:unsignedInt('4294967295') eq xs:unsignedInt('4294967295')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSUnsignedShort() throws Exception {
// Bug 277645
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// min value of xs:unsignedShort is 0
// max value of xs:unsignedShort is 65535
String xpath = "xs:unsignedShort('65535') eq 65535";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSYearMonthDurationMultiply() throws Exception {
// Bug 279373
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "xs:yearMonthDuration('P2Y11M') * 2.3";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSDuration result = (XSDuration) rs.first();
String actual = result.string_value();
assertEquals("P6Y9M", actual);
}
public void testXSYearMonthDurationDivide1() throws Exception {
// Bug 279376
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "xs:yearMonthDuration('P2Y11M') div 1.5";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSDuration result = (XSDuration) rs.first();
String actual = result.string_value();
assertEquals("P1Y11M", actual);
}
public void testXSYearMonthDurationDivide2() throws Exception {
// Bug 279376
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "xs:yearMonthDuration('P3Y4M') div xs:yearMonthDuration('-P1Y4M')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSDecimal result = (XSDecimal) rs.first();
String actual = result.string_value();
assertEquals("-2.5", actual);
}
public void testXSDayTimeDurationMultiply() throws Exception {
// Bug 279377
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "xs:dayTimeDuration('PT2H10M') * 2.1";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSDuration result = (XSDuration) rs.first();
String actual = result.string_value();
assertEquals("PT4H33M", actual);
}
public void testXSDayTimeDurationDivide() throws Exception {
// Bug 279377
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "xs:dayTimeDuration('P1DT2H30M10.5S') div 1.5";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSDuration result = (XSDuration) rs.first();
String actual = result.string_value();
assertEquals("PT17H40M7S", actual);
}
public void testNegativeZeroDouble() throws Exception {
// Bug 279406
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "-(xs:double('0'))";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSDouble result = (XSDouble) rs.first();
String actual = result.string_value();
assertEquals("-0", actual);
}
public void testNegativeZeroFloat() throws Exception {
// Bug 279406
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "-(xs:float('0'))";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSFloat result = (XSFloat) rs.first();
String actual = result.string_value();
assertEquals("-0", actual);
}
public void testXSUnsignedByte() throws Exception {
// Bug 277650
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
// min value of xs:unsignedByte is 0
// max value of xs:unsignedByte is 255
String xpath = "xs:unsignedByte('255') eq 255";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSBase64Binary() throws Exception {
// Bug 281046
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "xs:base64Binary('cmxjZ3R4c3JidnllcmVuZG91aWpsbXV5Z2NhamxpcmJkaWFhbmFob2VsYXVwZmJ1Z2dmanl2eHlzYmhheXFtZXR0anV2dG1q') eq xs:base64Binary('cmxjZ3R4c3JidnllcmVuZG91aWpsbXV5Z2NhamxpcmJkaWFhbmFob2VsYXVwZmJ1Z2dmanl2eHlzYmhheXFtZXR0anV2dG1q')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
public void testXSHexBinary() throws Exception {
// Bug 281054
URL fileURL = bundle.getEntry("/TestSources/emptydoc.xml");
loadDOMDocument(fileURL);
// Get XML Schema Information for the Document
XSModel schema = getGrammar();
DynamicContext dc = setupDynamicContext(schema);
String xpath = "xs:hexBinary('767479716c6a647663') eq xs:hexBinary('767479716c6a647663')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
}
| true | true | public void testBaseUriBug() throws Exception {
// Bug 274725
//DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//DocumentBuilder docBuilder = dbf.newDocumentBuilder();
loadDOMDocument(new URL("http://www.w3schools.com/xml/note.xml"));
// for testing this bug, we read the XML document from the web.
// this ensures, that base-uri property of DOM is not null.
//domDoc = docBuilder.parse("http://www.w3schools.com/xml/note.xml");
// we pass XSModel as null for this test case. Otherwise, we would
// get an exception.
DynamicContext dc = setupDynamicContext(null);
String xpath = "base-uri(note) eq xs:anyURI('http://www.w3schools.com/xml/note.xml')";
// please note: The below XPath would also work, with base-uri using
// arity 0.
// String xpath =
// "note/base-uri() eq xs:anyURI('http://www.w3schools.com/xml/note.xml')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("false", actual);
}
| public void testBaseUriBug() throws Exception {
// Bug 274725
//DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//DocumentBuilder docBuilder = dbf.newDocumentBuilder();
loadDOMDocument(new URL("http://www.w3schools.com/xml/note.xml"));
// for testing this bug, we read the XML document from the web.
// this ensures, that base-uri property of DOM is not null.
//domDoc = docBuilder.parse("http://www.w3schools.com/xml/note.xml");
// we pass XSModel as null for this test case. Otherwise, we would
// get an exception.
DynamicContext dc = setupDynamicContext(null);
String xpath = "base-uri(note) eq xs:anyURI('http://www.w3schools.com/xml/note.xml')";
// please note: The below XPath would also work, with base-uri using
// arity 0.
// String xpath =
// "note/base-uri() eq xs:anyURI('http://www.w3schools.com/xml/note.xml')";
XPath path = compileXPath(dc, xpath);
Evaluator eval = new DefaultEvaluator(dc, domDoc);
ResultSequence rs = eval.evaluate(path);
XSBoolean result = (XSBoolean) rs.first();
String actual = result.string_value();
assertEquals("true", actual);
}
|
diff --git a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/home/AddressHome.java b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/home/AddressHome.java
index bfc9b582..f75ddef0 100644
--- a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/home/AddressHome.java
+++ b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/home/AddressHome.java
@@ -1,72 +1,72 @@
/**
*
*/
package gr.sch.ira.minoas.seam.components.home;
import gr.sch.ira.minoas.model.core.Address;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Transactional;
/**
* @author <a href="mailto:[email protected]">Filippos Slavik</a>
* @version $Id$
*/
@Name("addressHome")
@Scope(ScopeType.CONVERSATION)
public class AddressHome extends MinoasEntityHome<Address> {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @see org.jboss.seam.framework.Home#createInstance()
*/
@Override
protected Address createInstance() {
Address instance = new Address();
return instance;
}
/**
* @see org.jboss.seam.framework.Home#getInstance()
*/
@Override
@Factory(value = "address", scope = ScopeType.PAGE)
public Address getInstance() {
// TODO Auto-generated method stub
return (Address) super.getInstance();
}
/**
* @see gr.sch.ira.minoas.seam.components.home.MinoasEntityHome#persist()
*/
@Override
@Transactional
public String persist() {
return super.persist();
}
@Transactional
public String revert() {
- info("principal #0 is reverting updates to adress #1", getPrincipalName(), getInstance());
+ info("principal #0 is reverting updates to address #1", getPrincipalName(), getInstance());
getEntityManager().refresh(getInstance());
return "reverted";
}
/**
* @see gr.sch.ira.minoas.seam.components.home.MinoasEntityHome#update()
*/
@Override
@Transactional
public String update() {
return super.update();
}
}
| true | true | public String revert() {
info("principal #0 is reverting updates to adress #1", getPrincipalName(), getInstance());
getEntityManager().refresh(getInstance());
return "reverted";
}
| public String revert() {
info("principal #0 is reverting updates to address #1", getPrincipalName(), getInstance());
getEntityManager().refresh(getInstance());
return "reverted";
}
|
diff --git a/molgenis-genotype-reader/src/test/java/org/molgenis/genotype/plink/writers/PedFileWriterTest.java b/molgenis-genotype-reader/src/test/java/org/molgenis/genotype/plink/writers/PedFileWriterTest.java
index 1273f3cc..c9deaaf2 100644
--- a/molgenis-genotype-reader/src/test/java/org/molgenis/genotype/plink/writers/PedFileWriterTest.java
+++ b/molgenis-genotype-reader/src/test/java/org/molgenis/genotype/plink/writers/PedFileWriterTest.java
@@ -1,92 +1,92 @@
package org.molgenis.genotype.plink.writers;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.molgenis.genotype.Alleles;
import org.molgenis.genotype.plink.datatypes.PedEntry;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PedFileWriterTest
{
@Test(expectedExceptions = IllegalArgumentException.class)
public void PedFileWriter() throws IOException
{
PedFileWriter fileWriter = null;
try
{
fileWriter = new PedFileWriter(null);
}
finally
{
if (fileWriter != null) fileWriter.close();
}
}
@Test
public void writePedEntry() throws IOException
{
File file0 = File.createTempFile("PedFileWriterTest_file0", null);
try
{
PedFileWriter fileWriter = null;
try
{
fileWriter = new PedFileWriter(file0);
fileWriter.write(new PedEntry("1", "1", "0", "0", (byte) 1, 1.0, Arrays.asList(
Alleles.createBasedOnChars('A', 'A'), Alleles.createBasedOnChars('G', 'T')).iterator()));
}
finally
{
IOUtils.closeQuietly(fileWriter);
}
String expected = "1 1 0 0 1 1 A A G T\n";
Assert.assertEquals(FileUtils.readFileToString(file0, Charset.forName("UTF-8")), expected);
}
finally
{
file0.delete();
}
}
@Test
public void writeIterablePedEntry() throws IOException
{
List<PedEntry> entryList = new ArrayList<PedEntry>();
entryList.add(new PedEntry("1", "1", "0", "0", (byte) 1, 1.0, Arrays.asList(
Alleles.createBasedOnChars('A', 'A'), Alleles.createBasedOnChars('G', 'T')).iterator()));
entryList.add(new PedEntry("2", "1", "0", "0", (byte) 1, 1.0, Arrays.asList(
Alleles.createBasedOnChars('A', 'C'), Alleles.createBasedOnChars('T', 'G')).iterator()));
File file0 = File.createTempFile("PedFileWriterTest_file0", null);
try
{
PedFileWriter fileWriter = null;
try
{
fileWriter = new PedFileWriter(file0);
fileWriter.write(entryList);
}
finally
{
IOUtils.closeQuietly(fileWriter);
}
- String expected = "1 1 0 0 1 1 A A G T\n2 1 0 0 1 1.0 A C T G\n";
+ String expected = "1 1 0 0 1 1 A A G T\n2 1 0 0 1 1 A C T G\n";
Assert.assertEquals(FileUtils.readFileToString(file0, Charset.forName("UTF-8")), expected);
}
finally
{
file0.delete();
}
}
}
| true | true | public void writeIterablePedEntry() throws IOException
{
List<PedEntry> entryList = new ArrayList<PedEntry>();
entryList.add(new PedEntry("1", "1", "0", "0", (byte) 1, 1.0, Arrays.asList(
Alleles.createBasedOnChars('A', 'A'), Alleles.createBasedOnChars('G', 'T')).iterator()));
entryList.add(new PedEntry("2", "1", "0", "0", (byte) 1, 1.0, Arrays.asList(
Alleles.createBasedOnChars('A', 'C'), Alleles.createBasedOnChars('T', 'G')).iterator()));
File file0 = File.createTempFile("PedFileWriterTest_file0", null);
try
{
PedFileWriter fileWriter = null;
try
{
fileWriter = new PedFileWriter(file0);
fileWriter.write(entryList);
}
finally
{
IOUtils.closeQuietly(fileWriter);
}
String expected = "1 1 0 0 1 1 A A G T\n2 1 0 0 1 1.0 A C T G\n";
Assert.assertEquals(FileUtils.readFileToString(file0, Charset.forName("UTF-8")), expected);
}
finally
{
file0.delete();
}
}
| public void writeIterablePedEntry() throws IOException
{
List<PedEntry> entryList = new ArrayList<PedEntry>();
entryList.add(new PedEntry("1", "1", "0", "0", (byte) 1, 1.0, Arrays.asList(
Alleles.createBasedOnChars('A', 'A'), Alleles.createBasedOnChars('G', 'T')).iterator()));
entryList.add(new PedEntry("2", "1", "0", "0", (byte) 1, 1.0, Arrays.asList(
Alleles.createBasedOnChars('A', 'C'), Alleles.createBasedOnChars('T', 'G')).iterator()));
File file0 = File.createTempFile("PedFileWriterTest_file0", null);
try
{
PedFileWriter fileWriter = null;
try
{
fileWriter = new PedFileWriter(file0);
fileWriter.write(entryList);
}
finally
{
IOUtils.closeQuietly(fileWriter);
}
String expected = "1 1 0 0 1 1 A A G T\n2 1 0 0 1 1 A C T G\n";
Assert.assertEquals(FileUtils.readFileToString(file0, Charset.forName("UTF-8")), expected);
}
finally
{
file0.delete();
}
}
|
diff --git a/src/common/com/vbitz/MinecraftScript/commands/MinecraftScriptHelpCommand.java b/src/common/com/vbitz/MinecraftScript/commands/MinecraftScriptHelpCommand.java
index e1d9ace..501698c 100644
--- a/src/common/com/vbitz/MinecraftScript/commands/MinecraftScriptHelpCommand.java
+++ b/src/common/com/vbitz/MinecraftScript/commands/MinecraftScriptHelpCommand.java
@@ -1,110 +1,110 @@
package com.vbitz.MinecraftScript.commands;
import java.util.ArrayList;
import java.util.HashMap;
import net.minecraft.src.CommandBase;
import net.minecraft.src.ICommandSender;
public class MinecraftScriptHelpCommand extends CommandBase {
private static ArrayList<HelpDoc> _helpDocs = new ArrayList<HelpDoc>();
private static void addHelp(String api, String name, String args, String description) {
MinecraftScriptHelpCommand c = new MinecraftScriptHelpCommand();
_helpDocs.add(c.new HelpDoc(api, name, args, description));
}
public class HelpDoc {
public String api;
public String name;
public String args;
public String description;
public HelpDoc(String api, String name, String args, String description) {
this.api = api;
this.name = name;
this.args = args;
this.description = description;
}
}
static {
addHelp("topics", "api", "", "General API functions. These can be called before Minecraft has started");
addHelp("topics", "playerapi", "", "Methods working on the set player");
addHelp("topics", "worldapi", "", "Methods for modifying the world");
addHelp("topics", "effectnames1", "", "A list of effect names");
addHelp("topics", "effectnames2", "", "A list of the effect names not covered in the first list");
addHelp("api", "getScriptedBlock", "int id", "Returns a Scripted block with the ID id");
addHelp("api", "log", "Object obj", "Prints obj to Console");
addHelp("api", "sendChat", "string chat", "Sends chat to the current player as a chat message");
addHelp("api", "getItemId", "string itemName", "Returns the ID of the item");
addHelp("api", "getPlayer", "string nickname", "Returns a PlayerAPI for nickname");
addHelp("api", "getWorld", "", "Returns the Current World");
addHelp("playerapi", "getHealth", "", "Returns the health of the player");
addHelp("playerapi", "give", "int itemID, int count", "Gives count of Item ID id to the player");
addHelp("playerapi", "getLocX", "", "Returns the X part of the player's current location");
addHelp("playerapi", "getLocY", "", "Returns the Y part of the player's current location");
addHelp("playerapi", "getLocZ", "", "Returns the Z part of the player's current location");
addHelp("playerapi", "tp", "double x, double y, double z", "Teleports the player to x, y, z");
addHelp("playerapi", "addEffect", "string effectName, int level, int time", "Gives the player effectName at level for time ticks");
addHelp("playerapi", "fly", "boolean fly", "Set's the ability for the player to fly and causes them to start flying");
addHelp("playerapi", "setOnFire", "boolean onFire", "Set's the player alight or extinguishes them");
addHelp("worldapi", "explode", "int amo, int x, int y, int z", "Explodes the point at x, y, z with a force of amo");
addHelp("worldapi", "setBlock", "int blockType, int x, int y, int z", "Set's the point at x, y, z to blockType");
addHelp("worldapi", "time", "long value", "Set's the time in all worlds to value");
addHelp("effectnames1", "moveSpeed", "", "Increase the player's move speed");
addHelp("effectnames1", "moveSlowdown", "", "Decreases the player's move speed");
addHelp("effectnames1", "digSpeed", "", "Increase the player's mining speed");
addHelp("effectnames1", "digSlowdown", "", "Decreases the player's mining speed");
addHelp("effectnames1", "damageBoost", "", "Boosts the amount of damage the player does");
addHelp("effectnames1", "heal", "", "Instantly heals the player");
addHelp("effectnames1", "harm", "", "Instantly harms the player");
addHelp("effectnames1", "jump", "", "Boosts the player's jumping height");
addHelp("effectnames1", "confusion", "", "Nausea?");
addHelp("effectnames1", "regeneration", "", "Regenerates the player's health over time");
addHelp("effectnames2", "resistance", "", "Decreases the amount of damage done to the player");
addHelp("effectnames2", "fireResist", "", "Decreases the amount of damage done by fire to the player");
addHelp("effectnames2", "waterBreathing", "", "Allows the player to stay underwater without oxygen draining");
addHelp("effectnames2", "invisibility", "", "Makes the player invisible");
addHelp("effectnames2", "blindness", "", "Darkens the player's vision and shortens there draw distance");
addHelp("effectnames2", "nightVision", "", "All blocks are visually at a light level of 16");
addHelp("effectnames2", "hunger", "", "The player's hunger bar will drain much faster");
addHelp("effectnames2", "weakness", "", "Decreases the amount of damage done by the player");
addHelp("effectnames2", "poison", "", "The player will take damage over time, this will not kill them");
}
@Override
public String getCommandName() {
return "mcshelp";
}
@Override
public String getCommandUsage(ICommandSender var1) {
return "/" + this.getCommandName() + " [api] - Leave api empty to list all apis";
}
@Override
public void processCommand(ICommandSender var1, String[] var2) {
if (var2.length == 0) {
- var1.sendChatToPlayer("�cMinecraftScript Help Topics");
+ var1.sendChatToPlayer("\u00A7cMinecraftScript Help Topics");
for (HelpDoc doc : _helpDocs) {
if (doc.api.equals("topics")) {
- var1.sendChatToPlayer("�f" + doc.name + " : �7" + doc.description);
+ var1.sendChatToPlayer("\u00A7f" + doc.name + " : \u00A77" + doc.description);
}
}
} else {
- var1.sendChatToPlayer("�cMinecraftScript Help Topics for " + var2[0]);
+ var1.sendChatToPlayer("\u00A7cMinecraftScript Help Topics for " + var2[0]);
for (HelpDoc doc : _helpDocs) {
if (doc.api.equals(var2[0])) {
- var1.sendChatToPlayer(" - �e" + doc.api + "�f : " + doc.name + " (" + doc.args + ") : �7" + doc.description);
+ var1.sendChatToPlayer(" - \u00A7e" + doc.api + "\u00A7f : " + doc.name + " (" + doc.args + ") : \u00A77" + doc.description);
}
}
}
}
}
| false | true | public void processCommand(ICommandSender var1, String[] var2) {
if (var2.length == 0) {
var1.sendChatToPlayer("�cMinecraftScript Help Topics");
for (HelpDoc doc : _helpDocs) {
if (doc.api.equals("topics")) {
var1.sendChatToPlayer("�f" + doc.name + " : �7" + doc.description);
}
}
} else {
var1.sendChatToPlayer("�cMinecraftScript Help Topics for " + var2[0]);
for (HelpDoc doc : _helpDocs) {
if (doc.api.equals(var2[0])) {
var1.sendChatToPlayer(" - �e" + doc.api + "�f : " + doc.name + " (" + doc.args + ") : �7" + doc.description);
}
}
}
}
| public void processCommand(ICommandSender var1, String[] var2) {
if (var2.length == 0) {
var1.sendChatToPlayer("\u00A7cMinecraftScript Help Topics");
for (HelpDoc doc : _helpDocs) {
if (doc.api.equals("topics")) {
var1.sendChatToPlayer("\u00A7f" + doc.name + " : \u00A77" + doc.description);
}
}
} else {
var1.sendChatToPlayer("\u00A7cMinecraftScript Help Topics for " + var2[0]);
for (HelpDoc doc : _helpDocs) {
if (doc.api.equals(var2[0])) {
var1.sendChatToPlayer(" - \u00A7e" + doc.api + "\u00A7f : " + doc.name + " (" + doc.args + ") : \u00A77" + doc.description);
}
}
}
}
|
diff --git a/Maniana/src/com/zapta/apps/maniana/model/AppModel.java b/Maniana/src/com/zapta/apps/maniana/model/AppModel.java
index 445f44d..c6b797c 100755
--- a/Maniana/src/com/zapta/apps/maniana/model/AppModel.java
+++ b/Maniana/src/com/zapta/apps/maniana/model/AppModel.java
@@ -1,261 +1,261 @@
/*
* Copyright (C) 2011 The original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.zapta.apps.maniana.model;
import java.util.ListIterator;
import com.zapta.apps.maniana.util.LogUtil;
/**
* Contains the app data. Persisted across app activations. Controlled by the app controller.
* Observed by the viewer via the ItemListViewAdapter.
*
* @author Tal Dayan
*/
public class AppModel {
/** Selected to not match any valid timestamp. */
private static final String DEFAULT_DATE_STAMP = "";
/** Model of Today page. */
private final PageModel mTodayPageModel;
/** Model of Tomorrow page. */
private final PageModel mTomorrowPageMode;
/** True if current state is not persisted */
private boolean mIsDirty = true;
/**
* Last date in which items were pushed from Tomorrow to Today pages. Used to determine when
* next push should be done. Using an empty string to indicate no datestamp.
*
* NOTE(tal): for now the format of this timestamp is opaque though it must be consistent.
*/
private String mLastPushDateStamp;
public AppModel() {
this.mTodayPageModel = new PageModel(PageKind.TODAY);
this.mTomorrowPageMode = new PageModel(PageKind.TOMOROW);
this.mLastPushDateStamp = DEFAULT_DATE_STAMP;
}
public final boolean isDirty() {
return mIsDirty;
}
public final void setDirty() {
if (!mIsDirty) {
LogUtil.info("Model became dirty");
mIsDirty = true;
}
}
public final void setClean() {
if (mIsDirty) {
LogUtil.info("Model became clean");
mIsDirty = false;
}
}
/** Get the model of given page. */
private final PageModel getPageModel(PageKind pageKind) {
switch (pageKind) {
case TODAY:
return mTodayPageModel;
case TOMOROW:
return mTomorrowPageMode;
default:
throw new RuntimeException("Unknown page kind: " + pageKind);
}
}
/** Get read only aspect of the item of given index in given page. */
public final ItemModelReadOnly getItemReadOnly(PageKind pageKind, int itemIndex) {
return getPageModel(pageKind).getItem(itemIndex);
}
/** Get a mutable item of given page and index. */
// TODO: replace with a setItem(,,,) method. Safer this way.
public final ItemModel getItemForMutation(PageKind pageKind, int itemIndex) {
setDirty();
return getPageModel(pageKind).getItem(itemIndex);
}
/** Get number of items in given page. */
public final int getPageItemCount(PageKind pageKind) {
return getPageModel(pageKind).itemCount();
}
/** Get total number of items. */
public final int getItemCount() {
return mTodayPageModel.itemCount() + mTomorrowPageMode.itemCount();
}
/** Clear the model. */
public final void clear() {
mTodayPageModel.clear();
mTomorrowPageMode.clear();
mLastPushDateStamp = DEFAULT_DATE_STAMP;
setDirty();
}
/** Clear undo buffers of both pages. */
public final void clearAllUndo() {
mTodayPageModel.clearUndo();
mTomorrowPageMode.clearUndo();
// NOTE(tal): does not affect dirty flag.
}
/** Clear undo buffer of given page. */
public final void clearPageUndo(PageKind pageKind) {
getPageModel(pageKind).clearUndo();
// NOTE(tal): does not affect dirty flag.
}
/** Test if given page has an active undo buffer. */
public final boolean pageHasUndo(PageKind pageKind) {
return getPageModel(pageKind).hasUndo();
}
/** Test if the page items are already sorted. */
public final boolean isPageSorted(PageKind pageKind) {
return getPageModel(pageKind).isPageSorted();
}
/** Insert item to given page at given item index. */
public final void insertItem(PageKind pageKind, int itemIndex, ItemModel item) {
setDirty();
getPageModel(pageKind).insertItem(itemIndex, item);
}
/** Add an item to the end of given page. */
public void appendItem(PageKind pageKind, ItemModel item) {
getPageModel(pageKind).appendItem(item);
setDirty();
}
/** Remove item of given index from given page. */
public final ItemModel removeItem(PageKind pageKind, int itemIndex) {
setDirty();
ItemModel result = getPageModel(pageKind).removeItem(itemIndex);
return result;
}
/** Remove item of given idnex from given page and set a corresponding undo at that page. */
public final void removeItemWithUndo(PageKind pageKind, int itemIndex) {
setDirty();
getPageModel(pageKind).removeItemWithUndo(itemIndex);
}
/**
* Organize the given page with undo. See details at
* {@link PageModel#organizePageWithUndo(boolean, PageOrganizeResult)()}.
*/
public final void organizePageWithUndo(PageKind pageKind, boolean deleteCompletedItems,
int itemOfInteresetIndex, OrganizePageSummary summary) {
getPageModel(pageKind).organizePageWithUndo(deleteCompletedItems, itemOfInteresetIndex,
summary);
if (summary.pageChanged()) {
setDirty();
}
}
/**
* Apply active undo operation of given page. The method asserts that the page has an active
* undo.
*
* @return the number of items resotred by the undo operation.
*/
public final int applyUndo(PageKind pageKind) {
final int result = getPageModel(pageKind).performUndo();
setDirty();
return result;
}
/**
* Move non locked items from Tomorow to Today. It's the caller responsibility to also set the
* last push datestamp. This method clears any previous undo buffer content of both pages.
*
* @param expireAllLocks
* if true, locked items are also pushed, after changing their status to unlocked.
*
* @param deleteCompletedItems
* if true, delete completed items, leaving them in the undo buffers of their
* respective pages.
*/
public final void pushToToday(boolean expireAllLocks, boolean deleteCompletedItems) {
clearAllUndo();
setDirty();
// Process Tomorrow items
{
int itemsMoved = 0;
final ListIterator<ItemModel> iterator = mTomorrowPageMode.listIterator();
while (iterator.hasNext()) {
final ItemModel item = iterator.next();
// Expire lock if needed
if (expireAllLocks && item.isLocked()) {
item.setIsLocked(false);
}
// If item is completed (even if blocked), move to undo buffer.
if (item.isCompleted()) {
iterator.remove();
mTomorrowPageMode.appendItemToUndo(item);
continue;
}
// If item is not unlocked, move Today page.
if (!item.isLocked()) {
// We move the items to the beginning of Today page, preserving there
// relative order from Tomorrow page.
iterator.remove();
mTodayPageModel.insertItem(itemsMoved, item);
itemsMoved++;
continue;
}
// Otherwise leave item in place.
}
}
// If need to delete completed items, scan also Today list and move
// completed items to the Today's undo buffer.
if (deleteCompletedItems) {
- final ListIterator<ItemModel> iterator = mTomorrowPageMode.listIterator();
+ final ListIterator<ItemModel> iterator = mTodayPageModel.listIterator();
while (iterator.hasNext()) {
final ItemModel item = iterator.next();
if (item.isCompleted()) {
iterator.remove();
mTodayPageModel.appendItemToUndo(item);
}
}
}
}
/** Get the datestamp of last item push. */
public final String getLastPushDateStamp() {
return mLastPushDateStamp;
}
/** Set the last item push datestamp. */
public final void setLastPushDateStamp(String lastPushDateStamp) {
// TODO: no need to set the dirty bit, right?
this.mLastPushDateStamp = lastPushDateStamp;
}
}
| true | true | public final void pushToToday(boolean expireAllLocks, boolean deleteCompletedItems) {
clearAllUndo();
setDirty();
// Process Tomorrow items
{
int itemsMoved = 0;
final ListIterator<ItemModel> iterator = mTomorrowPageMode.listIterator();
while (iterator.hasNext()) {
final ItemModel item = iterator.next();
// Expire lock if needed
if (expireAllLocks && item.isLocked()) {
item.setIsLocked(false);
}
// If item is completed (even if blocked), move to undo buffer.
if (item.isCompleted()) {
iterator.remove();
mTomorrowPageMode.appendItemToUndo(item);
continue;
}
// If item is not unlocked, move Today page.
if (!item.isLocked()) {
// We move the items to the beginning of Today page, preserving there
// relative order from Tomorrow page.
iterator.remove();
mTodayPageModel.insertItem(itemsMoved, item);
itemsMoved++;
continue;
}
// Otherwise leave item in place.
}
}
// If need to delete completed items, scan also Today list and move
// completed items to the Today's undo buffer.
if (deleteCompletedItems) {
final ListIterator<ItemModel> iterator = mTomorrowPageMode.listIterator();
while (iterator.hasNext()) {
final ItemModel item = iterator.next();
if (item.isCompleted()) {
iterator.remove();
mTodayPageModel.appendItemToUndo(item);
}
}
}
}
| public final void pushToToday(boolean expireAllLocks, boolean deleteCompletedItems) {
clearAllUndo();
setDirty();
// Process Tomorrow items
{
int itemsMoved = 0;
final ListIterator<ItemModel> iterator = mTomorrowPageMode.listIterator();
while (iterator.hasNext()) {
final ItemModel item = iterator.next();
// Expire lock if needed
if (expireAllLocks && item.isLocked()) {
item.setIsLocked(false);
}
// If item is completed (even if blocked), move to undo buffer.
if (item.isCompleted()) {
iterator.remove();
mTomorrowPageMode.appendItemToUndo(item);
continue;
}
// If item is not unlocked, move Today page.
if (!item.isLocked()) {
// We move the items to the beginning of Today page, preserving there
// relative order from Tomorrow page.
iterator.remove();
mTodayPageModel.insertItem(itemsMoved, item);
itemsMoved++;
continue;
}
// Otherwise leave item in place.
}
}
// If need to delete completed items, scan also Today list and move
// completed items to the Today's undo buffer.
if (deleteCompletedItems) {
final ListIterator<ItemModel> iterator = mTodayPageModel.listIterator();
while (iterator.hasNext()) {
final ItemModel item = iterator.next();
if (item.isCompleted()) {
iterator.remove();
mTodayPageModel.appendItemToUndo(item);
}
}
}
}
|
diff --git a/src/net/colar/netbeans/fan/types/FanResolvedType.java b/src/net/colar/netbeans/fan/types/FanResolvedType.java
index d9ffd6c..8b783a0 100644
--- a/src/net/colar/netbeans/fan/types/FanResolvedType.java
+++ b/src/net/colar/netbeans/fan/types/FanResolvedType.java
@@ -1,651 +1,651 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.colar.netbeans.fan.types;
import java.lang.reflect.Member;
import java.util.List;
import java.util.Vector;
import net.colar.netbeans.fan.FanParserResult;
import net.colar.netbeans.fan.FanUtilities;
import net.colar.netbeans.fan.antlr.FanParser;
import net.colar.netbeans.fan.ast.FanAstScope;
import net.colar.netbeans.fan.ast.FanLexAstUtils;
import net.colar.netbeans.fan.ast.FanRootScope;
import net.colar.netbeans.fan.ast.FanTypeScope;
import net.colar.netbeans.fan.indexer.FanIndexer;
import net.colar.netbeans.fan.indexer.FanIndexerFactory;
import net.colar.netbeans.fan.indexer.model.FanSlot;
import net.colar.netbeans.fan.indexer.model.FanType;
import org.antlr.runtime.tree.CommonTree;
/**
* Resolved type
* Store infos of a resolved type
* Also contains the factory methods / logic to resolve a type expr.
* @author tcolar
*/
public class FanResolvedType
{
private final String asTypedType;
private final FanType dbType;
// whether it's used in a nullable context : ex: Str? vs Str
private boolean nullableContext = false;
// whether it's used in a static context: ex Str. vs str.
private boolean staticContext = false;
private final String shortAsTypedType;
public FanResolvedType(String enteredType)
{
this.asTypedType = enteredType;
shortAsTypedType = asTypedType.indexOf("::") != -1 ? asTypedType.substring(asTypedType.indexOf("::") + 2) : asTypedType;
if (enteredType != null && !enteredType.equals(FanIndexer.UNRESOLVED_TYPE))
{
dbType = FanType.findByQualifiedName(enteredType);
} else
{
dbType = null;
}
}
public boolean isResolved()
{
return dbType != null;
}
public FanType getDbType()
{
return dbType;
}
public String getAsTypedType()
{
return asTypedType;
}
public String getShortAsTypedType()
{
return shortAsTypedType;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder(asTypedType).append(" resolved:").append(isResolved());
return sb.toString();
}
public static FanResolvedType makeUnresolved()
{
return new FanResolvedType(FanIndexer.UNRESOLVED_TYPE);
}
public static FanResolvedType makeFromTypeSigWithWarning(FanAstScope scope, CommonTree node)
{
FanResolvedType result = makeFromTypeSig(scope, node);
if (!result.isResolved())
{
String type = FanLexAstUtils.getNodeContent(scope.getRoot().getParserResult(), node);
//TODO: Propose to auto-add using statements (Hints)
scope.getRoot().addError("Unresolved type: " + type, node);
FanUtilities.GENERIC_LOGGER.info("Could not resolve type: "+(node==null?"null":node.toStringTree()));
}
return result;
}
/**
* Resolve a type (type signature)
* Recursive
* @param scope
* @param node
* @return
*/
public static FanResolvedType makeFromTypeSig(FanAstScope scope, CommonTree node)
{
return makeFromTypeSig(scope, node, FanResolvedType.makeUnresolved());
}
private static FanResolvedType makeFromTypeSig(FanAstScope scope, CommonTree node, FanResolvedType baseType)
{
if (node == null)
{
return baseType;
}
FanRootScope root = scope.getRoot();
//System.out.println("Node Type: " + node.toStringTree());
switch (node.getType())
{
// type is just a wrapper node
case FanParser.AST_TYPE:
case FanParser.AST_CHILD:
for (CommonTree n : (List<CommonTree>) node.getChildren())
{
baseType = makeFromTypeSig(scope, n, baseType);
}
break;
case FanParser.AST_ID:
String typeText = FanLexAstUtils.getNodeContent(scope.getRoot().getParserResult(), node);
baseType = root.lookupUsing(typeText);
break;
case FanParser.SP_QMARK:
baseType.setNullableContext(true);
case FanParser.LIST_TYPE:
baseType = new FanResolvedListType(baseType);
break;
case FanParser.AST_MAP:
if (node.getChildCount() >= 2)
{
CommonTree keyNode = (CommonTree) node.getChild(0);
CommonTree valueNode = (CommonTree) node.getChild(1);
FanResolvedType keyType = makeFromTypeSig(scope, keyNode);
FanResolvedType valueType = makeFromTypeSig(scope, valueNode);
if (keyType.isResolved() && valueType.isResolved())
{
baseType = new FanResolvedMapType(keyType, valueType);
}
}
break;
case FanParser.AST_FUNC_TYPE:
FanResolvedType returnType = null;
Vector<FanResolvedType> types = new Vector<FanResolvedType>();
boolean passedArrow = false;
for (CommonTree n : (List<CommonTree>) node.getChildren())
{
switch (n.getType())
{
case FanParser.OP_ARROW:
passedArrow = true;
break;
case FanParser.AST_TYPE:
if (!passedArrow)
{
types.add(makeFromTypeSig(scope, n));
} else
{
returnType = makeFromTypeSig(scope, n);
}
}
}
baseType = new FanResolvedFuncType(types, returnType);
break;
default:
FanUtilities.GENERIC_LOGGER.info("Unexpected item during type parsing" + node.toStringTree());
baseType = makeUnresolved();
break;
}
return baseType;
}
public static FanResolvedType makeFromExpr(FanAstScope sc, FanParserResult result, CommonTree exprNode, int lastGoodTokenIndex)
{
FanAstScope scope = sc.getRoot().findClosestScope(exprNode);
FanUtilities.GENERIC_LOGGER.debug("** scope: " + scope);
FanResolvedType type = resolveExpr(scope, null, exprNode, lastGoodTokenIndex);
if (type == null)
{
type = makeUnresolved();
}
FanUtilities.GENERIC_LOGGER.debug("** resolvedType: " + type);
return type;
}
/**
* recursive
* @param result
* @param scope
* @param baseType
* @param node
* @param index
* @return
*/
private static FanResolvedType resolveExpr(FanAstScope scope,
FanResolvedType baseType, CommonTree node, int index)
{
//FanUtilities.GENERIC_LOGGER.info("** type: " + node.toStringTree() + " " + baseType);
FanParserResult result = scope.getRoot().getParserResult();
// if unresolveable no point searching further
if (baseType != null && !baseType.isResolved())
{
return baseType;
}
//System.out.println("Node type: " + node.getType());
String t = FanLexAstUtils.getNodeContent(result, node);
if (node == null || t == null)
{
FanUtilities.GENERIC_LOGGER.info("Node is empty! " + node.getParent().toStringTree());
return makeUnresolved();
}
//System.out.println("Index: " + FanLexAstUtils.getTokenStart(node) + " VS " + index);
// Skip the imcomplete part past what we care about
if (!isValidTokenStart(node, index))
{
return baseType;
}
List<CommonTree> children = node.getChildren();
switch (node.getType())
{
//TODO: ranges (tricky)
case FanParser.AST_CAST:
CommonTree castType = (CommonTree) node.getFirstChildWithType(FanParser.AST_TYPE);
baseType = makeFromTypeSigWithWarning(scope, castType);
baseType.setStaticContext(false);
break;
case FanParser.AST_TERM_EXPR:
CommonTree termBase = children.get(0);
baseType = resolveExpr(scope, null, termBase, index);
CommonTree termChain = children.get(1);
baseType = resolveExpr(scope, baseType, termChain, index);
break;
case FanParser.AST_STATIC_CALL:
CommonTree type = children.get(0);
CommonTree idExpr = children.get(1);
baseType = resolveExpr(scope, null, type, index);
baseType = resolveExpr(scope, baseType, idExpr, index);
break;
case FanParser.AST_STR:
baseType = new FanResolvedType("sys::Str");
break;
case FanParser.KW_TRUE:
case FanParser.KW_FALSE:
baseType = new FanResolvedType("sys::Bool");
break;
case FanParser.CHAR:
baseType = new FanResolvedType("sys::Int");
break;
case FanParser.NUMBER:
String ftype = parseNumberType(node.getText());
baseType = new FanResolvedType(ftype);
break;
case FanParser.URI:
baseType = new FanResolvedType("sys::Uri");
break;
case FanParser.AST_NAMED_SUPER:
CommonTree nameNode = (CommonTree) node.getFirstChildWithType(FanParser.AST_ID);
baseType = resolveExpr(scope, baseType, nameNode, index);
baseType.setStaticContext(false);
break;
case FanParser.KW_SUPER:
baseType = new FanResolvedType(resolveSuper(scope));
baseType.setStaticContext(false);
break;
case FanParser.KW_THIS:
baseType = new FanResolvedType(resolveThisType(scope));
break;
case FanParser.AST_IT_BLOCK:
// Do nothing, keep type of left hand side.
baseType.setStaticContext(false);
break;
case FanParser.AST_CTOR_BLOCK:
CommonTree ctorNode = (CommonTree) node.getFirstChildWithType(FanParser.AST_TYPE);
baseType = resolveExpr(scope, baseType, ctorNode, index);
baseType.setStaticContext(false);
break;
case FanParser.AST_INDEX_EXPR:
baseType = resolveIndexExpr(scope, baseType, node, index);
break;
case FanParser.AST_LIST:
CommonTree firstNode = (CommonTree) children.get(0);
// Because of a grammar issue, some indexed expression show up as List
boolean isResolveExpr = false;
if (firstNode != null && firstNode.getType() == FanParser.AST_TYPE)
{
FanResolvedType lType = resolveExpr(scope, baseType, firstNode, index);
if (lType != null && !lType.isStaticContext())
{
isResolveExpr = true;
baseType = resolveIndexExpr(scope, lType, node, index);
}
}
if (!isResolveExpr)
{//Normal list type like Str[]
baseType = new FanResolvedType("sys::List");
CommonTree listTypeNode = (CommonTree) node.getFirstChildWithType(FanParser.AST_TERM_EXPR);
if (listTypeNode != null)
{
FanResolvedType listType = resolveExpr(scope, null, listTypeNode, index);
baseType = new FanResolvedListType(listType);
}
}
break;
case FanParser.AST_MAP:
baseType = new FanResolvedType("sys::Map");
List<CommonTree> mapElems = FanLexAstUtils.getAllChildrenWithType(node, FanParser.AST_TERM_EXPR);
if (mapElems.size() >= 2)
{
CommonTree keyNode = mapElems.get(0);
CommonTree valueNode = mapElems.get(1);
FanResolvedType keyType = resolveExpr(scope, null, keyNode, index);
FanResolvedType valueType = resolveExpr(scope, null, valueNode, index);
if (keyType.isResolved() && valueType.isResolved())
{
baseType = new FanResolvedMapType(keyType, valueType);
}
}
break;
case FanParser.AST_TYPE_LIT: // type litteral
- System.out.println("Lit: "+node.toStringTree());
+ //System.out.println("Lit: "+node.toStringTree());
CommonTree litNode=(CommonTree) node.getFirstChildWithType(FanParser.AST_TYPE);
baseType = makeFromExpr(scope, result, litNode, index);
baseType.setStaticContext(true);
break;
case FanParser.AST_FUNC_TYPE:
FanResolvedType returnType = null;
Vector<FanResolvedType> types = new Vector<FanResolvedType>();
boolean passedArrow = false;
for (CommonTree n : (List<CommonTree>) node.getChildren())
{
switch (n.getType())
{
case FanParser.OP_ARROW:
passedArrow = true;
break;
case FanParser.AST_TYPE:
if (!passedArrow)
{
types.add(makeFromTypeSig(scope, n));
} else
{
returnType = makeFromTypeSig(scope, n);
}
}
}
baseType = new FanResolvedFuncType(types, returnType);
baseType.setStaticContext(false);
break;
case FanParser.AST_SLOT_LIT:
baseType = new FanResolvedType("sys::Slot");
break;
case FanParser.AST_SYMBOL:
// TODO: is this correct - not sure
baseType = new FanResolvedType("sys::Symbol");
break;
case FanParser.AST_ID:
case FanParser.KW_IT:
if (baseType == null)
{
baseType = scope.resolveVar(t);
if (!baseType.isResolved())
{
// Try a static type (ex: Str.)
baseType = makeFromTypeSigWithWarning(scope, node);
baseType.setStaticContext(true);
}
} else
{
baseType = resolveSlotType(baseType, t);
}
break;
default:
// "Meaningless" 'wrapper' nodes (in term of expression resolving)
if (children != null && children.size() > 0)
{
for (CommonTree child : children)
{
baseType = resolveExpr(scope, baseType, child, index);
break; //TODO: to break or not ??
}
} else
{
FanUtilities.GENERIC_LOGGER.info("Don't know how to resolve: " + t + " " + node.toStringTree());
}
break;
}
//System.out.println("** End type: " + baseType + " "+baseType.isStaticContext());
return baseType;
}
public static FanResolvedType resolveSlotType(FanResolvedType baseType, String slotName)
{
if (baseType.getDbType().isJava())
{
// java slots
List<Member> members = FanIndexerFactory.getJavaIndexer().findTypeSlots(baseType.getAsTypedType());
boolean found = false;
// Returrning the first match .. because java has overloading this could be wrong
// However i assume overloaded methods return the same type (If it doesn't too bad, it's ugly coe anyway :) )
for (Member member : members)
{
if (member.getName().equalsIgnoreCase(slotName))
{
baseType = new FanResolvedType(FanIndexerFactory.getJavaIndexer().getReturnType(member));
found = true;
break;
}
}
if (!found)
{
baseType = makeUnresolved();
}
} else
{
// Fan slots
FanSlot slot = FanSlot.findByTypeAndName(baseType.getAsTypedType(), slotName);
if (slot != null)
{
baseType = fromDbSig(slot.returnedType);
} else
{
baseType = makeUnresolved();
}
}
return baseType;
}
private static FanResolvedType resolveIndexExpr(FanAstScope scope, FanResolvedType baseType, CommonTree node, int index)
{
//FanUtilities.GENERIC_LOGGER.info("Index expr: " + node.toStringTree());
if (baseType instanceof FanResolvedListType)
{
baseType = ((FanResolvedListType) baseType).getItemType();
} else if (baseType instanceof FanResolvedMapType)
{
baseType = ((FanResolvedMapType) baseType).getValType();
} else
{
baseType = resolveSlotType(baseType, "get");
}
return baseType;
}
private static boolean isValidTokenStart(CommonTree node, int maxIndex)
{
int index = FanLexAstUtils.getTokenStart(node);
// will be -1 for a Nill node
return index >= 0 && index <= maxIndex;
}
public boolean isStaticContext()
{
return staticContext;
}
public void setNullableContext(boolean nullable)
{
nullableContext = nullable;
}
public boolean isNullable()
{
return nullableContext;
}
public void setStaticContext(boolean b)
{
staticContext = b;
}
/**
* Parse number litterals
* http://fantom.org/doc/docLang/Literals.html#int
* @param text
* @return
*/
private static String parseNumberType(String text)
{
text = text.toLowerCase();
if (text.endsWith("ns") || text.endsWith("ms")
|| text.endsWith("sec") || text.endsWith("min")
|| text.endsWith("hr") || text.endsWith("day"))
{
return "sys::Duration";
}
if (text.startsWith("0x")) // hex
{
return "sys::Int"; // char
}
if (text.endsWith("f"))
{
return "sys::Float";
}
if (text.endsWith("d") || text.indexOf(".") != -1)
{
return "sys::Decimal";
}
return "sys::Int";
}
public static String resolveThisType(FanAstScope scope)
{
FanAstScope tscope = scope.getTypeScope();
if (tscope == null)
{
return FanIndexer.UNRESOLVED_TYPE;
}
return ((FanTypeScope) tscope).getQName();
}
public static String resolveSuper(FanAstScope scope)
{
FanAstScope tscope = scope;
while (tscope != null && !(tscope instanceof FanTypeScope))
{
tscope = tscope.getParent();
}
if (tscope != null)
{
FanResolvedType superType = ((FanTypeScope) tscope).getSuperClass();
return superType.getAsTypedType();
} else
{
return FanIndexer.UNRESOLVED_TYPE;
}
}
/**
* "Serialize" the type into a db signature
* @param fullyQualified
* @return
*/
public String toDbSig(boolean fullyQualified)
{
if (isResolved())
{
if (fullyQualified)
{
return dbType.getQualifiedName();
} else
{
return dbType.getSimpleName();
}
}
if (fullyQualified)
{
return getAsTypedType();
} else
{
return getShortAsTypedType();
}
}
/**
* Create type from the "Serialized" dbType
* @param sig
* @return
*/
public static FanResolvedType fromDbSig(String sig)
{
FanResolvedType type = makeUnresolved();
boolean nullable = false;
boolean list = false;
boolean nullableList = false;
if (sig.endsWith("?"))
{
sig = sig.substring(0, sig.length() - 1);
nullable = true;
}
if (sig.endsWith("[]"))
{
sig = sig.substring(0, sig.length() - 1);
list = true;
if (sig.endsWith("?"))
{
sig = sig.substring(0, sig.length() - 1);
nullableList = true;
}
}
if (sig.startsWith("[") && sig.endsWith("]"))
{// map
sig = sig.substring(1, sig.length() - 1);
int index = 0;
while (index != -1 && index < sig.length())
{
index = sig.indexOf(":", index);
if (index == -1)
{
break; // not found
} // looking for ":" but NOT "::"
if (index > 1 && index < sig.length() - 1 && sig.charAt(index - 1) != ':' && sig.charAt(index + 1) != ':')
{
break; // found
}
// try next one
index++;
}
if (index != -1 && index < sig.length() - 1)
{
FanResolvedType keyType = fromDbSig(sig.substring(0, index).trim());
FanResolvedType valType = fromDbSig(sig.substring(index + 1).trim());
type = new FanResolvedMapType(keyType, valType);
}
} else if (sig.startsWith("|") && sig.endsWith("|"))
{
Vector<FanResolvedType> types = new Vector<FanResolvedType>();
sig = sig.substring(1, sig.length() - 1);
String[] parts = sig.split("->");
if (parts.length == 2)
{
String[] typeParts = parts[0].split(",");
for (int i = 0; i != typeParts.length; i++)
{
types.add(fromDbSig(typeParts[i].trim()));
}
String returnType = parts[1].trim();
type = new FanResolvedFuncType(types, fromDbSig(returnType));
}
} else
{// simple type
type = new FanResolvedType(sig);
}
if (nullable)
{
type.setNullableContext(true);
}
if (list)
{
type = new FanResolvedListType(type);
if (nullableList)
{
type.setNullableContext(true);
}
}
return type;
}
}
| true | true | private static FanResolvedType resolveExpr(FanAstScope scope,
FanResolvedType baseType, CommonTree node, int index)
{
//FanUtilities.GENERIC_LOGGER.info("** type: " + node.toStringTree() + " " + baseType);
FanParserResult result = scope.getRoot().getParserResult();
// if unresolveable no point searching further
if (baseType != null && !baseType.isResolved())
{
return baseType;
}
//System.out.println("Node type: " + node.getType());
String t = FanLexAstUtils.getNodeContent(result, node);
if (node == null || t == null)
{
FanUtilities.GENERIC_LOGGER.info("Node is empty! " + node.getParent().toStringTree());
return makeUnresolved();
}
//System.out.println("Index: " + FanLexAstUtils.getTokenStart(node) + " VS " + index);
// Skip the imcomplete part past what we care about
if (!isValidTokenStart(node, index))
{
return baseType;
}
List<CommonTree> children = node.getChildren();
switch (node.getType())
{
//TODO: ranges (tricky)
case FanParser.AST_CAST:
CommonTree castType = (CommonTree) node.getFirstChildWithType(FanParser.AST_TYPE);
baseType = makeFromTypeSigWithWarning(scope, castType);
baseType.setStaticContext(false);
break;
case FanParser.AST_TERM_EXPR:
CommonTree termBase = children.get(0);
baseType = resolveExpr(scope, null, termBase, index);
CommonTree termChain = children.get(1);
baseType = resolveExpr(scope, baseType, termChain, index);
break;
case FanParser.AST_STATIC_CALL:
CommonTree type = children.get(0);
CommonTree idExpr = children.get(1);
baseType = resolveExpr(scope, null, type, index);
baseType = resolveExpr(scope, baseType, idExpr, index);
break;
case FanParser.AST_STR:
baseType = new FanResolvedType("sys::Str");
break;
case FanParser.KW_TRUE:
case FanParser.KW_FALSE:
baseType = new FanResolvedType("sys::Bool");
break;
case FanParser.CHAR:
baseType = new FanResolvedType("sys::Int");
break;
case FanParser.NUMBER:
String ftype = parseNumberType(node.getText());
baseType = new FanResolvedType(ftype);
break;
case FanParser.URI:
baseType = new FanResolvedType("sys::Uri");
break;
case FanParser.AST_NAMED_SUPER:
CommonTree nameNode = (CommonTree) node.getFirstChildWithType(FanParser.AST_ID);
baseType = resolveExpr(scope, baseType, nameNode, index);
baseType.setStaticContext(false);
break;
case FanParser.KW_SUPER:
baseType = new FanResolvedType(resolveSuper(scope));
baseType.setStaticContext(false);
break;
case FanParser.KW_THIS:
baseType = new FanResolvedType(resolveThisType(scope));
break;
case FanParser.AST_IT_BLOCK:
// Do nothing, keep type of left hand side.
baseType.setStaticContext(false);
break;
case FanParser.AST_CTOR_BLOCK:
CommonTree ctorNode = (CommonTree) node.getFirstChildWithType(FanParser.AST_TYPE);
baseType = resolveExpr(scope, baseType, ctorNode, index);
baseType.setStaticContext(false);
break;
case FanParser.AST_INDEX_EXPR:
baseType = resolveIndexExpr(scope, baseType, node, index);
break;
case FanParser.AST_LIST:
CommonTree firstNode = (CommonTree) children.get(0);
// Because of a grammar issue, some indexed expression show up as List
boolean isResolveExpr = false;
if (firstNode != null && firstNode.getType() == FanParser.AST_TYPE)
{
FanResolvedType lType = resolveExpr(scope, baseType, firstNode, index);
if (lType != null && !lType.isStaticContext())
{
isResolveExpr = true;
baseType = resolveIndexExpr(scope, lType, node, index);
}
}
if (!isResolveExpr)
{//Normal list type like Str[]
baseType = new FanResolvedType("sys::List");
CommonTree listTypeNode = (CommonTree) node.getFirstChildWithType(FanParser.AST_TERM_EXPR);
if (listTypeNode != null)
{
FanResolvedType listType = resolveExpr(scope, null, listTypeNode, index);
baseType = new FanResolvedListType(listType);
}
}
break;
case FanParser.AST_MAP:
baseType = new FanResolvedType("sys::Map");
List<CommonTree> mapElems = FanLexAstUtils.getAllChildrenWithType(node, FanParser.AST_TERM_EXPR);
if (mapElems.size() >= 2)
{
CommonTree keyNode = mapElems.get(0);
CommonTree valueNode = mapElems.get(1);
FanResolvedType keyType = resolveExpr(scope, null, keyNode, index);
FanResolvedType valueType = resolveExpr(scope, null, valueNode, index);
if (keyType.isResolved() && valueType.isResolved())
{
baseType = new FanResolvedMapType(keyType, valueType);
}
}
break;
case FanParser.AST_TYPE_LIT: // type litteral
System.out.println("Lit: "+node.toStringTree());
CommonTree litNode=(CommonTree) node.getFirstChildWithType(FanParser.AST_TYPE);
baseType = makeFromExpr(scope, result, litNode, index);
baseType.setStaticContext(true);
break;
case FanParser.AST_FUNC_TYPE:
FanResolvedType returnType = null;
Vector<FanResolvedType> types = new Vector<FanResolvedType>();
boolean passedArrow = false;
for (CommonTree n : (List<CommonTree>) node.getChildren())
{
switch (n.getType())
{
case FanParser.OP_ARROW:
passedArrow = true;
break;
case FanParser.AST_TYPE:
if (!passedArrow)
{
types.add(makeFromTypeSig(scope, n));
} else
{
returnType = makeFromTypeSig(scope, n);
}
}
}
baseType = new FanResolvedFuncType(types, returnType);
baseType.setStaticContext(false);
break;
case FanParser.AST_SLOT_LIT:
baseType = new FanResolvedType("sys::Slot");
break;
case FanParser.AST_SYMBOL:
// TODO: is this correct - not sure
baseType = new FanResolvedType("sys::Symbol");
break;
case FanParser.AST_ID:
case FanParser.KW_IT:
if (baseType == null)
{
baseType = scope.resolveVar(t);
if (!baseType.isResolved())
{
// Try a static type (ex: Str.)
baseType = makeFromTypeSigWithWarning(scope, node);
baseType.setStaticContext(true);
}
} else
{
baseType = resolveSlotType(baseType, t);
}
break;
default:
// "Meaningless" 'wrapper' nodes (in term of expression resolving)
if (children != null && children.size() > 0)
{
for (CommonTree child : children)
{
baseType = resolveExpr(scope, baseType, child, index);
break; //TODO: to break or not ??
}
} else
{
FanUtilities.GENERIC_LOGGER.info("Don't know how to resolve: " + t + " " + node.toStringTree());
}
break;
}
//System.out.println("** End type: " + baseType + " "+baseType.isStaticContext());
return baseType;
}
| private static FanResolvedType resolveExpr(FanAstScope scope,
FanResolvedType baseType, CommonTree node, int index)
{
//FanUtilities.GENERIC_LOGGER.info("** type: " + node.toStringTree() + " " + baseType);
FanParserResult result = scope.getRoot().getParserResult();
// if unresolveable no point searching further
if (baseType != null && !baseType.isResolved())
{
return baseType;
}
//System.out.println("Node type: " + node.getType());
String t = FanLexAstUtils.getNodeContent(result, node);
if (node == null || t == null)
{
FanUtilities.GENERIC_LOGGER.info("Node is empty! " + node.getParent().toStringTree());
return makeUnresolved();
}
//System.out.println("Index: " + FanLexAstUtils.getTokenStart(node) + " VS " + index);
// Skip the imcomplete part past what we care about
if (!isValidTokenStart(node, index))
{
return baseType;
}
List<CommonTree> children = node.getChildren();
switch (node.getType())
{
//TODO: ranges (tricky)
case FanParser.AST_CAST:
CommonTree castType = (CommonTree) node.getFirstChildWithType(FanParser.AST_TYPE);
baseType = makeFromTypeSigWithWarning(scope, castType);
baseType.setStaticContext(false);
break;
case FanParser.AST_TERM_EXPR:
CommonTree termBase = children.get(0);
baseType = resolveExpr(scope, null, termBase, index);
CommonTree termChain = children.get(1);
baseType = resolveExpr(scope, baseType, termChain, index);
break;
case FanParser.AST_STATIC_CALL:
CommonTree type = children.get(0);
CommonTree idExpr = children.get(1);
baseType = resolveExpr(scope, null, type, index);
baseType = resolveExpr(scope, baseType, idExpr, index);
break;
case FanParser.AST_STR:
baseType = new FanResolvedType("sys::Str");
break;
case FanParser.KW_TRUE:
case FanParser.KW_FALSE:
baseType = new FanResolvedType("sys::Bool");
break;
case FanParser.CHAR:
baseType = new FanResolvedType("sys::Int");
break;
case FanParser.NUMBER:
String ftype = parseNumberType(node.getText());
baseType = new FanResolvedType(ftype);
break;
case FanParser.URI:
baseType = new FanResolvedType("sys::Uri");
break;
case FanParser.AST_NAMED_SUPER:
CommonTree nameNode = (CommonTree) node.getFirstChildWithType(FanParser.AST_ID);
baseType = resolveExpr(scope, baseType, nameNode, index);
baseType.setStaticContext(false);
break;
case FanParser.KW_SUPER:
baseType = new FanResolvedType(resolveSuper(scope));
baseType.setStaticContext(false);
break;
case FanParser.KW_THIS:
baseType = new FanResolvedType(resolveThisType(scope));
break;
case FanParser.AST_IT_BLOCK:
// Do nothing, keep type of left hand side.
baseType.setStaticContext(false);
break;
case FanParser.AST_CTOR_BLOCK:
CommonTree ctorNode = (CommonTree) node.getFirstChildWithType(FanParser.AST_TYPE);
baseType = resolveExpr(scope, baseType, ctorNode, index);
baseType.setStaticContext(false);
break;
case FanParser.AST_INDEX_EXPR:
baseType = resolveIndexExpr(scope, baseType, node, index);
break;
case FanParser.AST_LIST:
CommonTree firstNode = (CommonTree) children.get(0);
// Because of a grammar issue, some indexed expression show up as List
boolean isResolveExpr = false;
if (firstNode != null && firstNode.getType() == FanParser.AST_TYPE)
{
FanResolvedType lType = resolveExpr(scope, baseType, firstNode, index);
if (lType != null && !lType.isStaticContext())
{
isResolveExpr = true;
baseType = resolveIndexExpr(scope, lType, node, index);
}
}
if (!isResolveExpr)
{//Normal list type like Str[]
baseType = new FanResolvedType("sys::List");
CommonTree listTypeNode = (CommonTree) node.getFirstChildWithType(FanParser.AST_TERM_EXPR);
if (listTypeNode != null)
{
FanResolvedType listType = resolveExpr(scope, null, listTypeNode, index);
baseType = new FanResolvedListType(listType);
}
}
break;
case FanParser.AST_MAP:
baseType = new FanResolvedType("sys::Map");
List<CommonTree> mapElems = FanLexAstUtils.getAllChildrenWithType(node, FanParser.AST_TERM_EXPR);
if (mapElems.size() >= 2)
{
CommonTree keyNode = mapElems.get(0);
CommonTree valueNode = mapElems.get(1);
FanResolvedType keyType = resolveExpr(scope, null, keyNode, index);
FanResolvedType valueType = resolveExpr(scope, null, valueNode, index);
if (keyType.isResolved() && valueType.isResolved())
{
baseType = new FanResolvedMapType(keyType, valueType);
}
}
break;
case FanParser.AST_TYPE_LIT: // type litteral
//System.out.println("Lit: "+node.toStringTree());
CommonTree litNode=(CommonTree) node.getFirstChildWithType(FanParser.AST_TYPE);
baseType = makeFromExpr(scope, result, litNode, index);
baseType.setStaticContext(true);
break;
case FanParser.AST_FUNC_TYPE:
FanResolvedType returnType = null;
Vector<FanResolvedType> types = new Vector<FanResolvedType>();
boolean passedArrow = false;
for (CommonTree n : (List<CommonTree>) node.getChildren())
{
switch (n.getType())
{
case FanParser.OP_ARROW:
passedArrow = true;
break;
case FanParser.AST_TYPE:
if (!passedArrow)
{
types.add(makeFromTypeSig(scope, n));
} else
{
returnType = makeFromTypeSig(scope, n);
}
}
}
baseType = new FanResolvedFuncType(types, returnType);
baseType.setStaticContext(false);
break;
case FanParser.AST_SLOT_LIT:
baseType = new FanResolvedType("sys::Slot");
break;
case FanParser.AST_SYMBOL:
// TODO: is this correct - not sure
baseType = new FanResolvedType("sys::Symbol");
break;
case FanParser.AST_ID:
case FanParser.KW_IT:
if (baseType == null)
{
baseType = scope.resolveVar(t);
if (!baseType.isResolved())
{
// Try a static type (ex: Str.)
baseType = makeFromTypeSigWithWarning(scope, node);
baseType.setStaticContext(true);
}
} else
{
baseType = resolveSlotType(baseType, t);
}
break;
default:
// "Meaningless" 'wrapper' nodes (in term of expression resolving)
if (children != null && children.size() > 0)
{
for (CommonTree child : children)
{
baseType = resolveExpr(scope, baseType, child, index);
break; //TODO: to break or not ??
}
} else
{
FanUtilities.GENERIC_LOGGER.info("Don't know how to resolve: " + t + " " + node.toStringTree());
}
break;
}
//System.out.println("** End type: " + baseType + " "+baseType.isStaticContext());
return baseType;
}
|
diff --git a/src/main/java/org/hardisonbrewing/maven/core/JoJoMojo.java b/src/main/java/org/hardisonbrewing/maven/core/JoJoMojo.java
index e352bad..6bac61c 100644
--- a/src/main/java/org/hardisonbrewing/maven/core/JoJoMojo.java
+++ b/src/main/java/org/hardisonbrewing/maven/core/JoJoMojo.java
@@ -1,170 +1,170 @@
/**
* Copyright (c) 2010-2011 Martin M Reed
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.hardisonbrewing.maven.core;
import java.util.List;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.installer.ArtifactInstaller;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.StreamConsumer;
import org.hardisonbrewing.maven.core.cli.CommandLineService;
import org.hardisonbrewing.maven.core.cli.LogStreamConsumer;
public abstract class JoJoMojo extends AbstractMojo {
/**
* The current {@link JoJoMojo} instance;
*/
private static JoJoMojo joJoMojo;
protected JoJoMojo() {
joJoMojo = this;
}
/**
* Return the current {@link JoJoMojo} instance;
* @return
*/
public static final JoJoMojo getMojo() {
return joJoMojo;
}
protected final int execute( List<String> cmd ) {
return execute( buildCommandline( cmd ) );
}
protected final int execute( List<String> cmd, StreamConsumer systemOut, StreamConsumer systemErr ) {
return execute( buildCommandline( cmd ), systemOut, systemErr );
}
protected final int execute( Commandline commandLine ) {
StreamConsumer systemOut = new LogStreamConsumer( LogStreamConsumer.LEVEL_INFO );
StreamConsumer systemErr = new LogStreamConsumer( LogStreamConsumer.LEVEL_ERROR );
return execute( commandLine, systemOut, systemErr );
}
protected final int execute( Commandline commandLine, StreamConsumer systemOut, StreamConsumer systemErr ) {
int exitValue;
try {
getLog().info( commandLine.toString() );
exitValue = CommandLineService.execute( commandLine, systemOut, systemErr );
}
catch (CommandLineException e) {
- throw new IllegalStateException( e.getCause() );
+ throw new IllegalStateException( e );
}
if ( exitValue != 0 ) {
throw new IllegalStateException( "Command exited with value[" + exitValue + "]" );
}
return exitValue;
}
protected Commandline buildCommandline( List<String> cmd ) {
Commandline commandLine;
try {
commandLine = CommandLineService.build( cmd );
}
catch (CommandLineException e) {
throw new IllegalStateException( e.getMessage() );
}
commandLine.setWorkingDirectory( TargetDirectoryService.getTargetDirectory() );
return commandLine;
}
/**
* Return the current {@link Log} instance.
*/
@Override
public final Log getLog() {
return super.getLog();
}
/**
* Return the current {@link MavenProject} instance.
* @return
*/
public abstract MavenProject getProject();
/**
* Return the current {@link ArchiverManager} instance.
* @return
*/
public abstract ArchiverManager getArchiverManager();
/**
*
* @return
*/
public abstract ArtifactResolver getArtifactResolver();
/**
*
* @return
*/
public abstract ArtifactRepository getLocalRepository();
/**
*
* @return
*/
public abstract ArtifactFactory getArtifactFactory();
/**
*
* @return
*/
public abstract MavenProjectBuilder getProjectBuilder();
/**
*
* @return
*/
public abstract List<ArtifactRepository> getRemoteRepositories();
/**
*
* @return
*/
public abstract ArtifactInstaller getArtifactInstaller();
/**
*
* @return
*/
public abstract MavenSession getMavenSession();
}
| true | true | protected final int execute( Commandline commandLine, StreamConsumer systemOut, StreamConsumer systemErr ) {
int exitValue;
try {
getLog().info( commandLine.toString() );
exitValue = CommandLineService.execute( commandLine, systemOut, systemErr );
}
catch (CommandLineException e) {
throw new IllegalStateException( e.getCause() );
}
if ( exitValue != 0 ) {
throw new IllegalStateException( "Command exited with value[" + exitValue + "]" );
}
return exitValue;
}
| protected final int execute( Commandline commandLine, StreamConsumer systemOut, StreamConsumer systemErr ) {
int exitValue;
try {
getLog().info( commandLine.toString() );
exitValue = CommandLineService.execute( commandLine, systemOut, systemErr );
}
catch (CommandLineException e) {
throw new IllegalStateException( e );
}
if ( exitValue != 0 ) {
throw new IllegalStateException( "Command exited with value[" + exitValue + "]" );
}
return exitValue;
}
|
diff --git a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/PlatformUiUtil.java b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/PlatformUiUtil.java
index 652a41f4..dc7d5a46 100644
--- a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/PlatformUiUtil.java
+++ b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/PlatformUiUtil.java
@@ -1,168 +1,175 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
* David Green - fix for bug 247182
* Frank Becker - fixes for bug 259877
*******************************************************************************/
package org.eclipse.mylyn.internal.provisional.commons.ui;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.ui.forms.widgets.Section;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;
/**
* @author Steffen Pingel
*/
public class PlatformUiUtil {
private static class Eclipse36Checker {
public static final boolean result;
static {
boolean methodAvailable = false;
try {
StyledText.class.getMethod("setTabStops", int[].class); //$NON-NLS-1$
methodAvailable = true;
} catch (NoSuchMethodException e) {
}
result = methodAvailable;
}
}
/**
* bug 247182: file import dialog doesn't work on Mac OS X if the file extension has more than one dot.
*/
public static String[] getFilterExtensions(String... extensions) {
for (int i = 0; i < extensions.length; i++) {
String extension = extensions[i];
if (Platform.OS_MACOSX.equals(Platform.getOS())) {
int j = extension.lastIndexOf('.');
if (j != -1) {
extension = extension.substring(j);
}
}
extensions[i] = "*" + extension; //$NON-NLS-1$
}
return extensions;
}
public static int getToolTipXShift() {
if ("gtk".equals(SWT.getPlatform()) || "carbon".equals(SWT.getPlatform()) || "cocoa".equals(SWT.getPlatform())) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return -26;
} else {
return -23;
}
}
public static int getTreeImageOffset() {
if ("carbon".equals(SWT.getPlatform())) { //$NON-NLS-1$
return 16;
} else if ("cocoa".equals(SWT.getPlatform())) { //$NON-NLS-1$
return 13;
} else {
return 20;
}
}
public static int getIncomingImageOffset() {
if ("carbon".equals(SWT.getPlatform())) { //$NON-NLS-1$
return 5;
} else if ("cocoa".equals(SWT.getPlatform())) { //$NON-NLS-1$
return 2;
} else {
return 6;
}
}
public static int getTreeItemSquish() {
if ("gtk".equals(SWT.getPlatform())) { //$NON-NLS-1$
return 8;
} else if (isMac()) {
return 3;
} else {
return 0;
}
}
private static boolean isMac() {
return "carbon".equals(SWT.getPlatform()) || "cocoa".equals(SWT.getPlatform()); //$NON-NLS-1$ //$NON-NLS-2$
}
// TODO e3.5: remove, platform has been fixed, see bug 272046
public static boolean isPaintItemClippingRequired() {
return "gtk".equals(SWT.getPlatform()); //$NON-NLS-1$
}
public static boolean spinnerHasNativeBorder() {
return isMac() && !isEclipse36orLater();
}
private static boolean isEclipse36orLater() {
return Eclipse36Checker.result;
}
public static boolean hasNarrowToolBar() {
return Platform.WS_WIN32.equals(SWT.getPlatform());
}
/**
* If a a section does not use a toolbar as its text client the spacing between the section header and client will
* be different from other sections. This method returns the value to set as the vertical spacing on those sections
* to align the vertical position of section clients.
*
* @return value for {@link Section#clientVerticalSpacing}
*/
public static int getToolbarSectionClientVerticalSpacing() {
if (Platform.WS_WIN32.equals(SWT.getPlatform())) {
return 5;
}
return 7;
}
/**
* Returns the width of the view menu drop-down button.
*/
public static int getViewMenuWidth() {
return 32;
}
/**
* Because of bug# 322293 (NPE when select Hyperlink from MultipleHyperlinkPresenter List) for MacOS we enable this
* only if running on Eclipse >= "3.7.0.v201101192000"
*/
public static boolean supportsMultipleHyperlinkPresenter() {
if (isMac()) {
Bundle bundle = Platform.getBundle("org.eclipse.platform"); //$NON-NLS-1$
if (bundle != null) {
String versionString = (String) bundle.getHeaders().get("Bundle-Version"); //$NON-NLS-1$
Version version = new Version(versionString);
return version.compareTo(new Version("3.7.0.v201101192000")) >= 0; //$NON-NLS-1$
} else {
- //TODO: change this to true when eclipse 3.6 reach end of live!
- return false;
+ bundle = Platform.getBundle("org.eclipse.swt"); //$NON-NLS-1$
+ if (bundle != null) {
+ String versionString = (String) bundle.getHeaders().get("Bundle-Version"); //$NON-NLS-1$
+ Version version = new Version(versionString);
+ return version.compareTo(new Version("3.7.0.v3721")) >= 0; //$NON-NLS-1$
+ } else {
+ //TODO e3.7 change this to true when eclipse 3.6 reach end of live!
+ return false;
+ }
}
}
return true;
}
/**
* Because of bug#175655: [context] provide an on-hover affordance to supplement Alt+click navigation Tooltips will
* show everyone on Linux unless they are balloons.
*/
public static int getSwtTooltipStyle() {
if ("gtk".equals(SWT.getPlatform())) { //$NON-NLS-1$
return SWT.BALLOON;
}
return SWT.NONE;
}
}
| true | true | public static boolean supportsMultipleHyperlinkPresenter() {
if (isMac()) {
Bundle bundle = Platform.getBundle("org.eclipse.platform"); //$NON-NLS-1$
if (bundle != null) {
String versionString = (String) bundle.getHeaders().get("Bundle-Version"); //$NON-NLS-1$
Version version = new Version(versionString);
return version.compareTo(new Version("3.7.0.v201101192000")) >= 0; //$NON-NLS-1$
} else {
//TODO: change this to true when eclipse 3.6 reach end of live!
return false;
}
}
return true;
}
| public static boolean supportsMultipleHyperlinkPresenter() {
if (isMac()) {
Bundle bundle = Platform.getBundle("org.eclipse.platform"); //$NON-NLS-1$
if (bundle != null) {
String versionString = (String) bundle.getHeaders().get("Bundle-Version"); //$NON-NLS-1$
Version version = new Version(versionString);
return version.compareTo(new Version("3.7.0.v201101192000")) >= 0; //$NON-NLS-1$
} else {
bundle = Platform.getBundle("org.eclipse.swt"); //$NON-NLS-1$
if (bundle != null) {
String versionString = (String) bundle.getHeaders().get("Bundle-Version"); //$NON-NLS-1$
Version version = new Version(versionString);
return version.compareTo(new Version("3.7.0.v3721")) >= 0; //$NON-NLS-1$
} else {
//TODO e3.7 change this to true when eclipse 3.6 reach end of live!
return false;
}
}
}
return true;
}
|
diff --git a/esmska/src/esmska/utils/Workarounds.java b/esmska/src/esmska/utils/Workarounds.java
index 5daac67a..bb549568 100644
--- a/esmska/src/esmska/utils/Workarounds.java
+++ b/esmska/src/esmska/utils/Workarounds.java
@@ -1,28 +1,31 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package esmska.utils;
import org.apache.commons.lang.StringEscapeUtils;
/** Workaround methods for bugs in JREs
*
* @author ripper
*/
public class Workarounds {
/** Escape text using html entities.
* Fixes bug in OpenJDK where scaron entity is not replaced by 'š'.
*
* @see org.apache.commons.lang.StringEscapeUtils#escapeHtml(String)
*/
public static String escapeHtml(String input) {
+ if (input == null) {
+ return input;
+ }
String output = StringEscapeUtils.escapeHtml(input);
output = output.replaceAll("\\š", "\\š");
output = output.replaceAll("\\Š", "\\Š");
return output;
}
}
| true | true | public static String escapeHtml(String input) {
String output = StringEscapeUtils.escapeHtml(input);
output = output.replaceAll("\\š", "\\š");
output = output.replaceAll("\\Š", "\\Š");
return output;
}
| public static String escapeHtml(String input) {
if (input == null) {
return input;
}
String output = StringEscapeUtils.escapeHtml(input);
output = output.replaceAll("\\š", "\\š");
output = output.replaceAll("\\Š", "\\Š");
return output;
}
|
diff --git a/src/org/waveprotocol/box/server/robots/RobotRegistrationServlet.java b/src/org/waveprotocol/box/server/robots/RobotRegistrationServlet.java
index 686ca62f..6b957131 100644
--- a/src/org/waveprotocol/box/server/robots/RobotRegistrationServlet.java
+++ b/src/org/waveprotocol/box/server/robots/RobotRegistrationServlet.java
@@ -1,187 +1,188 @@
/**
* Copyright 2010 Google 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 org.waveprotocol.box.server.robots;
import com.google.common.base.Strings;
import com.google.gxp.base.GxpContext;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.waveprotocol.box.server.CoreSettings;
import org.waveprotocol.box.server.account.AccountData;
import org.waveprotocol.box.server.account.RobotAccountData;
import org.waveprotocol.box.server.account.RobotAccountDataImpl;
import org.waveprotocol.box.server.gxp.robots.RobotRegistrationPage;
import org.waveprotocol.box.server.gxp.robots.RobotRegistrationSuccessPage;
import org.waveprotocol.box.server.persistence.AccountStore;
import org.waveprotocol.box.server.persistence.PersistenceException;
import org.waveprotocol.wave.model.id.TokenGenerator;
import org.waveprotocol.wave.model.wave.InvalidParticipantAddress;
import org.waveprotocol.wave.model.wave.ParticipantId;
import org.waveprotocol.wave.util.logging.Log;
import java.io.IOException;
import java.net.URI;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet for Robot Registration.
*
* @author [email protected] (Lennard de Rijk)
*/
public class RobotRegistrationServlet extends HttpServlet {
private static final String CREATE_PATH = "/create";
private static final int TOKEN_LENGTH = 48;
private static final Log LOG = Log.get(RobotRegistrationServlet.class);
private final AccountStore accountStore;
private final String domain;
private final TokenGenerator tokenGenerator;
@Inject
private RobotRegistrationServlet(AccountStore accountStore,
@Named(CoreSettings.WAVE_SERVER_DOMAIN) String domain, TokenGenerator tokenGenerator) {
this.accountStore = accountStore;
this.domain = domain;
this.tokenGenerator = tokenGenerator;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String pathInfo = req.getPathInfo();
if (CREATE_PATH.equals(pathInfo)) {
doRegisterGet(req, resp, "");
} else {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String pathInfo = req.getPathInfo();
if (CREATE_PATH.equals(pathInfo)) {
doRegisterPost(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Handles GET request for the register page.
*
* @param message non-null but optional message to show on the page
*/
private void doRegisterGet(HttpServletRequest req, HttpServletResponse resp, String message)
throws IOException {
RobotRegistrationPage.write(resp.getWriter(), new GxpContext(req.getLocale()), domain, message);
resp.setContentType("text/html");
resp.setStatus(HttpServletResponse.SC_OK);
}
/**
* Handles POST request for the register page.
*/
private void doRegisterPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter("username");
String location = req.getParameter("location");
if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(location)) {
doRegisterGet(req, resp, "Please complete all fields.");
return;
}
ParticipantId id;
try {
id = ParticipantId.of(username + "@" + domain);
} catch (InvalidParticipantAddress e) {
doRegisterGet(req, resp, "Invalid username specified, use alphanumeric characters only.");
return;
}
AccountData account;
try {
account = accountStore.getAccount(id);
} catch (PersistenceException e) {
LOG.severe("Failed to retrieve account data for " + id, e);
doRegisterGet(req, resp,
"Failed to retreive account data for " + username);
return;
}
if (account != null) {
doRegisterGet(req, resp, username + " is already in use, please choose another one.");
return;
}
URI uri;
try {
uri = URI.create(location);
} catch (IllegalArgumentException e) {
doRegisterGet(req, resp,
"Invalid Location specified, please specify a location in URI format.");
return;
}
String robotLocation;
- if (uri.getPort() != -1) {
- robotLocation = "http://" + uri.getHost() + ":" + uri.getPort() + uri.getPath();
+ String scheme = uri.getScheme();
+ if (scheme == null || !(scheme.equals("http") || scheme.equals("https"))) {
+ robotLocation = "http://" + uri.toString();
} else {
- robotLocation = "http://" + uri.getHost() + uri.getPath();
+ robotLocation = uri.toString();
}
if (robotLocation.endsWith("/")) {
robotLocation = robotLocation.substring(0, robotLocation.length() - 1);
}
// TODO(ljvderijk): Implement the verification.
RobotAccountData robotAccount = new RobotAccountDataImpl(
id, robotLocation, tokenGenerator.generateToken(TOKEN_LENGTH), null, true);
try {
accountStore.putAccount(robotAccount);
} catch (PersistenceException e) {
LOG.severe("Failed to update account data for " + id, e);
doRegisterGet(req, resp,
"An unexpected error occured while trying to store the account data for " + username);
return;
}
LOG.info(robotAccount.getId() + " is now registered as a RobotAccount with Url "
+ robotAccount.getUrl());
onRegisterSuccess(req, resp, robotAccount);
}
/**
* Shows the page that signals that a robot was successfully registered a
* robot. It will show the robot's token and token secret to use for the
* Active API.
*
* @param robotAccount the newly registered robot account.
*/
private void onRegisterSuccess(HttpServletRequest req, HttpServletResponse resp,
RobotAccountData robotAccount) throws IOException {
RobotRegistrationSuccessPage.write(resp.getWriter(), new GxpContext(req.getLocale()),
robotAccount.getId().getAddress(), robotAccount.getConsumerSecret());
resp.setContentType("text/html");
resp.setStatus(HttpServletResponse.SC_OK);
}
}
| false | true | private void doRegisterPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter("username");
String location = req.getParameter("location");
if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(location)) {
doRegisterGet(req, resp, "Please complete all fields.");
return;
}
ParticipantId id;
try {
id = ParticipantId.of(username + "@" + domain);
} catch (InvalidParticipantAddress e) {
doRegisterGet(req, resp, "Invalid username specified, use alphanumeric characters only.");
return;
}
AccountData account;
try {
account = accountStore.getAccount(id);
} catch (PersistenceException e) {
LOG.severe("Failed to retrieve account data for " + id, e);
doRegisterGet(req, resp,
"Failed to retreive account data for " + username);
return;
}
if (account != null) {
doRegisterGet(req, resp, username + " is already in use, please choose another one.");
return;
}
URI uri;
try {
uri = URI.create(location);
} catch (IllegalArgumentException e) {
doRegisterGet(req, resp,
"Invalid Location specified, please specify a location in URI format.");
return;
}
String robotLocation;
if (uri.getPort() != -1) {
robotLocation = "http://" + uri.getHost() + ":" + uri.getPort() + uri.getPath();
} else {
robotLocation = "http://" + uri.getHost() + uri.getPath();
}
if (robotLocation.endsWith("/")) {
robotLocation = robotLocation.substring(0, robotLocation.length() - 1);
}
// TODO(ljvderijk): Implement the verification.
RobotAccountData robotAccount = new RobotAccountDataImpl(
id, robotLocation, tokenGenerator.generateToken(TOKEN_LENGTH), null, true);
try {
accountStore.putAccount(robotAccount);
} catch (PersistenceException e) {
LOG.severe("Failed to update account data for " + id, e);
doRegisterGet(req, resp,
"An unexpected error occured while trying to store the account data for " + username);
return;
}
LOG.info(robotAccount.getId() + " is now registered as a RobotAccount with Url "
+ robotAccount.getUrl());
onRegisterSuccess(req, resp, robotAccount);
}
| private void doRegisterPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter("username");
String location = req.getParameter("location");
if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(location)) {
doRegisterGet(req, resp, "Please complete all fields.");
return;
}
ParticipantId id;
try {
id = ParticipantId.of(username + "@" + domain);
} catch (InvalidParticipantAddress e) {
doRegisterGet(req, resp, "Invalid username specified, use alphanumeric characters only.");
return;
}
AccountData account;
try {
account = accountStore.getAccount(id);
} catch (PersistenceException e) {
LOG.severe("Failed to retrieve account data for " + id, e);
doRegisterGet(req, resp,
"Failed to retreive account data for " + username);
return;
}
if (account != null) {
doRegisterGet(req, resp, username + " is already in use, please choose another one.");
return;
}
URI uri;
try {
uri = URI.create(location);
} catch (IllegalArgumentException e) {
doRegisterGet(req, resp,
"Invalid Location specified, please specify a location in URI format.");
return;
}
String robotLocation;
String scheme = uri.getScheme();
if (scheme == null || !(scheme.equals("http") || scheme.equals("https"))) {
robotLocation = "http://" + uri.toString();
} else {
robotLocation = uri.toString();
}
if (robotLocation.endsWith("/")) {
robotLocation = robotLocation.substring(0, robotLocation.length() - 1);
}
// TODO(ljvderijk): Implement the verification.
RobotAccountData robotAccount = new RobotAccountDataImpl(
id, robotLocation, tokenGenerator.generateToken(TOKEN_LENGTH), null, true);
try {
accountStore.putAccount(robotAccount);
} catch (PersistenceException e) {
LOG.severe("Failed to update account data for " + id, e);
doRegisterGet(req, resp,
"An unexpected error occured while trying to store the account data for " + username);
return;
}
LOG.info(robotAccount.getId() + " is now registered as a RobotAccount with Url "
+ robotAccount.getUrl());
onRegisterSuccess(req, resp, robotAccount);
}
|
diff --git a/src/main/java/uk/ac/ic/doc/campusProject/web/servlet/PlacesApi.java b/src/main/java/uk/ac/ic/doc/campusProject/web/servlet/PlacesApi.java
index c1e61d1..e19ce75 100644
--- a/src/main/java/uk/ac/ic/doc/campusProject/web/servlet/PlacesApi.java
+++ b/src/main/java/uk/ac/ic/doc/campusProject/web/servlet/PlacesApi.java
@@ -1,79 +1,79 @@
package uk.ac.ic.doc.campusProject.web.servlet;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import uk.ac.ic.doc.campusProject.utils.db.DatabaseConnectionManager;
public class PlacesApi extends HttpServlet {
private static final long serialVersionUID = 1L;
Logger log = Logger.getLogger(PlacesApi.class);
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Connection conn = DatabaseConnectionManager.getConnection("live");
String building = request.getParameter("building");
String floor = request.getParameter("floor");
String left = request.getParameter("left");
String right = request.getParameter("right");
String top = request.getParameter("top");
String bottom = request.getParameter("bottom");
try {
PreparedStatement stmt = conn.prepareStatement("SELECT Number, Type, Description, Image FROM Room LEFT JOIN Floor_Contains ON Number=Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?" +
" AND Xpixel <= ? AND Xpixel >= ? AND Ypixel <= ? AND Ypixel >= ?");
stmt.setString(1, building);
stmt.setString(2, floor);
stmt.setString(3, right);
stmt.setString(4, left);
stmt.setString(5, bottom);
stmt.setString(6, top);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
JSONObject jsonArray = new JSONObject();
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
String number = rs.getString("Number");
jsonObject.put("number", number);
jsonObject.put("type", rs.getString("Type"));
jsonObject.put("description", rs.getString("Description"));
Blob blob = rs.getBlob("Image");
if (blob == null) {
- jsonObject.put("image", 0);
+ jsonObject.put("image", new byte[]{});
}
else {
jsonObject.put("image", blob.getBytes(1, (int)blob.length()));
}
jsonArray.put("room", jsonObject);
}
os.write(jsonArray.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
} catch (SQLException | IOException | JSONException e) {
e.printStackTrace();
}
}
}
| true | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Connection conn = DatabaseConnectionManager.getConnection("live");
String building = request.getParameter("building");
String floor = request.getParameter("floor");
String left = request.getParameter("left");
String right = request.getParameter("right");
String top = request.getParameter("top");
String bottom = request.getParameter("bottom");
try {
PreparedStatement stmt = conn.prepareStatement("SELECT Number, Type, Description, Image FROM Room LEFT JOIN Floor_Contains ON Number=Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?" +
" AND Xpixel <= ? AND Xpixel >= ? AND Ypixel <= ? AND Ypixel >= ?");
stmt.setString(1, building);
stmt.setString(2, floor);
stmt.setString(3, right);
stmt.setString(4, left);
stmt.setString(5, bottom);
stmt.setString(6, top);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
JSONObject jsonArray = new JSONObject();
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
String number = rs.getString("Number");
jsonObject.put("number", number);
jsonObject.put("type", rs.getString("Type"));
jsonObject.put("description", rs.getString("Description"));
Blob blob = rs.getBlob("Image");
if (blob == null) {
jsonObject.put("image", 0);
}
else {
jsonObject.put("image", blob.getBytes(1, (int)blob.length()));
}
jsonArray.put("room", jsonObject);
}
os.write(jsonArray.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
} catch (SQLException | IOException | JSONException e) {
e.printStackTrace();
}
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Connection conn = DatabaseConnectionManager.getConnection("live");
String building = request.getParameter("building");
String floor = request.getParameter("floor");
String left = request.getParameter("left");
String right = request.getParameter("right");
String top = request.getParameter("top");
String bottom = request.getParameter("bottom");
try {
PreparedStatement stmt = conn.prepareStatement("SELECT Number, Type, Description, Image FROM Room LEFT JOIN Floor_Contains ON Number=Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?" +
" AND Xpixel <= ? AND Xpixel >= ? AND Ypixel <= ? AND Ypixel >= ?");
stmt.setString(1, building);
stmt.setString(2, floor);
stmt.setString(3, right);
stmt.setString(4, left);
stmt.setString(5, bottom);
stmt.setString(6, top);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
JSONObject jsonArray = new JSONObject();
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
String number = rs.getString("Number");
jsonObject.put("number", number);
jsonObject.put("type", rs.getString("Type"));
jsonObject.put("description", rs.getString("Description"));
Blob blob = rs.getBlob("Image");
if (blob == null) {
jsonObject.put("image", new byte[]{});
}
else {
jsonObject.put("image", blob.getBytes(1, (int)blob.length()));
}
jsonArray.put("room", jsonObject);
}
os.write(jsonArray.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
} catch (SQLException | IOException | JSONException e) {
e.printStackTrace();
}
}
|
diff --git a/client/src/es/deusto/weblab/client/lab/comm/WlLabCommunication.java b/client/src/es/deusto/weblab/client/lab/comm/WlLabCommunication.java
index c15a11650..93c566808 100644
--- a/client/src/es/deusto/weblab/client/lab/comm/WlLabCommunication.java
+++ b/client/src/es/deusto/weblab/client/lab/comm/WlLabCommunication.java
@@ -1,616 +1,623 @@
/*
* Copyright (C) 2005-2009 University of Deusto
* All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution.
*
* This software consists of contributions made by many individuals,
* listed below:
*
* Author: Pablo Orduña <[email protected]>
* Luis Rodriguez <[email protected]>
*
*/
package es.deusto.weblab.client.lab.comm;
import java.util.HashMap;
import java.util.Map;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import es.deusto.weblab.client.comm.IWlCommonSerializer;
import es.deusto.weblab.client.comm.WlCommonCommunication;
import es.deusto.weblab.client.comm.WlRequestCallback;
import es.deusto.weblab.client.comm.callbacks.IVoidCallback;
import es.deusto.weblab.client.comm.exceptions.SerializationException;
import es.deusto.weblab.client.comm.exceptions.WlCommException;
import es.deusto.weblab.client.comm.exceptions.WlServerException;
import es.deusto.weblab.client.comm.exceptions.core.SessionNotFoundException;
import es.deusto.weblab.client.configuration.IConfigurationManager;
import es.deusto.weblab.client.dto.SessionID;
import es.deusto.weblab.client.dto.experiments.Command;
import es.deusto.weblab.client.dto.experiments.ExperimentAllowed;
import es.deusto.weblab.client.dto.experiments.ExperimentID;
import es.deusto.weblab.client.dto.experiments.ResponseCommand;
import es.deusto.weblab.client.dto.reservations.ReservationStatus;
import es.deusto.weblab.client.lab.comm.callbacks.IExperimentsAllowedCallback;
import es.deusto.weblab.client.lab.comm.callbacks.IReservationCallback;
import es.deusto.weblab.client.lab.comm.callbacks.IResponseCommandCallback;
import es.deusto.weblab.client.lab.comm.exceptions.UnknownExperimentIdException;
public class WlLabCommunication extends WlCommonCommunication implements IWlLabCommunication {
public static final String FILE_SENT_ATTR = "file_sent";
public static final String SESSION_ID_ATTR = "session_id";
public static final String FILE_INFO_ATTR = "file_info";
public static final String FILE_IS_ASYNC_ATTR = "is_async";
public static final String WEBLAB_FILE_UPLOAD_POST_SERVICE_URL_PROPERTY = "weblab.service.fileupload.post.url";
public static final String DEFAULT_WEBLAB_FILE_UPLOAD_POST_SERVICE_URL = "/weblab/web/upload/";
// TODO:
// The existence of multiple managers is probably not required.
// As of now, I don't think there can be two different active sessions at the
// same time.
private final Map<SessionID, AsyncRequestsManager> asyncRequestsManagers =
new HashMap<SessionID, AsyncRequestsManager>();
public WlLabCommunication(IConfigurationManager configurationManager){
super(configurationManager);
}
private String getFilePostUrl(){
return this.configurationManager.getProperty(
WlLabCommunication.WEBLAB_FILE_UPLOAD_POST_SERVICE_URL_PROPERTY,
WlLabCommunication.DEFAULT_WEBLAB_FILE_UPLOAD_POST_SERVICE_URL
);
}
private class ReservationRequestCallback extends WlRequestCallback{
private final IReservationCallback reservationCallback;
public ReservationRequestCallback(IReservationCallback reservationCallback){
super(reservationCallback);
this.reservationCallback = reservationCallback;
}
@Override
public void onSuccessResponseReceived(String response) {
ReservationStatus reservation;
try {
reservation = ((IWlLabSerializer)WlLabCommunication.this.serializer).parseGetReservationStatusResponse(response);
} catch (final SerializationException e) {
this.reservationCallback.onFailure(e);
return;
} catch (final SessionNotFoundException e) {
this.reservationCallback.onFailure(e);
return;
} catch (final WlServerException e) {
this.reservationCallback.onFailure(e);
return;
}
this.reservationCallback.onSuccess(reservation);
}
}
@Override
public void getReservationStatus(SessionID sessionId, IReservationCallback callback) {
String requestSerialized;
try {
requestSerialized = ((IWlLabSerializer)this.serializer).serializeGetReservationStatusRequest(sessionId);
} catch (final SerializationException e1) {
callback.onFailure(e1);
return;
}
this.performRequest(
requestSerialized,
callback,
new ReservationRequestCallback(callback)
);
}
private class ListExperimentsRequestCallback extends WlRequestCallback{
private final IExperimentsAllowedCallback experimentsAllowedCallback;
public ListExperimentsRequestCallback(IExperimentsAllowedCallback experimentsAllowedCallback){
super(experimentsAllowedCallback);
this.experimentsAllowedCallback = experimentsAllowedCallback;
}
@Override
public void onSuccessResponseReceived(String response){
ExperimentAllowed [] experimentsAllowed;
try {
experimentsAllowed = ((IWlLabSerializer)WlLabCommunication.this.serializer).parseListExperimentsResponse(response);
} catch (final SerializationException e) {
this.experimentsAllowedCallback.onFailure(e);
return;
} catch (final SessionNotFoundException e) {
this.experimentsAllowedCallback.onFailure(e);
return;
} catch (final WlServerException e) {
this.experimentsAllowedCallback.onFailure(e);
return;
}
this.experimentsAllowedCallback.onSuccess(experimentsAllowed);
}
}
@Override
public void listExperiments(SessionID sessionId, IExperimentsAllowedCallback callback) {
String requestSerialized;
try {
requestSerialized = ((IWlLabSerializer)this.serializer).serializeListExperimentsRequest(sessionId);
} catch (final SerializationException e1) {
callback.onFailure(e1);
return;
}
this.performRequest(
requestSerialized,
callback,
new ListExperimentsRequestCallback(callback)
);
}
private class PollRequestCallback extends WlRequestCallback{
private final IVoidCallback voidCallback;
public PollRequestCallback(IVoidCallback voidCallback){
super(voidCallback);
this.voidCallback = voidCallback;
}
@Override
public void onSuccessResponseReceived(String response) {
try {
((IWlLabSerializer)WlLabCommunication.this.serializer).parsePollResponse(response);
} catch (final SerializationException e) {
this.voidCallback.onFailure(e);
return;
} catch (final SessionNotFoundException e) {
this.voidCallback.onFailure(e);
return;
} catch (final WlServerException e) {
this.voidCallback.onFailure(e);
return;
}
this.voidCallback.onSuccess();
}
}
@Override
public void poll(SessionID sessionId, IVoidCallback callback) {
String requestSerialized;
try {
requestSerialized = ((IWlLabSerializer)this.serializer).serializePollRequest(sessionId);
} catch (final SerializationException e1) {
callback.onFailure(e1);
return;
}
this.performRequest(
requestSerialized,
callback,
new PollRequestCallback(callback)
);
}
private class ReserveExperimentRequestCallback extends WlRequestCallback{
private final IReservationCallback reservationCallback;
public ReserveExperimentRequestCallback(IReservationCallback reservationCallback){
super(reservationCallback);
this.reservationCallback = reservationCallback;
}
@Override
public void onSuccessResponseReceived(String response) {
ReservationStatus reservation;
try {
reservation = ((IWlLabSerializer)WlLabCommunication.this.serializer).parseReserveExperimentResponse(response);
} catch (final SerializationException e) {
this.reservationCallback.onFailure(e);
return;
} catch (final UnknownExperimentIdException e) {
this.reservationCallback.onFailure(e);
return;
} catch (final SessionNotFoundException e) {
this.reservationCallback.onFailure(e);
return;
} catch (final WlServerException e) {
this.reservationCallback.onFailure(e);
return;
}
this.reservationCallback.onSuccess(reservation);
}
}
@Override
public void reserveExperiment(SessionID sessionId, ExperimentID experimentId, IReservationCallback callback) {
String requestSerialized;
try {
requestSerialized = ((IWlLabSerializer)this.serializer).serializeReserveExperimentRequest(sessionId, experimentId);
} catch (final SerializationException e1) {
callback.onFailure(e1);
return;
}
this.performRequest(
requestSerialized,
callback,
new ReserveExperimentRequestCallback(callback)
);
}
/**
* Callback to be notified when a send_command request finishes, either
* successfully or not.
*/
private class SendCommandRequestCallback extends WlRequestCallback{
private final IResponseCommandCallback responseCommandCallback;
/**
* Constructs the SendCommandRequestCallback.
* @param responseCommandCallback Callback to be invoked whenever a request
* fails or succeeds. IResponseCommandCallback extends IWlAsyncCallback, and
* together they have two separate methods to handle both cases.
*/
public SendCommandRequestCallback(IResponseCommandCallback responseCommandCallback){
super(responseCommandCallback);
this.responseCommandCallback = responseCommandCallback;
}
@Override
public void onSuccessResponseReceived(String response) {
ResponseCommand command;
try {
command = ((IWlLabSerializer)WlLabCommunication.this.serializer).parseSendCommandResponse(response);
} catch (final SerializationException e) {
this.responseCommandCallback.onFailure(e);
return;
} catch (final SessionNotFoundException e) {
this.responseCommandCallback.onFailure(e);
return;
} catch (final WlServerException e) {
this.responseCommandCallback.onFailure(e);
return;
}
this.responseCommandCallback.onSuccess(command);
}
}
/**
* Internal callback which will be used for receiving and handling the response
* of a send_async_command request.
* TODO: Consider whether error checking is necessary here.
*/
private class SendAsyncCommandRequestCallback extends WlRequestCallback{
private final IResponseCommandCallback responseCommandCallback;
public SendAsyncCommandRequestCallback(IResponseCommandCallback responseCommandCallback){
super(responseCommandCallback);
this.responseCommandCallback = responseCommandCallback;
}
@Override
public void onSuccessResponseReceived(String response) {
ResponseCommand command;
try {
command = ((IWlLabSerializer)WlLabCommunication.this.serializer).parseSendAsyncCommandResponse(response);
} catch (final SerializationException e) {
this.responseCommandCallback.onFailure(e);
return;
} catch (final SessionNotFoundException e) {
this.responseCommandCallback.onFailure(e);
return;
} catch (final WlServerException e) {
this.responseCommandCallback.onFailure(e);
return;
}
this.responseCommandCallback.onSuccess(command);
}
}
/**
* Sends a command to be executed asynchronously on the server-side.
*
* @param command The command
* @param callback Callback which will be notified when the asynchronous execution
* ends and the response of the server is retrieved. This response may take a
* particularly long time to arrive.
*/
@Override
public void sendAsyncCommand(final SessionID sessionId, Command command,
final IResponseCommandCallback commandCallback) {
// Serialize the request as an asynchronous send command request.
String requestSerialized;
try {
requestSerialized = ((IWlLabSerializer)this.serializer).serializeSendAsyncCommandRequest(sessionId, command);
} catch (final SerializationException e1) {
commandCallback.onFailure(e1);
return;
}
// Declare the callback that will be called once the initial response of the asynchronous request
// is received. Because the asynchronous request is precisely not executed synchronously, this response
// is simply a request id, through which we will later poll to check the actual status and result of
// the request.
final IResponseCommandCallback asyncCommandResponseCallback = new IResponseCommandCallback() {
@Override
public void onSuccess(ResponseCommand responseCommand) {
final String requestID = responseCommand.getCommandString();
// We will now need to register the command in the local manager, so
// that it handles the polling.
AsyncRequestsManager asyncReqMngr =
WlLabCommunication.this.asyncRequestsManagers.get(sessionId);
// TODO: Consider some better way of handling the managers.
if(asyncReqMngr == null)
asyncReqMngr = new AsyncRequestsManager(WlLabCommunication.this, sessionId, (IWlLabSerializer) WlLabCommunication.this.serializer);
asyncReqMngr.registerAsyncRequest(requestID, commandCallback);
}
@Override
public void onFailure(WlCommException e) {
commandCallback.onFailure(e);
}
};
// Execute the initial request which will return the identifier and
// register the command for polling.
WlLabCommunication.this.performRequest(
requestSerialized,
asyncCommandResponseCallback,
new SendAsyncCommandRequestCallback(asyncCommandResponseCallback)
);
}
/**
* Sends a file asynchronously. Upon doing the async request to the server, it will be internally stored
* in the async requests manager, and polling will be done until the response is available. Then, the
* specified callback will be notified with the result.
*/
@Override
public void sendAsyncFile(final SessionID sessionId, final UploadStructure uploadStructure,
final IResponseCommandCallback callback) {
// "Serialize" sessionId
// We will now create the Hidden elements which we will use to pass
// the required POST parameters to the web script that will actually handle
// the file upload request.
final Hidden sessionIdElement = new Hidden();
sessionIdElement.setName(WlLabCommunication.SESSION_ID_ATTR);
sessionIdElement.setValue(sessionId.getRealId());
final Hidden fileInfoElement = new Hidden();
fileInfoElement.setName(WlLabCommunication.FILE_INFO_ATTR);
fileInfoElement.setValue(uploadStructure.getFileInfo());
final Hidden isAsyncElement = new Hidden();
isAsyncElement.setName(WlLabCommunication.FILE_IS_ASYNC_ATTR);
isAsyncElement.setValue("true");
// Set up uploadStructure
uploadStructure.addInformation(sessionIdElement);
uploadStructure.addInformation(fileInfoElement);
uploadStructure.addInformation(isAsyncElement);
uploadStructure.getFileUpload().setName(WlLabCommunication.FILE_SENT_ATTR);
uploadStructure.getFormPanel().setAction(this.getFilePostUrl());
uploadStructure.getFormPanel().setEncoding(FormPanel.ENCODING_MULTIPART);
uploadStructure.getFormPanel().setMethod(FormPanel.METHOD_POST);
// Register handler
uploadStructure.getFormPanel().addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
uploadStructure.removeInformation(sessionIdElement);
- final String resultMessage = event.getResults();
+ final String resultMessage = event.getResults();
+ // resultMessage will be a string such as SUCCESS@34KJ2341KJ
if(GWT.isScript() && resultMessage == null) {
this.reportFail(callback);
} else {
this.processResultMessage(callback, resultMessage);
}
}
private void processResultMessage(IResponseCommandCallback commandCallback, String resultMessage) {
- final ResponseCommand parsedRequestIdCommand;
- try {
- parsedRequestIdCommand = ((IWlLabSerializer)WlLabCommunication.this.serializer).parseSendAsyncCommandResponse(resultMessage);
- } catch (final SerializationException e) {
- commandCallback.onFailure(e);
- return;
- } catch (final SessionNotFoundException e) {
- commandCallback.onFailure(e);
- return;
- } catch (final WlServerException e) {
- commandCallback.onFailure(e);
- return;
- }
+ final ResponseCommand parsedRequestIdCommand;
+ try {
+ // TODO: This should be improved.
+ if(!resultMessage.toLowerCase().startsWith("success@"))
+ throw new SerializationException("Async send file response does not start with success@");
+ final String reslt = resultMessage.substring("success@".length());
+ System.out.println("[DBG]: AsyncSendFile returned: " + reslt);
+ parsedRequestIdCommand = new ResponseCommand(reslt);
+ } catch (final SerializationException e) {
+ commandCallback.onFailure(e);
+ return;
+ }
+// } catch (final SessionNotFoundException e) {
+// commandCallback.onFailure(e);
+// return;
+// } catch (final WlServerException e) {
+// commandCallback.onFailure(e);
+// return;
+// }
// We now have the request id of our asynchronous send_file request.
// We will need to register the request with the asynchronous manager
// so that it automatically polls and notifies us when the request finishes.
final String requestID = parsedRequestIdCommand.getCommandString();
AsyncRequestsManager asyncReqMngr =
WlLabCommunication.this.asyncRequestsManagers.get(sessionId);
// TODO: Consider some better way of handling the managers.
if(asyncReqMngr == null)
asyncReqMngr = new AsyncRequestsManager(WlLabCommunication.this, sessionId, (IWlLabSerializer) WlLabCommunication.this.serializer);
asyncReqMngr.registerAsyncRequest(requestID, commandCallback);
}
private void reportFail(final IResponseCommandCallback callback) {
GWT.log("reportFail could not async send the file", null);
callback.onFailure(new WlCommException("Couldn't async send the file"));
}
});
// Submit
uploadStructure.getFormPanel().submit();
}
@Override
public void sendCommand(SessionID sessionId, Command command, IResponseCommandCallback callback) {
String requestSerialized;
try {
requestSerialized = ((IWlLabSerializer)this.serializer).serializeSendCommandRequest(sessionId, command);
} catch (final SerializationException e1) {
callback.onFailure(e1);
return;
}
this.performRequest(
requestSerialized,
callback,
new SendCommandRequestCallback(callback)
);
}
private class FinishedRequestCallback extends WlRequestCallback{
private final IVoidCallback voidCallback;
public FinishedRequestCallback(IVoidCallback voidCallback){
super(voidCallback);
this.voidCallback = voidCallback;
}
@Override
public void onSuccessResponseReceived(String response) {
try {
((IWlLabSerializer)WlLabCommunication.this.serializer).parseFinishedExperimentResponse(response);
} catch (final SerializationException e) {
this.voidCallback.onFailure(e);
return;
} catch (final SessionNotFoundException e) {
this.voidCallback.onFailure(e);
return;
} catch (final WlServerException e) {
this.voidCallback.onFailure(e);
return;
}
this.voidCallback.onSuccess();
}
}
@Override
public void finishedExperiment(SessionID sessionId, IVoidCallback callback) {
String requestSerialized;
try {
requestSerialized = ((IWlLabSerializer)this.serializer).serializeFinishedExperimentRequest(sessionId);
} catch (final SerializationException e1) {
callback.onFailure(e1);
return;
}
this.performRequest(
requestSerialized,
callback,
new FinishedRequestCallback(callback)
);
}
/**
* Sends the file specified through the upload structure to the server. This is done through an
* HTTP post, which is received by a server-side web-script that actually does call the server-side
* send_file method.
*/
@Override
public void sendFile(SessionID sessionId, final UploadStructure uploadStructure, final IResponseCommandCallback callback) {
// "Serialize" sessionId
// We will now create the Hidden elements which we will use to pass
// the required POST parameters to the web script that will actually handle
// the file upload request.
final Hidden sessionIdElement = new Hidden();
sessionIdElement.setName(WlLabCommunication.SESSION_ID_ATTR);
sessionIdElement.setValue(sessionId.getRealId());
final Hidden fileInfoElement = new Hidden();
fileInfoElement.setName(WlLabCommunication.FILE_INFO_ATTR);
fileInfoElement.setValue(uploadStructure.getFileInfo());
// TODO: This could be enabled. Left disabled for now just in case it has
// side effects. It isn't really required because the is_async attribute is
// optional and false by default.
final Hidden isAsyncElement = new Hidden();
isAsyncElement.setName(WlLabCommunication.FILE_IS_ASYNC_ATTR);
isAsyncElement.setValue("false");
// Set up uploadStructure
uploadStructure.addInformation(sessionIdElement);
uploadStructure.addInformation(fileInfoElement);
uploadStructure.addInformation(isAsyncElement);
uploadStructure.getFileUpload().setName(WlLabCommunication.FILE_SENT_ATTR);
uploadStructure.getFormPanel().setAction(this.getFilePostUrl());
uploadStructure.getFormPanel().setEncoding(FormPanel.ENCODING_MULTIPART);
uploadStructure.getFormPanel().setMethod(FormPanel.METHOD_POST);
// Register handler
uploadStructure.getFormPanel().addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
uploadStructure.removeInformation(sessionIdElement);
final String resultMessage = event.getResults();
if(GWT.isScript() && resultMessage == null) {
this.reportFail(callback);
} else {
this.processResultMessage(callback, resultMessage);
}
}
private void processResultMessage(IResponseCommandCallback callback, String resultMessage) {
final ResponseCommand parsedResponseCommand;
try {
parsedResponseCommand = ((IWlLabSerializer)WlLabCommunication.this.serializer).parseSendFileResponse(resultMessage);
} catch (final SerializationException e) {
callback.onFailure(e);
return;
} catch (final SessionNotFoundException e) {
callback.onFailure(e);
return;
} catch (final WlServerException e) {
callback.onFailure(e);
return;
}
callback.onSuccess(parsedResponseCommand);
}
private void reportFail(final IResponseCommandCallback callback) {
GWT.log("reportFail could not send the file", null);
callback.onFailure(new WlCommException("Couldn't send the file"));
}
});
// Submit
uploadStructure.getFormPanel().submit();
}
@Override
// For testing purposes
protected IWlCommonSerializer createSerializer(){
return new WlLabSerializerJSON();
}
}
| false | true | public void sendAsyncFile(final SessionID sessionId, final UploadStructure uploadStructure,
final IResponseCommandCallback callback) {
// "Serialize" sessionId
// We will now create the Hidden elements which we will use to pass
// the required POST parameters to the web script that will actually handle
// the file upload request.
final Hidden sessionIdElement = new Hidden();
sessionIdElement.setName(WlLabCommunication.SESSION_ID_ATTR);
sessionIdElement.setValue(sessionId.getRealId());
final Hidden fileInfoElement = new Hidden();
fileInfoElement.setName(WlLabCommunication.FILE_INFO_ATTR);
fileInfoElement.setValue(uploadStructure.getFileInfo());
final Hidden isAsyncElement = new Hidden();
isAsyncElement.setName(WlLabCommunication.FILE_IS_ASYNC_ATTR);
isAsyncElement.setValue("true");
// Set up uploadStructure
uploadStructure.addInformation(sessionIdElement);
uploadStructure.addInformation(fileInfoElement);
uploadStructure.addInformation(isAsyncElement);
uploadStructure.getFileUpload().setName(WlLabCommunication.FILE_SENT_ATTR);
uploadStructure.getFormPanel().setAction(this.getFilePostUrl());
uploadStructure.getFormPanel().setEncoding(FormPanel.ENCODING_MULTIPART);
uploadStructure.getFormPanel().setMethod(FormPanel.METHOD_POST);
// Register handler
uploadStructure.getFormPanel().addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
uploadStructure.removeInformation(sessionIdElement);
final String resultMessage = event.getResults();
if(GWT.isScript() && resultMessage == null) {
this.reportFail(callback);
} else {
this.processResultMessage(callback, resultMessage);
}
}
private void processResultMessage(IResponseCommandCallback commandCallback, String resultMessage) {
final ResponseCommand parsedRequestIdCommand;
try {
parsedRequestIdCommand = ((IWlLabSerializer)WlLabCommunication.this.serializer).parseSendAsyncCommandResponse(resultMessage);
} catch (final SerializationException e) {
commandCallback.onFailure(e);
return;
} catch (final SessionNotFoundException e) {
commandCallback.onFailure(e);
return;
} catch (final WlServerException e) {
commandCallback.onFailure(e);
return;
}
// We now have the request id of our asynchronous send_file request.
// We will need to register the request with the asynchronous manager
// so that it automatically polls and notifies us when the request finishes.
final String requestID = parsedRequestIdCommand.getCommandString();
AsyncRequestsManager asyncReqMngr =
WlLabCommunication.this.asyncRequestsManagers.get(sessionId);
// TODO: Consider some better way of handling the managers.
if(asyncReqMngr == null)
asyncReqMngr = new AsyncRequestsManager(WlLabCommunication.this, sessionId, (IWlLabSerializer) WlLabCommunication.this.serializer);
asyncReqMngr.registerAsyncRequest(requestID, commandCallback);
}
private void reportFail(final IResponseCommandCallback callback) {
GWT.log("reportFail could not async send the file", null);
callback.onFailure(new WlCommException("Couldn't async send the file"));
}
});
// Submit
uploadStructure.getFormPanel().submit();
}
| public void sendAsyncFile(final SessionID sessionId, final UploadStructure uploadStructure,
final IResponseCommandCallback callback) {
// "Serialize" sessionId
// We will now create the Hidden elements which we will use to pass
// the required POST parameters to the web script that will actually handle
// the file upload request.
final Hidden sessionIdElement = new Hidden();
sessionIdElement.setName(WlLabCommunication.SESSION_ID_ATTR);
sessionIdElement.setValue(sessionId.getRealId());
final Hidden fileInfoElement = new Hidden();
fileInfoElement.setName(WlLabCommunication.FILE_INFO_ATTR);
fileInfoElement.setValue(uploadStructure.getFileInfo());
final Hidden isAsyncElement = new Hidden();
isAsyncElement.setName(WlLabCommunication.FILE_IS_ASYNC_ATTR);
isAsyncElement.setValue("true");
// Set up uploadStructure
uploadStructure.addInformation(sessionIdElement);
uploadStructure.addInformation(fileInfoElement);
uploadStructure.addInformation(isAsyncElement);
uploadStructure.getFileUpload().setName(WlLabCommunication.FILE_SENT_ATTR);
uploadStructure.getFormPanel().setAction(this.getFilePostUrl());
uploadStructure.getFormPanel().setEncoding(FormPanel.ENCODING_MULTIPART);
uploadStructure.getFormPanel().setMethod(FormPanel.METHOD_POST);
// Register handler
uploadStructure.getFormPanel().addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
uploadStructure.removeInformation(sessionIdElement);
final String resultMessage = event.getResults();
// resultMessage will be a string such as SUCCESS@34KJ2341KJ
if(GWT.isScript() && resultMessage == null) {
this.reportFail(callback);
} else {
this.processResultMessage(callback, resultMessage);
}
}
private void processResultMessage(IResponseCommandCallback commandCallback, String resultMessage) {
final ResponseCommand parsedRequestIdCommand;
try {
// TODO: This should be improved.
if(!resultMessage.toLowerCase().startsWith("success@"))
throw new SerializationException("Async send file response does not start with success@");
final String reslt = resultMessage.substring("success@".length());
System.out.println("[DBG]: AsyncSendFile returned: " + reslt);
parsedRequestIdCommand = new ResponseCommand(reslt);
} catch (final SerializationException e) {
commandCallback.onFailure(e);
return;
}
// } catch (final SessionNotFoundException e) {
// commandCallback.onFailure(e);
// return;
// } catch (final WlServerException e) {
// commandCallback.onFailure(e);
// return;
// }
// We now have the request id of our asynchronous send_file request.
// We will need to register the request with the asynchronous manager
// so that it automatically polls and notifies us when the request finishes.
final String requestID = parsedRequestIdCommand.getCommandString();
AsyncRequestsManager asyncReqMngr =
WlLabCommunication.this.asyncRequestsManagers.get(sessionId);
// TODO: Consider some better way of handling the managers.
if(asyncReqMngr == null)
asyncReqMngr = new AsyncRequestsManager(WlLabCommunication.this, sessionId, (IWlLabSerializer) WlLabCommunication.this.serializer);
asyncReqMngr.registerAsyncRequest(requestID, commandCallback);
}
private void reportFail(final IResponseCommandCallback callback) {
GWT.log("reportFail could not async send the file", null);
callback.onFailure(new WlCommException("Couldn't async send the file"));
}
});
// Submit
uploadStructure.getFormPanel().submit();
}
|
diff --git a/src/haven/GLState.java b/src/haven/GLState.java
index 09a24e46..19b96f49 100644
--- a/src/haven/GLState.java
+++ b/src/haven/GLState.java
@@ -1,517 +1,523 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import java.util.*;
import javax.media.opengl.*;
import static haven.GOut.checkerr;
public abstract class GLState {
public abstract void apply(GOut g);
public abstract void unapply(GOut g);
public abstract void prep(Buffer buf);
public void applyfrom(GOut g, GLState from) {
throw(new RuntimeException("Called applyfrom on non-conformant GLState"));
}
public void applyto(GOut g, GLState to) {
}
public void reapply(GOut g) {
}
public GLShader[] shaders() {
return(null);
}
public boolean reqshaders() {
return(false);
}
public int capply() {
return(10);
}
public int cunapply() {
return(1);
}
public int capplyfrom(GLState from) {
return(-1);
}
public int capplyto(GLState to) {
return(0);
}
private static int slotnum = 0;
private static Slot<?>[] deplist = new Slot<?>[0];
private static Slot<?>[] idlist = new Slot<?>[0];
public static class Slot<T extends GLState> {
private static boolean dirty = false;
private static Collection<Slot<?>> all = new LinkedList<Slot<?>>();
public final int id;
public final Class<T> scl;
private int depid = -1;
private final Slot<?>[] dep, rdep;
private Slot[] grdep;
public Slot(Class<T> scl, Slot<?>[] dep, Slot<?>[] rdep) {
this.scl = scl;
synchronized(Slot.class) {
this.id = slotnum++;
dirty = true;
Slot<?>[] nlist = new Slot<?>[slotnum];
System.arraycopy(idlist, 0, nlist, 0, idlist.length);
nlist[this.id] = this;
idlist = nlist;
all.add(this);
}
if(dep == null)
this.dep = new Slot<?>[0];
else
this.dep = dep;
if(rdep == null)
this.rdep = new Slot<?>[0];
else
this.rdep = rdep;
for(Slot<?> ds : this.dep) {
if(ds == null)
throw(new NullPointerException());
}
for(Slot<?> ds : this.rdep) {
if(ds == null)
throw(new NullPointerException());
}
}
public Slot(Class<T> scl, Slot... dep) {
this(scl, dep, null);
}
private static void makedeps(Collection<Slot<?>> slots) {
Map<Slot<?>, Set<Slot<?>>> lrdep = new HashMap<Slot<?>, Set<Slot<?>>>();
for(Slot<?> s : slots)
lrdep.put(s, new HashSet<Slot<?>>());
for(Slot<?> s : slots) {
lrdep.get(s).addAll(Arrays.asList(s.rdep));
for(Slot<?> ds : s.dep)
lrdep.get(ds).add(s);
}
Set<Slot<?>> left = new HashSet<Slot<?>>(slots);
final Map<Slot<?>, Integer> order = new HashMap<Slot<?>, Integer>();
int id = left.size() - 1;
Slot<?>[] cp = new Slot<?>[0];
while(!left.isEmpty()) {
boolean err = true;
fin:
for(Iterator<Slot<?>> i = left.iterator(); i.hasNext();) {
Slot<?> s = i.next();
for(Slot<?> ds : lrdep.get(s)) {
if(left.contains(ds))
continue fin;
}
err = false;
order.put(s, s.depid = id--);
Set<Slot<?>> grdep = new HashSet<Slot<?>>();
for(Slot<?> ds : lrdep.get(s)) {
grdep.add(ds);
for(Slot<?> ds2 : ds.grdep)
grdep.add(ds2);
}
s.grdep = grdep.toArray(cp);
i.remove();
}
if(err)
throw(new RuntimeException("Cycle encountered while compiling state slot dependencies"));
}
Comparator<Slot<?>> cmp = new Comparator<Slot<?>>() {
public int compare(Slot<?> a, Slot<?> b) {
return(order.get(a) - order.get(b));
}
};
for(Slot<?> s : slots)
Arrays.sort(s.grdep, cmp);
}
public static void update() {
synchronized(Slot.class) {
if(!dirty)
return;
makedeps(all);
deplist = new Slot<?>[all.size()];
for(Slot s : all)
deplist[s.depid] = s;
dirty = false;
}
}
}
public static class Buffer {
private GLState[] states = new GLState[slotnum];
public Buffer copy() {
Buffer ret = new Buffer();
System.arraycopy(states, 0, ret.states, 0, states.length);
return(ret);
}
public void copy(Buffer dest) {
dest.adjust();
System.arraycopy(states, 0, dest.states, 0, states.length);
for(int i = states.length; i < dest.states.length; i++)
dest.states[i] = null;
}
private void adjust() {
if(states.length < slotnum) {
GLState[] n = new GLState[slotnum];
System.arraycopy(states, 0, n, 0, states.length);
this.states = n;
}
}
public <T extends GLState> void put(Slot<? super T> slot, T state) {
if(states.length <= slot.id)
adjust();
states[slot.id] = state;
}
@SuppressWarnings("unchecked")
public <T extends GLState> T get(Slot<T> slot) {
if(states.length <= slot.id)
return(null);
return((T)states[slot.id]);
}
public boolean equals(Object o) {
if(!(o instanceof Buffer))
return(false);
Buffer b = (Buffer)o;
adjust();
b.adjust();
for(int i = 0; i < states.length; i++) {
if(!states[i].equals(b.states[i]))
return(false);
}
return(true);
}
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append('[');
for(int i = 0; i < states.length; i++) {
if(i > 0)
buf.append(", ");
if(states[i] == null)
buf.append("null");
else
buf.append(states[i].toString());
}
buf.append(']');
return(buf.toString());
}
}
public static int bufdiff(Buffer f, Buffer t, boolean[] trans, boolean[] repl) {
Slot.update();
int cost = 0;
f.adjust(); t.adjust();
if(trans != null) {
for(int i = 0; i < trans.length; i++) {
trans[i] = false;
repl[i] = false;
}
}
for(int i = 0; i < f.states.length; i++) {
if(((f.states[i] == null) != (t.states[i] == null)) ||
((f.states[i] != null) && (t.states[i] != null) && !f.states[i].equals(t.states[i]))) {
if(!repl[i]) {
int cat = -1, caf = -1;
if((t.states[i] != null) && (f.states[i] != null)) {
cat = f.states[i].capplyto(t.states[i]);
caf = t.states[i].capplyfrom(f.states[i]);
}
if((cat >= 0) && (caf >= 0)) {
cost += cat + caf;
if(trans != null)
trans[i] = true;
} else {
if(f.states[i] != null)
cost += f.states[i].cunapply();
if(t.states[i] != null)
cost += t.states[i].capply();
if(trans != null)
repl[i] = true;
}
}
for(Slot ds : idlist[i].grdep) {
int id = ds.id;
if(repl[id])
continue;
if(trans != null)
repl[id] = true;
if(t.states[id] != null)
cost += t.states[id].cunapply();
if(f.states[id] != null)
cost += f.states[id].capply();
}
}
}
return(cost);
}
public static class Applier {
private Buffer cur = new Buffer(), next = new Buffer();
public final GL gl;
private boolean[] trans = new boolean[0], repl = new boolean[0];
private GLShader[][] shaders = new GLShader[0][];
private int proghash = 0;
public GLProgram prog;
public boolean usedprog;
public long time = 0;
public Applier(GL gl) {
this.gl = gl;
}
public <T extends GLState> void put(Slot<? super T> slot, T state) {
next.put(slot, state);
}
public <T extends GLState> T get(Slot<T> slot) {
return(next.get(slot));
}
public <T extends GLState> T cur(Slot<T> slot) {
return(cur.get(slot));
}
public void prep(GLState st) {
st.prep(next);
}
public void set(Buffer to) {
to.copy(next);
}
public void copy(Buffer dest) {
next.copy(dest);
}
public Buffer copy() {
return(next.copy());
}
public void apply(GOut g) {
long st = 0;
if(Config.profile) st = System.nanoTime();
if(trans.length < slotnum) {
synchronized(Slot.class) {
trans = new boolean[slotnum];
repl = new boolean[slotnum];
shaders = new GLShader[slotnum][];
}
}
bufdiff(cur, next, trans, repl);
boolean dirty = false, shreq = false;
for(int i = trans.length - 1; i >= 0; i--) {
if(repl[i] || trans[i]) {
GLState nst = next.states[i];
GLShader[] ns = (nst == null)?null:nst.shaders();
if(ns != shaders[i]) {
proghash ^= System.identityHashCode(shaders[i]) ^ System.identityHashCode(ns);
shaders[i] = ns;
dirty = true;
}
if(ns != null)
shreq |= nst.reqshaders();
}
}
usedprog = prog != null;
for(int i = trans.length - 1; i >= 0; i--) {
if(repl[i]) {
if(cur.states[i] != null)
cur.states[i].unapply(g);
cur.states[i] = null;
}
}
if(dirty) {
GLProgram np;
if(g.gc.shuse && shreq) {
np = findprog(proghash, shaders);
} else {
np = null;
}
if(np != prog) {
if(np != null)
np.apply(g);
else
g.gl.glUseProgramObjectARB(0);
prog = np;
} else {
dirty = false;
}
}
+ if((prog != null) != usedprog) {
+ for(int i = 0; i < trans.length; i++) {
+ if(trans[i])
+ repl[i] = true;
+ }
+ }
for(int i = 0; i < trans.length; i++) {
if(repl[i]) {
cur.states[i] = next.states[i];
if(cur.states[i] != null)
cur.states[i].apply(g);
} else if(trans[i]) {
cur.states[i].applyto(g, next.states[i]);
GLState cs = cur.states[i];
(cur.states[i] = next.states[i]).applyfrom(g, cs);
} else if((prog != null) && dirty && (shaders[i] != null)) {
cur.states[i].reapply(g);
}
}
checkerr(gl);
if(Config.profile)
time += System.nanoTime() - st;
}
/* "Meta-states" */
private int matmode = GL.GL_MODELVIEW;
private int texunit = 0;
public void matmode(int mode) {
if(mode != matmode) {
gl.glMatrixMode(mode);
matmode = mode;
}
}
public void texunit(int unit) {
if(unit != texunit) {
gl.glActiveTexture(GL.GL_TEXTURE0 + unit);
texunit = unit;
}
}
/* Program internation */
public static class SavedProg {
public final int hash;
public final GLProgram prog;
public final GLShader[][] shaders;
public SavedProg next;
public SavedProg(int hash, GLProgram prog, GLShader[][] shaders) {
this.hash = hash;
this.prog = prog;
this.shaders = shaders;
}
}
private SavedProg[] ptab = new SavedProg[32];
private int nprog = 0;
private GLProgram findprog(int hash, GLShader[][] shaders) {
int idx = hash & (ptab.length - 1);
outer: for(SavedProg s = ptab[idx]; s != null; s = s.next) {
if(s.hash != hash)
continue;
int i;
for(i = 0; i < s.shaders.length; i++) {
if(shaders[i] != s.shaders[i])
continue outer;
}
for(; i < shaders.length; i++) {
if(shaders[i] != null)
continue outer;
}
return(s.prog);
}
GLProgram prog = new GLProgram(shaders);
SavedProg s = new SavedProg(hash, prog, shaders);
s.next = ptab[idx];
ptab[idx] = s;
nprog++;
if(nprog > ptab.length)
rehash(ptab.length * 2);
return(prog);
}
private void rehash(int nlen) {
SavedProg[] ntab = new SavedProg[nlen];
for(int i = 0; i < ptab.length; i++) {
while(ptab[i] != null) {
SavedProg s = ptab[i];
ptab[i] = s.next;
int ni = s.hash & (ntab.length - 1);
s.next = ntab[ni];
ntab[ni] = s;
}
}
ptab = ntab;
}
public int numprogs() {
return(nprog);
}
}
private class Wrapping implements Rendered {
private final Rendered r;
private Wrapping(Rendered r) {
this.r = r;
}
public void draw(GOut g) {}
public Order setup(RenderList rl) {
rl.add(r, GLState.this);
return(null);
}
}
public Rendered apply(Rendered r) {
return(new Wrapping(r));
}
public static GLState compose(final GLState... states) {
return(new GLState() {
public void apply(GOut g) {}
public void unapply(GOut g) {}
public void prep(Buffer buf) {
for(GLState st : states) {
st.prep(buf);
}
}
});
}
public static abstract class StandAlone extends GLState {
public final Slot<StandAlone> slot;
public StandAlone(Slot<?>... dep) {
slot = new Slot<StandAlone>(StandAlone.class, dep);
}
public void prep(Buffer buf) {
buf.put(slot, this);
}
}
}
| true | true | public void apply(GOut g) {
long st = 0;
if(Config.profile) st = System.nanoTime();
if(trans.length < slotnum) {
synchronized(Slot.class) {
trans = new boolean[slotnum];
repl = new boolean[slotnum];
shaders = new GLShader[slotnum][];
}
}
bufdiff(cur, next, trans, repl);
boolean dirty = false, shreq = false;
for(int i = trans.length - 1; i >= 0; i--) {
if(repl[i] || trans[i]) {
GLState nst = next.states[i];
GLShader[] ns = (nst == null)?null:nst.shaders();
if(ns != shaders[i]) {
proghash ^= System.identityHashCode(shaders[i]) ^ System.identityHashCode(ns);
shaders[i] = ns;
dirty = true;
}
if(ns != null)
shreq |= nst.reqshaders();
}
}
usedprog = prog != null;
for(int i = trans.length - 1; i >= 0; i--) {
if(repl[i]) {
if(cur.states[i] != null)
cur.states[i].unapply(g);
cur.states[i] = null;
}
}
if(dirty) {
GLProgram np;
if(g.gc.shuse && shreq) {
np = findprog(proghash, shaders);
} else {
np = null;
}
if(np != prog) {
if(np != null)
np.apply(g);
else
g.gl.glUseProgramObjectARB(0);
prog = np;
} else {
dirty = false;
}
}
for(int i = 0; i < trans.length; i++) {
if(repl[i]) {
cur.states[i] = next.states[i];
if(cur.states[i] != null)
cur.states[i].apply(g);
} else if(trans[i]) {
cur.states[i].applyto(g, next.states[i]);
GLState cs = cur.states[i];
(cur.states[i] = next.states[i]).applyfrom(g, cs);
} else if((prog != null) && dirty && (shaders[i] != null)) {
cur.states[i].reapply(g);
}
}
checkerr(gl);
if(Config.profile)
time += System.nanoTime() - st;
}
| public void apply(GOut g) {
long st = 0;
if(Config.profile) st = System.nanoTime();
if(trans.length < slotnum) {
synchronized(Slot.class) {
trans = new boolean[slotnum];
repl = new boolean[slotnum];
shaders = new GLShader[slotnum][];
}
}
bufdiff(cur, next, trans, repl);
boolean dirty = false, shreq = false;
for(int i = trans.length - 1; i >= 0; i--) {
if(repl[i] || trans[i]) {
GLState nst = next.states[i];
GLShader[] ns = (nst == null)?null:nst.shaders();
if(ns != shaders[i]) {
proghash ^= System.identityHashCode(shaders[i]) ^ System.identityHashCode(ns);
shaders[i] = ns;
dirty = true;
}
if(ns != null)
shreq |= nst.reqshaders();
}
}
usedprog = prog != null;
for(int i = trans.length - 1; i >= 0; i--) {
if(repl[i]) {
if(cur.states[i] != null)
cur.states[i].unapply(g);
cur.states[i] = null;
}
}
if(dirty) {
GLProgram np;
if(g.gc.shuse && shreq) {
np = findprog(proghash, shaders);
} else {
np = null;
}
if(np != prog) {
if(np != null)
np.apply(g);
else
g.gl.glUseProgramObjectARB(0);
prog = np;
} else {
dirty = false;
}
}
if((prog != null) != usedprog) {
for(int i = 0; i < trans.length; i++) {
if(trans[i])
repl[i] = true;
}
}
for(int i = 0; i < trans.length; i++) {
if(repl[i]) {
cur.states[i] = next.states[i];
if(cur.states[i] != null)
cur.states[i].apply(g);
} else if(trans[i]) {
cur.states[i].applyto(g, next.states[i]);
GLState cs = cur.states[i];
(cur.states[i] = next.states[i]).applyfrom(g, cs);
} else if((prog != null) && dirty && (shaders[i] != null)) {
cur.states[i].reapply(g);
}
}
checkerr(gl);
if(Config.profile)
time += System.nanoTime() - st;
}
|
diff --git a/serialization-tests/src/test/java/com/gs/collections/impl/list/mutable/ArrayListAdapterTest.java b/serialization-tests/src/test/java/com/gs/collections/impl/list/mutable/ArrayListAdapterTest.java
index 323ff0a4..af634bfe 100644
--- a/serialization-tests/src/test/java/com/gs/collections/impl/list/mutable/ArrayListAdapterTest.java
+++ b/serialization-tests/src/test/java/com/gs/collections/impl/list/mutable/ArrayListAdapterTest.java
@@ -1,46 +1,47 @@
/*
* Copyright 2011 Goldman Sachs.
*
* 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.gs.collections.impl.list.mutable;
import com.gs.collections.impl.test.Verify;
import org.junit.Test;
public class ArrayListAdapterTest
{
@Test
public void serializedForm()
{
- if (System.getProperty("java.version").startsWith("1.8."))
+ String javaVersion = System.getProperty("java.version");
+ if (javaVersion.startsWith("1.8.") || "1.7.0_45".equals(javaVersion))
{
Verify.assertSerializedForm(
1L,
"rO0ABXNyADVjb20uZ3MuY29sbGVjdGlvbnMuaW1wbC5saXN0Lm11dGFibGUuQXJyYXlMaXN0QWRh\n"
+ "cHRlcgAAAAAAAAABAgABTAAIZGVsZWdhdGV0ABVMamF2YS91dGlsL0FycmF5TGlzdDt4cHNyABNq\n"
+ "YXZhLnV0aWwuQXJyYXlMaXN0eIHSHZnHYZ0DAAFJAARzaXpleHAAAAAAdwQAAAAAeA==",
ArrayListAdapter.newList());
}
else
{
Verify.assertSerializedForm(
1L,
"rO0ABXNyADVjb20uZ3MuY29sbGVjdGlvbnMuaW1wbC5saXN0Lm11dGFibGUuQXJyYXlMaXN0QWRh\n"
+ "cHRlcgAAAAAAAAABAgABTAAIZGVsZWdhdGV0ABVMamF2YS91dGlsL0FycmF5TGlzdDt4cHNyABNq\n"
+ "YXZhLnV0aWwuQXJyYXlMaXN0eIHSHZnHYZ0DAAFJAARzaXpleHAAAAAAdwQAAAAKeA==",
ArrayListAdapter.newList());
}
}
}
| true | true | public void serializedForm()
{
if (System.getProperty("java.version").startsWith("1.8."))
{
Verify.assertSerializedForm(
1L,
"rO0ABXNyADVjb20uZ3MuY29sbGVjdGlvbnMuaW1wbC5saXN0Lm11dGFibGUuQXJyYXlMaXN0QWRh\n"
+ "cHRlcgAAAAAAAAABAgABTAAIZGVsZWdhdGV0ABVMamF2YS91dGlsL0FycmF5TGlzdDt4cHNyABNq\n"
+ "YXZhLnV0aWwuQXJyYXlMaXN0eIHSHZnHYZ0DAAFJAARzaXpleHAAAAAAdwQAAAAAeA==",
ArrayListAdapter.newList());
}
else
{
Verify.assertSerializedForm(
1L,
"rO0ABXNyADVjb20uZ3MuY29sbGVjdGlvbnMuaW1wbC5saXN0Lm11dGFibGUuQXJyYXlMaXN0QWRh\n"
+ "cHRlcgAAAAAAAAABAgABTAAIZGVsZWdhdGV0ABVMamF2YS91dGlsL0FycmF5TGlzdDt4cHNyABNq\n"
+ "YXZhLnV0aWwuQXJyYXlMaXN0eIHSHZnHYZ0DAAFJAARzaXpleHAAAAAAdwQAAAAKeA==",
ArrayListAdapter.newList());
}
}
| public void serializedForm()
{
String javaVersion = System.getProperty("java.version");
if (javaVersion.startsWith("1.8.") || "1.7.0_45".equals(javaVersion))
{
Verify.assertSerializedForm(
1L,
"rO0ABXNyADVjb20uZ3MuY29sbGVjdGlvbnMuaW1wbC5saXN0Lm11dGFibGUuQXJyYXlMaXN0QWRh\n"
+ "cHRlcgAAAAAAAAABAgABTAAIZGVsZWdhdGV0ABVMamF2YS91dGlsL0FycmF5TGlzdDt4cHNyABNq\n"
+ "YXZhLnV0aWwuQXJyYXlMaXN0eIHSHZnHYZ0DAAFJAARzaXpleHAAAAAAdwQAAAAAeA==",
ArrayListAdapter.newList());
}
else
{
Verify.assertSerializedForm(
1L,
"rO0ABXNyADVjb20uZ3MuY29sbGVjdGlvbnMuaW1wbC5saXN0Lm11dGFibGUuQXJyYXlMaXN0QWRh\n"
+ "cHRlcgAAAAAAAAABAgABTAAIZGVsZWdhdGV0ABVMamF2YS91dGlsL0FycmF5TGlzdDt4cHNyABNq\n"
+ "YXZhLnV0aWwuQXJyYXlMaXN0eIHSHZnHYZ0DAAFJAARzaXpleHAAAAAAdwQAAAAKeA==",
ArrayListAdapter.newList());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.